2 * Copyright (C) 2001 Momchil Velikov
3 * Portions Copyright (C) 2001 Christoph Hellwig
4 * Copyright (C) 2005 SGI, Christoph Lameter
5 * Copyright (C) 2006 Nick Piggin
6 * Copyright (C) 2012 Konstantin Khlebnikov
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as
10 * published by the Free Software Foundation; either version 2, or (at
11 * your option) any later version.
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 #include <linux/errno.h>
24 #include <linux/init.h>
25 #include <linux/kernel.h>
26 #include <linux/export.h>
27 #include <linux/radix-tree.h>
28 #include <linux/percpu.h>
29 #include <linux/slab.h>
30 #include <linux/kmemleak.h>
31 #include <linux/notifier.h>
32 #include <linux/cpu.h>
33 #include <linux/string.h>
34 #include <linux/bitops.h>
35 #include <linux/rcupdate.h>
36 #include <linux/preempt_mask.h> /* in_interrupt() */
40 * The height_to_maxindex array needs to be one deeper than the maximum
41 * path as height 0 holds only 1 entry.
43 static unsigned long height_to_maxindex[RADIX_TREE_MAX_PATH + 1] __read_mostly;
46 * Radix tree node cache.
48 static struct kmem_cache *radix_tree_node_cachep;
51 * The radix tree is variable-height, so an insert operation not only has
52 * to build the branch to its corresponding item, it also has to build the
53 * branch to existing items if the size has to be increased (by
56 * The worst case is a zero height tree with just a single item at index 0,
57 * and then inserting an item at index ULONG_MAX. This requires 2 new branches
58 * of RADIX_TREE_MAX_PATH size to be created, with only the root node shared.
61 #define RADIX_TREE_PRELOAD_SIZE (RADIX_TREE_MAX_PATH * 2 - 1)
64 * Per-cpu pool of preloaded nodes
66 struct radix_tree_preload {
68 struct radix_tree_node *nodes[RADIX_TREE_PRELOAD_SIZE];
70 static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, };
72 static inline void *ptr_to_indirect(void *ptr)
74 return (void *)((unsigned long)ptr | RADIX_TREE_INDIRECT_PTR);
77 static inline void *indirect_to_ptr(void *ptr)
79 return (void *)((unsigned long)ptr & ~RADIX_TREE_INDIRECT_PTR);
82 static inline gfp_t root_gfp_mask(struct radix_tree_root *root)
84 return root->gfp_mask & __GFP_BITS_MASK;
87 static inline void tag_set(struct radix_tree_node *node, unsigned int tag,
90 __set_bit(offset, node->tags[tag]);
93 static inline void tag_clear(struct radix_tree_node *node, unsigned int tag,
96 __clear_bit(offset, node->tags[tag]);
99 static inline int tag_get(struct radix_tree_node *node, unsigned int tag,
102 return test_bit(offset, node->tags[tag]);
105 static inline void root_tag_set(struct radix_tree_root *root, unsigned int tag)
107 root->gfp_mask |= (__force gfp_t)(1 << (tag + __GFP_BITS_SHIFT));
110 static inline void root_tag_clear(struct radix_tree_root *root, unsigned int tag)
112 root->gfp_mask &= (__force gfp_t)~(1 << (tag + __GFP_BITS_SHIFT));
115 static inline void root_tag_clear_all(struct radix_tree_root *root)
117 root->gfp_mask &= __GFP_BITS_MASK;
120 static inline int root_tag_get(struct radix_tree_root *root, unsigned int tag)
122 return (__force unsigned)root->gfp_mask & (1 << (tag + __GFP_BITS_SHIFT));
126 * Returns 1 if any slot in the node has this tag set.
127 * Otherwise returns 0.
129 static inline int any_tag_set(struct radix_tree_node *node, unsigned int tag)
132 for (idx = 0; idx < RADIX_TREE_TAG_LONGS; idx++) {
133 if (node->tags[tag][idx])
140 * radix_tree_find_next_bit - find the next set bit in a memory region
142 * @addr: The address to base the search on
143 * @size: The bitmap size in bits
144 * @offset: The bitnumber to start searching at
146 * Unrollable variant of find_next_bit() for constant size arrays.
147 * Tail bits starting from size to roundup(size, BITS_PER_LONG) must be zero.
148 * Returns next bit offset, or size if nothing found.
150 static __always_inline unsigned long
151 radix_tree_find_next_bit(const unsigned long *addr,
152 unsigned long size, unsigned long offset)
154 if (!__builtin_constant_p(size))
155 return find_next_bit(addr, size, offset);
160 addr += offset / BITS_PER_LONG;
161 tmp = *addr >> (offset % BITS_PER_LONG);
163 return __ffs(tmp) + offset;
164 offset = (offset + BITS_PER_LONG) & ~(BITS_PER_LONG - 1);
165 while (offset < size) {
168 return __ffs(tmp) + offset;
169 offset += BITS_PER_LONG;
176 * This assumes that the caller has performed appropriate preallocation, and
177 * that the caller has pinned this thread of control to the current CPU.
179 static struct radix_tree_node *
180 radix_tree_node_alloc(struct radix_tree_root *root)
182 struct radix_tree_node *ret = NULL;
183 gfp_t gfp_mask = root_gfp_mask(root);
186 * Preload code isn't irq safe and it doesn't make sence to use
187 * preloading in the interrupt anyway as all the allocations have to
188 * be atomic. So just do normal allocation when in interrupt.
190 if (!(gfp_mask & __GFP_WAIT) && !in_interrupt()) {
191 struct radix_tree_preload *rtp;
194 * Provided the caller has preloaded here, we will always
195 * succeed in getting a node here (and never reach
198 rtp = &get_cpu_var(radix_tree_preloads);
200 ret = rtp->nodes[rtp->nr - 1];
201 rtp->nodes[rtp->nr - 1] = NULL;
204 put_cpu_var(radix_tree_preloads);
206 * Update the allocation stack trace as this is more useful
209 kmemleak_update_trace(ret);
212 ret = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
214 BUG_ON(radix_tree_is_indirect_ptr(ret));
218 static void radix_tree_node_rcu_free(struct rcu_head *head)
220 struct radix_tree_node *node =
221 container_of(head, struct radix_tree_node, rcu_head);
225 * must only free zeroed nodes into the slab. radix_tree_shrink
226 * can leave us with a non-NULL entry in the first slot, so clear
227 * that here to make sure.
229 for (i = 0; i < RADIX_TREE_MAX_TAGS; i++)
230 tag_clear(node, i, 0);
232 node->slots[0] = NULL;
235 kmem_cache_free(radix_tree_node_cachep, node);
239 radix_tree_node_free(struct radix_tree_node *node)
241 call_rcu(&node->rcu_head, radix_tree_node_rcu_free);
244 #ifndef CONFIG_PREEMPT_RT_FULL
246 * Load up this CPU's radix_tree_node buffer with sufficient objects to
247 * ensure that the addition of a single element in the tree cannot fail. On
248 * success, return zero, with preemption disabled. On error, return -ENOMEM
249 * with preemption not disabled.
251 * To make use of this facility, the radix tree must be initialised without
252 * __GFP_WAIT being passed to INIT_RADIX_TREE().
254 static int __radix_tree_preload(gfp_t gfp_mask)
256 struct radix_tree_preload *rtp;
257 struct radix_tree_node *node;
261 rtp = this_cpu_ptr(&radix_tree_preloads);
262 while (rtp->nr < ARRAY_SIZE(rtp->nodes)) {
264 node = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
268 rtp = this_cpu_ptr(&radix_tree_preloads);
269 if (rtp->nr < ARRAY_SIZE(rtp->nodes))
270 rtp->nodes[rtp->nr++] = node;
272 kmem_cache_free(radix_tree_node_cachep, node);
280 * Load up this CPU's radix_tree_node buffer with sufficient objects to
281 * ensure that the addition of a single element in the tree cannot fail. On
282 * success, return zero, with preemption disabled. On error, return -ENOMEM
283 * with preemption not disabled.
285 * To make use of this facility, the radix tree must be initialised without
286 * __GFP_WAIT being passed to INIT_RADIX_TREE().
288 int radix_tree_preload(gfp_t gfp_mask)
290 /* Warn on non-sensical use... */
291 WARN_ON_ONCE(!(gfp_mask & __GFP_WAIT));
292 return __radix_tree_preload(gfp_mask);
294 EXPORT_SYMBOL(radix_tree_preload);
297 * The same as above function, except we don't guarantee preloading happens.
298 * We do it, if we decide it helps. On success, return zero with preemption
299 * disabled. On error, return -ENOMEM with preemption not disabled.
301 int radix_tree_maybe_preload(gfp_t gfp_mask)
303 if (gfp_mask & __GFP_WAIT)
304 return __radix_tree_preload(gfp_mask);
305 /* Preloading doesn't help anything with this gfp mask, skip it */
309 EXPORT_SYMBOL(radix_tree_maybe_preload);
313 * Return the maximum key which can be store into a
314 * radix tree with height HEIGHT.
316 static inline unsigned long radix_tree_maxindex(unsigned int height)
318 return height_to_maxindex[height];
322 * Extend a radix tree so it can store key @index.
324 static int radix_tree_extend(struct radix_tree_root *root, unsigned long index)
326 struct radix_tree_node *node;
327 struct radix_tree_node *slot;
331 /* Figure out what the height should be. */
332 height = root->height + 1;
333 while (index > radix_tree_maxindex(height))
336 if (root->rnode == NULL) {
337 root->height = height;
342 unsigned int newheight;
343 if (!(node = radix_tree_node_alloc(root)))
346 /* Propagate the aggregated tag info into the new root */
347 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
348 if (root_tag_get(root, tag))
349 tag_set(node, tag, 0);
352 /* Increase the height. */
353 newheight = root->height+1;
354 BUG_ON(newheight & ~RADIX_TREE_HEIGHT_MASK);
355 node->path = newheight;
360 slot = indirect_to_ptr(slot);
363 node->slots[0] = slot;
364 node = ptr_to_indirect(node);
365 rcu_assign_pointer(root->rnode, node);
366 root->height = newheight;
367 } while (height > root->height);
373 * __radix_tree_create - create a slot in a radix tree
374 * @root: radix tree root
376 * @nodep: returns node
377 * @slotp: returns slot
379 * Create, if necessary, and return the node and slot for an item
380 * at position @index in the radix tree @root.
382 * Until there is more than one item in the tree, no nodes are
383 * allocated and @root->rnode is used as a direct slot instead of
384 * pointing to a node, in which case *@nodep will be NULL.
386 * Returns -ENOMEM, or 0 for success.
388 int __radix_tree_create(struct radix_tree_root *root, unsigned long index,
389 struct radix_tree_node **nodep, void ***slotp)
391 struct radix_tree_node *node = NULL, *slot;
392 unsigned int height, shift, offset;
395 /* Make sure the tree is high enough. */
396 if (index > radix_tree_maxindex(root->height)) {
397 error = radix_tree_extend(root, index);
402 slot = indirect_to_ptr(root->rnode);
404 height = root->height;
405 shift = (height-1) * RADIX_TREE_MAP_SHIFT;
407 offset = 0; /* uninitialised var warning */
410 /* Have to add a child node. */
411 if (!(slot = radix_tree_node_alloc(root)))
416 rcu_assign_pointer(node->slots[offset], slot);
418 slot->path |= offset << RADIX_TREE_HEIGHT_SHIFT;
420 rcu_assign_pointer(root->rnode, ptr_to_indirect(slot));
423 /* Go a level down */
424 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
426 slot = node->slots[offset];
427 shift -= RADIX_TREE_MAP_SHIFT;
434 *slotp = node ? node->slots + offset : (void **)&root->rnode;
439 * radix_tree_insert - insert into a radix tree
440 * @root: radix tree root
442 * @item: item to insert
444 * Insert an item into the radix tree at position @index.
446 int radix_tree_insert(struct radix_tree_root *root,
447 unsigned long index, void *item)
449 struct radix_tree_node *node;
453 BUG_ON(radix_tree_is_indirect_ptr(item));
455 error = __radix_tree_create(root, index, &node, &slot);
460 rcu_assign_pointer(*slot, item);
464 BUG_ON(tag_get(node, 0, index & RADIX_TREE_MAP_MASK));
465 BUG_ON(tag_get(node, 1, index & RADIX_TREE_MAP_MASK));
467 BUG_ON(root_tag_get(root, 0));
468 BUG_ON(root_tag_get(root, 1));
473 EXPORT_SYMBOL(radix_tree_insert);
476 * __radix_tree_lookup - lookup an item in a radix tree
477 * @root: radix tree root
479 * @nodep: returns node
480 * @slotp: returns slot
482 * Lookup and return the item at position @index in the radix
485 * Until there is more than one item in the tree, no nodes are
486 * allocated and @root->rnode is used as a direct slot instead of
487 * pointing to a node, in which case *@nodep will be NULL.
489 void *__radix_tree_lookup(struct radix_tree_root *root, unsigned long index,
490 struct radix_tree_node **nodep, void ***slotp)
492 struct radix_tree_node *node, *parent;
493 unsigned int height, shift;
496 node = rcu_dereference_raw(root->rnode);
500 if (!radix_tree_is_indirect_ptr(node)) {
507 *slotp = (void **)&root->rnode;
510 node = indirect_to_ptr(node);
512 height = node->path & RADIX_TREE_HEIGHT_MASK;
513 if (index > radix_tree_maxindex(height))
516 shift = (height-1) * RADIX_TREE_MAP_SHIFT;
520 slot = node->slots + ((index >> shift) & RADIX_TREE_MAP_MASK);
521 node = rcu_dereference_raw(*slot);
525 shift -= RADIX_TREE_MAP_SHIFT;
527 } while (height > 0);
537 * radix_tree_lookup_slot - lookup a slot in a radix tree
538 * @root: radix tree root
541 * Returns: the slot corresponding to the position @index in the
542 * radix tree @root. This is useful for update-if-exists operations.
544 * This function can be called under rcu_read_lock iff the slot is not
545 * modified by radix_tree_replace_slot, otherwise it must be called
546 * exclusive from other writers. Any dereference of the slot must be done
547 * using radix_tree_deref_slot.
549 void **radix_tree_lookup_slot(struct radix_tree_root *root, unsigned long index)
553 if (!__radix_tree_lookup(root, index, NULL, &slot))
557 EXPORT_SYMBOL(radix_tree_lookup_slot);
560 * radix_tree_lookup - perform lookup operation on a radix tree
561 * @root: radix tree root
564 * Lookup the item at the position @index in the radix tree @root.
566 * This function can be called under rcu_read_lock, however the caller
567 * must manage lifetimes of leaf nodes (eg. RCU may also be used to free
568 * them safely). No RCU barriers are required to access or modify the
569 * returned item, however.
571 void *radix_tree_lookup(struct radix_tree_root *root, unsigned long index)
573 return __radix_tree_lookup(root, index, NULL, NULL);
575 EXPORT_SYMBOL(radix_tree_lookup);
578 * radix_tree_tag_set - set a tag on a radix tree node
579 * @root: radix tree root
583 * Set the search tag (which must be < RADIX_TREE_MAX_TAGS)
584 * corresponding to @index in the radix tree. From
585 * the root all the way down to the leaf node.
587 * Returns the address of the tagged item. Setting a tag on a not-present
590 void *radix_tree_tag_set(struct radix_tree_root *root,
591 unsigned long index, unsigned int tag)
593 unsigned int height, shift;
594 struct radix_tree_node *slot;
596 height = root->height;
597 BUG_ON(index > radix_tree_maxindex(height));
599 slot = indirect_to_ptr(root->rnode);
600 shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
605 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
606 if (!tag_get(slot, tag, offset))
607 tag_set(slot, tag, offset);
608 slot = slot->slots[offset];
609 BUG_ON(slot == NULL);
610 shift -= RADIX_TREE_MAP_SHIFT;
614 /* set the root's tag bit */
615 if (slot && !root_tag_get(root, tag))
616 root_tag_set(root, tag);
620 EXPORT_SYMBOL(radix_tree_tag_set);
623 * radix_tree_tag_clear - clear a tag on a radix tree node
624 * @root: radix tree root
628 * Clear the search tag (which must be < RADIX_TREE_MAX_TAGS)
629 * corresponding to @index in the radix tree. If
630 * this causes the leaf node to have no tags set then clear the tag in the
631 * next-to-leaf node, etc.
633 * Returns the address of the tagged item on success, else NULL. ie:
634 * has the same return value and semantics as radix_tree_lookup().
636 void *radix_tree_tag_clear(struct radix_tree_root *root,
637 unsigned long index, unsigned int tag)
639 struct radix_tree_node *node = NULL;
640 struct radix_tree_node *slot = NULL;
641 unsigned int height, shift;
642 int uninitialized_var(offset);
644 height = root->height;
645 if (index > radix_tree_maxindex(height))
648 shift = height * RADIX_TREE_MAP_SHIFT;
649 slot = indirect_to_ptr(root->rnode);
655 shift -= RADIX_TREE_MAP_SHIFT;
656 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
658 slot = slot->slots[offset];
665 if (!tag_get(node, tag, offset))
667 tag_clear(node, tag, offset);
668 if (any_tag_set(node, tag))
671 index >>= RADIX_TREE_MAP_SHIFT;
672 offset = index & RADIX_TREE_MAP_MASK;
676 /* clear the root's tag bit */
677 if (root_tag_get(root, tag))
678 root_tag_clear(root, tag);
683 EXPORT_SYMBOL(radix_tree_tag_clear);
686 * radix_tree_tag_get - get a tag on a radix tree node
687 * @root: radix tree root
689 * @tag: tag index (< RADIX_TREE_MAX_TAGS)
693 * 0: tag not present or not set
696 * Note that the return value of this function may not be relied on, even if
697 * the RCU lock is held, unless tag modification and node deletion are excluded
700 int radix_tree_tag_get(struct radix_tree_root *root,
701 unsigned long index, unsigned int tag)
703 unsigned int height, shift;
704 struct radix_tree_node *node;
706 /* check the root's tag bit */
707 if (!root_tag_get(root, tag))
710 node = rcu_dereference_raw(root->rnode);
714 if (!radix_tree_is_indirect_ptr(node))
716 node = indirect_to_ptr(node);
718 height = node->path & RADIX_TREE_HEIGHT_MASK;
719 if (index > radix_tree_maxindex(height))
722 shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
730 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
731 if (!tag_get(node, tag, offset))
735 node = rcu_dereference_raw(node->slots[offset]);
736 shift -= RADIX_TREE_MAP_SHIFT;
740 EXPORT_SYMBOL(radix_tree_tag_get);
743 * radix_tree_next_chunk - find next chunk of slots for iteration
745 * @root: radix tree root
746 * @iter: iterator state
747 * @flags: RADIX_TREE_ITER_* flags and tag index
748 * Returns: pointer to chunk first slot, or NULL if iteration is over
750 void **radix_tree_next_chunk(struct radix_tree_root *root,
751 struct radix_tree_iter *iter, unsigned flags)
753 unsigned shift, tag = flags & RADIX_TREE_ITER_TAG_MASK;
754 struct radix_tree_node *rnode, *node;
755 unsigned long index, offset, height;
757 if ((flags & RADIX_TREE_ITER_TAGGED) && !root_tag_get(root, tag))
761 * Catch next_index overflow after ~0UL. iter->index never overflows
762 * during iterating; it can be zero only at the beginning.
763 * And we cannot overflow iter->next_index in a single step,
764 * because RADIX_TREE_MAP_SHIFT < BITS_PER_LONG.
766 * This condition also used by radix_tree_next_slot() to stop
767 * contiguous iterating, and forbid swithing to the next chunk.
769 index = iter->next_index;
770 if (!index && iter->index)
773 rnode = rcu_dereference_raw(root->rnode);
774 if (radix_tree_is_indirect_ptr(rnode)) {
775 rnode = indirect_to_ptr(rnode);
776 } else if (rnode && !index) {
777 /* Single-slot tree */
779 iter->next_index = 1;
781 return (void **)&root->rnode;
786 height = rnode->path & RADIX_TREE_HEIGHT_MASK;
787 shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
788 offset = index >> shift;
790 /* Index outside of the tree */
791 if (offset >= RADIX_TREE_MAP_SIZE)
796 if ((flags & RADIX_TREE_ITER_TAGGED) ?
797 !test_bit(offset, node->tags[tag]) :
798 !node->slots[offset]) {
800 if (flags & RADIX_TREE_ITER_CONTIG)
803 if (flags & RADIX_TREE_ITER_TAGGED)
804 offset = radix_tree_find_next_bit(
809 while (++offset < RADIX_TREE_MAP_SIZE) {
810 if (node->slots[offset])
813 index &= ~((RADIX_TREE_MAP_SIZE << shift) - 1);
814 index += offset << shift;
815 /* Overflow after ~0UL */
818 if (offset == RADIX_TREE_MAP_SIZE)
822 /* This is leaf-node */
826 node = rcu_dereference_raw(node->slots[offset]);
829 shift -= RADIX_TREE_MAP_SHIFT;
830 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
833 /* Update the iterator state */
835 iter->next_index = (index | RADIX_TREE_MAP_MASK) + 1;
837 /* Construct iter->tags bit-mask from node->tags[tag] array */
838 if (flags & RADIX_TREE_ITER_TAGGED) {
839 unsigned tag_long, tag_bit;
841 tag_long = offset / BITS_PER_LONG;
842 tag_bit = offset % BITS_PER_LONG;
843 iter->tags = node->tags[tag][tag_long] >> tag_bit;
844 /* This never happens if RADIX_TREE_TAG_LONGS == 1 */
845 if (tag_long < RADIX_TREE_TAG_LONGS - 1) {
846 /* Pick tags from next element */
848 iter->tags |= node->tags[tag][tag_long + 1] <<
849 (BITS_PER_LONG - tag_bit);
850 /* Clip chunk size, here only BITS_PER_LONG tags */
851 iter->next_index = index + BITS_PER_LONG;
855 return node->slots + offset;
857 EXPORT_SYMBOL(radix_tree_next_chunk);
860 * radix_tree_range_tag_if_tagged - for each item in given range set given
861 * tag if item has another tag set
862 * @root: radix tree root
863 * @first_indexp: pointer to a starting index of a range to scan
864 * @last_index: last index of a range to scan
865 * @nr_to_tag: maximum number items to tag
866 * @iftag: tag index to test
867 * @settag: tag index to set if tested tag is set
869 * This function scans range of radix tree from first_index to last_index
870 * (inclusive). For each item in the range if iftag is set, the function sets
871 * also settag. The function stops either after tagging nr_to_tag items or
872 * after reaching last_index.
874 * The tags must be set from the leaf level only and propagated back up the
875 * path to the root. We must do this so that we resolve the full path before
876 * setting any tags on intermediate nodes. If we set tags as we descend, then
877 * we can get to the leaf node and find that the index that has the iftag
878 * set is outside the range we are scanning. This reults in dangling tags and
879 * can lead to problems with later tag operations (e.g. livelocks on lookups).
881 * The function returns number of leaves where the tag was set and sets
882 * *first_indexp to the first unscanned index.
883 * WARNING! *first_indexp can wrap if last_index is ULONG_MAX. Caller must
884 * be prepared to handle that.
886 unsigned long radix_tree_range_tag_if_tagged(struct radix_tree_root *root,
887 unsigned long *first_indexp, unsigned long last_index,
888 unsigned long nr_to_tag,
889 unsigned int iftag, unsigned int settag)
891 unsigned int height = root->height;
892 struct radix_tree_node *node = NULL;
893 struct radix_tree_node *slot;
895 unsigned long tagged = 0;
896 unsigned long index = *first_indexp;
898 last_index = min(last_index, radix_tree_maxindex(height));
899 if (index > last_index)
903 if (!root_tag_get(root, iftag)) {
904 *first_indexp = last_index + 1;
908 *first_indexp = last_index + 1;
909 root_tag_set(root, settag);
913 shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
914 slot = indirect_to_ptr(root->rnode);
917 unsigned long upindex;
920 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
921 if (!slot->slots[offset])
923 if (!tag_get(slot, iftag, offset))
926 /* Go down one level */
927 shift -= RADIX_TREE_MAP_SHIFT;
929 slot = slot->slots[offset];
935 tag_set(slot, settag, offset);
937 /* walk back up the path tagging interior nodes */
940 upindex >>= RADIX_TREE_MAP_SHIFT;
941 offset = upindex & RADIX_TREE_MAP_MASK;
943 /* stop if we find a node with the tag already set */
944 if (tag_get(node, settag, offset))
946 tag_set(node, settag, offset);
951 * Small optimization: now clear that node pointer.
952 * Since all of this slot's ancestors now have the tag set
953 * from setting it above, we have no further need to walk
954 * back up the tree setting tags, until we update slot to
955 * point to another radix_tree_node.
960 /* Go to next item at level determined by 'shift' */
961 index = ((index >> shift) + 1) << shift;
962 /* Overflow can happen when last_index is ~0UL... */
963 if (index > last_index || !index)
965 if (tagged >= nr_to_tag)
967 while (((index >> shift) & RADIX_TREE_MAP_MASK) == 0) {
969 * We've fully scanned this node. Go up. Because
970 * last_index is guaranteed to be in the tree, what
971 * we do below cannot wander astray.
974 shift += RADIX_TREE_MAP_SHIFT;
978 * We need not to tag the root tag if there is no tag which is set with
979 * settag within the range from *first_indexp to last_index.
982 root_tag_set(root, settag);
983 *first_indexp = index;
987 EXPORT_SYMBOL(radix_tree_range_tag_if_tagged);
990 * radix_tree_gang_lookup - perform multiple lookup on a radix tree
991 * @root: radix tree root
992 * @results: where the results of the lookup are placed
993 * @first_index: start the lookup from this key
994 * @max_items: place up to this many items at *results
996 * Performs an index-ascending scan of the tree for present items. Places
997 * them at *@results and returns the number of items which were placed at
1000 * The implementation is naive.
1002 * Like radix_tree_lookup, radix_tree_gang_lookup may be called under
1003 * rcu_read_lock. In this case, rather than the returned results being
1004 * an atomic snapshot of the tree at a single point in time, the semantics
1005 * of an RCU protected gang lookup are as though multiple radix_tree_lookups
1006 * have been issued in individual locks, and results stored in 'results'.
1009 radix_tree_gang_lookup(struct radix_tree_root *root, void **results,
1010 unsigned long first_index, unsigned int max_items)
1012 struct radix_tree_iter iter;
1014 unsigned int ret = 0;
1016 if (unlikely(!max_items))
1019 radix_tree_for_each_slot(slot, root, &iter, first_index) {
1020 results[ret] = indirect_to_ptr(rcu_dereference_raw(*slot));
1023 if (++ret == max_items)
1029 EXPORT_SYMBOL(radix_tree_gang_lookup);
1032 * radix_tree_gang_lookup_slot - perform multiple slot lookup on radix tree
1033 * @root: radix tree root
1034 * @results: where the results of the lookup are placed
1035 * @indices: where their indices should be placed (but usually NULL)
1036 * @first_index: start the lookup from this key
1037 * @max_items: place up to this many items at *results
1039 * Performs an index-ascending scan of the tree for present items. Places
1040 * their slots at *@results and returns the number of items which were
1041 * placed at *@results.
1043 * The implementation is naive.
1045 * Like radix_tree_gang_lookup as far as RCU and locking goes. Slots must
1046 * be dereferenced with radix_tree_deref_slot, and if using only RCU
1047 * protection, radix_tree_deref_slot may fail requiring a retry.
1050 radix_tree_gang_lookup_slot(struct radix_tree_root *root,
1051 void ***results, unsigned long *indices,
1052 unsigned long first_index, unsigned int max_items)
1054 struct radix_tree_iter iter;
1056 unsigned int ret = 0;
1058 if (unlikely(!max_items))
1061 radix_tree_for_each_slot(slot, root, &iter, first_index) {
1062 results[ret] = slot;
1064 indices[ret] = iter.index;
1065 if (++ret == max_items)
1071 EXPORT_SYMBOL(radix_tree_gang_lookup_slot);
1074 * radix_tree_gang_lookup_tag - perform multiple lookup on a radix tree
1076 * @root: radix tree root
1077 * @results: where the results of the lookup are placed
1078 * @first_index: start the lookup from this key
1079 * @max_items: place up to this many items at *results
1080 * @tag: the tag index (< RADIX_TREE_MAX_TAGS)
1082 * Performs an index-ascending scan of the tree for present items which
1083 * have the tag indexed by @tag set. Places the items at *@results and
1084 * returns the number of items which were placed at *@results.
1087 radix_tree_gang_lookup_tag(struct radix_tree_root *root, void **results,
1088 unsigned long first_index, unsigned int max_items,
1091 struct radix_tree_iter iter;
1093 unsigned int ret = 0;
1095 if (unlikely(!max_items))
1098 radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
1099 results[ret] = indirect_to_ptr(rcu_dereference_raw(*slot));
1102 if (++ret == max_items)
1108 EXPORT_SYMBOL(radix_tree_gang_lookup_tag);
1111 * radix_tree_gang_lookup_tag_slot - perform multiple slot lookup on a
1112 * radix tree based on a tag
1113 * @root: radix tree root
1114 * @results: where the results of the lookup are placed
1115 * @first_index: start the lookup from this key
1116 * @max_items: place up to this many items at *results
1117 * @tag: the tag index (< RADIX_TREE_MAX_TAGS)
1119 * Performs an index-ascending scan of the tree for present items which
1120 * have the tag indexed by @tag set. Places the slots at *@results and
1121 * returns the number of slots which were placed at *@results.
1124 radix_tree_gang_lookup_tag_slot(struct radix_tree_root *root, void ***results,
1125 unsigned long first_index, unsigned int max_items,
1128 struct radix_tree_iter iter;
1130 unsigned int ret = 0;
1132 if (unlikely(!max_items))
1135 radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
1136 results[ret] = slot;
1137 if (++ret == max_items)
1143 EXPORT_SYMBOL(radix_tree_gang_lookup_tag_slot);
1145 #if defined(CONFIG_SHMEM) && defined(CONFIG_SWAP)
1146 #include <linux/sched.h> /* for cond_resched() */
1149 * This linear search is at present only useful to shmem_unuse_inode().
1151 static unsigned long __locate(struct radix_tree_node *slot, void *item,
1152 unsigned long index, unsigned long *found_index)
1154 unsigned int shift, height;
1157 height = slot->path & RADIX_TREE_HEIGHT_MASK;
1158 shift = (height-1) * RADIX_TREE_MAP_SHIFT;
1160 for ( ; height > 1; height--) {
1161 i = (index >> shift) & RADIX_TREE_MAP_MASK;
1163 if (slot->slots[i] != NULL)
1165 index &= ~((1UL << shift) - 1);
1166 index += 1UL << shift;
1168 goto out; /* 32-bit wraparound */
1170 if (i == RADIX_TREE_MAP_SIZE)
1174 shift -= RADIX_TREE_MAP_SHIFT;
1175 slot = rcu_dereference_raw(slot->slots[i]);
1180 /* Bottom level: check items */
1181 for (i = 0; i < RADIX_TREE_MAP_SIZE; i++) {
1182 if (slot->slots[i] == item) {
1183 *found_index = index + i;
1188 index += RADIX_TREE_MAP_SIZE;
1194 * radix_tree_locate_item - search through radix tree for item
1195 * @root: radix tree root
1196 * @item: item to be found
1198 * Returns index where item was found, or -1 if not found.
1199 * Caller must hold no lock (since this time-consuming function needs
1200 * to be preemptible), and must check afterwards if item is still there.
1202 unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
1204 struct radix_tree_node *node;
1205 unsigned long max_index;
1206 unsigned long cur_index = 0;
1207 unsigned long found_index = -1;
1211 node = rcu_dereference_raw(root->rnode);
1212 if (!radix_tree_is_indirect_ptr(node)) {
1219 node = indirect_to_ptr(node);
1220 max_index = radix_tree_maxindex(node->path &
1221 RADIX_TREE_HEIGHT_MASK);
1222 if (cur_index > max_index) {
1227 cur_index = __locate(node, item, cur_index, &found_index);
1230 } while (cur_index != 0 && cur_index <= max_index);
1235 unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
1239 #endif /* CONFIG_SHMEM && CONFIG_SWAP */
1242 * radix_tree_shrink - shrink height of a radix tree to minimal
1243 * @root radix tree root
1245 static inline void radix_tree_shrink(struct radix_tree_root *root)
1247 /* try to shrink tree height */
1248 while (root->height > 0) {
1249 struct radix_tree_node *to_free = root->rnode;
1250 struct radix_tree_node *slot;
1252 BUG_ON(!radix_tree_is_indirect_ptr(to_free));
1253 to_free = indirect_to_ptr(to_free);
1256 * The candidate node has more than one child, or its child
1257 * is not at the leftmost slot, we cannot shrink.
1259 if (to_free->count != 1)
1261 if (!to_free->slots[0])
1265 * We don't need rcu_assign_pointer(), since we are simply
1266 * moving the node from one part of the tree to another: if it
1267 * was safe to dereference the old pointer to it
1268 * (to_free->slots[0]), it will be safe to dereference the new
1269 * one (root->rnode) as far as dependent read barriers go.
1271 slot = to_free->slots[0];
1272 if (root->height > 1) {
1273 slot->parent = NULL;
1274 slot = ptr_to_indirect(slot);
1280 * We have a dilemma here. The node's slot[0] must not be
1281 * NULLed in case there are concurrent lookups expecting to
1282 * find the item. However if this was a bottom-level node,
1283 * then it may be subject to the slot pointer being visible
1284 * to callers dereferencing it. If item corresponding to
1285 * slot[0] is subsequently deleted, these callers would expect
1286 * their slot to become empty sooner or later.
1288 * For example, lockless pagecache will look up a slot, deref
1289 * the page pointer, and if the page is 0 refcount it means it
1290 * was concurrently deleted from pagecache so try the deref
1291 * again. Fortunately there is already a requirement for logic
1292 * to retry the entire slot lookup -- the indirect pointer
1293 * problem (replacing direct root node with an indirect pointer
1294 * also results in a stale slot). So tag the slot as indirect
1295 * to force callers to retry.
1297 if (root->height == 0)
1298 *((unsigned long *)&to_free->slots[0]) |=
1299 RADIX_TREE_INDIRECT_PTR;
1301 radix_tree_node_free(to_free);
1306 * __radix_tree_delete_node - try to free node after clearing a slot
1307 * @root: radix tree root
1308 * @node: node containing @index
1310 * After clearing the slot at @index in @node from radix tree
1311 * rooted at @root, call this function to attempt freeing the
1312 * node and shrinking the tree.
1314 * Returns %true if @node was freed, %false otherwise.
1316 bool __radix_tree_delete_node(struct radix_tree_root *root,
1317 struct radix_tree_node *node)
1319 bool deleted = false;
1322 struct radix_tree_node *parent;
1325 if (node == indirect_to_ptr(root->rnode)) {
1326 radix_tree_shrink(root);
1327 if (root->height == 0)
1333 parent = node->parent;
1335 unsigned int offset;
1337 offset = node->path >> RADIX_TREE_HEIGHT_SHIFT;
1338 parent->slots[offset] = NULL;
1341 root_tag_clear_all(root);
1346 radix_tree_node_free(node);
1356 * radix_tree_delete_item - delete an item from a radix tree
1357 * @root: radix tree root
1359 * @item: expected item
1361 * Remove @item at @index from the radix tree rooted at @root.
1363 * Returns the address of the deleted item, or NULL if it was not present
1364 * or the entry at the given @index was not @item.
1366 void *radix_tree_delete_item(struct radix_tree_root *root,
1367 unsigned long index, void *item)
1369 struct radix_tree_node *node;
1370 unsigned int offset;
1375 entry = __radix_tree_lookup(root, index, &node, &slot);
1379 if (item && entry != item)
1383 root_tag_clear_all(root);
1388 offset = index & RADIX_TREE_MAP_MASK;
1391 * Clear all tags associated with the item to be deleted.
1392 * This way of doing it would be inefficient, but seldom is any set.
1394 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
1395 if (tag_get(node, tag, offset))
1396 radix_tree_tag_clear(root, index, tag);
1399 node->slots[offset] = NULL;
1402 __radix_tree_delete_node(root, node);
1406 EXPORT_SYMBOL(radix_tree_delete_item);
1409 * radix_tree_delete - delete an item from a radix tree
1410 * @root: radix tree root
1413 * Remove the item at @index from the radix tree rooted at @root.
1415 * Returns the address of the deleted item, or NULL if it was not present.
1417 void *radix_tree_delete(struct radix_tree_root *root, unsigned long index)
1419 return radix_tree_delete_item(root, index, NULL);
1421 EXPORT_SYMBOL(radix_tree_delete);
1424 * radix_tree_tagged - test whether any items in the tree are tagged
1425 * @root: radix tree root
1428 int radix_tree_tagged(struct radix_tree_root *root, unsigned int tag)
1430 return root_tag_get(root, tag);
1432 EXPORT_SYMBOL(radix_tree_tagged);
1435 radix_tree_node_ctor(void *arg)
1437 struct radix_tree_node *node = arg;
1439 memset(node, 0, sizeof(*node));
1440 INIT_LIST_HEAD(&node->private_list);
1443 static __init unsigned long __maxindex(unsigned int height)
1445 unsigned int width = height * RADIX_TREE_MAP_SHIFT;
1446 int shift = RADIX_TREE_INDEX_BITS - width;
1450 if (shift >= BITS_PER_LONG)
1452 return ~0UL >> shift;
1455 static __init void radix_tree_init_maxindex(void)
1459 for (i = 0; i < ARRAY_SIZE(height_to_maxindex); i++)
1460 height_to_maxindex[i] = __maxindex(i);
1463 static int radix_tree_callback(struct notifier_block *nfb,
1464 unsigned long action,
1467 int cpu = (long)hcpu;
1468 struct radix_tree_preload *rtp;
1470 /* Free per-cpu pool of perloaded nodes */
1471 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
1472 rtp = &per_cpu(radix_tree_preloads, cpu);
1474 kmem_cache_free(radix_tree_node_cachep,
1475 rtp->nodes[rtp->nr-1]);
1476 rtp->nodes[rtp->nr-1] = NULL;
1483 void __init radix_tree_init(void)
1485 radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
1486 sizeof(struct radix_tree_node), 0,
1487 SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
1488 radix_tree_node_ctor);
1489 radix_tree_init_maxindex();
1490 hotcpu_notifier(radix_tree_callback, 0);