lpm_trie.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /*
  2. * Longest prefix match list implementation
  3. *
  4. * Copyright (c) 2016,2017 Daniel Mack
  5. * Copyright (c) 2016 David Herrmann
  6. *
  7. * This file is subject to the terms and conditions of version 2 of the GNU
  8. * General Public License. See the file COPYING in the main directory of the
  9. * Linux distribution for more details.
  10. */
  11. #include <linux/bpf.h>
  12. #include <linux/err.h>
  13. #include <linux/slab.h>
  14. #include <linux/spinlock.h>
  15. #include <linux/vmalloc.h>
  16. #include <net/ipv6.h>
  17. /* Intermediate node */
  18. #define LPM_TREE_NODE_FLAG_IM BIT(0)
  19. struct lpm_trie_node;
  20. struct lpm_trie_node {
  21. struct rcu_head rcu;
  22. struct lpm_trie_node __rcu *child[2];
  23. u32 prefixlen;
  24. u32 flags;
  25. u8 data[0];
  26. };
  27. struct lpm_trie {
  28. struct bpf_map map;
  29. struct lpm_trie_node __rcu *root;
  30. size_t n_entries;
  31. size_t max_prefixlen;
  32. size_t data_size;
  33. raw_spinlock_t lock;
  34. };
  35. /* This trie implements a longest prefix match algorithm that can be used to
  36. * match IP addresses to a stored set of ranges.
  37. *
  38. * Data stored in @data of struct bpf_lpm_key and struct lpm_trie_node is
  39. * interpreted as big endian, so data[0] stores the most significant byte.
  40. *
  41. * Match ranges are internally stored in instances of struct lpm_trie_node
  42. * which each contain their prefix length as well as two pointers that may
  43. * lead to more nodes containing more specific matches. Each node also stores
  44. * a value that is defined by and returned to userspace via the update_elem
  45. * and lookup functions.
  46. *
  47. * For instance, let's start with a trie that was created with a prefix length
  48. * of 32, so it can be used for IPv4 addresses, and one single element that
  49. * matches 192.168.0.0/16. The data array would hence contain
  50. * [0xc0, 0xa8, 0x00, 0x00] in big-endian notation. This documentation will
  51. * stick to IP-address notation for readability though.
  52. *
  53. * As the trie is empty initially, the new node (1) will be places as root
  54. * node, denoted as (R) in the example below. As there are no other node, both
  55. * child pointers are %NULL.
  56. *
  57. * +----------------+
  58. * | (1) (R) |
  59. * | 192.168.0.0/16 |
  60. * | value: 1 |
  61. * | [0] [1] |
  62. * +----------------+
  63. *
  64. * Next, let's add a new node (2) matching 192.168.0.0/24. As there is already
  65. * a node with the same data and a smaller prefix (ie, a less specific one),
  66. * node (2) will become a child of (1). In child index depends on the next bit
  67. * that is outside of what (1) matches, and that bit is 0, so (2) will be
  68. * child[0] of (1):
  69. *
  70. * +----------------+
  71. * | (1) (R) |
  72. * | 192.168.0.0/16 |
  73. * | value: 1 |
  74. * | [0] [1] |
  75. * +----------------+
  76. * |
  77. * +----------------+
  78. * | (2) |
  79. * | 192.168.0.0/24 |
  80. * | value: 2 |
  81. * | [0] [1] |
  82. * +----------------+
  83. *
  84. * The child[1] slot of (1) could be filled with another node which has bit #17
  85. * (the next bit after the ones that (1) matches on) set to 1. For instance,
  86. * 192.168.128.0/24:
  87. *
  88. * +----------------+
  89. * | (1) (R) |
  90. * | 192.168.0.0/16 |
  91. * | value: 1 |
  92. * | [0] [1] |
  93. * +----------------+
  94. * | |
  95. * +----------------+ +------------------+
  96. * | (2) | | (3) |
  97. * | 192.168.0.0/24 | | 192.168.128.0/24 |
  98. * | value: 2 | | value: 3 |
  99. * | [0] [1] | | [0] [1] |
  100. * +----------------+ +------------------+
  101. *
  102. * Let's add another node (4) to the game for 192.168.1.0/24. In order to place
  103. * it, node (1) is looked at first, and because (4) of the semantics laid out
  104. * above (bit #17 is 0), it would normally be attached to (1) as child[0].
  105. * However, that slot is already allocated, so a new node is needed in between.
  106. * That node does not have a value attached to it and it will never be
  107. * returned to users as result of a lookup. It is only there to differentiate
  108. * the traversal further. It will get a prefix as wide as necessary to
  109. * distinguish its two children:
  110. *
  111. * +----------------+
  112. * | (1) (R) |
  113. * | 192.168.0.0/16 |
  114. * | value: 1 |
  115. * | [0] [1] |
  116. * +----------------+
  117. * | |
  118. * +----------------+ +------------------+
  119. * | (4) (I) | | (3) |
  120. * | 192.168.0.0/23 | | 192.168.128.0/24 |
  121. * | value: --- | | value: 3 |
  122. * | [0] [1] | | [0] [1] |
  123. * +----------------+ +------------------+
  124. * | |
  125. * +----------------+ +----------------+
  126. * | (2) | | (5) |
  127. * | 192.168.0.0/24 | | 192.168.1.0/24 |
  128. * | value: 2 | | value: 5 |
  129. * | [0] [1] | | [0] [1] |
  130. * +----------------+ +----------------+
  131. *
  132. * 192.168.1.1/32 would be a child of (5) etc.
  133. *
  134. * An intermediate node will be turned into a 'real' node on demand. In the
  135. * example above, (4) would be re-used if 192.168.0.0/23 is added to the trie.
  136. *
  137. * A fully populated trie would have a height of 32 nodes, as the trie was
  138. * created with a prefix length of 32.
  139. *
  140. * The lookup starts at the root node. If the current node matches and if there
  141. * is a child that can be used to become more specific, the trie is traversed
  142. * downwards. The last node in the traversal that is a non-intermediate one is
  143. * returned.
  144. */
  145. static inline int extract_bit(const u8 *data, size_t index)
  146. {
  147. return !!(data[index / 8] & (1 << (7 - (index % 8))));
  148. }
  149. /**
  150. * longest_prefix_match() - determine the longest prefix
  151. * @trie: The trie to get internal sizes from
  152. * @node: The node to operate on
  153. * @key: The key to compare to @node
  154. *
  155. * Determine the longest prefix of @node that matches the bits in @key.
  156. */
  157. static size_t longest_prefix_match(const struct lpm_trie *trie,
  158. const struct lpm_trie_node *node,
  159. const struct bpf_lpm_trie_key *key)
  160. {
  161. size_t prefixlen = 0;
  162. size_t i;
  163. for (i = 0; i < trie->data_size; i++) {
  164. size_t b;
  165. b = 8 - fls(node->data[i] ^ key->data[i]);
  166. prefixlen += b;
  167. if (prefixlen >= node->prefixlen || prefixlen >= key->prefixlen)
  168. return min(node->prefixlen, key->prefixlen);
  169. if (b < 8)
  170. break;
  171. }
  172. return prefixlen;
  173. }
  174. /* Called from syscall or from eBPF program */
  175. static void *trie_lookup_elem(struct bpf_map *map, void *_key)
  176. {
  177. struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
  178. struct lpm_trie_node *node, *found = NULL;
  179. struct bpf_lpm_trie_key *key = _key;
  180. /* Start walking the trie from the root node ... */
  181. for (node = rcu_dereference(trie->root); node;) {
  182. unsigned int next_bit;
  183. size_t matchlen;
  184. /* Determine the longest prefix of @node that matches @key.
  185. * If it's the maximum possible prefix for this trie, we have
  186. * an exact match and can return it directly.
  187. */
  188. matchlen = longest_prefix_match(trie, node, key);
  189. if (matchlen == trie->max_prefixlen) {
  190. found = node;
  191. break;
  192. }
  193. /* If the number of bits that match is smaller than the prefix
  194. * length of @node, bail out and return the node we have seen
  195. * last in the traversal (ie, the parent).
  196. */
  197. if (matchlen < node->prefixlen)
  198. break;
  199. /* Consider this node as return candidate unless it is an
  200. * artificially added intermediate one.
  201. */
  202. if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
  203. found = node;
  204. /* If the node match is fully satisfied, let's see if we can
  205. * become more specific. Determine the next bit in the key and
  206. * traverse down.
  207. */
  208. next_bit = extract_bit(key->data, node->prefixlen);
  209. node = rcu_dereference(node->child[next_bit]);
  210. }
  211. if (!found)
  212. return NULL;
  213. return found->data + trie->data_size;
  214. }
  215. static struct lpm_trie_node *lpm_trie_node_alloc(const struct lpm_trie *trie,
  216. const void *value)
  217. {
  218. struct lpm_trie_node *node;
  219. size_t size = sizeof(struct lpm_trie_node) + trie->data_size;
  220. if (value)
  221. size += trie->map.value_size;
  222. node = kmalloc_node(size, GFP_ATOMIC | __GFP_NOWARN,
  223. trie->map.numa_node);
  224. if (!node)
  225. return NULL;
  226. node->flags = 0;
  227. if (value)
  228. memcpy(node->data + trie->data_size, value,
  229. trie->map.value_size);
  230. return node;
  231. }
  232. /* Called from syscall or from eBPF program */
  233. static int trie_update_elem(struct bpf_map *map,
  234. void *_key, void *value, u64 flags)
  235. {
  236. struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
  237. struct lpm_trie_node *node, *im_node = NULL, *new_node = NULL;
  238. struct lpm_trie_node __rcu **slot;
  239. struct bpf_lpm_trie_key *key = _key;
  240. unsigned long irq_flags;
  241. unsigned int next_bit;
  242. size_t matchlen = 0;
  243. int ret = 0;
  244. if (unlikely(flags > BPF_EXIST))
  245. return -EINVAL;
  246. if (key->prefixlen > trie->max_prefixlen)
  247. return -EINVAL;
  248. raw_spin_lock_irqsave(&trie->lock, irq_flags);
  249. /* Allocate and fill a new node */
  250. if (trie->n_entries == trie->map.max_entries) {
  251. ret = -ENOSPC;
  252. goto out;
  253. }
  254. new_node = lpm_trie_node_alloc(trie, value);
  255. if (!new_node) {
  256. ret = -ENOMEM;
  257. goto out;
  258. }
  259. trie->n_entries++;
  260. new_node->prefixlen = key->prefixlen;
  261. RCU_INIT_POINTER(new_node->child[0], NULL);
  262. RCU_INIT_POINTER(new_node->child[1], NULL);
  263. memcpy(new_node->data, key->data, trie->data_size);
  264. /* Now find a slot to attach the new node. To do that, walk the tree
  265. * from the root and match as many bits as possible for each node until
  266. * we either find an empty slot or a slot that needs to be replaced by
  267. * an intermediate node.
  268. */
  269. slot = &trie->root;
  270. while ((node = rcu_dereference_protected(*slot,
  271. lockdep_is_held(&trie->lock)))) {
  272. matchlen = longest_prefix_match(trie, node, key);
  273. if (node->prefixlen != matchlen ||
  274. node->prefixlen == key->prefixlen ||
  275. node->prefixlen == trie->max_prefixlen)
  276. break;
  277. next_bit = extract_bit(key->data, node->prefixlen);
  278. slot = &node->child[next_bit];
  279. }
  280. /* If the slot is empty (a free child pointer or an empty root),
  281. * simply assign the @new_node to that slot and be done.
  282. */
  283. if (!node) {
  284. rcu_assign_pointer(*slot, new_node);
  285. goto out;
  286. }
  287. /* If the slot we picked already exists, replace it with @new_node
  288. * which already has the correct data array set.
  289. */
  290. if (node->prefixlen == matchlen) {
  291. new_node->child[0] = node->child[0];
  292. new_node->child[1] = node->child[1];
  293. if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
  294. trie->n_entries--;
  295. rcu_assign_pointer(*slot, new_node);
  296. kfree_rcu(node, rcu);
  297. goto out;
  298. }
  299. /* If the new node matches the prefix completely, it must be inserted
  300. * as an ancestor. Simply insert it between @node and *@slot.
  301. */
  302. if (matchlen == key->prefixlen) {
  303. next_bit = extract_bit(node->data, matchlen);
  304. rcu_assign_pointer(new_node->child[next_bit], node);
  305. rcu_assign_pointer(*slot, new_node);
  306. goto out;
  307. }
  308. im_node = lpm_trie_node_alloc(trie, NULL);
  309. if (!im_node) {
  310. ret = -ENOMEM;
  311. goto out;
  312. }
  313. im_node->prefixlen = matchlen;
  314. im_node->flags |= LPM_TREE_NODE_FLAG_IM;
  315. memcpy(im_node->data, node->data, trie->data_size);
  316. /* Now determine which child to install in which slot */
  317. if (extract_bit(key->data, matchlen)) {
  318. rcu_assign_pointer(im_node->child[0], node);
  319. rcu_assign_pointer(im_node->child[1], new_node);
  320. } else {
  321. rcu_assign_pointer(im_node->child[0], new_node);
  322. rcu_assign_pointer(im_node->child[1], node);
  323. }
  324. /* Finally, assign the intermediate node to the determined spot */
  325. rcu_assign_pointer(*slot, im_node);
  326. out:
  327. if (ret) {
  328. if (new_node)
  329. trie->n_entries--;
  330. kfree(new_node);
  331. kfree(im_node);
  332. }
  333. raw_spin_unlock_irqrestore(&trie->lock, irq_flags);
  334. return ret;
  335. }
  336. static int trie_delete_elem(struct bpf_map *map, void *key)
  337. {
  338. /* TODO */
  339. return -ENOSYS;
  340. }
  341. #define LPM_DATA_SIZE_MAX 256
  342. #define LPM_DATA_SIZE_MIN 1
  343. #define LPM_VAL_SIZE_MAX (KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
  344. sizeof(struct lpm_trie_node))
  345. #define LPM_VAL_SIZE_MIN 1
  346. #define LPM_KEY_SIZE(X) (sizeof(struct bpf_lpm_trie_key) + (X))
  347. #define LPM_KEY_SIZE_MAX LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
  348. #define LPM_KEY_SIZE_MIN LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
  349. #define LPM_CREATE_FLAG_MASK (BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE | \
  350. BPF_F_RDONLY | BPF_F_WRONLY)
  351. static struct bpf_map *trie_alloc(union bpf_attr *attr)
  352. {
  353. struct lpm_trie *trie;
  354. u64 cost = sizeof(*trie), cost_per_node;
  355. int ret;
  356. if (!capable(CAP_SYS_ADMIN))
  357. return ERR_PTR(-EPERM);
  358. /* check sanity of attributes */
  359. if (attr->max_entries == 0 ||
  360. !(attr->map_flags & BPF_F_NO_PREALLOC) ||
  361. attr->map_flags & ~LPM_CREATE_FLAG_MASK ||
  362. attr->key_size < LPM_KEY_SIZE_MIN ||
  363. attr->key_size > LPM_KEY_SIZE_MAX ||
  364. attr->value_size < LPM_VAL_SIZE_MIN ||
  365. attr->value_size > LPM_VAL_SIZE_MAX)
  366. return ERR_PTR(-EINVAL);
  367. trie = kzalloc(sizeof(*trie), GFP_USER | __GFP_NOWARN);
  368. if (!trie)
  369. return ERR_PTR(-ENOMEM);
  370. /* copy mandatory map attributes */
  371. trie->map.map_type = attr->map_type;
  372. trie->map.key_size = attr->key_size;
  373. trie->map.value_size = attr->value_size;
  374. trie->map.max_entries = attr->max_entries;
  375. trie->map.map_flags = attr->map_flags;
  376. trie->map.numa_node = bpf_map_attr_numa_node(attr);
  377. trie->data_size = attr->key_size -
  378. offsetof(struct bpf_lpm_trie_key, data);
  379. trie->max_prefixlen = trie->data_size * 8;
  380. cost_per_node = sizeof(struct lpm_trie_node) +
  381. attr->value_size + trie->data_size;
  382. cost += (u64) attr->max_entries * cost_per_node;
  383. if (cost >= U32_MAX - PAGE_SIZE) {
  384. ret = -E2BIG;
  385. goto out_err;
  386. }
  387. trie->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  388. ret = bpf_map_precharge_memlock(trie->map.pages);
  389. if (ret)
  390. goto out_err;
  391. raw_spin_lock_init(&trie->lock);
  392. return &trie->map;
  393. out_err:
  394. kfree(trie);
  395. return ERR_PTR(ret);
  396. }
  397. static void trie_free(struct bpf_map *map)
  398. {
  399. struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
  400. struct lpm_trie_node __rcu **slot;
  401. struct lpm_trie_node *node;
  402. /* Wait for outstanding programs to complete
  403. * update/lookup/delete/get_next_key and free the trie.
  404. */
  405. synchronize_rcu();
  406. /* Always start at the root and walk down to a node that has no
  407. * children. Then free that node, nullify its reference in the parent
  408. * and start over.
  409. */
  410. for (;;) {
  411. slot = &trie->root;
  412. for (;;) {
  413. node = rcu_dereference_protected(*slot, 1);
  414. if (!node)
  415. goto out;
  416. if (rcu_access_pointer(node->child[0])) {
  417. slot = &node->child[0];
  418. continue;
  419. }
  420. if (rcu_access_pointer(node->child[1])) {
  421. slot = &node->child[1];
  422. continue;
  423. }
  424. kfree(node);
  425. RCU_INIT_POINTER(*slot, NULL);
  426. break;
  427. }
  428. }
  429. out:
  430. kfree(trie);
  431. }
  432. static int trie_get_next_key(struct bpf_map *map, void *key, void *next_key)
  433. {
  434. return -ENOTSUPP;
  435. }
  436. const struct bpf_map_ops trie_map_ops = {
  437. .map_alloc = trie_alloc,
  438. .map_free = trie_free,
  439. .map_get_next_key = trie_get_next_key,
  440. .map_lookup_elem = trie_lookup_elem,
  441. .map_update_elem = trie_update_elem,
  442. .map_delete_elem = trie_delete_elem,
  443. };