xref: /linux/kernel/bpf/lpm_trie.c (revision d0d106a2bd21499901299160744e5fe9f4c83ddb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Longest prefix match list implementation
4  *
5  * Copyright (c) 2016,2017 Daniel Mack
6  * Copyright (c) 2016 David Herrmann
7  */
8 
9 #include <linux/bpf.h>
10 #include <linux/btf.h>
11 #include <linux/err.h>
12 #include <linux/slab.h>
13 #include <linux/spinlock.h>
14 #include <linux/vmalloc.h>
15 #include <net/ipv6.h>
16 #include <uapi/linux/btf.h>
17 #include <linux/btf_ids.h>
18 #include <linux/bpf_mem_alloc.h>
19 
20 /* Intermediate node */
21 #define LPM_TREE_NODE_FLAG_IM BIT(0)
22 
23 struct lpm_trie_node;
24 
25 struct lpm_trie_node {
26 	struct lpm_trie_node __rcu	*child[2];
27 	u32				prefixlen;
28 	u32				flags;
29 	u8				data[];
30 };
31 
32 struct lpm_trie {
33 	struct bpf_map			map;
34 	struct lpm_trie_node __rcu	*root;
35 	struct bpf_mem_alloc		ma;
36 	size_t				n_entries;
37 	size_t				max_prefixlen;
38 	size_t				data_size;
39 	raw_spinlock_t			lock;
40 };
41 
42 /* This trie implements a longest prefix match algorithm that can be used to
43  * match IP addresses to a stored set of ranges.
44  *
45  * Data stored in @data of struct bpf_lpm_key and struct lpm_trie_node is
46  * interpreted as big endian, so data[0] stores the most significant byte.
47  *
48  * Match ranges are internally stored in instances of struct lpm_trie_node
49  * which each contain their prefix length as well as two pointers that may
50  * lead to more nodes containing more specific matches. Each node also stores
51  * a value that is defined by and returned to userspace via the update_elem
52  * and lookup functions.
53  *
54  * For instance, let's start with a trie that was created with a prefix length
55  * of 32, so it can be used for IPv4 addresses, and one single element that
56  * matches 192.168.0.0/16. The data array would hence contain
57  * [0xc0, 0xa8, 0x00, 0x00] in big-endian notation. This documentation will
58  * stick to IP-address notation for readability though.
59  *
60  * As the trie is empty initially, the new node (1) will be places as root
61  * node, denoted as (R) in the example below. As there are no other node, both
62  * child pointers are %NULL.
63  *
64  *              +----------------+
65  *              |       (1)  (R) |
66  *              | 192.168.0.0/16 |
67  *              |    value: 1    |
68  *              |   [0]    [1]   |
69  *              +----------------+
70  *
71  * Next, let's add a new node (2) matching 192.168.0.0/24. As there is already
72  * a node with the same data and a smaller prefix (ie, a less specific one),
73  * node (2) will become a child of (1). In child index depends on the next bit
74  * that is outside of what (1) matches, and that bit is 0, so (2) will be
75  * child[0] of (1):
76  *
77  *              +----------------+
78  *              |       (1)  (R) |
79  *              | 192.168.0.0/16 |
80  *              |    value: 1    |
81  *              |   [0]    [1]   |
82  *              +----------------+
83  *                   |
84  *    +----------------+
85  *    |       (2)      |
86  *    | 192.168.0.0/24 |
87  *    |    value: 2    |
88  *    |   [0]    [1]   |
89  *    +----------------+
90  *
91  * The child[1] slot of (1) could be filled with another node which has bit #17
92  * (the next bit after the ones that (1) matches on) set to 1. For instance,
93  * 192.168.128.0/24:
94  *
95  *              +----------------+
96  *              |       (1)  (R) |
97  *              | 192.168.0.0/16 |
98  *              |    value: 1    |
99  *              |   [0]    [1]   |
100  *              +----------------+
101  *                   |      |
102  *    +----------------+  +------------------+
103  *    |       (2)      |  |        (3)       |
104  *    | 192.168.0.0/24 |  | 192.168.128.0/24 |
105  *    |    value: 2    |  |     value: 3     |
106  *    |   [0]    [1]   |  |    [0]    [1]    |
107  *    +----------------+  +------------------+
108  *
109  * Let's add another node (4) to the game for 192.168.1.0/24. In order to place
110  * it, node (1) is looked at first, and because (4) of the semantics laid out
111  * above (bit #17 is 0), it would normally be attached to (1) as child[0].
112  * However, that slot is already allocated, so a new node is needed in between.
113  * That node does not have a value attached to it and it will never be
114  * returned to users as result of a lookup. It is only there to differentiate
115  * the traversal further. It will get a prefix as wide as necessary to
116  * distinguish its two children:
117  *
118  *                      +----------------+
119  *                      |       (1)  (R) |
120  *                      | 192.168.0.0/16 |
121  *                      |    value: 1    |
122  *                      |   [0]    [1]   |
123  *                      +----------------+
124  *                           |      |
125  *            +----------------+  +------------------+
126  *            |       (4)  (I) |  |        (3)       |
127  *            | 192.168.0.0/23 |  | 192.168.128.0/24 |
128  *            |    value: ---  |  |     value: 3     |
129  *            |   [0]    [1]   |  |    [0]    [1]    |
130  *            +----------------+  +------------------+
131  *                 |      |
132  *  +----------------+  +----------------+
133  *  |       (2)      |  |       (5)      |
134  *  | 192.168.0.0/24 |  | 192.168.1.0/24 |
135  *  |    value: 2    |  |     value: 5   |
136  *  |   [0]    [1]   |  |   [0]    [1]   |
137  *  +----------------+  +----------------+
138  *
139  * 192.168.1.1/32 would be a child of (5) etc.
140  *
141  * An intermediate node will be turned into a 'real' node on demand. In the
142  * example above, (4) would be re-used if 192.168.0.0/23 is added to the trie.
143  *
144  * A fully populated trie would have a height of 32 nodes, as the trie was
145  * created with a prefix length of 32.
146  *
147  * The lookup starts at the root node. If the current node matches and if there
148  * is a child that can be used to become more specific, the trie is traversed
149  * downwards. The last node in the traversal that is a non-intermediate one is
150  * returned.
151  */
152 
extract_bit(const u8 * data,size_t index)153 static inline int extract_bit(const u8 *data, size_t index)
154 {
155 	return !!(data[index / 8] & (1 << (7 - (index % 8))));
156 }
157 
158 /**
159  * __longest_prefix_match() - determine the longest prefix
160  * @trie:	The trie to get internal sizes from
161  * @node:	The node to operate on
162  * @key:	The key to compare to @node
163  *
164  * Determine the longest prefix of @node that matches the bits in @key.
165  */
166 static __always_inline
__longest_prefix_match(const struct lpm_trie * trie,const struct lpm_trie_node * node,const struct bpf_lpm_trie_key_u8 * key)167 size_t __longest_prefix_match(const struct lpm_trie *trie,
168 			      const struct lpm_trie_node *node,
169 			      const struct bpf_lpm_trie_key_u8 *key)
170 {
171 	u32 limit = min(node->prefixlen, key->prefixlen);
172 	u32 prefixlen = 0, i = 0;
173 
174 	BUILD_BUG_ON(offsetof(struct lpm_trie_node, data) % sizeof(u32));
175 	BUILD_BUG_ON(offsetof(struct bpf_lpm_trie_key_u8, data) % sizeof(u32));
176 
177 #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) && defined(CONFIG_64BIT)
178 
179 	/* data_size >= 16 has very small probability.
180 	 * We do not use a loop for optimal code generation.
181 	 */
182 	if (trie->data_size >= 8) {
183 		u64 diff = be64_to_cpu(*(__be64 *)node->data ^
184 				       *(__be64 *)key->data);
185 
186 		prefixlen = 64 - fls64(diff);
187 		if (prefixlen >= limit)
188 			return limit;
189 		if (diff)
190 			return prefixlen;
191 		i = 8;
192 	}
193 #endif
194 
195 	while (trie->data_size >= i + 4) {
196 		u32 diff = be32_to_cpu(*(__be32 *)&node->data[i] ^
197 				       *(__be32 *)&key->data[i]);
198 
199 		prefixlen += 32 - fls(diff);
200 		if (prefixlen >= limit)
201 			return limit;
202 		if (diff)
203 			return prefixlen;
204 		i += 4;
205 	}
206 
207 	if (trie->data_size >= i + 2) {
208 		u16 diff = be16_to_cpu(*(__be16 *)&node->data[i] ^
209 				       *(__be16 *)&key->data[i]);
210 
211 		prefixlen += 16 - fls(diff);
212 		if (prefixlen >= limit)
213 			return limit;
214 		if (diff)
215 			return prefixlen;
216 		i += 2;
217 	}
218 
219 	if (trie->data_size >= i + 1) {
220 		prefixlen += 8 - fls(node->data[i] ^ key->data[i]);
221 
222 		if (prefixlen >= limit)
223 			return limit;
224 	}
225 
226 	return prefixlen;
227 }
228 
longest_prefix_match(const struct lpm_trie * trie,const struct lpm_trie_node * node,const struct bpf_lpm_trie_key_u8 * key)229 static size_t longest_prefix_match(const struct lpm_trie *trie,
230 				   const struct lpm_trie_node *node,
231 				   const struct bpf_lpm_trie_key_u8 *key)
232 {
233 	return __longest_prefix_match(trie, node, key);
234 }
235 
236 /* Called from syscall or from eBPF program */
trie_lookup_elem(struct bpf_map * map,void * _key)237 static void *trie_lookup_elem(struct bpf_map *map, void *_key)
238 {
239 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
240 	struct lpm_trie_node *node, *found = NULL;
241 	struct bpf_lpm_trie_key_u8 *key = _key;
242 
243 	if (key->prefixlen > trie->max_prefixlen)
244 		return NULL;
245 
246 	/* Start walking the trie from the root node ... */
247 
248 	for (node = rcu_dereference_check(trie->root, rcu_read_lock_bh_held());
249 	     node;) {
250 		unsigned int next_bit;
251 		size_t matchlen;
252 
253 		/* Determine the longest prefix of @node that matches @key.
254 		 * If it's the maximum possible prefix for this trie, we have
255 		 * an exact match and can return it directly.
256 		 */
257 		matchlen = __longest_prefix_match(trie, node, key);
258 		if (matchlen == trie->max_prefixlen) {
259 			found = node;
260 			break;
261 		}
262 
263 		/* If the number of bits that match is smaller than the prefix
264 		 * length of @node, bail out and return the node we have seen
265 		 * last in the traversal (ie, the parent).
266 		 */
267 		if (matchlen < node->prefixlen)
268 			break;
269 
270 		/* Consider this node as return candidate unless it is an
271 		 * artificially added intermediate one.
272 		 */
273 		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
274 			found = node;
275 
276 		/* If the node match is fully satisfied, let's see if we can
277 		 * become more specific. Determine the next bit in the key and
278 		 * traverse down.
279 		 */
280 		next_bit = extract_bit(key->data, node->prefixlen);
281 		node = rcu_dereference_check(node->child[next_bit],
282 					     rcu_read_lock_bh_held());
283 	}
284 
285 	if (!found)
286 		return NULL;
287 
288 	return found->data + trie->data_size;
289 }
290 
lpm_trie_node_alloc(struct lpm_trie * trie,const void * value)291 static struct lpm_trie_node *lpm_trie_node_alloc(struct lpm_trie *trie,
292 						 const void *value)
293 {
294 	struct lpm_trie_node *node;
295 
296 	node = bpf_mem_cache_alloc(&trie->ma);
297 
298 	if (!node)
299 		return NULL;
300 
301 	node->flags = 0;
302 
303 	if (value)
304 		memcpy(node->data + trie->data_size, value,
305 		       trie->map.value_size);
306 
307 	return node;
308 }
309 
trie_check_add_elem(struct lpm_trie * trie,u64 flags)310 static int trie_check_add_elem(struct lpm_trie *trie, u64 flags)
311 {
312 	if (flags == BPF_EXIST)
313 		return -ENOENT;
314 	if (trie->n_entries == trie->map.max_entries)
315 		return -ENOSPC;
316 	trie->n_entries++;
317 	return 0;
318 }
319 
320 /* Called from syscall or from eBPF program */
trie_update_elem(struct bpf_map * map,void * _key,void * value,u64 flags)321 static long trie_update_elem(struct bpf_map *map,
322 			     void *_key, void *value, u64 flags)
323 {
324 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
325 	struct lpm_trie_node *node, *im_node, *new_node;
326 	struct lpm_trie_node *free_node = NULL;
327 	struct lpm_trie_node __rcu **slot;
328 	struct bpf_lpm_trie_key_u8 *key = _key;
329 	unsigned long irq_flags;
330 	unsigned int next_bit;
331 	size_t matchlen = 0;
332 	int ret = 0;
333 
334 	if (unlikely(flags > BPF_EXIST))
335 		return -EINVAL;
336 
337 	if (key->prefixlen > trie->max_prefixlen)
338 		return -EINVAL;
339 
340 	/* Allocate and fill a new node */
341 	new_node = lpm_trie_node_alloc(trie, value);
342 	if (!new_node)
343 		return -ENOMEM;
344 
345 	raw_spin_lock_irqsave(&trie->lock, irq_flags);
346 
347 	new_node->prefixlen = key->prefixlen;
348 	RCU_INIT_POINTER(new_node->child[0], NULL);
349 	RCU_INIT_POINTER(new_node->child[1], NULL);
350 	memcpy(new_node->data, key->data, trie->data_size);
351 
352 	/* Now find a slot to attach the new node. To do that, walk the tree
353 	 * from the root and match as many bits as possible for each node until
354 	 * we either find an empty slot or a slot that needs to be replaced by
355 	 * an intermediate node.
356 	 */
357 	slot = &trie->root;
358 
359 	while ((node = rcu_dereference_protected(*slot,
360 					lockdep_is_held(&trie->lock)))) {
361 		matchlen = longest_prefix_match(trie, node, key);
362 
363 		if (node->prefixlen != matchlen ||
364 		    node->prefixlen == key->prefixlen)
365 			break;
366 
367 		next_bit = extract_bit(key->data, node->prefixlen);
368 		slot = &node->child[next_bit];
369 	}
370 
371 	/* If the slot is empty (a free child pointer or an empty root),
372 	 * simply assign the @new_node to that slot and be done.
373 	 */
374 	if (!node) {
375 		ret = trie_check_add_elem(trie, flags);
376 		if (ret)
377 			goto out;
378 
379 		rcu_assign_pointer(*slot, new_node);
380 		goto out;
381 	}
382 
383 	/* If the slot we picked already exists, replace it with @new_node
384 	 * which already has the correct data array set.
385 	 */
386 	if (node->prefixlen == matchlen) {
387 		if (!(node->flags & LPM_TREE_NODE_FLAG_IM)) {
388 			if (flags == BPF_NOEXIST) {
389 				ret = -EEXIST;
390 				goto out;
391 			}
392 		} else {
393 			ret = trie_check_add_elem(trie, flags);
394 			if (ret)
395 				goto out;
396 		}
397 
398 		new_node->child[0] = node->child[0];
399 		new_node->child[1] = node->child[1];
400 
401 		rcu_assign_pointer(*slot, new_node);
402 		free_node = node;
403 
404 		goto out;
405 	}
406 
407 	ret = trie_check_add_elem(trie, flags);
408 	if (ret)
409 		goto out;
410 
411 	/* If the new node matches the prefix completely, it must be inserted
412 	 * as an ancestor. Simply insert it between @node and *@slot.
413 	 */
414 	if (matchlen == key->prefixlen) {
415 		next_bit = extract_bit(node->data, matchlen);
416 		rcu_assign_pointer(new_node->child[next_bit], node);
417 		rcu_assign_pointer(*slot, new_node);
418 		goto out;
419 	}
420 
421 	im_node = lpm_trie_node_alloc(trie, NULL);
422 	if (!im_node) {
423 		trie->n_entries--;
424 		ret = -ENOMEM;
425 		goto out;
426 	}
427 
428 	im_node->prefixlen = matchlen;
429 	im_node->flags |= LPM_TREE_NODE_FLAG_IM;
430 	memcpy(im_node->data, node->data, trie->data_size);
431 
432 	/* Now determine which child to install in which slot */
433 	if (extract_bit(key->data, matchlen)) {
434 		rcu_assign_pointer(im_node->child[0], node);
435 		rcu_assign_pointer(im_node->child[1], new_node);
436 	} else {
437 		rcu_assign_pointer(im_node->child[0], new_node);
438 		rcu_assign_pointer(im_node->child[1], node);
439 	}
440 
441 	/* Finally, assign the intermediate node to the determined slot */
442 	rcu_assign_pointer(*slot, im_node);
443 
444 out:
445 	raw_spin_unlock_irqrestore(&trie->lock, irq_flags);
446 
447 	if (ret)
448 		bpf_mem_cache_free(&trie->ma, new_node);
449 	bpf_mem_cache_free_rcu(&trie->ma, free_node);
450 
451 	return ret;
452 }
453 
454 /* Called from syscall or from eBPF program */
trie_delete_elem(struct bpf_map * map,void * _key)455 static long trie_delete_elem(struct bpf_map *map, void *_key)
456 {
457 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
458 	struct lpm_trie_node *free_node = NULL, *free_parent = NULL;
459 	struct bpf_lpm_trie_key_u8 *key = _key;
460 	struct lpm_trie_node __rcu **trim, **trim2;
461 	struct lpm_trie_node *node, *parent;
462 	unsigned long irq_flags;
463 	unsigned int next_bit;
464 	size_t matchlen = 0;
465 	int ret = 0;
466 
467 	if (key->prefixlen > trie->max_prefixlen)
468 		return -EINVAL;
469 
470 	raw_spin_lock_irqsave(&trie->lock, irq_flags);
471 
472 	/* Walk the tree looking for an exact key/length match and keeping
473 	 * track of the path we traverse.  We will need to know the node
474 	 * we wish to delete, and the slot that points to the node we want
475 	 * to delete.  We may also need to know the nodes parent and the
476 	 * slot that contains it.
477 	 */
478 	trim = &trie->root;
479 	trim2 = trim;
480 	parent = NULL;
481 	while ((node = rcu_dereference_protected(
482 		       *trim, lockdep_is_held(&trie->lock)))) {
483 		matchlen = longest_prefix_match(trie, node, key);
484 
485 		if (node->prefixlen != matchlen ||
486 		    node->prefixlen == key->prefixlen)
487 			break;
488 
489 		parent = node;
490 		trim2 = trim;
491 		next_bit = extract_bit(key->data, node->prefixlen);
492 		trim = &node->child[next_bit];
493 	}
494 
495 	if (!node || node->prefixlen != key->prefixlen ||
496 	    node->prefixlen != matchlen ||
497 	    (node->flags & LPM_TREE_NODE_FLAG_IM)) {
498 		ret = -ENOENT;
499 		goto out;
500 	}
501 
502 	trie->n_entries--;
503 
504 	/* If the node we are removing has two children, simply mark it
505 	 * as intermediate and we are done.
506 	 */
507 	if (rcu_access_pointer(node->child[0]) &&
508 	    rcu_access_pointer(node->child[1])) {
509 		node->flags |= LPM_TREE_NODE_FLAG_IM;
510 		goto out;
511 	}
512 
513 	/* If the parent of the node we are about to delete is an intermediate
514 	 * node, and the deleted node doesn't have any children, we can delete
515 	 * the intermediate parent as well and promote its other child
516 	 * up the tree.  Doing this maintains the invariant that all
517 	 * intermediate nodes have exactly 2 children and that there are no
518 	 * unnecessary intermediate nodes in the tree.
519 	 */
520 	if (parent && (parent->flags & LPM_TREE_NODE_FLAG_IM) &&
521 	    !node->child[0] && !node->child[1]) {
522 		if (node == rcu_access_pointer(parent->child[0]))
523 			rcu_assign_pointer(
524 				*trim2, rcu_access_pointer(parent->child[1]));
525 		else
526 			rcu_assign_pointer(
527 				*trim2, rcu_access_pointer(parent->child[0]));
528 		free_parent = parent;
529 		free_node = node;
530 		goto out;
531 	}
532 
533 	/* The node we are removing has either zero or one child. If there
534 	 * is a child, move it into the removed node's slot then delete
535 	 * the node.  Otherwise just clear the slot and delete the node.
536 	 */
537 	if (node->child[0])
538 		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[0]));
539 	else if (node->child[1])
540 		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[1]));
541 	else
542 		RCU_INIT_POINTER(*trim, NULL);
543 	free_node = node;
544 
545 out:
546 	raw_spin_unlock_irqrestore(&trie->lock, irq_flags);
547 
548 	bpf_mem_cache_free_rcu(&trie->ma, free_parent);
549 	bpf_mem_cache_free_rcu(&trie->ma, free_node);
550 
551 	return ret;
552 }
553 
554 #define LPM_DATA_SIZE_MAX	256
555 #define LPM_DATA_SIZE_MIN	1
556 
557 #define LPM_VAL_SIZE_MAX	(KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
558 				 sizeof(struct lpm_trie_node))
559 #define LPM_VAL_SIZE_MIN	1
560 
561 #define LPM_KEY_SIZE(X)		(sizeof(struct bpf_lpm_trie_key_u8) + (X))
562 #define LPM_KEY_SIZE_MAX	LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
563 #define LPM_KEY_SIZE_MIN	LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
564 
565 #define LPM_CREATE_FLAG_MASK	(BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE |	\
566 				 BPF_F_ACCESS_MASK)
567 
trie_alloc(union bpf_attr * attr)568 static struct bpf_map *trie_alloc(union bpf_attr *attr)
569 {
570 	struct lpm_trie *trie;
571 	size_t leaf_size;
572 	int err;
573 
574 	/* check sanity of attributes */
575 	if (attr->max_entries == 0 ||
576 	    !(attr->map_flags & BPF_F_NO_PREALLOC) ||
577 	    attr->map_flags & ~LPM_CREATE_FLAG_MASK ||
578 	    !bpf_map_flags_access_ok(attr->map_flags) ||
579 	    attr->key_size < LPM_KEY_SIZE_MIN ||
580 	    attr->key_size > LPM_KEY_SIZE_MAX ||
581 	    attr->value_size < LPM_VAL_SIZE_MIN ||
582 	    attr->value_size > LPM_VAL_SIZE_MAX)
583 		return ERR_PTR(-EINVAL);
584 
585 	trie = bpf_map_area_alloc(sizeof(*trie), NUMA_NO_NODE);
586 	if (!trie)
587 		return ERR_PTR(-ENOMEM);
588 
589 	/* copy mandatory map attributes */
590 	bpf_map_init_from_attr(&trie->map, attr);
591 	trie->data_size = attr->key_size -
592 			  offsetof(struct bpf_lpm_trie_key_u8, data);
593 	trie->max_prefixlen = trie->data_size * 8;
594 
595 	raw_spin_lock_init(&trie->lock);
596 
597 	/* Allocate intermediate and leaf nodes from the same allocator */
598 	leaf_size = sizeof(struct lpm_trie_node) + trie->data_size +
599 		    trie->map.value_size;
600 	err = bpf_mem_alloc_init(&trie->ma, leaf_size, false);
601 	if (err)
602 		goto free_out;
603 	return &trie->map;
604 
605 free_out:
606 	bpf_map_area_free(trie);
607 	return ERR_PTR(err);
608 }
609 
trie_free(struct bpf_map * map)610 static void trie_free(struct bpf_map *map)
611 {
612 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
613 	struct lpm_trie_node __rcu **slot;
614 	struct lpm_trie_node *node;
615 
616 	/* Always start at the root and walk down to a node that has no
617 	 * children. Then free that node, nullify its reference in the parent
618 	 * and start over.
619 	 */
620 
621 	for (;;) {
622 		slot = &trie->root;
623 
624 		for (;;) {
625 			node = rcu_dereference_protected(*slot, 1);
626 			if (!node)
627 				goto out;
628 
629 			if (rcu_access_pointer(node->child[0])) {
630 				slot = &node->child[0];
631 				continue;
632 			}
633 
634 			if (rcu_access_pointer(node->child[1])) {
635 				slot = &node->child[1];
636 				continue;
637 			}
638 
639 			/* No bpf program may access the map, so freeing the
640 			 * node without waiting for the extra RCU GP.
641 			 */
642 			bpf_mem_cache_raw_free(node);
643 			RCU_INIT_POINTER(*slot, NULL);
644 			break;
645 		}
646 	}
647 
648 out:
649 	bpf_mem_alloc_destroy(&trie->ma);
650 	bpf_map_area_free(trie);
651 }
652 
trie_get_next_key(struct bpf_map * map,void * _key,void * _next_key)653 static int trie_get_next_key(struct bpf_map *map, void *_key, void *_next_key)
654 {
655 	struct lpm_trie_node *node, *next_node = NULL, *parent, *search_root;
656 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
657 	struct bpf_lpm_trie_key_u8 *key = _key, *next_key = _next_key;
658 	struct lpm_trie_node **node_stack = NULL;
659 	int err = 0, stack_ptr = -1;
660 	unsigned int next_bit;
661 	size_t matchlen = 0;
662 
663 	/* The get_next_key follows postorder. For the 4 node example in
664 	 * the top of this file, the trie_get_next_key() returns the following
665 	 * one after another:
666 	 *   192.168.0.0/24
667 	 *   192.168.1.0/24
668 	 *   192.168.128.0/24
669 	 *   192.168.0.0/16
670 	 *
671 	 * The idea is to return more specific keys before less specific ones.
672 	 */
673 
674 	/* Empty trie */
675 	search_root = rcu_dereference(trie->root);
676 	if (!search_root)
677 		return -ENOENT;
678 
679 	/* For invalid key, find the leftmost node in the trie */
680 	if (!key || key->prefixlen > trie->max_prefixlen)
681 		goto find_leftmost;
682 
683 	node_stack = kmalloc_array(trie->max_prefixlen + 1,
684 				   sizeof(struct lpm_trie_node *),
685 				   GFP_ATOMIC | __GFP_NOWARN);
686 	if (!node_stack)
687 		return -ENOMEM;
688 
689 	/* Try to find the exact node for the given key */
690 	for (node = search_root; node;) {
691 		node_stack[++stack_ptr] = node;
692 		matchlen = longest_prefix_match(trie, node, key);
693 		if (node->prefixlen != matchlen ||
694 		    node->prefixlen == key->prefixlen)
695 			break;
696 
697 		next_bit = extract_bit(key->data, node->prefixlen);
698 		node = rcu_dereference(node->child[next_bit]);
699 	}
700 	if (!node || node->prefixlen != matchlen ||
701 	    (node->flags & LPM_TREE_NODE_FLAG_IM))
702 		goto find_leftmost;
703 
704 	/* The node with the exactly-matching key has been found,
705 	 * find the first node in postorder after the matched node.
706 	 */
707 	node = node_stack[stack_ptr];
708 	while (stack_ptr > 0) {
709 		parent = node_stack[stack_ptr - 1];
710 		if (rcu_dereference(parent->child[0]) == node) {
711 			search_root = rcu_dereference(parent->child[1]);
712 			if (search_root)
713 				goto find_leftmost;
714 		}
715 		if (!(parent->flags & LPM_TREE_NODE_FLAG_IM)) {
716 			next_node = parent;
717 			goto do_copy;
718 		}
719 
720 		node = parent;
721 		stack_ptr--;
722 	}
723 
724 	/* did not find anything */
725 	err = -ENOENT;
726 	goto free_stack;
727 
728 find_leftmost:
729 	/* Find the leftmost non-intermediate node, all intermediate nodes
730 	 * have exact two children, so this function will never return NULL.
731 	 */
732 	for (node = search_root; node;) {
733 		if (node->flags & LPM_TREE_NODE_FLAG_IM) {
734 			node = rcu_dereference(node->child[0]);
735 		} else {
736 			next_node = node;
737 			node = rcu_dereference(node->child[0]);
738 			if (!node)
739 				node = rcu_dereference(next_node->child[1]);
740 		}
741 	}
742 do_copy:
743 	next_key->prefixlen = next_node->prefixlen;
744 	memcpy((void *)next_key + offsetof(struct bpf_lpm_trie_key_u8, data),
745 	       next_node->data, trie->data_size);
746 free_stack:
747 	kfree(node_stack);
748 	return err;
749 }
750 
trie_check_btf(const struct bpf_map * map,const struct btf * btf,const struct btf_type * key_type,const struct btf_type * value_type)751 static int trie_check_btf(const struct bpf_map *map,
752 			  const struct btf *btf,
753 			  const struct btf_type *key_type,
754 			  const struct btf_type *value_type)
755 {
756 	/* Keys must have struct bpf_lpm_trie_key_u8 embedded. */
757 	return BTF_INFO_KIND(key_type->info) != BTF_KIND_STRUCT ?
758 	       -EINVAL : 0;
759 }
760 
trie_mem_usage(const struct bpf_map * map)761 static u64 trie_mem_usage(const struct bpf_map *map)
762 {
763 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
764 	u64 elem_size;
765 
766 	elem_size = sizeof(struct lpm_trie_node) + trie->data_size +
767 			    trie->map.value_size;
768 	return elem_size * READ_ONCE(trie->n_entries);
769 }
770 
771 BTF_ID_LIST_SINGLE(trie_map_btf_ids, struct, lpm_trie)
772 const struct bpf_map_ops trie_map_ops = {
773 	.map_meta_equal = bpf_map_meta_equal,
774 	.map_alloc = trie_alloc,
775 	.map_free = trie_free,
776 	.map_get_next_key = trie_get_next_key,
777 	.map_lookup_elem = trie_lookup_elem,
778 	.map_update_elem = trie_update_elem,
779 	.map_delete_elem = trie_delete_elem,
780 	.map_lookup_batch = generic_map_lookup_batch,
781 	.map_update_batch = generic_map_update_batch,
782 	.map_delete_batch = generic_map_delete_batch,
783 	.map_check_btf = trie_check_btf,
784 	.map_mem_usage = trie_mem_usage,
785 	.map_btf_id = &trie_map_btf_ids[0],
786 };
787