2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
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.
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
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.
53 #include <sys/cdefs.h>
54 __FBSDID("$FreeBSD$");
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/kernel.h>
61 #include <sys/vmmeter.h>
65 #include <vm/vm_param.h>
66 #include <vm/vm_page.h>
67 #include <vm/vm_radix.h>
74 * These widths should allow the pointers to a node's children to fit within
75 * a single cache line. The extra levels from a narrow width should not be
76 * a problem thanks to path compression.
79 #define VM_RADIX_WIDTH 4
81 #define VM_RADIX_WIDTH 3
84 #define VM_RADIX_COUNT (1 << VM_RADIX_WIDTH)
85 #define VM_RADIX_MASK (VM_RADIX_COUNT - 1)
86 #define VM_RADIX_LIMIT \
87 (howmany(sizeof(vm_pindex_t) * NBBY, VM_RADIX_WIDTH) - 1)
89 /* Flag bits stored in node pointers. */
90 #define VM_RADIX_ISLEAF 0x1
91 #define VM_RADIX_FLAGS 0x1
92 #define VM_RADIX_PAD VM_RADIX_FLAGS
94 /* Returns one unit associated with specified level. */
95 #define VM_RADIX_UNITLEVEL(lev) \
96 ((vm_pindex_t)1 << ((lev) * VM_RADIX_WIDTH))
98 struct vm_radix_node {
99 vm_pindex_t rn_owner; /* Owner of record. */
100 uint16_t rn_count; /* Valid children. */
101 uint16_t rn_clev; /* Current level. */
102 void *rn_child[VM_RADIX_COUNT]; /* Child nodes. */
105 static uma_zone_t vm_radix_node_zone;
108 * Allocate a radix node.
110 static __inline struct vm_radix_node *
111 vm_radix_node_get(vm_pindex_t owner, uint16_t count, uint16_t clevel)
113 struct vm_radix_node *rnode;
115 rnode = uma_zalloc(vm_radix_node_zone, M_NOWAIT | M_ZERO);
118 rnode->rn_owner = owner;
119 rnode->rn_count = count;
120 rnode->rn_clev = clevel;
128 vm_radix_node_put(struct vm_radix_node *rnode)
131 uma_zfree(vm_radix_node_zone, rnode);
135 * Return the position in the array for a given level.
138 vm_radix_slot(vm_pindex_t index, uint16_t level)
141 return ((index >> (level * VM_RADIX_WIDTH)) & VM_RADIX_MASK);
144 /* Trims the key after the specified level. */
145 static __inline vm_pindex_t
146 vm_radix_trimkey(vm_pindex_t index, uint16_t level)
152 ret >>= level * VM_RADIX_WIDTH;
153 ret <<= level * VM_RADIX_WIDTH;
159 * Get the root node for a radix tree.
161 static __inline struct vm_radix_node *
162 vm_radix_getroot(struct vm_radix *rtree)
165 return ((struct vm_radix_node *)rtree->rt_root);
169 * Set the root node for a radix tree.
172 vm_radix_setroot(struct vm_radix *rtree, struct vm_radix_node *rnode)
175 rtree->rt_root = (uintptr_t)rnode;
179 * Returns TRUE if the specified radix node is a leaf and FALSE otherwise.
181 static __inline boolean_t
182 vm_radix_isleaf(struct vm_radix_node *rnode)
185 return (((uintptr_t)rnode & VM_RADIX_ISLEAF) != 0);
189 * Returns the associated page extracted from rnode.
191 static __inline vm_page_t
192 vm_radix_topage(struct vm_radix_node *rnode)
195 return ((vm_page_t)((uintptr_t)rnode & ~VM_RADIX_FLAGS));
199 * Adds the page as a child of the provided node.
202 vm_radix_addpage(struct vm_radix_node *rnode, vm_pindex_t index, uint16_t clev,
207 slot = vm_radix_slot(index, clev);
208 rnode->rn_child[slot] = (void *)((uintptr_t)page | VM_RADIX_ISLEAF);
212 * Returns the slot where two keys differ.
213 * It cannot accept 2 equal keys.
215 static __inline uint16_t
216 vm_radix_keydiff(vm_pindex_t index1, vm_pindex_t index2)
220 KASSERT(index1 != index2, ("%s: passing the same key value %jx",
221 __func__, (uintmax_t)index1));
224 for (clev = VM_RADIX_LIMIT;; clev--)
225 if (vm_radix_slot(index1, clev) != 0)
230 * Returns TRUE if it can be determined that key does not belong to the
231 * specified rnode. Otherwise, returns FALSE.
233 static __inline boolean_t
234 vm_radix_keybarr(struct vm_radix_node *rnode, vm_pindex_t idx)
237 if (rnode->rn_clev < VM_RADIX_LIMIT) {
238 idx = vm_radix_trimkey(idx, rnode->rn_clev + 1);
239 return (idx != rnode->rn_owner);
245 * Internal helper for vm_radix_reclaim_allnodes().
246 * This function is recursive.
249 vm_radix_reclaim_allnodes_int(struct vm_radix_node *rnode)
253 KASSERT(rnode->rn_count <= VM_RADIX_COUNT,
254 ("vm_radix_reclaim_allnodes_int: bad count in rnode %p", rnode));
255 for (slot = 0; rnode->rn_count != 0; slot++) {
256 if (rnode->rn_child[slot] == NULL)
258 if (!vm_radix_isleaf(rnode->rn_child[slot]))
259 vm_radix_reclaim_allnodes_int(rnode->rn_child[slot]);
260 rnode->rn_child[slot] = NULL;
263 vm_radix_node_put(rnode);
268 * Radix node zone destructor.
271 vm_radix_node_zone_dtor(void *mem, int size __unused, void *arg __unused)
273 struct vm_radix_node *rnode;
277 KASSERT(rnode->rn_count == 0,
278 ("vm_radix_node_put: rnode %p has %d children", rnode,
280 for (slot = 0; slot < VM_RADIX_COUNT; slot++)
281 KASSERT(rnode->rn_child[slot] == NULL,
282 ("vm_radix_node_put: rnode %p has a child", rnode));
286 #ifndef UMA_MD_SMALL_ALLOC
287 void vm_radix_reserve_kva(void);
289 * Reserve the KVA necessary to satisfy the node allocation.
290 * This is mandatory in architectures not supporting direct
291 * mapping as they will need otherwise to carve into the kernel maps for
292 * every node allocation, resulting into deadlocks for consumers already
293 * working with kernel maps.
296 vm_radix_reserve_kva(void)
300 * Calculate the number of reserved nodes, discounting the pages that
301 * are needed to store them.
303 if (!uma_zone_reserve_kva(vm_radix_node_zone,
304 ((vm_paddr_t)vm_cnt.v_page_count * PAGE_SIZE) / (PAGE_SIZE +
305 sizeof(struct vm_radix_node))))
306 panic("%s: unable to reserve KVA", __func__);
311 * Initialize the UMA slab zone.
317 vm_radix_node_zone = uma_zcreate("RADIX NODE",
318 sizeof(struct vm_radix_node), NULL,
320 vm_radix_node_zone_dtor,
324 NULL, NULL, VM_RADIX_PAD, UMA_ZONE_VM);
328 * Inserts the key-value pair into the trie.
329 * Panics if the key already exists.
332 vm_radix_insert(struct vm_radix *rtree, vm_page_t page)
334 vm_pindex_t index, newind;
336 struct vm_radix_node *rnode, *tmp;
341 index = page->pindex;
344 * The owner of record for root is not really important because it
345 * will never be used.
347 rnode = vm_radix_getroot(rtree);
349 rtree->rt_root = (uintptr_t)page | VM_RADIX_ISLEAF;
352 parentp = (void **)&rtree->rt_root;
354 if (vm_radix_isleaf(rnode)) {
355 m = vm_radix_topage(rnode);
356 if (m->pindex == index)
357 panic("%s: key %jx is already present",
358 __func__, (uintmax_t)index);
359 clev = vm_radix_keydiff(m->pindex, index);
360 tmp = vm_radix_node_get(vm_radix_trimkey(index,
365 vm_radix_addpage(tmp, index, clev, page);
366 vm_radix_addpage(tmp, m->pindex, clev, m);
368 } else if (vm_radix_keybarr(rnode, index))
370 slot = vm_radix_slot(index, rnode->rn_clev);
371 if (rnode->rn_child[slot] == NULL) {
373 vm_radix_addpage(rnode, index, rnode->rn_clev, page);
376 parentp = &rnode->rn_child[slot];
377 rnode = rnode->rn_child[slot];
381 * A new node is needed because the right insertion level is reached.
382 * Setup the new intermediate node and add the 2 children: the
383 * new object and the older edge.
385 newind = rnode->rn_owner;
386 clev = vm_radix_keydiff(newind, index);
387 tmp = vm_radix_node_get(vm_radix_trimkey(index, clev + 1), 2, clev);
391 vm_radix_addpage(tmp, index, clev, page);
392 slot = vm_radix_slot(newind, clev);
393 tmp->rn_child[slot] = rnode;
398 * Returns TRUE if the specified radix tree contains a single leaf and FALSE
402 vm_radix_is_singleton(struct vm_radix *rtree)
404 struct vm_radix_node *rnode;
406 rnode = vm_radix_getroot(rtree);
409 return (vm_radix_isleaf(rnode));
413 * Returns the value stored at the index. If the index is not present,
417 vm_radix_lookup(struct vm_radix *rtree, vm_pindex_t index)
419 struct vm_radix_node *rnode;
423 rnode = vm_radix_getroot(rtree);
424 while (rnode != NULL) {
425 if (vm_radix_isleaf(rnode)) {
426 m = vm_radix_topage(rnode);
427 if (m->pindex == index)
431 } else if (vm_radix_keybarr(rnode, index))
433 slot = vm_radix_slot(index, rnode->rn_clev);
434 rnode = rnode->rn_child[slot];
440 * Look up the nearest entry at a position bigger than or equal to index.
443 vm_radix_lookup_ge(struct vm_radix *rtree, vm_pindex_t index)
445 struct vm_radix_node *stack[VM_RADIX_LIMIT];
448 struct vm_radix_node *child, *rnode;
454 rnode = vm_radix_getroot(rtree);
457 else if (vm_radix_isleaf(rnode)) {
458 m = vm_radix_topage(rnode);
459 if (m->pindex >= index)
467 * If the keys differ before the current bisection node,
468 * then the search key might rollback to the earliest
469 * available bisection node or to the smallest key
470 * in the current node (if the owner is bigger than the
473 if (vm_radix_keybarr(rnode, index)) {
474 if (index > rnode->rn_owner) {
476 KASSERT(++loops < 1000,
477 ("vm_radix_lookup_ge: too many loops"));
480 * Pop nodes from the stack until either the
481 * stack is empty or a node that could have a
482 * matching descendant is found.
487 rnode = stack[--tos];
488 } while (vm_radix_slot(index,
489 rnode->rn_clev) == (VM_RADIX_COUNT - 1));
492 * The following computation cannot overflow
493 * because index's slot at the current level
494 * is less than VM_RADIX_COUNT - 1.
496 index = vm_radix_trimkey(index,
498 index += VM_RADIX_UNITLEVEL(rnode->rn_clev);
500 index = rnode->rn_owner;
501 KASSERT(!vm_radix_keybarr(rnode, index),
502 ("vm_radix_lookup_ge: keybarr failed"));
504 slot = vm_radix_slot(index, rnode->rn_clev);
505 child = rnode->rn_child[slot];
506 if (vm_radix_isleaf(child)) {
507 m = vm_radix_topage(child);
508 if (m->pindex >= index)
510 } else if (child != NULL)
514 * Look for an available edge or page within the current
517 if (slot < (VM_RADIX_COUNT - 1)) {
518 inc = VM_RADIX_UNITLEVEL(rnode->rn_clev);
519 index = vm_radix_trimkey(index, rnode->rn_clev);
523 child = rnode->rn_child[slot];
524 if (vm_radix_isleaf(child)) {
525 m = vm_radix_topage(child);
526 if (m->pindex >= index)
528 } else if (child != NULL)
530 } while (slot < (VM_RADIX_COUNT - 1));
532 KASSERT(child == NULL || vm_radix_isleaf(child),
533 ("vm_radix_lookup_ge: child is radix node"));
536 * If a page or edge bigger than the search slot is not found
537 * in the current node, ascend to the next higher-level node.
541 KASSERT(rnode->rn_clev > 0,
542 ("vm_radix_lookup_ge: pushing leaf's parent"));
543 KASSERT(tos < VM_RADIX_LIMIT,
544 ("vm_radix_lookup_ge: stack overflow"));
545 stack[tos++] = rnode;
551 * Look up the nearest entry at a position less than or equal to index.
554 vm_radix_lookup_le(struct vm_radix *rtree, vm_pindex_t index)
556 struct vm_radix_node *stack[VM_RADIX_LIMIT];
559 struct vm_radix_node *child, *rnode;
565 rnode = vm_radix_getroot(rtree);
568 else if (vm_radix_isleaf(rnode)) {
569 m = vm_radix_topage(rnode);
570 if (m->pindex <= index)
578 * If the keys differ before the current bisection node,
579 * then the search key might rollback to the earliest
580 * available bisection node or to the largest key
581 * in the current node (if the owner is smaller than the
584 if (vm_radix_keybarr(rnode, index)) {
585 if (index > rnode->rn_owner) {
586 index = rnode->rn_owner + VM_RADIX_COUNT *
587 VM_RADIX_UNITLEVEL(rnode->rn_clev);
590 KASSERT(++loops < 1000,
591 ("vm_radix_lookup_le: too many loops"));
594 * Pop nodes from the stack until either the
595 * stack is empty or a node that could have a
596 * matching descendant is found.
601 rnode = stack[--tos];
602 } while (vm_radix_slot(index,
603 rnode->rn_clev) == 0);
606 * The following computation cannot overflow
607 * because index's slot at the current level
610 index = vm_radix_trimkey(index,
614 KASSERT(!vm_radix_keybarr(rnode, index),
615 ("vm_radix_lookup_le: keybarr failed"));
617 slot = vm_radix_slot(index, rnode->rn_clev);
618 child = rnode->rn_child[slot];
619 if (vm_radix_isleaf(child)) {
620 m = vm_radix_topage(child);
621 if (m->pindex <= index)
623 } else if (child != NULL)
627 * Look for an available edge or page within the current
631 inc = VM_RADIX_UNITLEVEL(rnode->rn_clev);
636 child = rnode->rn_child[slot];
637 if (vm_radix_isleaf(child)) {
638 m = vm_radix_topage(child);
639 if (m->pindex <= index)
641 } else if (child != NULL)
645 KASSERT(child == NULL || vm_radix_isleaf(child),
646 ("vm_radix_lookup_le: child is radix node"));
649 * If a page or edge smaller than the search slot is not found
650 * in the current node, ascend to the next higher-level node.
654 KASSERT(rnode->rn_clev > 0,
655 ("vm_radix_lookup_le: pushing leaf's parent"));
656 KASSERT(tos < VM_RADIX_LIMIT,
657 ("vm_radix_lookup_le: stack overflow"));
658 stack[tos++] = rnode;
664 * Remove the specified index from the trie, and return the value stored at
665 * that index. If the index is not present, return NULL.
668 vm_radix_remove(struct vm_radix *rtree, vm_pindex_t index)
670 struct vm_radix_node *rnode, *parent;
674 rnode = vm_radix_getroot(rtree);
675 if (vm_radix_isleaf(rnode)) {
676 m = vm_radix_topage(rnode);
677 if (m->pindex != index)
679 vm_radix_setroot(rtree, NULL);
686 slot = vm_radix_slot(index, rnode->rn_clev);
687 if (vm_radix_isleaf(rnode->rn_child[slot])) {
688 m = vm_radix_topage(rnode->rn_child[slot]);
689 if (m->pindex != index)
691 rnode->rn_child[slot] = NULL;
693 if (rnode->rn_count > 1)
695 for (i = 0; i < VM_RADIX_COUNT; i++)
696 if (rnode->rn_child[i] != NULL)
698 KASSERT(i != VM_RADIX_COUNT,
699 ("%s: invalid node configuration", __func__));
701 vm_radix_setroot(rtree, rnode->rn_child[i]);
703 slot = vm_radix_slot(index, parent->rn_clev);
704 KASSERT(parent->rn_child[slot] == rnode,
705 ("%s: invalid child value", __func__));
706 parent->rn_child[slot] = rnode->rn_child[i];
709 rnode->rn_child[i] = NULL;
710 vm_radix_node_put(rnode);
714 rnode = rnode->rn_child[slot];
719 * Remove and free all the nodes from the radix tree.
720 * This function is recursive but there is a tight control on it as the
721 * maximum depth of the tree is fixed.
724 vm_radix_reclaim_allnodes(struct vm_radix *rtree)
726 struct vm_radix_node *root;
728 root = vm_radix_getroot(rtree);
731 vm_radix_setroot(rtree, NULL);
732 if (!vm_radix_isleaf(root))
733 vm_radix_reclaim_allnodes_int(root);
737 * Replace an existing page in the trie with another one.
738 * Panics if there is not an old page in the trie at the new page's index.
741 vm_radix_replace(struct vm_radix *rtree, vm_page_t newpage)
743 struct vm_radix_node *rnode;
748 index = newpage->pindex;
749 rnode = vm_radix_getroot(rtree);
751 panic("%s: replacing page on an empty trie", __func__);
752 if (vm_radix_isleaf(rnode)) {
753 m = vm_radix_topage(rnode);
754 if (m->pindex != index)
755 panic("%s: original replacing root key not found",
757 rtree->rt_root = (uintptr_t)newpage | VM_RADIX_ISLEAF;
761 slot = vm_radix_slot(index, rnode->rn_clev);
762 if (vm_radix_isleaf(rnode->rn_child[slot])) {
763 m = vm_radix_topage(rnode->rn_child[slot]);
764 if (m->pindex == index) {
765 rnode->rn_child[slot] =
766 (void *)((uintptr_t)newpage |
771 } else if (rnode->rn_child[slot] == NULL ||
772 vm_radix_keybarr(rnode->rn_child[slot], index))
774 rnode = rnode->rn_child[slot];
776 panic("%s: original replacing page not found", __func__);
782 uma_zwait(vm_radix_node_zone);
787 * Show details about the given radix node.
789 DB_SHOW_COMMAND(radixnode, db_show_radixnode)
791 struct vm_radix_node *rnode;
796 rnode = (struct vm_radix_node *)addr;
797 db_printf("radixnode %p, owner %jx, children count %u, level %u:\n",
798 (void *)rnode, (uintmax_t)rnode->rn_owner, rnode->rn_count,
800 for (i = 0; i < VM_RADIX_COUNT; i++)
801 if (rnode->rn_child[i] != NULL)
802 db_printf("slot: %d, val: %p, page: %p, clev: %d\n",
803 i, (void *)rnode->rn_child[i],
804 vm_radix_isleaf(rnode->rn_child[i]) ?
805 vm_radix_topage(rnode->rn_child[i]) : NULL,