blob: 52ebdb19f8af92e051f1ddda7194c3cd00be9b03 [file] [log] [blame]
yuezonghe824eb0c2024-06-27 02:32:26 -07001/*
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
7 *
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.
12 *
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.
17 *
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.
21 */
22
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/notifier.h>
31#include <linux/cpu.h>
32#include <linux/string.h>
33#include <linux/bitops.h>
34#include <linux/rcupdate.h>
35
36
37#ifdef __KERNEL__
38#define RADIX_TREE_MAP_SHIFT (CONFIG_BASE_SMALL ? 4 : 6)
39#else
40#define RADIX_TREE_MAP_SHIFT 3 /* For more stressful testing */
41#endif
42
43#define RADIX_TREE_MAP_SIZE (1UL << RADIX_TREE_MAP_SHIFT)
44#define RADIX_TREE_MAP_MASK (RADIX_TREE_MAP_SIZE-1)
45
46#define RADIX_TREE_TAG_LONGS \
47 ((RADIX_TREE_MAP_SIZE + BITS_PER_LONG - 1) / BITS_PER_LONG)
48
49struct radix_tree_node {
50 unsigned int height; /* Height from the bottom */
51 unsigned int count;
52 union {
53 struct radix_tree_node *parent; /* Used when ascending tree */
54 struct rcu_head rcu_head; /* Used when freeing node */
55 };
56 void __rcu *slots[RADIX_TREE_MAP_SIZE];
57 unsigned long tags[RADIX_TREE_MAX_TAGS][RADIX_TREE_TAG_LONGS];
58};
59
60#define RADIX_TREE_INDEX_BITS (8 /* CHAR_BIT */ * sizeof(unsigned long))
61#define RADIX_TREE_MAX_PATH (DIV_ROUND_UP(RADIX_TREE_INDEX_BITS, \
62 RADIX_TREE_MAP_SHIFT))
63
64/*
65 * The height_to_maxindex array needs to be one deeper than the maximum
66 * path as height 0 holds only 1 entry.
67 */
68static unsigned long height_to_maxindex[RADIX_TREE_MAX_PATH + 1] __read_mostly;
69
70/*
71 * Radix tree node cache.
72 */
73static struct kmem_cache *radix_tree_node_cachep;
74
75/*
76 * Per-cpu pool of preloaded nodes
77 */
78struct radix_tree_preload {
79 int nr;
80 struct radix_tree_node *nodes[RADIX_TREE_MAX_PATH];
81};
82static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, };
83
84static inline void *ptr_to_indirect(void *ptr)
85{
86 return (void *)((unsigned long)ptr | RADIX_TREE_INDIRECT_PTR);
87}
88
89static inline void *indirect_to_ptr(void *ptr)
90{
91 return (void *)((unsigned long)ptr & ~RADIX_TREE_INDIRECT_PTR);
92}
93
94static inline gfp_t root_gfp_mask(struct radix_tree_root *root)
95{
96 return root->gfp_mask & __GFP_BITS_MASK;
97}
98
99static inline void tag_set(struct radix_tree_node *node, unsigned int tag,
100 int offset)
101{
102 __set_bit(offset, node->tags[tag]);
103}
104
105static inline void tag_clear(struct radix_tree_node *node, unsigned int tag,
106 int offset)
107{
108 __clear_bit(offset, node->tags[tag]);
109}
110
111static inline int tag_get(struct radix_tree_node *node, unsigned int tag,
112 int offset)
113{
114 return test_bit(offset, node->tags[tag]);
115}
116
117static inline void root_tag_set(struct radix_tree_root *root, unsigned int tag)
118{
119 root->gfp_mask |= (__force gfp_t)(1 << (tag + __GFP_BITS_SHIFT));
120}
121
122static inline void root_tag_clear(struct radix_tree_root *root, unsigned int tag)
123{
124 root->gfp_mask &= (__force gfp_t)~(1 << (tag + __GFP_BITS_SHIFT));
125}
126
127static inline void root_tag_clear_all(struct radix_tree_root *root)
128{
129 root->gfp_mask &= __GFP_BITS_MASK;
130}
131
132static inline int root_tag_get(struct radix_tree_root *root, unsigned int tag)
133{
134 return (__force unsigned)root->gfp_mask & (1 << (tag + __GFP_BITS_SHIFT));
135}
136
137/*
138 * Returns 1 if any slot in the node has this tag set.
139 * Otherwise returns 0.
140 */
141static inline int any_tag_set(struct radix_tree_node *node, unsigned int tag)
142{
143 int idx;
144 for (idx = 0; idx < RADIX_TREE_TAG_LONGS; idx++) {
145 if (node->tags[tag][idx])
146 return 1;
147 }
148 return 0;
149}
150
151/**
152 * radix_tree_find_next_bit - find the next set bit in a memory region
153 *
154 * @addr: The address to base the search on
155 * @size: The bitmap size in bits
156 * @offset: The bitnumber to start searching at
157 *
158 * Unrollable variant of find_next_bit() for constant size arrays.
159 * Tail bits starting from size to roundup(size, BITS_PER_LONG) must be zero.
160 * Returns next bit offset, or size if nothing found.
161 */
162static __always_inline unsigned long
163radix_tree_find_next_bit(const unsigned long *addr,
164 unsigned long size, unsigned long offset)
165{
166 if (!__builtin_constant_p(size))
167 return find_next_bit(addr, size, offset);
168
169 if (offset < size) {
170 unsigned long tmp;
171
172 addr += offset / BITS_PER_LONG;
173 tmp = *addr >> (offset % BITS_PER_LONG);
174 if (tmp)
175 return __ffs(tmp) + offset;
176 offset = (offset + BITS_PER_LONG) & ~(BITS_PER_LONG - 1);
177 while (offset < size) {
178 tmp = *++addr;
179 if (tmp)
180 return __ffs(tmp) + offset;
181 offset += BITS_PER_LONG;
182 }
183 }
184 return size;
185}
186
187/*
188 * This assumes that the caller has performed appropriate preallocation, and
189 * that the caller has pinned this thread of control to the current CPU.
190 */
191static struct radix_tree_node *
192radix_tree_node_alloc(struct radix_tree_root *root)
193{
194 struct radix_tree_node *ret = NULL;
195 gfp_t gfp_mask = root_gfp_mask(root);
196
197 if (!(gfp_mask & __GFP_WAIT)) {
198 struct radix_tree_preload *rtp;
199
200 /*
201 * Provided the caller has preloaded here, we will always
202 * succeed in getting a node here (and never reach
203 * kmem_cache_alloc)
204 */
205 rtp = &get_cpu_var(radix_tree_preloads);
206 if (rtp->nr) {
207 ret = rtp->nodes[rtp->nr - 1];
208 rtp->nodes[rtp->nr - 1] = NULL;
209 rtp->nr--;
210 }
211 put_cpu_var(radix_tree_preloads);
212 }
213 if (ret == NULL)
214 ret = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
215
216 BUG_ON(radix_tree_is_indirect_ptr(ret));
217 return ret;
218}
219
220static void radix_tree_node_rcu_free(struct rcu_head *head)
221{
222 struct radix_tree_node *node =
223 container_of(head, struct radix_tree_node, rcu_head);
224 int i;
225
226 /*
227 * must only free zeroed nodes into the slab. radix_tree_shrink
228 * can leave us with a non-NULL entry in the first slot, so clear
229 * that here to make sure.
230 */
231 for (i = 0; i < RADIX_TREE_MAX_TAGS; i++)
232 tag_clear(node, i, 0);
233
234 node->slots[0] = NULL;
235 node->count = 0;
236
237 kmem_cache_free(radix_tree_node_cachep, node);
238}
239
240static inline void
241radix_tree_node_free(struct radix_tree_node *node)
242{
243 call_rcu(&node->rcu_head, radix_tree_node_rcu_free);
244}
245
246#ifndef CONFIG_PREEMPT_RT_FULL
247/*
248 * Load up this CPU's radix_tree_node buffer with sufficient objects to
249 * ensure that the addition of a single element in the tree cannot fail. On
250 * success, return zero, with preemption disabled. On error, return -ENOMEM
251 * with preemption not disabled.
252 *
253 * To make use of this facility, the radix tree must be initialised without
254 * __GFP_WAIT being passed to INIT_RADIX_TREE().
255 */
256int radix_tree_preload(gfp_t gfp_mask)
257{
258 struct radix_tree_preload *rtp;
259 struct radix_tree_node *node;
260 int ret = -ENOMEM;
261
262 preempt_disable();
263 rtp = &__get_cpu_var(radix_tree_preloads);
264 while (rtp->nr < ARRAY_SIZE(rtp->nodes)) {
265 preempt_enable();
266 node = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
267 if (node == NULL)
268 goto out;
269 preempt_disable();
270 rtp = &__get_cpu_var(radix_tree_preloads);
271 if (rtp->nr < ARRAY_SIZE(rtp->nodes))
272 rtp->nodes[rtp->nr++] = node;
273 else
274 kmem_cache_free(radix_tree_node_cachep, node);
275 }
276 ret = 0;
277out:
278 return ret;
279}
280EXPORT_SYMBOL(radix_tree_preload);
281#endif
282
283/*
284 * Return the maximum key which can be store into a
285 * radix tree with height HEIGHT.
286 */
287static inline unsigned long radix_tree_maxindex(unsigned int height)
288{
289 return height_to_maxindex[height];
290}
291
292/*
293 * Extend a radix tree so it can store key @index.
294 */
295static int radix_tree_extend(struct radix_tree_root *root, unsigned long index)
296{
297 struct radix_tree_node *node;
298 struct radix_tree_node *slot;
299 unsigned int height;
300 int tag;
301
302 /* Figure out what the height should be. */
303 height = root->height + 1;
304 while (index > radix_tree_maxindex(height))
305 height++;
306
307 if (root->rnode == NULL) {
308 root->height = height;
309 goto out;
310 }
311
312 do {
313 unsigned int newheight;
314 if (!(node = radix_tree_node_alloc(root)))
315 return -ENOMEM;
316
317 /* Propagate the aggregated tag info into the new root */
318 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
319 if (root_tag_get(root, tag))
320 tag_set(node, tag, 0);
321 }
322
323 /* Increase the height. */
324 newheight = root->height+1;
325 node->height = newheight;
326 node->count = 1;
327 node->parent = NULL;
328 slot = root->rnode;
329 if (newheight > 1) {
330 slot = indirect_to_ptr(slot);
331 slot->parent = node;
332 }
333 node->slots[0] = slot;
334 node = ptr_to_indirect(node);
335 rcu_assign_pointer(root->rnode, node);
336 root->height = newheight;
337 } while (height > root->height);
338out:
339 return 0;
340}
341
342/**
343 * radix_tree_insert - insert into a radix tree
344 * @root: radix tree root
345 * @index: index key
346 * @item: item to insert
347 *
348 * Insert an item into the radix tree at position @index.
349 */
350int radix_tree_insert(struct radix_tree_root *root,
351 unsigned long index, void *item)
352{
353 struct radix_tree_node *node = NULL, *slot;
354 unsigned int height, shift;
355 int offset;
356 int error;
357
358 BUG_ON(radix_tree_is_indirect_ptr(item));
359
360 /* Make sure the tree is high enough. */
361 if (index > radix_tree_maxindex(root->height)) {
362 error = radix_tree_extend(root, index);
363 if (error)
364 return error;
365 }
366
367 slot = indirect_to_ptr(root->rnode);
368
369 height = root->height;
370 shift = (height-1) * RADIX_TREE_MAP_SHIFT;
371
372 offset = 0; /* uninitialised var warning */
373 while (height > 0) {
374 if (slot == NULL) {
375 /* Have to add a child node. */
376 if (!(slot = radix_tree_node_alloc(root)))
377 return -ENOMEM;
378 slot->height = height;
379 slot->parent = node;
380 if (node) {
381 rcu_assign_pointer(node->slots[offset], slot);
382 node->count++;
383 } else
384 rcu_assign_pointer(root->rnode, ptr_to_indirect(slot));
385 }
386
387 /* Go a level down */
388 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
389 node = slot;
390 slot = node->slots[offset];
391 shift -= RADIX_TREE_MAP_SHIFT;
392 height--;
393 }
394
395 if (slot != NULL)
396 return -EEXIST;
397
398 if (node) {
399 node->count++;
400 rcu_assign_pointer(node->slots[offset], item);
401 BUG_ON(tag_get(node, 0, offset));
402 BUG_ON(tag_get(node, 1, offset));
403 } else {
404 rcu_assign_pointer(root->rnode, item);
405 BUG_ON(root_tag_get(root, 0));
406 BUG_ON(root_tag_get(root, 1));
407 }
408
409 return 0;
410}
411EXPORT_SYMBOL(radix_tree_insert);
412
413/*
414 * is_slot == 1 : search for the slot.
415 * is_slot == 0 : search for the node.
416 */
417static void *radix_tree_lookup_element(struct radix_tree_root *root,
418 unsigned long index, int is_slot)
419{
420 unsigned int height, shift;
421 struct radix_tree_node *node, **slot;
422
423 node = rcu_dereference_raw(root->rnode);
424 if (node == NULL)
425 return NULL;
426
427 if (!radix_tree_is_indirect_ptr(node)) {
428 if (index > 0)
429 return NULL;
430 return is_slot ? (void *)&root->rnode : node;
431 }
432 node = indirect_to_ptr(node);
433
434 height = node->height;
435 if (index > radix_tree_maxindex(height))
436 return NULL;
437
438 shift = (height-1) * RADIX_TREE_MAP_SHIFT;
439
440 do {
441 slot = (struct radix_tree_node **)
442 (node->slots + ((index>>shift) & RADIX_TREE_MAP_MASK));
443 node = rcu_dereference_raw(*slot);
444 if (node == NULL)
445 return NULL;
446
447 shift -= RADIX_TREE_MAP_SHIFT;
448 height--;
449 } while (height > 0);
450
451 return is_slot ? (void *)slot : indirect_to_ptr(node);
452}
453
454/**
455 * radix_tree_lookup_slot - lookup a slot in a radix tree
456 * @root: radix tree root
457 * @index: index key
458 *
459 * Returns: the slot corresponding to the position @index in the
460 * radix tree @root. This is useful for update-if-exists operations.
461 *
462 * This function can be called under rcu_read_lock iff the slot is not
463 * modified by radix_tree_replace_slot, otherwise it must be called
464 * exclusive from other writers. Any dereference of the slot must be done
465 * using radix_tree_deref_slot.
466 */
467void **radix_tree_lookup_slot(struct radix_tree_root *root, unsigned long index)
468{
469 return (void **)radix_tree_lookup_element(root, index, 1);
470}
471EXPORT_SYMBOL(radix_tree_lookup_slot);
472
473/**
474 * radix_tree_lookup - perform lookup operation on a radix tree
475 * @root: radix tree root
476 * @index: index key
477 *
478 * Lookup the item at the position @index in the radix tree @root.
479 *
480 * This function can be called under rcu_read_lock, however the caller
481 * must manage lifetimes of leaf nodes (eg. RCU may also be used to free
482 * them safely). No RCU barriers are required to access or modify the
483 * returned item, however.
484 */
485void *radix_tree_lookup(struct radix_tree_root *root, unsigned long index)
486{
487 return radix_tree_lookup_element(root, index, 0);
488}
489EXPORT_SYMBOL(radix_tree_lookup);
490
491/**
492 * radix_tree_tag_set - set a tag on a radix tree node
493 * @root: radix tree root
494 * @index: index key
495 * @tag: tag index
496 *
497 * Set the search tag (which must be < RADIX_TREE_MAX_TAGS)
498 * corresponding to @index in the radix tree. From
499 * the root all the way down to the leaf node.
500 *
501 * Returns the address of the tagged item. Setting a tag on a not-present
502 * item is a bug.
503 */
504void *radix_tree_tag_set(struct radix_tree_root *root,
505 unsigned long index, unsigned int tag)
506{
507 unsigned int height, shift;
508 struct radix_tree_node *slot;
509
510 height = root->height;
511 BUG_ON(index > radix_tree_maxindex(height));
512
513 slot = indirect_to_ptr(root->rnode);
514 shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
515
516 while (height > 0) {
517 int offset;
518
519 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
520 if (!tag_get(slot, tag, offset))
521 tag_set(slot, tag, offset);
522 slot = slot->slots[offset];
523 BUG_ON(slot == NULL);
524 shift -= RADIX_TREE_MAP_SHIFT;
525 height--;
526 }
527
528 /* set the root's tag bit */
529 if (slot && !root_tag_get(root, tag))
530 root_tag_set(root, tag);
531
532 return slot;
533}
534EXPORT_SYMBOL(radix_tree_tag_set);
535
536/**
537 * radix_tree_tag_clear - clear a tag on a radix tree node
538 * @root: radix tree root
539 * @index: index key
540 * @tag: tag index
541 *
542 * Clear the search tag (which must be < RADIX_TREE_MAX_TAGS)
543 * corresponding to @index in the radix tree. If
544 * this causes the leaf node to have no tags set then clear the tag in the
545 * next-to-leaf node, etc.
546 *
547 * Returns the address of the tagged item on success, else NULL. ie:
548 * has the same return value and semantics as radix_tree_lookup().
549 */
550void *radix_tree_tag_clear(struct radix_tree_root *root,
551 unsigned long index, unsigned int tag)
552{
553 struct radix_tree_node *node = NULL;
554 struct radix_tree_node *slot = NULL;
555 unsigned int height, shift;
556 int uninitialized_var(offset);
557
558 height = root->height;
559 if (index > radix_tree_maxindex(height))
560 goto out;
561
562 shift = height * RADIX_TREE_MAP_SHIFT;
563 slot = indirect_to_ptr(root->rnode);
564
565 while (shift) {
566 if (slot == NULL)
567 goto out;
568
569 shift -= RADIX_TREE_MAP_SHIFT;
570 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
571 node = slot;
572 slot = slot->slots[offset];
573 }
574
575 if (slot == NULL)
576 goto out;
577
578 while (node) {
579 if (!tag_get(node, tag, offset))
580 goto out;
581 tag_clear(node, tag, offset);
582 if (any_tag_set(node, tag))
583 goto out;
584
585 index >>= RADIX_TREE_MAP_SHIFT;
586 offset = index & RADIX_TREE_MAP_MASK;
587 node = node->parent;
588 }
589
590 /* clear the root's tag bit */
591 if (root_tag_get(root, tag))
592 root_tag_clear(root, tag);
593
594out:
595 return slot;
596}
597EXPORT_SYMBOL(radix_tree_tag_clear);
598
599/**
600 * radix_tree_tag_get - get a tag on a radix tree node
601 * @root: radix tree root
602 * @index: index key
603 * @tag: tag index (< RADIX_TREE_MAX_TAGS)
604 *
605 * Return values:
606 *
607 * 0: tag not present or not set
608 * 1: tag set
609 *
610 * Note that the return value of this function may not be relied on, even if
611 * the RCU lock is held, unless tag modification and node deletion are excluded
612 * from concurrency.
613 */
614int radix_tree_tag_get(struct radix_tree_root *root,
615 unsigned long index, unsigned int tag)
616{
617 unsigned int height, shift;
618 struct radix_tree_node *node;
619
620 /* check the root's tag bit */
621 if (!root_tag_get(root, tag))
622 return 0;
623
624 node = rcu_dereference_raw(root->rnode);
625 if (node == NULL)
626 return 0;
627
628 if (!radix_tree_is_indirect_ptr(node))
629 return (index == 0);
630 node = indirect_to_ptr(node);
631
632 height = node->height;
633 if (index > radix_tree_maxindex(height))
634 return 0;
635
636 shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
637
638 for ( ; ; ) {
639 int offset;
640
641 if (node == NULL)
642 return 0;
643
644 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
645 if (!tag_get(node, tag, offset))
646 return 0;
647 if (height == 1)
648 return 1;
649 node = rcu_dereference_raw(node->slots[offset]);
650 shift -= RADIX_TREE_MAP_SHIFT;
651 height--;
652 }
653}
654EXPORT_SYMBOL(radix_tree_tag_get);
655
656/**
657 * radix_tree_next_chunk - find next chunk of slots for iteration
658 *
659 * @root: radix tree root
660 * @iter: iterator state
661 * @flags: RADIX_TREE_ITER_* flags and tag index
662 * Returns: pointer to chunk first slot, or NULL if iteration is over
663 */
664void **radix_tree_next_chunk(struct radix_tree_root *root,
665 struct radix_tree_iter *iter, unsigned flags)
666{
667 unsigned shift, tag = flags & RADIX_TREE_ITER_TAG_MASK;
668 struct radix_tree_node *rnode, *node;
669 unsigned long index, offset;
670
671 if ((flags & RADIX_TREE_ITER_TAGGED) && !root_tag_get(root, tag))
672 return NULL;
673
674 /*
675 * Catch next_index overflow after ~0UL. iter->index never overflows
676 * during iterating; it can be zero only at the beginning.
677 * And we cannot overflow iter->next_index in a single step,
678 * because RADIX_TREE_MAP_SHIFT < BITS_PER_LONG.
679 *
680 * This condition also used by radix_tree_next_slot() to stop
681 * contiguous iterating, and forbid swithing to the next chunk.
682 */
683 index = iter->next_index;
684 if (!index && iter->index)
685 return NULL;
686
687 rnode = rcu_dereference_raw(root->rnode);
688 if (radix_tree_is_indirect_ptr(rnode)) {
689 rnode = indirect_to_ptr(rnode);
690 } else if (rnode && !index) {
691 /* Single-slot tree */
692 iter->index = 0;
693 iter->next_index = 1;
694 iter->tags = 1;
695 return (void **)&root->rnode;
696 } else
697 return NULL;
698
699restart:
700 shift = (rnode->height - 1) * RADIX_TREE_MAP_SHIFT;
701 offset = index >> shift;
702
703 /* Index outside of the tree */
704 if (offset >= RADIX_TREE_MAP_SIZE)
705 return NULL;
706
707 node = rnode;
708 while (1) {
709 if ((flags & RADIX_TREE_ITER_TAGGED) ?
710 !test_bit(offset, node->tags[tag]) :
711 !node->slots[offset]) {
712 /* Hole detected */
713 if (flags & RADIX_TREE_ITER_CONTIG)
714 return NULL;
715
716 if (flags & RADIX_TREE_ITER_TAGGED)
717 offset = radix_tree_find_next_bit(
718 node->tags[tag],
719 RADIX_TREE_MAP_SIZE,
720 offset + 1);
721 else
722 while (++offset < RADIX_TREE_MAP_SIZE) {
723 if (node->slots[offset])
724 break;
725 }
726 index &= ~((RADIX_TREE_MAP_SIZE << shift) - 1);
727 index += offset << shift;
728 /* Overflow after ~0UL */
729 if (!index)
730 return NULL;
731 if (offset == RADIX_TREE_MAP_SIZE)
732 goto restart;
733 }
734
735 /* This is leaf-node */
736 if (!shift)
737 break;
738
739 node = rcu_dereference_raw(node->slots[offset]);
740 if (node == NULL)
741 goto restart;
742 shift -= RADIX_TREE_MAP_SHIFT;
743 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
744 }
745
746 /* Update the iterator state */
747 iter->index = index;
748 iter->next_index = (index | RADIX_TREE_MAP_MASK) + 1;
749
750 /* Construct iter->tags bit-mask from node->tags[tag] array */
751 if (flags & RADIX_TREE_ITER_TAGGED) {
752 unsigned tag_long, tag_bit;
753
754 tag_long = offset / BITS_PER_LONG;
755 tag_bit = offset % BITS_PER_LONG;
756 iter->tags = node->tags[tag][tag_long] >> tag_bit;
757 /* This never happens if RADIX_TREE_TAG_LONGS == 1 */
758 if (tag_long < RADIX_TREE_TAG_LONGS - 1) {
759 /* Pick tags from next element */
760 if (tag_bit)
761 iter->tags |= node->tags[tag][tag_long + 1] <<
762 (BITS_PER_LONG - tag_bit);
763 /* Clip chunk size, here only BITS_PER_LONG tags */
764 iter->next_index = index + BITS_PER_LONG;
765 }
766 }
767
768 return node->slots + offset;
769}
770EXPORT_SYMBOL(radix_tree_next_chunk);
771
772/**
773 * radix_tree_range_tag_if_tagged - for each item in given range set given
774 * tag if item has another tag set
775 * @root: radix tree root
776 * @first_indexp: pointer to a starting index of a range to scan
777 * @last_index: last index of a range to scan
778 * @nr_to_tag: maximum number items to tag
779 * @iftag: tag index to test
780 * @settag: tag index to set if tested tag is set
781 *
782 * This function scans range of radix tree from first_index to last_index
783 * (inclusive). For each item in the range if iftag is set, the function sets
784 * also settag. The function stops either after tagging nr_to_tag items or
785 * after reaching last_index.
786 *
787 * The tags must be set from the leaf level only and propagated back up the
788 * path to the root. We must do this so that we resolve the full path before
789 * setting any tags on intermediate nodes. If we set tags as we descend, then
790 * we can get to the leaf node and find that the index that has the iftag
791 * set is outside the range we are scanning. This reults in dangling tags and
792 * can lead to problems with later tag operations (e.g. livelocks on lookups).
793 *
794 * The function returns number of leaves where the tag was set and sets
795 * *first_indexp to the first unscanned index.
796 * WARNING! *first_indexp can wrap if last_index is ULONG_MAX. Caller must
797 * be prepared to handle that.
798 */
799unsigned long radix_tree_range_tag_if_tagged(struct radix_tree_root *root,
800 unsigned long *first_indexp, unsigned long last_index,
801 unsigned long nr_to_tag,
802 unsigned int iftag, unsigned int settag)
803{
804 unsigned int height = root->height;
805 struct radix_tree_node *node = NULL;
806 struct radix_tree_node *slot;
807 unsigned int shift;
808 unsigned long tagged = 0;
809 unsigned long index = *first_indexp;
810
811 last_index = min(last_index, radix_tree_maxindex(height));
812 if (index > last_index)
813 return 0;
814 if (!nr_to_tag)
815 return 0;
816 if (!root_tag_get(root, iftag)) {
817 *first_indexp = last_index + 1;
818 return 0;
819 }
820 if (height == 0) {
821 *first_indexp = last_index + 1;
822 root_tag_set(root, settag);
823 return 1;
824 }
825
826 shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
827 slot = indirect_to_ptr(root->rnode);
828
829 for (;;) {
830 unsigned long upindex;
831 int offset;
832
833 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
834 if (!slot->slots[offset])
835 goto next;
836 if (!tag_get(slot, iftag, offset))
837 goto next;
838 if (shift) {
839 /* Go down one level */
840 shift -= RADIX_TREE_MAP_SHIFT;
841 node = slot;
842 slot = slot->slots[offset];
843 continue;
844 }
845
846 /* tag the leaf */
847 tagged++;
848 tag_set(slot, settag, offset);
849
850 /* walk back up the path tagging interior nodes */
851 upindex = index;
852 while (node) {
853 upindex >>= RADIX_TREE_MAP_SHIFT;
854 offset = upindex & RADIX_TREE_MAP_MASK;
855
856 /* stop if we find a node with the tag already set */
857 if (tag_get(node, settag, offset))
858 break;
859 tag_set(node, settag, offset);
860 node = node->parent;
861 }
862
863 /*
864 * Small optimization: now clear that node pointer.
865 * Since all of this slot's ancestors now have the tag set
866 * from setting it above, we have no further need to walk
867 * back up the tree setting tags, until we update slot to
868 * point to another radix_tree_node.
869 */
870 node = NULL;
871
872next:
873 /* Go to next item at level determined by 'shift' */
874 index = ((index >> shift) + 1) << shift;
875 /* Overflow can happen when last_index is ~0UL... */
876 if (index > last_index || !index)
877 break;
878 if (tagged >= nr_to_tag)
879 break;
880 while (((index >> shift) & RADIX_TREE_MAP_MASK) == 0) {
881 /*
882 * We've fully scanned this node. Go up. Because
883 * last_index is guaranteed to be in the tree, what
884 * we do below cannot wander astray.
885 */
886 slot = slot->parent;
887 shift += RADIX_TREE_MAP_SHIFT;
888 }
889 }
890 /*
891 * We need not to tag the root tag if there is no tag which is set with
892 * settag within the range from *first_indexp to last_index.
893 */
894 if (tagged > 0)
895 root_tag_set(root, settag);
896 *first_indexp = index;
897
898 return tagged;
899}
900EXPORT_SYMBOL(radix_tree_range_tag_if_tagged);
901
902
903/**
904 * radix_tree_next_hole - find the next hole (not-present entry)
905 * @root: tree root
906 * @index: index key
907 * @max_scan: maximum range to search
908 *
909 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the lowest
910 * indexed hole.
911 *
912 * Returns: the index of the hole if found, otherwise returns an index
913 * outside of the set specified (in which case 'return - index >= max_scan'
914 * will be true). In rare cases of index wrap-around, 0 will be returned.
915 *
916 * radix_tree_next_hole may be called under rcu_read_lock. However, like
917 * radix_tree_gang_lookup, this will not atomically search a snapshot of
918 * the tree at a single point in time. For example, if a hole is created
919 * at index 5, then subsequently a hole is created at index 10,
920 * radix_tree_next_hole covering both indexes may return 10 if called
921 * under rcu_read_lock.
922 */
923unsigned long radix_tree_next_hole(struct radix_tree_root *root,
924 unsigned long index, unsigned long max_scan)
925{
926 unsigned long i;
927
928 for (i = 0; i < max_scan; i++) {
929 if (!radix_tree_lookup(root, index))
930 break;
931 index++;
932 if (index == 0)
933 break;
934 }
935
936 return index;
937}
938EXPORT_SYMBOL(radix_tree_next_hole);
939
940/**
941 * radix_tree_prev_hole - find the prev hole (not-present entry)
942 * @root: tree root
943 * @index: index key
944 * @max_scan: maximum range to search
945 *
946 * Search backwards in the range [max(index-max_scan+1, 0), index]
947 * for the first hole.
948 *
949 * Returns: the index of the hole if found, otherwise returns an index
950 * outside of the set specified (in which case 'index - return >= max_scan'
951 * will be true). In rare cases of wrap-around, ULONG_MAX will be returned.
952 *
953 * radix_tree_next_hole may be called under rcu_read_lock. However, like
954 * radix_tree_gang_lookup, this will not atomically search a snapshot of
955 * the tree at a single point in time. For example, if a hole is created
956 * at index 10, then subsequently a hole is created at index 5,
957 * radix_tree_prev_hole covering both indexes may return 5 if called under
958 * rcu_read_lock.
959 */
960unsigned long radix_tree_prev_hole(struct radix_tree_root *root,
961 unsigned long index, unsigned long max_scan)
962{
963 unsigned long i;
964
965 for (i = 0; i < max_scan; i++) {
966 if (!radix_tree_lookup(root, index))
967 break;
968 index--;
969 if (index == ULONG_MAX)
970 break;
971 }
972
973 return index;
974}
975EXPORT_SYMBOL(radix_tree_prev_hole);
976
977/**
978 * radix_tree_gang_lookup - perform multiple lookup on a radix tree
979 * @root: radix tree root
980 * @results: where the results of the lookup are placed
981 * @first_index: start the lookup from this key
982 * @max_items: place up to this many items at *results
983 *
984 * Performs an index-ascending scan of the tree for present items. Places
985 * them at *@results and returns the number of items which were placed at
986 * *@results.
987 *
988 * The implementation is naive.
989 *
990 * Like radix_tree_lookup, radix_tree_gang_lookup may be called under
991 * rcu_read_lock. In this case, rather than the returned results being
992 * an atomic snapshot of the tree at a single point in time, the semantics
993 * of an RCU protected gang lookup are as though multiple radix_tree_lookups
994 * have been issued in individual locks, and results stored in 'results'.
995 */
996unsigned int
997radix_tree_gang_lookup(struct radix_tree_root *root, void **results,
998 unsigned long first_index, unsigned int max_items)
999{
1000 struct radix_tree_iter iter;
1001 void **slot;
1002 unsigned int ret = 0;
1003
1004 if (unlikely(!max_items))
1005 return 0;
1006
1007 radix_tree_for_each_slot(slot, root, &iter, first_index) {
1008 results[ret] = indirect_to_ptr(rcu_dereference_raw(*slot));
1009 if (!results[ret])
1010 continue;
1011 if (++ret == max_items)
1012 break;
1013 }
1014
1015 return ret;
1016}
1017EXPORT_SYMBOL(radix_tree_gang_lookup);
1018
1019/**
1020 * radix_tree_gang_lookup_slot - perform multiple slot lookup on radix tree
1021 * @root: radix tree root
1022 * @results: where the results of the lookup are placed
1023 * @indices: where their indices should be placed (but usually NULL)
1024 * @first_index: start the lookup from this key
1025 * @max_items: place up to this many items at *results
1026 *
1027 * Performs an index-ascending scan of the tree for present items. Places
1028 * their slots at *@results and returns the number of items which were
1029 * placed at *@results.
1030 *
1031 * The implementation is naive.
1032 *
1033 * Like radix_tree_gang_lookup as far as RCU and locking goes. Slots must
1034 * be dereferenced with radix_tree_deref_slot, and if using only RCU
1035 * protection, radix_tree_deref_slot may fail requiring a retry.
1036 */
1037unsigned int
1038radix_tree_gang_lookup_slot(struct radix_tree_root *root,
1039 void ***results, unsigned long *indices,
1040 unsigned long first_index, unsigned int max_items)
1041{
1042 struct radix_tree_iter iter;
1043 void **slot;
1044 unsigned int ret = 0;
1045
1046 if (unlikely(!max_items))
1047 return 0;
1048
1049 radix_tree_for_each_slot(slot, root, &iter, first_index) {
1050 results[ret] = slot;
1051 if (indices)
1052 indices[ret] = iter.index;
1053 if (++ret == max_items)
1054 break;
1055 }
1056
1057 return ret;
1058}
1059EXPORT_SYMBOL(radix_tree_gang_lookup_slot);
1060
1061/**
1062 * radix_tree_gang_lookup_tag - perform multiple lookup on a radix tree
1063 * based on a tag
1064 * @root: radix tree root
1065 * @results: where the results of the lookup are placed
1066 * @first_index: start the lookup from this key
1067 * @max_items: place up to this many items at *results
1068 * @tag: the tag index (< RADIX_TREE_MAX_TAGS)
1069 *
1070 * Performs an index-ascending scan of the tree for present items which
1071 * have the tag indexed by @tag set. Places the items at *@results and
1072 * returns the number of items which were placed at *@results.
1073 */
1074unsigned int
1075radix_tree_gang_lookup_tag(struct radix_tree_root *root, void **results,
1076 unsigned long first_index, unsigned int max_items,
1077 unsigned int tag)
1078{
1079 struct radix_tree_iter iter;
1080 void **slot;
1081 unsigned int ret = 0;
1082
1083 if (unlikely(!max_items))
1084 return 0;
1085
1086 radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
1087 results[ret] = indirect_to_ptr(rcu_dereference_raw(*slot));
1088 if (!results[ret])
1089 continue;
1090 if (++ret == max_items)
1091 break;
1092 }
1093
1094 return ret;
1095}
1096EXPORT_SYMBOL(radix_tree_gang_lookup_tag);
1097
1098/**
1099 * radix_tree_gang_lookup_tag_slot - perform multiple slot lookup on a
1100 * radix tree based on a tag
1101 * @root: radix tree root
1102 * @results: where the results of the lookup are placed
1103 * @first_index: start the lookup from this key
1104 * @max_items: place up to this many items at *results
1105 * @tag: the tag index (< RADIX_TREE_MAX_TAGS)
1106 *
1107 * Performs an index-ascending scan of the tree for present items which
1108 * have the tag indexed by @tag set. Places the slots at *@results and
1109 * returns the number of slots which were placed at *@results.
1110 */
1111unsigned int
1112radix_tree_gang_lookup_tag_slot(struct radix_tree_root *root, void ***results,
1113 unsigned long first_index, unsigned int max_items,
1114 unsigned int tag)
1115{
1116 struct radix_tree_iter iter;
1117 void **slot;
1118 unsigned int ret = 0;
1119
1120 if (unlikely(!max_items))
1121 return 0;
1122
1123 radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
1124 results[ret] = slot;
1125 if (++ret == max_items)
1126 break;
1127 }
1128
1129 return ret;
1130}
1131EXPORT_SYMBOL(radix_tree_gang_lookup_tag_slot);
1132
1133#if defined(CONFIG_SHMEM) && defined(CONFIG_SWAP)
1134#include <linux/sched.h> /* for cond_resched() */
1135
1136/*
1137 * This linear search is at present only useful to shmem_unuse_inode().
1138 */
1139static unsigned long __locate(struct radix_tree_node *slot, void *item,
1140 unsigned long index, unsigned long *found_index)
1141{
1142 unsigned int shift, height;
1143 unsigned long i;
1144
1145 height = slot->height;
1146 shift = (height-1) * RADIX_TREE_MAP_SHIFT;
1147
1148 for ( ; height > 1; height--) {
1149 i = (index >> shift) & RADIX_TREE_MAP_MASK;
1150 for (;;) {
1151 if (slot->slots[i] != NULL)
1152 break;
1153 index &= ~((1UL << shift) - 1);
1154 index += 1UL << shift;
1155 if (index == 0)
1156 goto out; /* 32-bit wraparound */
1157 i++;
1158 if (i == RADIX_TREE_MAP_SIZE)
1159 goto out;
1160 }
1161
1162 shift -= RADIX_TREE_MAP_SHIFT;
1163 slot = rcu_dereference_raw(slot->slots[i]);
1164 if (slot == NULL)
1165 goto out;
1166 }
1167
1168 /* Bottom level: check items */
1169 for (i = 0; i < RADIX_TREE_MAP_SIZE; i++) {
1170 if (slot->slots[i] == item) {
1171 *found_index = index + i;
1172 index = 0;
1173 goto out;
1174 }
1175 }
1176 index += RADIX_TREE_MAP_SIZE;
1177out:
1178 return index;
1179}
1180
1181/**
1182 * radix_tree_locate_item - search through radix tree for item
1183 * @root: radix tree root
1184 * @item: item to be found
1185 *
1186 * Returns index where item was found, or -1 if not found.
1187 * Caller must hold no lock (since this time-consuming function needs
1188 * to be preemptible), and must check afterwards if item is still there.
1189 */
1190unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
1191{
1192 struct radix_tree_node *node;
1193 unsigned long max_index;
1194 unsigned long cur_index = 0;
1195 unsigned long found_index = -1;
1196
1197 do {
1198 rcu_read_lock();
1199 node = rcu_dereference_raw(root->rnode);
1200 if (!radix_tree_is_indirect_ptr(node)) {
1201 rcu_read_unlock();
1202 if (node == item)
1203 found_index = 0;
1204 break;
1205 }
1206
1207 node = indirect_to_ptr(node);
1208 max_index = radix_tree_maxindex(node->height);
1209 if (cur_index > max_index)
1210 break;
1211
1212 cur_index = __locate(node, item, cur_index, &found_index);
1213 rcu_read_unlock();
1214 cond_resched();
1215 } while (cur_index != 0 && cur_index <= max_index);
1216
1217 return found_index;
1218}
1219#else
1220unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
1221{
1222 return -1;
1223}
1224#endif /* CONFIG_SHMEM && CONFIG_SWAP */
1225
1226/**
1227 * radix_tree_shrink - shrink height of a radix tree to minimal
1228 * @root radix tree root
1229 */
1230static inline void radix_tree_shrink(struct radix_tree_root *root)
1231{
1232 /* try to shrink tree height */
1233 while (root->height > 0) {
1234 struct radix_tree_node *to_free = root->rnode;
1235 struct radix_tree_node *slot;
1236
1237 BUG_ON(!radix_tree_is_indirect_ptr(to_free));
1238 to_free = indirect_to_ptr(to_free);
1239
1240 /*
1241 * The candidate node has more than one child, or its child
1242 * is not at the leftmost slot, we cannot shrink.
1243 */
1244 if (to_free->count != 1)
1245 break;
1246 if (!to_free->slots[0])
1247 break;
1248
1249 /*
1250 * We don't need rcu_assign_pointer(), since we are simply
1251 * moving the node from one part of the tree to another: if it
1252 * was safe to dereference the old pointer to it
1253 * (to_free->slots[0]), it will be safe to dereference the new
1254 * one (root->rnode) as far as dependent read barriers go.
1255 */
1256 slot = to_free->slots[0];
1257 if (root->height > 1) {
1258 slot->parent = NULL;
1259 slot = ptr_to_indirect(slot);
1260 }
1261 root->rnode = slot;
1262 root->height--;
1263
1264 /*
1265 * We have a dilemma here. The node's slot[0] must not be
1266 * NULLed in case there are concurrent lookups expecting to
1267 * find the item. However if this was a bottom-level node,
1268 * then it may be subject to the slot pointer being visible
1269 * to callers dereferencing it. If item corresponding to
1270 * slot[0] is subsequently deleted, these callers would expect
1271 * their slot to become empty sooner or later.
1272 *
1273 * For example, lockless pagecache will look up a slot, deref
1274 * the page pointer, and if the page is 0 refcount it means it
1275 * was concurrently deleted from pagecache so try the deref
1276 * again. Fortunately there is already a requirement for logic
1277 * to retry the entire slot lookup -- the indirect pointer
1278 * problem (replacing direct root node with an indirect pointer
1279 * also results in a stale slot). So tag the slot as indirect
1280 * to force callers to retry.
1281 */
1282 if (root->height == 0)
1283 *((unsigned long *)&to_free->slots[0]) |=
1284 RADIX_TREE_INDIRECT_PTR;
1285
1286 radix_tree_node_free(to_free);
1287 }
1288}
1289
1290/**
1291 * radix_tree_delete - delete an item from a radix tree
1292 * @root: radix tree root
1293 * @index: index key
1294 *
1295 * Remove the item at @index from the radix tree rooted at @root.
1296 *
1297 * Returns the address of the deleted item, or NULL if it was not present.
1298 */
1299void *radix_tree_delete(struct radix_tree_root *root, unsigned long index)
1300{
1301 struct radix_tree_node *node = NULL;
1302 struct radix_tree_node *slot = NULL;
1303 struct radix_tree_node *to_free;
1304 unsigned int height, shift;
1305 int tag;
1306 int uninitialized_var(offset);
1307
1308 height = root->height;
1309 if (index > radix_tree_maxindex(height))
1310 goto out;
1311
1312 slot = root->rnode;
1313 if (height == 0) {
1314 root_tag_clear_all(root);
1315 root->rnode = NULL;
1316 goto out;
1317 }
1318 slot = indirect_to_ptr(slot);
1319 shift = height * RADIX_TREE_MAP_SHIFT;
1320
1321 do {
1322 if (slot == NULL)
1323 goto out;
1324
1325 shift -= RADIX_TREE_MAP_SHIFT;
1326 offset = (index >> shift) & RADIX_TREE_MAP_MASK;
1327 node = slot;
1328 slot = slot->slots[offset];
1329 } while (shift);
1330
1331 if (slot == NULL)
1332 goto out;
1333
1334 /*
1335 * Clear all tags associated with the item to be deleted.
1336 * This way of doing it would be inefficient, but seldom is any set.
1337 */
1338 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
1339 if (tag_get(node, tag, offset))
1340 radix_tree_tag_clear(root, index, tag);
1341 }
1342
1343 to_free = NULL;
1344 /* Now free the nodes we do not need anymore */
1345 while (node) {
1346 node->slots[offset] = NULL;
1347 node->count--;
1348 /*
1349 * Queue the node for deferred freeing after the
1350 * last reference to it disappears (set NULL, above).
1351 */
1352 if (to_free)
1353 radix_tree_node_free(to_free);
1354
1355 if (node->count) {
1356 if (node == indirect_to_ptr(root->rnode))
1357 radix_tree_shrink(root);
1358 goto out;
1359 }
1360
1361 /* Node with zero slots in use so free it */
1362 to_free = node;
1363
1364 index >>= RADIX_TREE_MAP_SHIFT;
1365 offset = index & RADIX_TREE_MAP_MASK;
1366 node = node->parent;
1367 }
1368
1369 root_tag_clear_all(root);
1370 root->height = 0;
1371 root->rnode = NULL;
1372 if (to_free)
1373 radix_tree_node_free(to_free);
1374
1375out:
1376 return slot;
1377}
1378EXPORT_SYMBOL(radix_tree_delete);
1379
1380/**
1381 * radix_tree_tagged - test whether any items in the tree are tagged
1382 * @root: radix tree root
1383 * @tag: tag to test
1384 */
1385int radix_tree_tagged(struct radix_tree_root *root, unsigned int tag)
1386{
1387 return root_tag_get(root, tag);
1388}
1389EXPORT_SYMBOL(radix_tree_tagged);
1390
1391static void
1392radix_tree_node_ctor(void *node)
1393{
1394 memset(node, 0, sizeof(struct radix_tree_node));
1395}
1396
1397static __init unsigned long __maxindex(unsigned int height)
1398{
1399 unsigned int width = height * RADIX_TREE_MAP_SHIFT;
1400 int shift = RADIX_TREE_INDEX_BITS - width;
1401
1402 if (shift < 0)
1403 return ~0UL;
1404 if (shift >= BITS_PER_LONG)
1405 return 0UL;
1406 return ~0UL >> shift;
1407}
1408
1409static __init void radix_tree_init_maxindex(void)
1410{
1411 unsigned int i;
1412
1413 for (i = 0; i < ARRAY_SIZE(height_to_maxindex); i++)
1414 height_to_maxindex[i] = __maxindex(i);
1415}
1416
1417static int radix_tree_callback(struct notifier_block *nfb,
1418 unsigned long action,
1419 void *hcpu)
1420{
1421 int cpu = (long)hcpu;
1422 struct radix_tree_preload *rtp;
1423
1424 /* Free per-cpu pool of perloaded nodes */
1425 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
1426 rtp = &per_cpu(radix_tree_preloads, cpu);
1427 while (rtp->nr) {
1428 kmem_cache_free(radix_tree_node_cachep,
1429 rtp->nodes[rtp->nr-1]);
1430 rtp->nodes[rtp->nr-1] = NULL;
1431 rtp->nr--;
1432 }
1433 }
1434 return NOTIFY_OK;
1435}
1436
1437void __init radix_tree_init(void)
1438{
1439 radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
1440 sizeof(struct radix_tree_node), 0,
1441 SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
1442 radix_tree_node_ctor);
1443 radix_tree_init_maxindex();
1444 hotcpu_notifier(radix_tree_callback, 0);
1445}