xref: /freebsd/sys/vm/vm_radix.c (revision 2a0c0aea42092f89c2a5345991e6e3ce4cbef99a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2013 EMC Corp.
5  * Copyright (c) 2011 Jeffrey Roberson <jeff@freebsd.org>
6  * Copyright (c) 2008 Mayur Shardul <mayur.shardul@gmail.com>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 /*
33  * Path-compressed radix trie implementation.
34  * The following code is not generalized into a general purpose library
35  * because there are way too many parameters embedded that should really
36  * be decided by the library consumers.  At the same time, consumers
37  * of this code must achieve highest possible performance.
38  *
39  * The implementation takes into account the following rationale:
40  * - Size of the nodes should be as small as possible but still big enough
41  *   to avoid a large maximum depth for the trie.  This is a balance
42  *   between the necessity to not wire too much physical memory for the nodes
43  *   and the necessity to avoid too much cache pollution during the trie
44  *   operations.
45  * - There is not a huge bias toward the number of lookup operations over
46  *   the number of insert and remove operations.  This basically implies
47  *   that optimizations supposedly helping one operation but hurting the
48  *   other might be carefully evaluated.
49  * - On average not many nodes are expected to be fully populated, hence
50  *   level compression may just complicate things.
51  */
52 
53 #include <sys/cdefs.h>
54 __FBSDID("$FreeBSD$");
55 
56 #include "opt_ddb.h"
57 
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/kernel.h>
61 #include <sys/libkern.h>
62 #include <sys/proc.h>
63 #include <sys/vmmeter.h>
64 #include <sys/smr.h>
65 #include <sys/smr_types.h>
66 
67 #include <vm/uma.h>
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <vm/vm_object.h>
71 #include <vm/vm_page.h>
72 #include <vm/vm_radix.h>
73 
74 #ifdef DDB
75 #include <ddb/ddb.h>
76 #endif
77 
78 /*
79  * These widths should allow the pointers to a node's children to fit within
80  * a single cache line.  The extra levels from a narrow width should not be
81  * a problem thanks to path compression.
82  */
83 #ifdef __LP64__
84 #define	VM_RADIX_WIDTH	4
85 #else
86 #define	VM_RADIX_WIDTH	3
87 #endif
88 
89 #define	VM_RADIX_COUNT	(1 << VM_RADIX_WIDTH)
90 #define	VM_RADIX_MASK	(VM_RADIX_COUNT - 1)
91 #define	VM_RADIX_LIMIT							\
92 	(howmany(sizeof(vm_pindex_t) * NBBY, VM_RADIX_WIDTH) - 1)
93 
94 #if VM_RADIX_WIDTH == 3
95 typedef uint8_t rn_popmap_t;
96 #elif VM_RADIX_WIDTH == 4
97 typedef uint16_t rn_popmap_t;
98 #elif VM_RADIX_WIDTH == 5
99 typedef uint32_t rn_popmap_t;
100 #else
101 #error Unsupported width
102 #endif
103 _Static_assert(sizeof(rn_popmap_t) <= sizeof(int),
104     "rn_popmap_t too wide");
105 
106 /* Flag bits stored in node pointers. */
107 #define	VM_RADIX_ISLEAF	0x1
108 #define	VM_RADIX_FLAGS	0x1
109 #define	VM_RADIX_PAD	VM_RADIX_FLAGS
110 
111 /* Returns one unit associated with specified level. */
112 #define	VM_RADIX_UNITLEVEL(lev)						\
113 	((vm_pindex_t)1 << ((lev) * VM_RADIX_WIDTH))
114 
115 enum vm_radix_access { SMR, LOCKED, UNSERIALIZED };
116 
117 struct vm_radix_node;
118 typedef SMR_POINTER(struct vm_radix_node *) smrnode_t;
119 
120 struct vm_radix_node {
121 	vm_pindex_t	rn_owner;			/* Owner of record. */
122 	rn_popmap_t	rn_popmap;			/* Valid children. */
123 	uint8_t		rn_clev;			/* Current level. */
124 	smrnode_t	rn_child[VM_RADIX_COUNT];	/* Child nodes. */
125 };
126 
127 static uma_zone_t vm_radix_node_zone;
128 static smr_t vm_radix_smr;
129 
130 static void vm_radix_node_store(smrnode_t *p, struct vm_radix_node *v,
131     enum vm_radix_access access);
132 
133 /*
134  * Return the position in the array for a given level.
135  */
136 static __inline int
137 vm_radix_slot(vm_pindex_t index, uint16_t level)
138 {
139 	return ((index >> (level * VM_RADIX_WIDTH)) & VM_RADIX_MASK);
140 }
141 
142 /* Computes the key (index) with the low-order 'level' radix-digits zeroed. */
143 static __inline vm_pindex_t
144 vm_radix_trimkey(vm_pindex_t index, uint16_t level)
145 {
146 	return (index & -VM_RADIX_UNITLEVEL(level));
147 }
148 
149 /*
150  * Allocate a radix node.
151  */
152 static struct vm_radix_node *
153 vm_radix_node_get(vm_pindex_t index, uint16_t clevel)
154 {
155 	struct vm_radix_node *rnode;
156 
157 	rnode = uma_zalloc_smr(vm_radix_node_zone, M_NOWAIT);
158 	if (rnode == NULL)
159 		return (NULL);
160 
161 	/*
162 	 * We want to clear the last child pointer after the final section
163 	 * has exited so lookup can not return false negatives.  It is done
164 	 * here because it will be cache-cold in the dtor callback.
165 	 */
166 	if (rnode->rn_popmap != 0) {
167 		vm_radix_node_store(&rnode->rn_child[ffs(rnode->rn_popmap) - 1],
168 		    NULL, UNSERIALIZED);
169 		rnode->rn_popmap = 0;
170 	}
171 	rnode->rn_owner = vm_radix_trimkey(index, clevel + 1);
172 	rnode->rn_clev = clevel;
173 	return (rnode);
174 }
175 
176 /*
177  * Free radix node.
178  */
179 static __inline void
180 vm_radix_node_put(struct vm_radix_node *rnode)
181 {
182 #ifdef INVARIANTS
183 	int slot;
184 
185 	KASSERT(powerof2(rnode->rn_popmap),
186 	    ("vm_radix_node_put: rnode %p has too many children %04x", rnode,
187 	    rnode->rn_popmap));
188 	for (slot = 0; slot < VM_RADIX_COUNT; slot++) {
189 		if ((rnode->rn_popmap & (1 << slot)) != 0)
190 			continue;
191 		KASSERT(smr_unserialized_load(&rnode->rn_child[slot], true) ==
192 		    NULL, ("vm_radix_node_put: rnode %p has a child", rnode));
193 	}
194 #endif
195 	uma_zfree_smr(vm_radix_node_zone, rnode);
196 }
197 
198 /*
199  * Fetch a node pointer from a slot in another node.
200  */
201 static __inline struct vm_radix_node *
202 vm_radix_node_load(smrnode_t *p, enum vm_radix_access access)
203 {
204 
205 	switch (access) {
206 	case UNSERIALIZED:
207 		return (smr_unserialized_load(p, true));
208 	case LOCKED:
209 		return (smr_serialized_load(p, true));
210 	case SMR:
211 		return (smr_entered_load(p, vm_radix_smr));
212 	}
213 	__assert_unreachable();
214 }
215 
216 static __inline void
217 vm_radix_node_store(smrnode_t *p, struct vm_radix_node *v,
218     enum vm_radix_access access)
219 {
220 
221 	switch (access) {
222 	case UNSERIALIZED:
223 		smr_unserialized_store(p, v, true);
224 		break;
225 	case LOCKED:
226 		smr_serialized_store(p, v, true);
227 		break;
228 	case SMR:
229 		panic("vm_radix_node_store: Not supported in smr section.");
230 	}
231 }
232 
233 /*
234  * Get the root node for a radix tree.
235  */
236 static __inline struct vm_radix_node *
237 vm_radix_root_load(struct vm_radix *rtree, enum vm_radix_access access)
238 {
239 
240 	return (vm_radix_node_load((smrnode_t *)&rtree->rt_root, access));
241 }
242 
243 /*
244  * Set the root node for a radix tree.
245  */
246 static __inline void
247 vm_radix_root_store(struct vm_radix *rtree, struct vm_radix_node *rnode,
248     enum vm_radix_access access)
249 {
250 
251 	vm_radix_node_store((smrnode_t *)&rtree->rt_root, rnode, access);
252 }
253 
254 /*
255  * Returns TRUE if the specified radix node is a leaf and FALSE otherwise.
256  */
257 static __inline bool
258 vm_radix_isleaf(struct vm_radix_node *rnode)
259 {
260 
261 	return (((uintptr_t)rnode & VM_RADIX_ISLEAF) != 0);
262 }
263 
264 /*
265  * Returns page cast to radix node with leaf bit set.
266  */
267 static __inline struct vm_radix_node *
268 vm_radix_toleaf(vm_page_t page)
269 {
270 	return ((struct vm_radix_node *)((uintptr_t)page | VM_RADIX_ISLEAF));
271 }
272 
273 /*
274  * Returns the associated page extracted from rnode.
275  */
276 static __inline vm_page_t
277 vm_radix_topage(struct vm_radix_node *rnode)
278 {
279 
280 	return ((vm_page_t)((uintptr_t)rnode & ~VM_RADIX_FLAGS));
281 }
282 
283 /*
284  * Make 'child' a child of 'rnode'.
285  */
286 static __inline void
287 vm_radix_addnode(struct vm_radix_node *rnode, vm_pindex_t index, uint16_t clev,
288     struct vm_radix_node *child, enum vm_radix_access access)
289 {
290 	int slot;
291 
292 	slot = vm_radix_slot(index, clev);
293 	vm_radix_node_store(&rnode->rn_child[slot], child, access);
294 	rnode->rn_popmap ^= 1 << slot;
295 	KASSERT((rnode->rn_popmap & (1 << slot)) != 0,
296 	    ("%s: bad popmap slot %d in rnode %p", __func__, slot, rnode));
297 }
298 
299 /*
300  * Returns the level where two keys differ.
301  * It cannot accept 2 equal keys.
302  */
303 static __inline uint16_t
304 vm_radix_keydiff(vm_pindex_t index1, vm_pindex_t index2)
305 {
306 
307 	KASSERT(index1 != index2, ("%s: passing the same key value %jx",
308 	    __func__, (uintmax_t)index1));
309 	CTASSERT(sizeof(long long) >= sizeof(vm_pindex_t));
310 
311 	/*
312 	 * From the highest-order bit where the indexes differ,
313 	 * compute the highest level in the trie where they differ.
314 	 */
315 	return ((flsll(index1 ^ index2) - 1) / VM_RADIX_WIDTH);
316 }
317 
318 /*
319  * Returns TRUE if it can be determined that key does not belong to the
320  * specified rnode.  Otherwise, returns FALSE.
321  */
322 static __inline bool
323 vm_radix_keybarr(struct vm_radix_node *rnode, vm_pindex_t idx)
324 {
325 
326 	if (rnode->rn_clev < VM_RADIX_LIMIT) {
327 		idx = vm_radix_trimkey(idx, rnode->rn_clev + 1);
328 		return (idx != rnode->rn_owner);
329 	}
330 	return (false);
331 }
332 
333 /*
334  * Internal helper for vm_radix_reclaim_allnodes().
335  * This function is recursive.
336  */
337 static void
338 vm_radix_reclaim_allnodes_int(struct vm_radix_node *rnode)
339 {
340 	struct vm_radix_node *child;
341 	int slot;
342 
343 	while (rnode->rn_popmap != 0) {
344 		slot = ffs(rnode->rn_popmap) - 1;
345 		child = vm_radix_node_load(&rnode->rn_child[slot],
346 		    UNSERIALIZED);
347 		KASSERT(child != NULL, ("%s: bad popmap slot %d in rnode %p",
348 		    __func__, slot, rnode));
349 		if (!vm_radix_isleaf(child))
350 			vm_radix_reclaim_allnodes_int(child);
351 		rnode->rn_popmap ^= 1 << slot;
352 		vm_radix_node_store(&rnode->rn_child[slot], NULL,
353 		    UNSERIALIZED);
354 	}
355 	vm_radix_node_put(rnode);
356 }
357 
358 #ifndef UMA_MD_SMALL_ALLOC
359 void vm_radix_reserve_kva(void);
360 /*
361  * Reserve the KVA necessary to satisfy the node allocation.
362  * This is mandatory in architectures not supporting direct
363  * mapping as they will need otherwise to carve into the kernel maps for
364  * every node allocation, resulting into deadlocks for consumers already
365  * working with kernel maps.
366  */
367 void
368 vm_radix_reserve_kva(void)
369 {
370 
371 	/*
372 	 * Calculate the number of reserved nodes, discounting the pages that
373 	 * are needed to store them.
374 	 */
375 	if (!uma_zone_reserve_kva(vm_radix_node_zone,
376 	    ((vm_paddr_t)vm_cnt.v_page_count * PAGE_SIZE) / (PAGE_SIZE +
377 	    sizeof(struct vm_radix_node))))
378 		panic("%s: unable to reserve KVA", __func__);
379 }
380 #endif
381 
382 /*
383  * Initialize the UMA slab zone.
384  */
385 void
386 vm_radix_zinit(void)
387 {
388 
389 	vm_radix_node_zone = uma_zcreate("RADIX NODE",
390 	    sizeof(struct vm_radix_node), NULL, NULL, NULL, NULL,
391 	    VM_RADIX_PAD, UMA_ZONE_VM | UMA_ZONE_SMR | UMA_ZONE_ZINIT);
392 	vm_radix_smr = uma_zone_get_smr(vm_radix_node_zone);
393 }
394 
395 /*
396  * Inserts the key-value pair into the trie.
397  * Panics if the key already exists.
398  */
399 int
400 vm_radix_insert(struct vm_radix *rtree, vm_page_t page)
401 {
402 	vm_pindex_t index, newind;
403 	struct vm_radix_node *leaf, *rnode, *tmp;
404 	smrnode_t *parentp;
405 	int slot;
406 	uint16_t clev;
407 
408 	index = page->pindex;
409 	leaf = vm_radix_toleaf(page);
410 
411 	/*
412 	 * The owner of record for root is not really important because it
413 	 * will never be used.
414 	 */
415 	rnode = vm_radix_root_load(rtree, LOCKED);
416 	if (rnode == NULL) {
417 		rtree->rt_root = (uintptr_t)leaf;
418 		return (0);
419 	}
420 	for (parentp = (smrnode_t *)&rtree->rt_root;; rnode = tmp) {
421 		if (vm_radix_isleaf(rnode)) {
422 			newind = vm_radix_topage(rnode)->pindex;
423 			if (newind == index)
424 				panic("%s: key %jx is already present",
425 				    __func__, (uintmax_t)index);
426 			break;
427 		} else if (vm_radix_keybarr(rnode, index)) {
428 			newind = rnode->rn_owner;
429 			break;
430 		}
431 		slot = vm_radix_slot(index, rnode->rn_clev);
432 		parentp = &rnode->rn_child[slot];
433 		tmp = vm_radix_node_load(parentp, LOCKED);
434 		if (tmp == NULL) {
435 			vm_radix_addnode(rnode, index, rnode->rn_clev, leaf,
436 			    LOCKED);
437 			return (0);
438 		}
439 	}
440 
441 	/*
442 	 * A new node is needed because the right insertion level is reached.
443 	 * Setup the new intermediate node and add the 2 children: the
444 	 * new object and the older edge or object.
445 	 */
446 	clev = vm_radix_keydiff(newind, index);
447 	tmp = vm_radix_node_get(index, clev);
448 	if (tmp == NULL)
449 		return (ENOMEM);
450 	/* These writes are not yet visible due to ordering. */
451 	vm_radix_addnode(tmp, index, clev, leaf, UNSERIALIZED);
452 	vm_radix_addnode(tmp, newind, clev, rnode, UNSERIALIZED);
453 	/* Serializing write to make the above visible. */
454 	vm_radix_node_store(parentp, tmp, LOCKED);
455 	return (0);
456 }
457 
458 /*
459  * Returns the value stored at the index.  If the index is not present,
460  * NULL is returned.
461  */
462 static __always_inline vm_page_t
463 _vm_radix_lookup(struct vm_radix *rtree, vm_pindex_t index,
464     enum vm_radix_access access)
465 {
466 	struct vm_radix_node *rnode;
467 	vm_page_t m;
468 	int slot;
469 
470 	rnode = vm_radix_root_load(rtree, access);
471 	while (rnode != NULL) {
472 		if (vm_radix_isleaf(rnode)) {
473 			m = vm_radix_topage(rnode);
474 			if (m->pindex == index)
475 				return (m);
476 			break;
477 		}
478 		if (vm_radix_keybarr(rnode, index))
479 			break;
480 		slot = vm_radix_slot(index, rnode->rn_clev);
481 		rnode = vm_radix_node_load(&rnode->rn_child[slot], access);
482 	}
483 	return (NULL);
484 }
485 
486 /*
487  * Returns the value stored at the index assuming there is an external lock.
488  *
489  * If the index is not present, NULL is returned.
490  */
491 vm_page_t
492 vm_radix_lookup(struct vm_radix *rtree, vm_pindex_t index)
493 {
494 
495 	return _vm_radix_lookup(rtree, index, LOCKED);
496 }
497 
498 /*
499  * Returns the value stored at the index without requiring an external lock.
500  *
501  * If the index is not present, NULL is returned.
502  */
503 vm_page_t
504 vm_radix_lookup_unlocked(struct vm_radix *rtree, vm_pindex_t index)
505 {
506 	vm_page_t m;
507 
508 	smr_enter(vm_radix_smr);
509 	m = _vm_radix_lookup(rtree, index, SMR);
510 	smr_exit(vm_radix_smr);
511 
512 	return (m);
513 }
514 
515 /*
516  * Look up the nearest entry at a position greater than or equal to index.
517  */
518 vm_page_t
519 vm_radix_lookup_ge(struct vm_radix *rtree, vm_pindex_t index)
520 {
521 	struct vm_radix_node *stack[VM_RADIX_LIMIT];
522 	vm_page_t m;
523 	struct vm_radix_node *child, *rnode;
524 #ifdef INVARIANTS
525 	int loops = 0;
526 #endif
527 	int slot, tos;
528 
529 	rnode = vm_radix_root_load(rtree, LOCKED);
530 	if (rnode == NULL)
531 		return (NULL);
532 	else if (vm_radix_isleaf(rnode)) {
533 		m = vm_radix_topage(rnode);
534 		if (m->pindex >= index)
535 			return (m);
536 		else
537 			return (NULL);
538 	}
539 	tos = 0;
540 	for (;;) {
541 		/*
542 		 * If the keys differ before the current bisection node,
543 		 * then the search key might rollback to the earliest
544 		 * available bisection node or to the smallest key
545 		 * in the current node (if the owner is greater than the
546 		 * search key).
547 		 */
548 		if (vm_radix_keybarr(rnode, index)) {
549 			if (index > rnode->rn_owner) {
550 ascend:
551 				KASSERT(++loops < 1000,
552 				    ("vm_radix_lookup_ge: too many loops"));
553 
554 				/*
555 				 * Pop nodes from the stack until either the
556 				 * stack is empty or a node that could have a
557 				 * matching descendant is found.
558 				 */
559 				do {
560 					if (tos == 0)
561 						return (NULL);
562 					rnode = stack[--tos];
563 				} while (vm_radix_slot(index,
564 				    rnode->rn_clev) == (VM_RADIX_COUNT - 1));
565 
566 				/*
567 				 * The following computation cannot overflow
568 				 * because index's slot at the current level
569 				 * is less than VM_RADIX_COUNT - 1.
570 				 */
571 				index = vm_radix_trimkey(index,
572 				    rnode->rn_clev);
573 				index += VM_RADIX_UNITLEVEL(rnode->rn_clev);
574 			} else
575 				index = rnode->rn_owner;
576 			KASSERT(!vm_radix_keybarr(rnode, index),
577 			    ("vm_radix_lookup_ge: keybarr failed"));
578 		}
579 		slot = vm_radix_slot(index, rnode->rn_clev);
580 		child = vm_radix_node_load(&rnode->rn_child[slot], LOCKED);
581 		if (vm_radix_isleaf(child)) {
582 			m = vm_radix_topage(child);
583 			if (m->pindex >= index)
584 				return (m);
585 		} else if (child != NULL)
586 			goto descend;
587 
588 		/* Find the first set bit beyond the first slot+1 bits. */
589 		slot = ffs(rnode->rn_popmap & (-2 << slot)) - 1;
590 		if (slot < 0) {
591 			/*
592 			 * A page or edge greater than the search slot is not
593 			 * found in the current node; ascend to the next
594 			 * higher-level node.
595 			 */
596 			goto ascend;
597 		}
598 		child = vm_radix_node_load(&rnode->rn_child[slot], LOCKED);
599 		KASSERT(child != NULL, ("%s: bad popmap slot %d in rnode %p",
600 		    __func__, slot, rnode));
601 		if (vm_radix_isleaf(child))
602 			return (vm_radix_topage(child));
603 		index = vm_radix_trimkey(index, rnode->rn_clev + 1) +
604 		    slot * VM_RADIX_UNITLEVEL(rnode->rn_clev);
605 descend:
606 		KASSERT(rnode->rn_clev > 0,
607 		    ("vm_radix_lookup_ge: pushing leaf's parent"));
608 		KASSERT(tos < VM_RADIX_LIMIT,
609 		    ("vm_radix_lookup_ge: stack overflow"));
610 		stack[tos++] = rnode;
611 		rnode = child;
612 	}
613 }
614 
615 /*
616  * Look up the nearest entry at a position less than or equal to index.
617  */
618 vm_page_t
619 vm_radix_lookup_le(struct vm_radix *rtree, vm_pindex_t index)
620 {
621 	struct vm_radix_node *stack[VM_RADIX_LIMIT];
622 	vm_page_t m;
623 	struct vm_radix_node *child, *rnode;
624 #ifdef INVARIANTS
625 	int loops = 0;
626 #endif
627 	int slot, tos;
628 
629 	rnode = vm_radix_root_load(rtree, LOCKED);
630 	if (rnode == NULL)
631 		return (NULL);
632 	else if (vm_radix_isleaf(rnode)) {
633 		m = vm_radix_topage(rnode);
634 		if (m->pindex <= index)
635 			return (m);
636 		else
637 			return (NULL);
638 	}
639 	tos = 0;
640 	for (;;) {
641 		/*
642 		 * If the keys differ before the current bisection node,
643 		 * then the search key might rollback to the earliest
644 		 * available bisection node or to the largest key
645 		 * in the current node (if the owner is smaller than the
646 		 * search key).
647 		 */
648 		if (vm_radix_keybarr(rnode, index)) {
649 			if (index > rnode->rn_owner) {
650 				index = rnode->rn_owner + VM_RADIX_COUNT *
651 				    VM_RADIX_UNITLEVEL(rnode->rn_clev);
652 			} else {
653 ascend:
654 				KASSERT(++loops < 1000,
655 				    ("vm_radix_lookup_le: too many loops"));
656 
657 				/*
658 				 * Pop nodes from the stack until either the
659 				 * stack is empty or a node that could have a
660 				 * matching descendant is found.
661 				 */
662 				do {
663 					if (tos == 0)
664 						return (NULL);
665 					rnode = stack[--tos];
666 				} while (vm_radix_slot(index,
667 				    rnode->rn_clev) == 0);
668 
669 				/*
670 				 * The following computation cannot overflow
671 				 * because index's slot at the current level
672 				 * is greater than 0.
673 				 */
674 				index = vm_radix_trimkey(index,
675 				    rnode->rn_clev);
676 			}
677 			index--;
678 			KASSERT(!vm_radix_keybarr(rnode, index),
679 			    ("vm_radix_lookup_le: keybarr failed"));
680 		}
681 		slot = vm_radix_slot(index, rnode->rn_clev);
682 		child = vm_radix_node_load(&rnode->rn_child[slot], LOCKED);
683 		if (vm_radix_isleaf(child)) {
684 			m = vm_radix_topage(child);
685 			if (m->pindex <= index)
686 				return (m);
687 		} else if (child != NULL)
688 			goto descend;
689 
690 		/* Find the last set bit among the first slot bits. */
691 		slot = fls(rnode->rn_popmap & ((1 << slot) - 1)) - 1;
692 		if (slot < 0) {
693 			/*
694 			 * A page or edge smaller than the search slot is not
695 			 * found in the current node; ascend to the next
696 			 * higher-level node.
697 			 */
698 			goto ascend;
699 		}
700 		child = vm_radix_node_load(&rnode->rn_child[slot], LOCKED);
701 		KASSERT(child != NULL, ("%s: bad popmap slot %d in rnode %p",
702 		    __func__, slot, rnode));
703 		if (vm_radix_isleaf(child))
704 			return (vm_radix_topage(child));
705 		index = vm_radix_trimkey(index, rnode->rn_clev + 1) +
706 		    (slot + 1) * VM_RADIX_UNITLEVEL(rnode->rn_clev) - 1;
707 descend:
708 		KASSERT(rnode->rn_clev > 0,
709 		    ("vm_radix_lookup_le: pushing leaf's parent"));
710 		KASSERT(tos < VM_RADIX_LIMIT,
711 		    ("vm_radix_lookup_le: stack overflow"));
712 		stack[tos++] = rnode;
713 		rnode = child;
714 	}
715 }
716 
717 /*
718  * Remove the specified index from the trie, and return the value stored at
719  * that index.  If the index is not present, return NULL.
720  */
721 vm_page_t
722 vm_radix_remove(struct vm_radix *rtree, vm_pindex_t index)
723 {
724 	struct vm_radix_node *rnode, *parent, *tmp;
725 	vm_page_t m;
726 	int slot;
727 
728 	rnode = vm_radix_root_load(rtree, LOCKED);
729 	if (vm_radix_isleaf(rnode)) {
730 		m = vm_radix_topage(rnode);
731 		if (m->pindex != index)
732 			return (NULL);
733 		vm_radix_root_store(rtree, NULL, LOCKED);
734 		return (m);
735 	}
736 	parent = NULL;
737 	for (;;) {
738 		if (rnode == NULL)
739 			return (NULL);
740 		slot = vm_radix_slot(index, rnode->rn_clev);
741 		tmp = vm_radix_node_load(&rnode->rn_child[slot], LOCKED);
742 		if (vm_radix_isleaf(tmp)) {
743 			m = vm_radix_topage(tmp);
744 			if (m->pindex != index)
745 				return (NULL);
746 			KASSERT((rnode->rn_popmap & (1 << slot)) != 0,
747 			    ("%s: bad popmap slot %d in rnode %p",
748 			    __func__, slot, rnode));
749 			rnode->rn_popmap ^= 1 << slot;
750 			vm_radix_node_store(
751 			    &rnode->rn_child[slot], NULL, LOCKED);
752 			if (!powerof2(rnode->rn_popmap))
753 				return (m);
754 			KASSERT(rnode->rn_popmap != 0,
755 			    ("%s: bad popmap all zeroes", __func__));
756 			slot = ffs(rnode->rn_popmap) - 1;
757 			tmp = vm_radix_node_load(&rnode->rn_child[slot], LOCKED);
758 			KASSERT(tmp != NULL,
759 			    ("%s: bad popmap slot %d in rnode %p",
760 			    __func__, slot, rnode));
761 			if (parent == NULL)
762 				vm_radix_root_store(rtree, tmp, LOCKED);
763 			else {
764 				slot = vm_radix_slot(index, parent->rn_clev);
765 				KASSERT(vm_radix_node_load(
766 				    &parent->rn_child[slot], LOCKED) == rnode,
767 				    ("%s: invalid child value", __func__));
768 				vm_radix_node_store(&parent->rn_child[slot],
769 				    tmp, LOCKED);
770 			}
771 			/*
772 			 * The child is still valid and we can not zero the
773 			 * pointer until all smr references are gone.
774 			 */
775 			vm_radix_node_put(rnode);
776 			return (m);
777 		}
778 		parent = rnode;
779 		rnode = tmp;
780 	}
781 }
782 
783 /*
784  * Remove and free all the nodes from the radix tree.
785  * This function is recursive but there is a tight control on it as the
786  * maximum depth of the tree is fixed.
787  */
788 void
789 vm_radix_reclaim_allnodes(struct vm_radix *rtree)
790 {
791 	struct vm_radix_node *root;
792 
793 	root = vm_radix_root_load(rtree, LOCKED);
794 	if (root == NULL)
795 		return;
796 	vm_radix_root_store(rtree, NULL, UNSERIALIZED);
797 	if (!vm_radix_isleaf(root))
798 		vm_radix_reclaim_allnodes_int(root);
799 }
800 
801 /*
802  * Replace an existing page in the trie with another one.
803  * Panics if there is not an old page in the trie at the new page's index.
804  */
805 vm_page_t
806 vm_radix_replace(struct vm_radix *rtree, vm_page_t newpage)
807 {
808 	struct vm_radix_node *rnode, *tmp;
809 	vm_page_t m;
810 	vm_pindex_t index;
811 	int slot;
812 
813 	index = newpage->pindex;
814 	rnode = vm_radix_root_load(rtree, LOCKED);
815 	if (rnode == NULL)
816 		panic("%s: replacing page on an empty trie", __func__);
817 	if (vm_radix_isleaf(rnode)) {
818 		m = vm_radix_topage(rnode);
819 		if (m->pindex != index)
820 			panic("%s: original replacing root key not found",
821 			    __func__);
822 		rtree->rt_root = (uintptr_t)vm_radix_toleaf(newpage);
823 		return (m);
824 	}
825 	for (;;) {
826 		slot = vm_radix_slot(index, rnode->rn_clev);
827 		tmp = vm_radix_node_load(&rnode->rn_child[slot], LOCKED);
828 		if (vm_radix_isleaf(tmp)) {
829 			m = vm_radix_topage(tmp);
830 			if (m->pindex != index)
831 				break;
832 			vm_radix_node_store(&rnode->rn_child[slot],
833 			    vm_radix_toleaf(newpage), LOCKED);
834 			return (m);
835 		} else if (tmp == NULL || vm_radix_keybarr(tmp, index))
836 			break;
837 		rnode = tmp;
838 	}
839 	panic("%s: original replacing page not found", __func__);
840 }
841 
842 void
843 vm_radix_wait(void)
844 {
845 	uma_zwait(vm_radix_node_zone);
846 }
847 
848 #ifdef DDB
849 /*
850  * Show details about the given radix node.
851  */
852 DB_SHOW_COMMAND(radixnode, db_show_radixnode)
853 {
854 	struct vm_radix_node *rnode, *tmp;
855 	int slot;
856 	rn_popmap_t popmap;
857 
858         if (!have_addr)
859                 return;
860 	rnode = (struct vm_radix_node *)addr;
861 	db_printf("radixnode %p, owner %jx, children popmap %04x, level %u:\n",
862 	    (void *)rnode, (uintmax_t)rnode->rn_owner, rnode->rn_popmap,
863 	    rnode->rn_clev);
864 	for (popmap = rnode->rn_popmap; popmap != 0; popmap ^= 1 << slot) {
865 		slot = ffs(popmap) - 1;
866 		tmp = vm_radix_node_load(&rnode->rn_child[slot], UNSERIALIZED);
867 		db_printf("slot: %d, val: %p, page: %p, clev: %d\n",
868 		    slot, (void *)tmp,
869 		    vm_radix_isleaf(tmp) ?  vm_radix_topage(tmp) : NULL,
870 		    rnode->rn_clev);
871 	}
872 }
873 #endif /* DDB */
874