libnvdimm, pfn: fix start_pad handling for aligned namespaces
[linux-2.6/btrfs-unstable.git] / kernel / bpf / lpm_trie.c
blob885e45479680508a11681290c0a52bc25c849c3b
1 /*
2 * Longest prefix match list implementation
4 * Copyright (c) 2016,2017 Daniel Mack
5 * Copyright (c) 2016 David Herrmann
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.
12 #include <linux/bpf.h>
13 #include <linux/err.h>
14 #include <linux/slab.h>
15 #include <linux/spinlock.h>
16 #include <linux/vmalloc.h>
17 #include <net/ipv6.h>
19 /* Intermediate node */
20 #define LPM_TREE_NODE_FLAG_IM BIT(0)
22 struct lpm_trie_node;
24 struct lpm_trie_node {
25 struct rcu_head rcu;
26 struct lpm_trie_node __rcu *child[2];
27 u32 prefixlen;
28 u32 flags;
29 u8 data[0];
32 struct lpm_trie {
33 struct bpf_map map;
34 struct lpm_trie_node __rcu *root;
35 size_t n_entries;
36 size_t max_prefixlen;
37 size_t data_size;
38 raw_spinlock_t lock;
41 /* This trie implements a longest prefix match algorithm that can be used to
42 * match IP addresses to a stored set of ranges.
44 * Data stored in @data of struct bpf_lpm_key and struct lpm_trie_node is
45 * interpreted as big endian, so data[0] stores the most significant byte.
47 * Match ranges are internally stored in instances of struct lpm_trie_node
48 * which each contain their prefix length as well as two pointers that may
49 * lead to more nodes containing more specific matches. Each node also stores
50 * a value that is defined by and returned to userspace via the update_elem
51 * and lookup functions.
53 * For instance, let's start with a trie that was created with a prefix length
54 * of 32, so it can be used for IPv4 addresses, and one single element that
55 * matches 192.168.0.0/16. The data array would hence contain
56 * [0xc0, 0xa8, 0x00, 0x00] in big-endian notation. This documentation will
57 * stick to IP-address notation for readability though.
59 * As the trie is empty initially, the new node (1) will be places as root
60 * node, denoted as (R) in the example below. As there are no other node, both
61 * child pointers are %NULL.
63 * +----------------+
64 * | (1) (R) |
65 * | 192.168.0.0/16 |
66 * | value: 1 |
67 * | [0] [1] |
68 * +----------------+
70 * Next, let's add a new node (2) matching 192.168.0.0/24. As there is already
71 * a node with the same data and a smaller prefix (ie, a less specific one),
72 * node (2) will become a child of (1). In child index depends on the next bit
73 * that is outside of what (1) matches, and that bit is 0, so (2) will be
74 * child[0] of (1):
76 * +----------------+
77 * | (1) (R) |
78 * | 192.168.0.0/16 |
79 * | value: 1 |
80 * | [0] [1] |
81 * +----------------+
82 * |
83 * +----------------+
84 * | (2) |
85 * | 192.168.0.0/24 |
86 * | value: 2 |
87 * | [0] [1] |
88 * +----------------+
90 * The child[1] slot of (1) could be filled with another node which has bit #17
91 * (the next bit after the ones that (1) matches on) set to 1. For instance,
92 * 192.168.128.0/24:
94 * +----------------+
95 * | (1) (R) |
96 * | 192.168.0.0/16 |
97 * | value: 1 |
98 * | [0] [1] |
99 * +----------------+
100 * | |
101 * +----------------+ +------------------+
102 * | (2) | | (3) |
103 * | 192.168.0.0/24 | | 192.168.128.0/24 |
104 * | value: 2 | | value: 3 |
105 * | [0] [1] | | [0] [1] |
106 * +----------------+ +------------------+
108 * Let's add another node (4) to the game for 192.168.1.0/24. In order to place
109 * it, node (1) is looked at first, and because (4) of the semantics laid out
110 * above (bit #17 is 0), it would normally be attached to (1) as child[0].
111 * However, that slot is already allocated, so a new node is needed in between.
112 * That node does not have a value attached to it and it will never be
113 * returned to users as result of a lookup. It is only there to differentiate
114 * the traversal further. It will get a prefix as wide as necessary to
115 * distinguish its two children:
117 * +----------------+
118 * | (1) (R) |
119 * | 192.168.0.0/16 |
120 * | value: 1 |
121 * | [0] [1] |
122 * +----------------+
123 * | |
124 * +----------------+ +------------------+
125 * | (4) (I) | | (3) |
126 * | 192.168.0.0/23 | | 192.168.128.0/24 |
127 * | value: --- | | value: 3 |
128 * | [0] [1] | | [0] [1] |
129 * +----------------+ +------------------+
130 * | |
131 * +----------------+ +----------------+
132 * | (2) | | (5) |
133 * | 192.168.0.0/24 | | 192.168.1.0/24 |
134 * | value: 2 | | value: 5 |
135 * | [0] [1] | | [0] [1] |
136 * +----------------+ +----------------+
138 * 192.168.1.1/32 would be a child of (5) etc.
140 * An intermediate node will be turned into a 'real' node on demand. In the
141 * example above, (4) would be re-used if 192.168.0.0/23 is added to the trie.
143 * A fully populated trie would have a height of 32 nodes, as the trie was
144 * created with a prefix length of 32.
146 * The lookup starts at the root node. If the current node matches and if there
147 * is a child that can be used to become more specific, the trie is traversed
148 * downwards. The last node in the traversal that is a non-intermediate one is
149 * returned.
152 static inline int extract_bit(const u8 *data, size_t index)
154 return !!(data[index / 8] & (1 << (7 - (index % 8))));
158 * longest_prefix_match() - determine the longest prefix
159 * @trie: The trie to get internal sizes from
160 * @node: The node to operate on
161 * @key: The key to compare to @node
163 * Determine the longest prefix of @node that matches the bits in @key.
165 static size_t longest_prefix_match(const struct lpm_trie *trie,
166 const struct lpm_trie_node *node,
167 const struct bpf_lpm_trie_key *key)
169 size_t prefixlen = 0;
170 size_t i;
172 for (i = 0; i < trie->data_size; i++) {
173 size_t b;
175 b = 8 - fls(node->data[i] ^ key->data[i]);
176 prefixlen += b;
178 if (prefixlen >= node->prefixlen || prefixlen >= key->prefixlen)
179 return min(node->prefixlen, key->prefixlen);
181 if (b < 8)
182 break;
185 return prefixlen;
188 /* Called from syscall or from eBPF program */
189 static void *trie_lookup_elem(struct bpf_map *map, void *_key)
191 struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
192 struct lpm_trie_node *node, *found = NULL;
193 struct bpf_lpm_trie_key *key = _key;
195 /* Start walking the trie from the root node ... */
197 for (node = rcu_dereference(trie->root); node;) {
198 unsigned int next_bit;
199 size_t matchlen;
201 /* Determine the longest prefix of @node that matches @key.
202 * If it's the maximum possible prefix for this trie, we have
203 * an exact match and can return it directly.
205 matchlen = longest_prefix_match(trie, node, key);
206 if (matchlen == trie->max_prefixlen) {
207 found = node;
208 break;
211 /* If the number of bits that match is smaller than the prefix
212 * length of @node, bail out and return the node we have seen
213 * last in the traversal (ie, the parent).
215 if (matchlen < node->prefixlen)
216 break;
218 /* Consider this node as return candidate unless it is an
219 * artificially added intermediate one.
221 if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
222 found = node;
224 /* If the node match is fully satisfied, let's see if we can
225 * become more specific. Determine the next bit in the key and
226 * traverse down.
228 next_bit = extract_bit(key->data, node->prefixlen);
229 node = rcu_dereference(node->child[next_bit]);
232 if (!found)
233 return NULL;
235 return found->data + trie->data_size;
238 static struct lpm_trie_node *lpm_trie_node_alloc(const struct lpm_trie *trie,
239 const void *value)
241 struct lpm_trie_node *node;
242 size_t size = sizeof(struct lpm_trie_node) + trie->data_size;
244 if (value)
245 size += trie->map.value_size;
247 node = kmalloc_node(size, GFP_ATOMIC | __GFP_NOWARN,
248 trie->map.numa_node);
249 if (!node)
250 return NULL;
252 node->flags = 0;
254 if (value)
255 memcpy(node->data + trie->data_size, value,
256 trie->map.value_size);
258 return node;
261 /* Called from syscall or from eBPF program */
262 static int trie_update_elem(struct bpf_map *map,
263 void *_key, void *value, u64 flags)
265 struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
266 struct lpm_trie_node *node, *im_node = NULL, *new_node = NULL;
267 struct lpm_trie_node __rcu **slot;
268 struct bpf_lpm_trie_key *key = _key;
269 unsigned long irq_flags;
270 unsigned int next_bit;
271 size_t matchlen = 0;
272 int ret = 0;
274 if (unlikely(flags > BPF_EXIST))
275 return -EINVAL;
277 if (key->prefixlen > trie->max_prefixlen)
278 return -EINVAL;
280 raw_spin_lock_irqsave(&trie->lock, irq_flags);
282 /* Allocate and fill a new node */
284 if (trie->n_entries == trie->map.max_entries) {
285 ret = -ENOSPC;
286 goto out;
289 new_node = lpm_trie_node_alloc(trie, value);
290 if (!new_node) {
291 ret = -ENOMEM;
292 goto out;
295 trie->n_entries++;
297 new_node->prefixlen = key->prefixlen;
298 RCU_INIT_POINTER(new_node->child[0], NULL);
299 RCU_INIT_POINTER(new_node->child[1], NULL);
300 memcpy(new_node->data, key->data, trie->data_size);
302 /* Now find a slot to attach the new node. To do that, walk the tree
303 * from the root and match as many bits as possible for each node until
304 * we either find an empty slot or a slot that needs to be replaced by
305 * an intermediate node.
307 slot = &trie->root;
309 while ((node = rcu_dereference_protected(*slot,
310 lockdep_is_held(&trie->lock)))) {
311 matchlen = longest_prefix_match(trie, node, key);
313 if (node->prefixlen != matchlen ||
314 node->prefixlen == key->prefixlen ||
315 node->prefixlen == trie->max_prefixlen)
316 break;
318 next_bit = extract_bit(key->data, node->prefixlen);
319 slot = &node->child[next_bit];
322 /* If the slot is empty (a free child pointer or an empty root),
323 * simply assign the @new_node to that slot and be done.
325 if (!node) {
326 rcu_assign_pointer(*slot, new_node);
327 goto out;
330 /* If the slot we picked already exists, replace it with @new_node
331 * which already has the correct data array set.
333 if (node->prefixlen == matchlen) {
334 new_node->child[0] = node->child[0];
335 new_node->child[1] = node->child[1];
337 if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
338 trie->n_entries--;
340 rcu_assign_pointer(*slot, new_node);
341 kfree_rcu(node, rcu);
343 goto out;
346 /* If the new node matches the prefix completely, it must be inserted
347 * as an ancestor. Simply insert it between @node and *@slot.
349 if (matchlen == key->prefixlen) {
350 next_bit = extract_bit(node->data, matchlen);
351 rcu_assign_pointer(new_node->child[next_bit], node);
352 rcu_assign_pointer(*slot, new_node);
353 goto out;
356 im_node = lpm_trie_node_alloc(trie, NULL);
357 if (!im_node) {
358 ret = -ENOMEM;
359 goto out;
362 im_node->prefixlen = matchlen;
363 im_node->flags |= LPM_TREE_NODE_FLAG_IM;
364 memcpy(im_node->data, node->data, trie->data_size);
366 /* Now determine which child to install in which slot */
367 if (extract_bit(key->data, matchlen)) {
368 rcu_assign_pointer(im_node->child[0], node);
369 rcu_assign_pointer(im_node->child[1], new_node);
370 } else {
371 rcu_assign_pointer(im_node->child[0], new_node);
372 rcu_assign_pointer(im_node->child[1], node);
375 /* Finally, assign the intermediate node to the determined spot */
376 rcu_assign_pointer(*slot, im_node);
378 out:
379 if (ret) {
380 if (new_node)
381 trie->n_entries--;
383 kfree(new_node);
384 kfree(im_node);
387 raw_spin_unlock_irqrestore(&trie->lock, irq_flags);
389 return ret;
392 /* Called from syscall or from eBPF program */
393 static int trie_delete_elem(struct bpf_map *map, void *_key)
395 struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
396 struct bpf_lpm_trie_key *key = _key;
397 struct lpm_trie_node __rcu **trim, **trim2;
398 struct lpm_trie_node *node, *parent;
399 unsigned long irq_flags;
400 unsigned int next_bit;
401 size_t matchlen = 0;
402 int ret = 0;
404 if (key->prefixlen > trie->max_prefixlen)
405 return -EINVAL;
407 raw_spin_lock_irqsave(&trie->lock, irq_flags);
409 /* Walk the tree looking for an exact key/length match and keeping
410 * track of the path we traverse. We will need to know the node
411 * we wish to delete, and the slot that points to the node we want
412 * to delete. We may also need to know the nodes parent and the
413 * slot that contains it.
415 trim = &trie->root;
416 trim2 = trim;
417 parent = NULL;
418 while ((node = rcu_dereference_protected(
419 *trim, lockdep_is_held(&trie->lock)))) {
420 matchlen = longest_prefix_match(trie, node, key);
422 if (node->prefixlen != matchlen ||
423 node->prefixlen == key->prefixlen)
424 break;
426 parent = node;
427 trim2 = trim;
428 next_bit = extract_bit(key->data, node->prefixlen);
429 trim = &node->child[next_bit];
432 if (!node || node->prefixlen != key->prefixlen ||
433 (node->flags & LPM_TREE_NODE_FLAG_IM)) {
434 ret = -ENOENT;
435 goto out;
438 trie->n_entries--;
440 /* If the node we are removing has two children, simply mark it
441 * as intermediate and we are done.
443 if (rcu_access_pointer(node->child[0]) &&
444 rcu_access_pointer(node->child[1])) {
445 node->flags |= LPM_TREE_NODE_FLAG_IM;
446 goto out;
449 /* If the parent of the node we are about to delete is an intermediate
450 * node, and the deleted node doesn't have any children, we can delete
451 * the intermediate parent as well and promote its other child
452 * up the tree. Doing this maintains the invariant that all
453 * intermediate nodes have exactly 2 children and that there are no
454 * unnecessary intermediate nodes in the tree.
456 if (parent && (parent->flags & LPM_TREE_NODE_FLAG_IM) &&
457 !node->child[0] && !node->child[1]) {
458 if (node == rcu_access_pointer(parent->child[0]))
459 rcu_assign_pointer(
460 *trim2, rcu_access_pointer(parent->child[1]));
461 else
462 rcu_assign_pointer(
463 *trim2, rcu_access_pointer(parent->child[0]));
464 kfree_rcu(parent, rcu);
465 kfree_rcu(node, rcu);
466 goto out;
469 /* The node we are removing has either zero or one child. If there
470 * is a child, move it into the removed node's slot then delete
471 * the node. Otherwise just clear the slot and delete the node.
473 if (node->child[0])
474 rcu_assign_pointer(*trim, rcu_access_pointer(node->child[0]));
475 else if (node->child[1])
476 rcu_assign_pointer(*trim, rcu_access_pointer(node->child[1]));
477 else
478 RCU_INIT_POINTER(*trim, NULL);
479 kfree_rcu(node, rcu);
481 out:
482 raw_spin_unlock_irqrestore(&trie->lock, irq_flags);
484 return ret;
487 #define LPM_DATA_SIZE_MAX 256
488 #define LPM_DATA_SIZE_MIN 1
490 #define LPM_VAL_SIZE_MAX (KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
491 sizeof(struct lpm_trie_node))
492 #define LPM_VAL_SIZE_MIN 1
494 #define LPM_KEY_SIZE(X) (sizeof(struct bpf_lpm_trie_key) + (X))
495 #define LPM_KEY_SIZE_MAX LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
496 #define LPM_KEY_SIZE_MIN LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
498 #define LPM_CREATE_FLAG_MASK (BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE | \
499 BPF_F_RDONLY | BPF_F_WRONLY)
501 static struct bpf_map *trie_alloc(union bpf_attr *attr)
503 struct lpm_trie *trie;
504 u64 cost = sizeof(*trie), cost_per_node;
505 int ret;
507 if (!capable(CAP_SYS_ADMIN))
508 return ERR_PTR(-EPERM);
510 /* check sanity of attributes */
511 if (attr->max_entries == 0 ||
512 !(attr->map_flags & BPF_F_NO_PREALLOC) ||
513 attr->map_flags & ~LPM_CREATE_FLAG_MASK ||
514 attr->key_size < LPM_KEY_SIZE_MIN ||
515 attr->key_size > LPM_KEY_SIZE_MAX ||
516 attr->value_size < LPM_VAL_SIZE_MIN ||
517 attr->value_size > LPM_VAL_SIZE_MAX)
518 return ERR_PTR(-EINVAL);
520 trie = kzalloc(sizeof(*trie), GFP_USER | __GFP_NOWARN);
521 if (!trie)
522 return ERR_PTR(-ENOMEM);
524 /* copy mandatory map attributes */
525 trie->map.map_type = attr->map_type;
526 trie->map.key_size = attr->key_size;
527 trie->map.value_size = attr->value_size;
528 trie->map.max_entries = attr->max_entries;
529 trie->map.map_flags = attr->map_flags;
530 trie->map.numa_node = bpf_map_attr_numa_node(attr);
531 trie->data_size = attr->key_size -
532 offsetof(struct bpf_lpm_trie_key, data);
533 trie->max_prefixlen = trie->data_size * 8;
535 cost_per_node = sizeof(struct lpm_trie_node) +
536 attr->value_size + trie->data_size;
537 cost += (u64) attr->max_entries * cost_per_node;
538 if (cost >= U32_MAX - PAGE_SIZE) {
539 ret = -E2BIG;
540 goto out_err;
543 trie->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
545 ret = bpf_map_precharge_memlock(trie->map.pages);
546 if (ret)
547 goto out_err;
549 raw_spin_lock_init(&trie->lock);
551 return &trie->map;
552 out_err:
553 kfree(trie);
554 return ERR_PTR(ret);
557 static void trie_free(struct bpf_map *map)
559 struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
560 struct lpm_trie_node __rcu **slot;
561 struct lpm_trie_node *node;
563 raw_spin_lock(&trie->lock);
565 /* Always start at the root and walk down to a node that has no
566 * children. Then free that node, nullify its reference in the parent
567 * and start over.
570 for (;;) {
571 slot = &trie->root;
573 for (;;) {
574 node = rcu_dereference_protected(*slot,
575 lockdep_is_held(&trie->lock));
576 if (!node)
577 goto unlock;
579 if (rcu_access_pointer(node->child[0])) {
580 slot = &node->child[0];
581 continue;
584 if (rcu_access_pointer(node->child[1])) {
585 slot = &node->child[1];
586 continue;
589 kfree(node);
590 RCU_INIT_POINTER(*slot, NULL);
591 break;
595 unlock:
596 raw_spin_unlock(&trie->lock);
599 static int trie_get_next_key(struct bpf_map *map, void *key, void *next_key)
601 return -ENOTSUPP;
604 const struct bpf_map_ops trie_map_ops = {
605 .map_alloc = trie_alloc,
606 .map_free = trie_free,
607 .map_get_next_key = trie_get_next_key,
608 .map_lookup_elem = trie_lookup_elem,
609 .map_update_elem = trie_update_elem,
610 .map_delete_elem = trie_delete_elem,