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 
19 /* Intermediate node */
20 #define LPM_TREE_NODE_FLAG_IM BIT(0)
21 
22 struct lpm_trie_node;
23 
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[];
30 };
31 
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 	spinlock_t			lock;
39 };
40 
41 /* This trie implements a longest prefix match algorithm that can be used to
42  * match IP addresses to a stored set of ranges.
43  *
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.
46  *
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.
52  *
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.
58  *
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.
62  *
63  *              +----------------+
64  *              |       (1)  (R) |
65  *              | 192.168.0.0/16 |
66  *              |    value: 1    |
67  *              |   [0]    [1]   |
68  *              +----------------+
69  *
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):
75  *
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  *    +----------------+
89  *
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:
93  *
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  *    +----------------+  +------------------+
107  *
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:
116  *
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  *  +----------------+  +----------------+
137  *
138  * 192.168.1.1/32 would be a child of (5) etc.
139  *
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.
142  *
143  * A fully populated trie would have a height of 32 nodes, as the trie was
144  * created with a prefix length of 32.
145  *
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.
150  */
151 
extract_bit(const u8 * data,size_t index)152 static inline int extract_bit(const u8 *data, size_t index)
153 {
154 	return !!(data[index / 8] & (1 << (7 - (index % 8))));
155 }
156 
157 /**
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
162  *
163  * Determine the longest prefix of @node that matches the bits in @key.
164  */
165 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)166 size_t __longest_prefix_match(const struct lpm_trie *trie,
167 			      const struct lpm_trie_node *node,
168 			      const struct bpf_lpm_trie_key_u8 *key)
169 {
170 	u32 limit = min(node->prefixlen, key->prefixlen);
171 	u32 prefixlen = 0, i = 0;
172 
173 	BUILD_BUG_ON(offsetof(struct lpm_trie_node, data) % sizeof(u32));
174 	BUILD_BUG_ON(offsetof(struct bpf_lpm_trie_key_u8, data) % sizeof(u32));
175 
176 #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) && defined(CONFIG_64BIT)
177 
178 	/* data_size >= 16 has very small probability.
179 	 * We do not use a loop for optimal code generation.
180 	 */
181 	if (trie->data_size >= 8) {
182 		u64 diff = be64_to_cpu(*(__be64 *)node->data ^
183 				       *(__be64 *)key->data);
184 
185 		prefixlen = 64 - fls64(diff);
186 		if (prefixlen >= limit)
187 			return limit;
188 		if (diff)
189 			return prefixlen;
190 		i = 8;
191 	}
192 #endif
193 
194 	while (trie->data_size >= i + 4) {
195 		u32 diff = be32_to_cpu(*(__be32 *)&node->data[i] ^
196 				       *(__be32 *)&key->data[i]);
197 
198 		prefixlen += 32 - fls(diff);
199 		if (prefixlen >= limit)
200 			return limit;
201 		if (diff)
202 			return prefixlen;
203 		i += 4;
204 	}
205 
206 	if (trie->data_size >= i + 2) {
207 		u16 diff = be16_to_cpu(*(__be16 *)&node->data[i] ^
208 				       *(__be16 *)&key->data[i]);
209 
210 		prefixlen += 16 - fls(diff);
211 		if (prefixlen >= limit)
212 			return limit;
213 		if (diff)
214 			return prefixlen;
215 		i += 2;
216 	}
217 
218 	if (trie->data_size >= i + 1) {
219 		prefixlen += 8 - fls(node->data[i] ^ key->data[i]);
220 
221 		if (prefixlen >= limit)
222 			return limit;
223 	}
224 
225 	return prefixlen;
226 }
227 
longest_prefix_match(const struct lpm_trie * trie,const struct lpm_trie_node * node,const struct bpf_lpm_trie_key_u8 * key)228 static size_t longest_prefix_match(const struct lpm_trie *trie,
229 				   const struct lpm_trie_node *node,
230 				   const struct bpf_lpm_trie_key_u8 *key)
231 {
232 	return __longest_prefix_match(trie, node, key);
233 }
234 
235 /* Called from syscall or from eBPF program */
trie_lookup_elem(struct bpf_map * map,void * _key)236 static void *trie_lookup_elem(struct bpf_map *map, void *_key)
237 {
238 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
239 	struct lpm_trie_node *node, *found = NULL;
240 	struct bpf_lpm_trie_key_u8 *key = _key;
241 
242 	if (key->prefixlen > trie->max_prefixlen)
243 		return NULL;
244 
245 	/* Start walking the trie from the root node ... */
246 
247 	for (node = rcu_dereference_check(trie->root, rcu_read_lock_bh_held());
248 	     node;) {
249 		unsigned int next_bit;
250 		size_t matchlen;
251 
252 		/* Determine the longest prefix of @node that matches @key.
253 		 * If it's the maximum possible prefix for this trie, we have
254 		 * an exact match and can return it directly.
255 		 */
256 		matchlen = __longest_prefix_match(trie, node, key);
257 		if (matchlen == trie->max_prefixlen) {
258 			found = node;
259 			break;
260 		}
261 
262 		/* If the number of bits that match is smaller than the prefix
263 		 * length of @node, bail out and return the node we have seen
264 		 * last in the traversal (ie, the parent).
265 		 */
266 		if (matchlen < node->prefixlen)
267 			break;
268 
269 		/* Consider this node as return candidate unless it is an
270 		 * artificially added intermediate one.
271 		 */
272 		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
273 			found = node;
274 
275 		/* If the node match is fully satisfied, let's see if we can
276 		 * become more specific. Determine the next bit in the key and
277 		 * traverse down.
278 		 */
279 		next_bit = extract_bit(key->data, node->prefixlen);
280 		node = rcu_dereference_check(node->child[next_bit],
281 					     rcu_read_lock_bh_held());
282 	}
283 
284 	if (!found)
285 		return NULL;
286 
287 	return found->data + trie->data_size;
288 }
289 
lpm_trie_node_alloc(const struct lpm_trie * trie,const void * value)290 static struct lpm_trie_node *lpm_trie_node_alloc(const struct lpm_trie *trie,
291 						 const void *value)
292 {
293 	struct lpm_trie_node *node;
294 	size_t size = sizeof(struct lpm_trie_node) + trie->data_size;
295 
296 	if (value)
297 		size += trie->map.value_size;
298 
299 	node = bpf_map_kmalloc_node(&trie->map, size, GFP_NOWAIT | __GFP_NOWARN,
300 				    trie->map.numa_node);
301 	if (!node)
302 		return NULL;
303 
304 	node->flags = 0;
305 
306 	if (value)
307 		memcpy(node->data + trie->data_size, value,
308 		       trie->map.value_size);
309 
310 	return node;
311 }
312 
313 /* Called from syscall or from eBPF program */
trie_update_elem(struct bpf_map * map,void * _key,void * value,u64 flags)314 static long trie_update_elem(struct bpf_map *map,
315 			     void *_key, void *value, u64 flags)
316 {
317 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
318 	struct lpm_trie_node *node, *im_node = NULL, *new_node = NULL;
319 	struct lpm_trie_node *free_node = NULL;
320 	struct lpm_trie_node __rcu **slot;
321 	struct bpf_lpm_trie_key_u8 *key = _key;
322 	unsigned long irq_flags;
323 	unsigned int next_bit;
324 	size_t matchlen = 0;
325 	int ret = 0;
326 
327 	if (unlikely(flags > BPF_EXIST))
328 		return -EINVAL;
329 
330 	if (key->prefixlen > trie->max_prefixlen)
331 		return -EINVAL;
332 
333 	spin_lock_irqsave(&trie->lock, irq_flags);
334 
335 	/* Allocate and fill a new node */
336 
337 	if (trie->n_entries == trie->map.max_entries) {
338 		ret = -ENOSPC;
339 		goto out;
340 	}
341 
342 	new_node = lpm_trie_node_alloc(trie, value);
343 	if (!new_node) {
344 		ret = -ENOMEM;
345 		goto out;
346 	}
347 
348 	trie->n_entries++;
349 
350 	new_node->prefixlen = key->prefixlen;
351 	RCU_INIT_POINTER(new_node->child[0], NULL);
352 	RCU_INIT_POINTER(new_node->child[1], NULL);
353 	memcpy(new_node->data, key->data, trie->data_size);
354 
355 	/* Now find a slot to attach the new node. To do that, walk the tree
356 	 * from the root and match as many bits as possible for each node until
357 	 * we either find an empty slot or a slot that needs to be replaced by
358 	 * an intermediate node.
359 	 */
360 	slot = &trie->root;
361 
362 	while ((node = rcu_dereference_protected(*slot,
363 					lockdep_is_held(&trie->lock)))) {
364 		matchlen = longest_prefix_match(trie, node, key);
365 
366 		if (node->prefixlen != matchlen ||
367 		    node->prefixlen == key->prefixlen ||
368 		    node->prefixlen == trie->max_prefixlen)
369 			break;
370 
371 		next_bit = extract_bit(key->data, node->prefixlen);
372 		slot = &node->child[next_bit];
373 	}
374 
375 	/* If the slot is empty (a free child pointer or an empty root),
376 	 * simply assign the @new_node to that slot and be done.
377 	 */
378 	if (!node) {
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 		new_node->child[0] = node->child[0];
388 		new_node->child[1] = node->child[1];
389 
390 		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
391 			trie->n_entries--;
392 
393 		rcu_assign_pointer(*slot, new_node);
394 		free_node = node;
395 
396 		goto out;
397 	}
398 
399 	/* If the new node matches the prefix completely, it must be inserted
400 	 * as an ancestor. Simply insert it between @node and *@slot.
401 	 */
402 	if (matchlen == key->prefixlen) {
403 		next_bit = extract_bit(node->data, matchlen);
404 		rcu_assign_pointer(new_node->child[next_bit], node);
405 		rcu_assign_pointer(*slot, new_node);
406 		goto out;
407 	}
408 
409 	im_node = lpm_trie_node_alloc(trie, NULL);
410 	if (!im_node) {
411 		ret = -ENOMEM;
412 		goto out;
413 	}
414 
415 	im_node->prefixlen = matchlen;
416 	im_node->flags |= LPM_TREE_NODE_FLAG_IM;
417 	memcpy(im_node->data, node->data, trie->data_size);
418 
419 	/* Now determine which child to install in which slot */
420 	if (extract_bit(key->data, matchlen)) {
421 		rcu_assign_pointer(im_node->child[0], node);
422 		rcu_assign_pointer(im_node->child[1], new_node);
423 	} else {
424 		rcu_assign_pointer(im_node->child[0], new_node);
425 		rcu_assign_pointer(im_node->child[1], node);
426 	}
427 
428 	/* Finally, assign the intermediate node to the determined slot */
429 	rcu_assign_pointer(*slot, im_node);
430 
431 out:
432 	if (ret) {
433 		if (new_node)
434 			trie->n_entries--;
435 
436 		kfree(new_node);
437 		kfree(im_node);
438 	}
439 
440 	spin_unlock_irqrestore(&trie->lock, irq_flags);
441 	kfree_rcu(free_node, rcu);
442 
443 	return ret;
444 }
445 
446 /* Called from syscall or from eBPF program */
trie_delete_elem(struct bpf_map * map,void * _key)447 static long trie_delete_elem(struct bpf_map *map, void *_key)
448 {
449 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
450 	struct lpm_trie_node *free_node = NULL, *free_parent = NULL;
451 	struct bpf_lpm_trie_key_u8 *key = _key;
452 	struct lpm_trie_node __rcu **trim, **trim2;
453 	struct lpm_trie_node *node, *parent;
454 	unsigned long irq_flags;
455 	unsigned int next_bit;
456 	size_t matchlen = 0;
457 	int ret = 0;
458 
459 	if (key->prefixlen > trie->max_prefixlen)
460 		return -EINVAL;
461 
462 	spin_lock_irqsave(&trie->lock, irq_flags);
463 
464 	/* Walk the tree looking for an exact key/length match and keeping
465 	 * track of the path we traverse.  We will need to know the node
466 	 * we wish to delete, and the slot that points to the node we want
467 	 * to delete.  We may also need to know the nodes parent and the
468 	 * slot that contains it.
469 	 */
470 	trim = &trie->root;
471 	trim2 = trim;
472 	parent = NULL;
473 	while ((node = rcu_dereference_protected(
474 		       *trim, lockdep_is_held(&trie->lock)))) {
475 		matchlen = longest_prefix_match(trie, node, key);
476 
477 		if (node->prefixlen != matchlen ||
478 		    node->prefixlen == key->prefixlen)
479 			break;
480 
481 		parent = node;
482 		trim2 = trim;
483 		next_bit = extract_bit(key->data, node->prefixlen);
484 		trim = &node->child[next_bit];
485 	}
486 
487 	if (!node || node->prefixlen != key->prefixlen ||
488 	    node->prefixlen != matchlen ||
489 	    (node->flags & LPM_TREE_NODE_FLAG_IM)) {
490 		ret = -ENOENT;
491 		goto out;
492 	}
493 
494 	trie->n_entries--;
495 
496 	/* If the node we are removing has two children, simply mark it
497 	 * as intermediate and we are done.
498 	 */
499 	if (rcu_access_pointer(node->child[0]) &&
500 	    rcu_access_pointer(node->child[1])) {
501 		node->flags |= LPM_TREE_NODE_FLAG_IM;
502 		goto out;
503 	}
504 
505 	/* If the parent of the node we are about to delete is an intermediate
506 	 * node, and the deleted node doesn't have any children, we can delete
507 	 * the intermediate parent as well and promote its other child
508 	 * up the tree.  Doing this maintains the invariant that all
509 	 * intermediate nodes have exactly 2 children and that there are no
510 	 * unnecessary intermediate nodes in the tree.
511 	 */
512 	if (parent && (parent->flags & LPM_TREE_NODE_FLAG_IM) &&
513 	    !node->child[0] && !node->child[1]) {
514 		if (node == rcu_access_pointer(parent->child[0]))
515 			rcu_assign_pointer(
516 				*trim2, rcu_access_pointer(parent->child[1]));
517 		else
518 			rcu_assign_pointer(
519 				*trim2, rcu_access_pointer(parent->child[0]));
520 		free_parent = parent;
521 		free_node = node;
522 		goto out;
523 	}
524 
525 	/* The node we are removing has either zero or one child. If there
526 	 * is a child, move it into the removed node's slot then delete
527 	 * the node.  Otherwise just clear the slot and delete the node.
528 	 */
529 	if (node->child[0])
530 		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[0]));
531 	else if (node->child[1])
532 		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[1]));
533 	else
534 		RCU_INIT_POINTER(*trim, NULL);
535 	free_node = node;
536 
537 out:
538 	spin_unlock_irqrestore(&trie->lock, irq_flags);
539 	kfree_rcu(free_parent, rcu);
540 	kfree_rcu(free_node, rcu);
541 
542 	return ret;
543 }
544 
545 #define LPM_DATA_SIZE_MAX	256
546 #define LPM_DATA_SIZE_MIN	1
547 
548 #define LPM_VAL_SIZE_MAX	(KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
549 				 sizeof(struct lpm_trie_node))
550 #define LPM_VAL_SIZE_MIN	1
551 
552 #define LPM_KEY_SIZE(X)		(sizeof(struct bpf_lpm_trie_key_u8) + (X))
553 #define LPM_KEY_SIZE_MAX	LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
554 #define LPM_KEY_SIZE_MIN	LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
555 
556 #define LPM_CREATE_FLAG_MASK	(BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE |	\
557 				 BPF_F_ACCESS_MASK)
558 
trie_alloc(union bpf_attr * attr)559 static struct bpf_map *trie_alloc(union bpf_attr *attr)
560 {
561 	struct lpm_trie *trie;
562 
563 	/* check sanity of attributes */
564 	if (attr->max_entries == 0 ||
565 	    !(attr->map_flags & BPF_F_NO_PREALLOC) ||
566 	    attr->map_flags & ~LPM_CREATE_FLAG_MASK ||
567 	    !bpf_map_flags_access_ok(attr->map_flags) ||
568 	    attr->key_size < LPM_KEY_SIZE_MIN ||
569 	    attr->key_size > LPM_KEY_SIZE_MAX ||
570 	    attr->value_size < LPM_VAL_SIZE_MIN ||
571 	    attr->value_size > LPM_VAL_SIZE_MAX)
572 		return ERR_PTR(-EINVAL);
573 
574 	trie = bpf_map_area_alloc(sizeof(*trie), NUMA_NO_NODE);
575 	if (!trie)
576 		return ERR_PTR(-ENOMEM);
577 
578 	/* copy mandatory map attributes */
579 	bpf_map_init_from_attr(&trie->map, attr);
580 	trie->data_size = attr->key_size -
581 			  offsetof(struct bpf_lpm_trie_key_u8, data);
582 	trie->max_prefixlen = trie->data_size * 8;
583 
584 	spin_lock_init(&trie->lock);
585 
586 	return &trie->map;
587 }
588 
trie_free(struct bpf_map * map)589 static void trie_free(struct bpf_map *map)
590 {
591 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
592 	struct lpm_trie_node __rcu **slot;
593 	struct lpm_trie_node *node;
594 
595 	/* Always start at the root and walk down to a node that has no
596 	 * children. Then free that node, nullify its reference in the parent
597 	 * and start over.
598 	 */
599 
600 	for (;;) {
601 		slot = &trie->root;
602 
603 		for (;;) {
604 			node = rcu_dereference_protected(*slot, 1);
605 			if (!node)
606 				goto out;
607 
608 			if (rcu_access_pointer(node->child[0])) {
609 				slot = &node->child[0];
610 				continue;
611 			}
612 
613 			if (rcu_access_pointer(node->child[1])) {
614 				slot = &node->child[1];
615 				continue;
616 			}
617 
618 			kfree(node);
619 			RCU_INIT_POINTER(*slot, NULL);
620 			break;
621 		}
622 	}
623 
624 out:
625 	bpf_map_area_free(trie);
626 }
627 
trie_get_next_key(struct bpf_map * map,void * _key,void * _next_key)628 static int trie_get_next_key(struct bpf_map *map, void *_key, void *_next_key)
629 {
630 	struct lpm_trie_node *node, *next_node = NULL, *parent, *search_root;
631 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
632 	struct bpf_lpm_trie_key_u8 *key = _key, *next_key = _next_key;
633 	struct lpm_trie_node **node_stack = NULL;
634 	int err = 0, stack_ptr = -1;
635 	unsigned int next_bit;
636 	size_t matchlen;
637 
638 	/* The get_next_key follows postorder. For the 4 node example in
639 	 * the top of this file, the trie_get_next_key() returns the following
640 	 * one after another:
641 	 *   192.168.0.0/24
642 	 *   192.168.1.0/24
643 	 *   192.168.128.0/24
644 	 *   192.168.0.0/16
645 	 *
646 	 * The idea is to return more specific keys before less specific ones.
647 	 */
648 
649 	/* Empty trie */
650 	search_root = rcu_dereference(trie->root);
651 	if (!search_root)
652 		return -ENOENT;
653 
654 	/* For invalid key, find the leftmost node in the trie */
655 	if (!key || key->prefixlen > trie->max_prefixlen)
656 		goto find_leftmost;
657 
658 	node_stack = kmalloc_array(trie->max_prefixlen + 1,
659 				   sizeof(struct lpm_trie_node *),
660 				   GFP_ATOMIC | __GFP_NOWARN);
661 	if (!node_stack)
662 		return -ENOMEM;
663 
664 	/* Try to find the exact node for the given key */
665 	for (node = search_root; node;) {
666 		node_stack[++stack_ptr] = node;
667 		matchlen = longest_prefix_match(trie, node, key);
668 		if (node->prefixlen != matchlen ||
669 		    node->prefixlen == key->prefixlen)
670 			break;
671 
672 		next_bit = extract_bit(key->data, node->prefixlen);
673 		node = rcu_dereference(node->child[next_bit]);
674 	}
675 	if (!node || node->prefixlen != key->prefixlen ||
676 	    (node->flags & LPM_TREE_NODE_FLAG_IM))
677 		goto find_leftmost;
678 
679 	/* The node with the exactly-matching key has been found,
680 	 * find the first node in postorder after the matched node.
681 	 */
682 	node = node_stack[stack_ptr];
683 	while (stack_ptr > 0) {
684 		parent = node_stack[stack_ptr - 1];
685 		if (rcu_dereference(parent->child[0]) == node) {
686 			search_root = rcu_dereference(parent->child[1]);
687 			if (search_root)
688 				goto find_leftmost;
689 		}
690 		if (!(parent->flags & LPM_TREE_NODE_FLAG_IM)) {
691 			next_node = parent;
692 			goto do_copy;
693 		}
694 
695 		node = parent;
696 		stack_ptr--;
697 	}
698 
699 	/* did not find anything */
700 	err = -ENOENT;
701 	goto free_stack;
702 
703 find_leftmost:
704 	/* Find the leftmost non-intermediate node, all intermediate nodes
705 	 * have exact two children, so this function will never return NULL.
706 	 */
707 	for (node = search_root; node;) {
708 		if (node->flags & LPM_TREE_NODE_FLAG_IM) {
709 			node = rcu_dereference(node->child[0]);
710 		} else {
711 			next_node = node;
712 			node = rcu_dereference(node->child[0]);
713 			if (!node)
714 				node = rcu_dereference(next_node->child[1]);
715 		}
716 	}
717 do_copy:
718 	next_key->prefixlen = next_node->prefixlen;
719 	memcpy((void *)next_key + offsetof(struct bpf_lpm_trie_key_u8, data),
720 	       next_node->data, trie->data_size);
721 free_stack:
722 	kfree(node_stack);
723 	return err;
724 }
725 
trie_check_btf(const struct bpf_map * map,const struct btf * btf,const struct btf_type * key_type,const struct btf_type * value_type)726 static int trie_check_btf(const struct bpf_map *map,
727 			  const struct btf *btf,
728 			  const struct btf_type *key_type,
729 			  const struct btf_type *value_type)
730 {
731 	/* Keys must have struct bpf_lpm_trie_key_u8 embedded. */
732 	return BTF_INFO_KIND(key_type->info) != BTF_KIND_STRUCT ?
733 	       -EINVAL : 0;
734 }
735 
trie_mem_usage(const struct bpf_map * map)736 static u64 trie_mem_usage(const struct bpf_map *map)
737 {
738 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
739 	u64 elem_size;
740 
741 	elem_size = sizeof(struct lpm_trie_node) + trie->data_size +
742 			    trie->map.value_size;
743 	return elem_size * READ_ONCE(trie->n_entries);
744 }
745 
746 BTF_ID_LIST_SINGLE(trie_map_btf_ids, struct, lpm_trie)
747 const struct bpf_map_ops trie_map_ops = {
748 	.map_meta_equal = bpf_map_meta_equal,
749 	.map_alloc = trie_alloc,
750 	.map_free = trie_free,
751 	.map_get_next_key = trie_get_next_key,
752 	.map_lookup_elem = trie_lookup_elem,
753 	.map_update_elem = trie_update_elem,
754 	.map_delete_elem = trie_delete_elem,
755 	.map_lookup_batch = generic_map_lookup_batch,
756 	.map_update_batch = generic_map_update_batch,
757 	.map_delete_batch = generic_map_delete_batch,
758 	.map_check_btf = trie_check_btf,
759 	.map_mem_usage = trie_mem_usage,
760 	.map_btf_id = &trie_map_btf_ids[0],
761 };
762