lpm_trie.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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(size, GFP_ATOMIC | __GFP_NOWARN);
  223. if (!node)
  224. return NULL;
  225. node->flags = 0;
  226. if (value)
  227. memcpy(node->data + trie->data_size, value,
  228. trie->map.value_size);
  229. return node;
  230. }
  231. /* Called from syscall or from eBPF program */
  232. static int trie_update_elem(struct bpf_map *map,
  233. void *_key, void *value, u64 flags)
  234. {
  235. struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
  236. struct lpm_trie_node *node, *im_node = NULL, *new_node = NULL;
  237. struct lpm_trie_node __rcu **slot;
  238. struct bpf_lpm_trie_key *key = _key;
  239. unsigned long irq_flags;
  240. unsigned int next_bit;
  241. size_t matchlen = 0;
  242. int ret = 0;
  243. if (unlikely(flags > BPF_EXIST))
  244. return -EINVAL;
  245. if (key->prefixlen > trie->max_prefixlen)
  246. return -EINVAL;
  247. raw_spin_lock_irqsave(&trie->lock, irq_flags);
  248. /* Allocate and fill a new node */
  249. if (trie->n_entries == trie->map.max_entries) {
  250. ret = -ENOSPC;
  251. goto out;
  252. }
  253. new_node = lpm_trie_node_alloc(trie, value);
  254. if (!new_node) {
  255. ret = -ENOMEM;
  256. goto out;
  257. }
  258. trie->n_entries++;
  259. new_node->prefixlen = key->prefixlen;
  260. RCU_INIT_POINTER(new_node->child[0], NULL);
  261. RCU_INIT_POINTER(new_node->child[1], NULL);
  262. memcpy(new_node->data, key->data, trie->data_size);
  263. /* Now find a slot to attach the new node. To do that, walk the tree
  264. * from the root and match as many bits as possible for each node until
  265. * we either find an empty slot or a slot that needs to be replaced by
  266. * an intermediate node.
  267. */
  268. slot = &trie->root;
  269. while ((node = rcu_dereference_protected(*slot,
  270. lockdep_is_held(&trie->lock)))) {
  271. matchlen = longest_prefix_match(trie, node, key);
  272. if (node->prefixlen != matchlen ||
  273. node->prefixlen == key->prefixlen ||
  274. node->prefixlen == trie->max_prefixlen)
  275. break;
  276. next_bit = extract_bit(key->data, node->prefixlen);
  277. slot = &node->child[next_bit];
  278. }
  279. /* If the slot is empty (a free child pointer or an empty root),
  280. * simply assign the @new_node to that slot and be done.
  281. */
  282. if (!node) {
  283. rcu_assign_pointer(*slot, new_node);
  284. goto out;
  285. }
  286. /* If the slot we picked already exists, replace it with @new_node
  287. * which already has the correct data array set.
  288. */
  289. if (node->prefixlen == matchlen) {
  290. new_node->child[0] = node->child[0];
  291. new_node->child[1] = node->child[1];
  292. if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
  293. trie->n_entries--;
  294. rcu_assign_pointer(*slot, new_node);
  295. kfree_rcu(node, rcu);
  296. goto out;
  297. }
  298. /* If the new node matches the prefix completely, it must be inserted
  299. * as an ancestor. Simply insert it between @node and *@slot.
  300. */
  301. if (matchlen == key->prefixlen) {
  302. next_bit = extract_bit(node->data, matchlen);
  303. rcu_assign_pointer(new_node->child[next_bit], node);
  304. rcu_assign_pointer(*slot, new_node);
  305. goto out;
  306. }
  307. im_node = lpm_trie_node_alloc(trie, NULL);
  308. if (!im_node) {
  309. ret = -ENOMEM;
  310. goto out;
  311. }
  312. im_node->prefixlen = matchlen;
  313. im_node->flags |= LPM_TREE_NODE_FLAG_IM;
  314. memcpy(im_node->data, node->data, trie->data_size);
  315. /* Now determine which child to install in which slot */
  316. if (extract_bit(key->data, matchlen)) {
  317. rcu_assign_pointer(im_node->child[0], node);
  318. rcu_assign_pointer(im_node->child[1], new_node);
  319. } else {
  320. rcu_assign_pointer(im_node->child[0], new_node);
  321. rcu_assign_pointer(im_node->child[1], node);
  322. }
  323. /* Finally, assign the intermediate node to the determined spot */
  324. rcu_assign_pointer(*slot, im_node);
  325. out:
  326. if (ret) {
  327. if (new_node)
  328. trie->n_entries--;
  329. kfree(new_node);
  330. kfree(im_node);
  331. }
  332. raw_spin_unlock_irqrestore(&trie->lock, irq_flags);
  333. return ret;
  334. }
  335. static int trie_delete_elem(struct bpf_map *map, void *key)
  336. {
  337. /* TODO */
  338. return -ENOSYS;
  339. }
  340. #define LPM_DATA_SIZE_MAX 256
  341. #define LPM_DATA_SIZE_MIN 1
  342. #define LPM_VAL_SIZE_MAX (KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
  343. sizeof(struct lpm_trie_node))
  344. #define LPM_VAL_SIZE_MIN 1
  345. #define LPM_KEY_SIZE(X) (sizeof(struct bpf_lpm_trie_key) + (X))
  346. #define LPM_KEY_SIZE_MAX LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
  347. #define LPM_KEY_SIZE_MIN LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
  348. static struct bpf_map *trie_alloc(union bpf_attr *attr)
  349. {
  350. struct lpm_trie *trie;
  351. u64 cost = sizeof(*trie), cost_per_node;
  352. int ret;
  353. if (!capable(CAP_SYS_ADMIN))
  354. return ERR_PTR(-EPERM);
  355. /* check sanity of attributes */
  356. if (attr->max_entries == 0 ||
  357. attr->map_flags != BPF_F_NO_PREALLOC ||
  358. attr->key_size < LPM_KEY_SIZE_MIN ||
  359. attr->key_size > LPM_KEY_SIZE_MAX ||
  360. attr->value_size < LPM_VAL_SIZE_MIN ||
  361. attr->value_size > LPM_VAL_SIZE_MAX)
  362. return ERR_PTR(-EINVAL);
  363. trie = kzalloc(sizeof(*trie), GFP_USER | __GFP_NOWARN);
  364. if (!trie)
  365. return ERR_PTR(-ENOMEM);
  366. /* copy mandatory map attributes */
  367. trie->map.map_type = attr->map_type;
  368. trie->map.key_size = attr->key_size;
  369. trie->map.value_size = attr->value_size;
  370. trie->map.max_entries = attr->max_entries;
  371. trie->data_size = attr->key_size -
  372. offsetof(struct bpf_lpm_trie_key, data);
  373. trie->max_prefixlen = trie->data_size * 8;
  374. cost_per_node = sizeof(struct lpm_trie_node) +
  375. attr->value_size + trie->data_size;
  376. cost += (u64) attr->max_entries * cost_per_node;
  377. if (cost >= U32_MAX - PAGE_SIZE) {
  378. ret = -E2BIG;
  379. goto out_err;
  380. }
  381. trie->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  382. ret = bpf_map_precharge_memlock(trie->map.pages);
  383. if (ret)
  384. goto out_err;
  385. raw_spin_lock_init(&trie->lock);
  386. return &trie->map;
  387. out_err:
  388. kfree(trie);
  389. return ERR_PTR(ret);
  390. }
  391. static void trie_free(struct bpf_map *map)
  392. {
  393. struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
  394. struct lpm_trie_node __rcu **slot;
  395. struct lpm_trie_node *node;
  396. raw_spin_lock(&trie->lock);
  397. /* Always start at the root and walk down to a node that has no
  398. * children. Then free that node, nullify its reference in the parent
  399. * and start over.
  400. */
  401. for (;;) {
  402. slot = &trie->root;
  403. for (;;) {
  404. node = rcu_dereference_protected(*slot,
  405. lockdep_is_held(&trie->lock));
  406. if (!node)
  407. goto unlock;
  408. if (rcu_access_pointer(node->child[0])) {
  409. slot = &node->child[0];
  410. continue;
  411. }
  412. if (rcu_access_pointer(node->child[1])) {
  413. slot = &node->child[1];
  414. continue;
  415. }
  416. kfree(node);
  417. RCU_INIT_POINTER(*slot, NULL);
  418. break;
  419. }
  420. }
  421. unlock:
  422. raw_spin_unlock(&trie->lock);
  423. }
  424. static int trie_get_next_key(struct bpf_map *map, void *key, void *next_key)
  425. {
  426. return -ENOTSUPP;
  427. }
  428. const struct bpf_map_ops trie_map_ops = {
  429. .map_alloc = trie_alloc,
  430. .map_free = trie_free,
  431. .map_get_next_key = trie_get_next_key,
  432. .map_lookup_elem = trie_lookup_elem,
  433. .map_update_elem = trie_update_elem,
  434. .map_delete_elem = trie_delete_elem,
  435. };