]> asedeno.scripts.mit.edu Git - linux.git/blob - lib/radix-tree.c
c1c079ffadcd320b7e28d2e7b8853ed18acc5c49
[linux.git] / lib / radix-tree.c
1 /*
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  * Copyright (C) 2016 Intel, Matthew Wilcox
8  * Copyright (C) 2016 Intel, Ross Zwisler
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License as
12  * published by the Free Software Foundation; either version 2, or (at
13  * your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include <linux/bitmap.h>
26 #include <linux/bitops.h>
27 #include <linux/cpu.h>
28 #include <linux/errno.h>
29 #include <linux/export.h>
30 #include <linux/idr.h>
31 #include <linux/init.h>
32 #include <linux/kernel.h>
33 #include <linux/kmemleak.h>
34 #include <linux/percpu.h>
35 #include <linux/preempt.h>              /* in_interrupt() */
36 #include <linux/radix-tree.h>
37 #include <linux/rcupdate.h>
38 #include <linux/slab.h>
39 #include <linux/string.h>
40
41
42 /* Number of nodes in fully populated tree of given height */
43 static unsigned long height_to_maxnodes[RADIX_TREE_MAX_PATH + 1] __read_mostly;
44
45 /*
46  * Radix tree node cache.
47  */
48 static struct kmem_cache *radix_tree_node_cachep;
49
50 /*
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
54  * radix_tree_extend).
55  *
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.
59  * Hence:
60  */
61 #define RADIX_TREE_PRELOAD_SIZE (RADIX_TREE_MAX_PATH * 2 - 1)
62
63 /*
64  * The IDR does not have to be as high as the radix tree since it uses
65  * signed integers, not unsigned longs.
66  */
67 #define IDR_INDEX_BITS          (8 /* CHAR_BIT */ * sizeof(int) - 1)
68 #define IDR_MAX_PATH            (DIV_ROUND_UP(IDR_INDEX_BITS, \
69                                                 RADIX_TREE_MAP_SHIFT))
70 #define IDR_PRELOAD_SIZE        (IDR_MAX_PATH * 2 - 1)
71
72 /*
73  * The IDA is even shorter since it uses a bitmap at the last level.
74  */
75 #define IDA_INDEX_BITS          (8 * sizeof(int) - 1 - ilog2(IDA_BITMAP_BITS))
76 #define IDA_MAX_PATH            (DIV_ROUND_UP(IDA_INDEX_BITS, \
77                                                 RADIX_TREE_MAP_SHIFT))
78 #define IDA_PRELOAD_SIZE        (IDA_MAX_PATH * 2 - 1)
79
80 /*
81  * Per-cpu pool of preloaded nodes
82  */
83 struct radix_tree_preload {
84         unsigned nr;
85         /* nodes->parent points to next preallocated node */
86         struct radix_tree_node *nodes;
87 };
88 static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, };
89
90 static inline struct radix_tree_node *entry_to_node(void *ptr)
91 {
92         return (void *)((unsigned long)ptr & ~RADIX_TREE_INTERNAL_NODE);
93 }
94
95 static inline void *node_to_entry(void *ptr)
96 {
97         return (void *)((unsigned long)ptr | RADIX_TREE_INTERNAL_NODE);
98 }
99
100 #define RADIX_TREE_RETRY        node_to_entry(NULL)
101
102 #ifdef CONFIG_RADIX_TREE_MULTIORDER
103 /* Sibling slots point directly to another slot in the same node */
104 static inline
105 bool is_sibling_entry(const struct radix_tree_node *parent, void *node)
106 {
107         void **ptr = node;
108         return (parent->slots <= ptr) &&
109                         (ptr < parent->slots + RADIX_TREE_MAP_SIZE);
110 }
111 #else
112 static inline
113 bool is_sibling_entry(const struct radix_tree_node *parent, void *node)
114 {
115         return false;
116 }
117 #endif
118
119 static inline
120 unsigned long get_slot_offset(const struct radix_tree_node *parent, void **slot)
121 {
122         return slot - parent->slots;
123 }
124
125 static unsigned int radix_tree_descend(const struct radix_tree_node *parent,
126                         struct radix_tree_node **nodep, unsigned long index)
127 {
128         unsigned int offset = (index >> parent->shift) & RADIX_TREE_MAP_MASK;
129         void **entry = rcu_dereference_raw(parent->slots[offset]);
130
131 #ifdef CONFIG_RADIX_TREE_MULTIORDER
132         if (radix_tree_is_internal_node(entry)) {
133                 if (is_sibling_entry(parent, entry)) {
134                         void **sibentry = (void **) entry_to_node(entry);
135                         offset = get_slot_offset(parent, sibentry);
136                         entry = rcu_dereference_raw(*sibentry);
137                 }
138         }
139 #endif
140
141         *nodep = (void *)entry;
142         return offset;
143 }
144
145 static inline gfp_t root_gfp_mask(const struct radix_tree_root *root)
146 {
147         return root->gfp_mask & __GFP_BITS_MASK;
148 }
149
150 static inline void tag_set(struct radix_tree_node *node, unsigned int tag,
151                 int offset)
152 {
153         __set_bit(offset, node->tags[tag]);
154 }
155
156 static inline void tag_clear(struct radix_tree_node *node, unsigned int tag,
157                 int offset)
158 {
159         __clear_bit(offset, node->tags[tag]);
160 }
161
162 static inline int tag_get(const struct radix_tree_node *node, unsigned int tag,
163                 int offset)
164 {
165         return test_bit(offset, node->tags[tag]);
166 }
167
168 static inline void root_tag_set(struct radix_tree_root *root, unsigned tag)
169 {
170         root->gfp_mask |= (__force gfp_t)(1 << (tag + ROOT_TAG_SHIFT));
171 }
172
173 static inline void root_tag_clear(struct radix_tree_root *root, unsigned tag)
174 {
175         root->gfp_mask &= (__force gfp_t)~(1 << (tag + ROOT_TAG_SHIFT));
176 }
177
178 static inline void root_tag_clear_all(struct radix_tree_root *root)
179 {
180         root->gfp_mask &= (1 << ROOT_TAG_SHIFT) - 1;
181 }
182
183 static inline int root_tag_get(const struct radix_tree_root *root, unsigned tag)
184 {
185         return (__force int)root->gfp_mask & (1 << (tag + ROOT_TAG_SHIFT));
186 }
187
188 static inline unsigned root_tags_get(const struct radix_tree_root *root)
189 {
190         return (__force unsigned)root->gfp_mask >> ROOT_TAG_SHIFT;
191 }
192
193 static inline bool is_idr(const struct radix_tree_root *root)
194 {
195         return !!(root->gfp_mask & ROOT_IS_IDR);
196 }
197
198 /*
199  * Returns 1 if any slot in the node has this tag set.
200  * Otherwise returns 0.
201  */
202 static inline int any_tag_set(const struct radix_tree_node *node,
203                                                         unsigned int tag)
204 {
205         unsigned idx;
206         for (idx = 0; idx < RADIX_TREE_TAG_LONGS; idx++) {
207                 if (node->tags[tag][idx])
208                         return 1;
209         }
210         return 0;
211 }
212
213 static inline void all_tag_set(struct radix_tree_node *node, unsigned int tag)
214 {
215         bitmap_fill(node->tags[tag], RADIX_TREE_MAP_SIZE);
216 }
217
218 /**
219  * radix_tree_find_next_bit - find the next set bit in a memory region
220  *
221  * @addr: The address to base the search on
222  * @size: The bitmap size in bits
223  * @offset: The bitnumber to start searching at
224  *
225  * Unrollable variant of find_next_bit() for constant size arrays.
226  * Tail bits starting from size to roundup(size, BITS_PER_LONG) must be zero.
227  * Returns next bit offset, or size if nothing found.
228  */
229 static __always_inline unsigned long
230 radix_tree_find_next_bit(struct radix_tree_node *node, unsigned int tag,
231                          unsigned long offset)
232 {
233         const unsigned long *addr = node->tags[tag];
234
235         if (offset < RADIX_TREE_MAP_SIZE) {
236                 unsigned long tmp;
237
238                 addr += offset / BITS_PER_LONG;
239                 tmp = *addr >> (offset % BITS_PER_LONG);
240                 if (tmp)
241                         return __ffs(tmp) + offset;
242                 offset = (offset + BITS_PER_LONG) & ~(BITS_PER_LONG - 1);
243                 while (offset < RADIX_TREE_MAP_SIZE) {
244                         tmp = *++addr;
245                         if (tmp)
246                                 return __ffs(tmp) + offset;
247                         offset += BITS_PER_LONG;
248                 }
249         }
250         return RADIX_TREE_MAP_SIZE;
251 }
252
253 static unsigned int iter_offset(const struct radix_tree_iter *iter)
254 {
255         return (iter->index >> iter_shift(iter)) & RADIX_TREE_MAP_MASK;
256 }
257
258 /*
259  * The maximum index which can be stored in a radix tree
260  */
261 static inline unsigned long shift_maxindex(unsigned int shift)
262 {
263         return (RADIX_TREE_MAP_SIZE << shift) - 1;
264 }
265
266 static inline unsigned long node_maxindex(const struct radix_tree_node *node)
267 {
268         return shift_maxindex(node->shift);
269 }
270
271 static unsigned long next_index(unsigned long index,
272                                 const struct radix_tree_node *node,
273                                 unsigned long offset)
274 {
275         return (index & ~node_maxindex(node)) + (offset << node->shift);
276 }
277
278 #ifndef __KERNEL__
279 static void dump_node(struct radix_tree_node *node, unsigned long index)
280 {
281         unsigned long i;
282
283         pr_debug("radix node: %p offset %d indices %lu-%lu parent %p tags %lx %lx %lx shift %d count %d exceptional %d\n",
284                 node, node->offset, index, index | node_maxindex(node),
285                 node->parent,
286                 node->tags[0][0], node->tags[1][0], node->tags[2][0],
287                 node->shift, node->count, node->exceptional);
288
289         for (i = 0; i < RADIX_TREE_MAP_SIZE; i++) {
290                 unsigned long first = index | (i << node->shift);
291                 unsigned long last = first | ((1UL << node->shift) - 1);
292                 void *entry = node->slots[i];
293                 if (!entry)
294                         continue;
295                 if (entry == RADIX_TREE_RETRY) {
296                         pr_debug("radix retry offset %ld indices %lu-%lu parent %p\n",
297                                         i, first, last, node);
298                 } else if (!radix_tree_is_internal_node(entry)) {
299                         pr_debug("radix entry %p offset %ld indices %lu-%lu parent %p\n",
300                                         entry, i, first, last, node);
301                 } else if (is_sibling_entry(node, entry)) {
302                         pr_debug("radix sblng %p offset %ld indices %lu-%lu parent %p val %p\n",
303                                         entry, i, first, last, node,
304                                         *(void **)entry_to_node(entry));
305                 } else {
306                         dump_node(entry_to_node(entry), first);
307                 }
308         }
309 }
310
311 /* For debug */
312 static void radix_tree_dump(struct radix_tree_root *root)
313 {
314         pr_debug("radix root: %p rnode %p tags %x\n",
315                         root, root->rnode,
316                         root->gfp_mask >> ROOT_TAG_SHIFT);
317         if (!radix_tree_is_internal_node(root->rnode))
318                 return;
319         dump_node(entry_to_node(root->rnode), 0);
320 }
321
322 static void dump_ida_node(void *entry, unsigned long index)
323 {
324         unsigned long i;
325
326         if (!entry)
327                 return;
328
329         if (radix_tree_is_internal_node(entry)) {
330                 struct radix_tree_node *node = entry_to_node(entry);
331
332                 pr_debug("ida node: %p offset %d indices %lu-%lu parent %p free %lx shift %d count %d\n",
333                         node, node->offset, index * IDA_BITMAP_BITS,
334                         ((index | node_maxindex(node)) + 1) *
335                                 IDA_BITMAP_BITS - 1,
336                         node->parent, node->tags[0][0], node->shift,
337                         node->count);
338                 for (i = 0; i < RADIX_TREE_MAP_SIZE; i++)
339                         dump_ida_node(node->slots[i],
340                                         index | (i << node->shift));
341         } else if (radix_tree_exceptional_entry(entry)) {
342                 pr_debug("ida excp: %p offset %d indices %lu-%lu data %lx\n",
343                                 entry, (int)(index & RADIX_TREE_MAP_MASK),
344                                 index * IDA_BITMAP_BITS,
345                                 index * IDA_BITMAP_BITS + BITS_PER_LONG -
346                                         RADIX_TREE_EXCEPTIONAL_SHIFT,
347                                 (unsigned long)entry >>
348                                         RADIX_TREE_EXCEPTIONAL_SHIFT);
349         } else {
350                 struct ida_bitmap *bitmap = entry;
351
352                 pr_debug("ida btmp: %p offset %d indices %lu-%lu data", bitmap,
353                                 (int)(index & RADIX_TREE_MAP_MASK),
354                                 index * IDA_BITMAP_BITS,
355                                 (index + 1) * IDA_BITMAP_BITS - 1);
356                 for (i = 0; i < IDA_BITMAP_LONGS; i++)
357                         pr_cont(" %lx", bitmap->bitmap[i]);
358                 pr_cont("\n");
359         }
360 }
361
362 static void ida_dump(struct ida *ida)
363 {
364         struct radix_tree_root *root = &ida->ida_rt;
365         pr_debug("ida: %p node %p free %d\n", ida, root->rnode,
366                                 root->gfp_mask >> ROOT_TAG_SHIFT);
367         dump_ida_node(root->rnode, 0);
368 }
369 #endif
370
371 /*
372  * This assumes that the caller has performed appropriate preallocation, and
373  * that the caller has pinned this thread of control to the current CPU.
374  */
375 static struct radix_tree_node *
376 radix_tree_node_alloc(gfp_t gfp_mask, struct radix_tree_node *parent,
377                         struct radix_tree_root *root,
378                         unsigned int shift, unsigned int offset,
379                         unsigned int count, unsigned int exceptional)
380 {
381         struct radix_tree_node *ret = NULL;
382
383         /*
384          * Preload code isn't irq safe and it doesn't make sense to use
385          * preloading during an interrupt anyway as all the allocations have
386          * to be atomic. So just do normal allocation when in interrupt.
387          */
388         if (!gfpflags_allow_blocking(gfp_mask) && !in_interrupt()) {
389                 struct radix_tree_preload *rtp;
390
391                 /*
392                  * Even if the caller has preloaded, try to allocate from the
393                  * cache first for the new node to get accounted to the memory
394                  * cgroup.
395                  */
396                 ret = kmem_cache_alloc(radix_tree_node_cachep,
397                                        gfp_mask | __GFP_NOWARN);
398                 if (ret)
399                         goto out;
400
401                 /*
402                  * Provided the caller has preloaded here, we will always
403                  * succeed in getting a node here (and never reach
404                  * kmem_cache_alloc)
405                  */
406                 rtp = this_cpu_ptr(&radix_tree_preloads);
407                 if (rtp->nr) {
408                         ret = rtp->nodes;
409                         rtp->nodes = ret->parent;
410                         rtp->nr--;
411                 }
412                 /*
413                  * Update the allocation stack trace as this is more useful
414                  * for debugging.
415                  */
416                 kmemleak_update_trace(ret);
417                 goto out;
418         }
419         ret = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
420 out:
421         BUG_ON(radix_tree_is_internal_node(ret));
422         if (ret) {
423                 ret->shift = shift;
424                 ret->offset = offset;
425                 ret->count = count;
426                 ret->exceptional = exceptional;
427                 ret->parent = parent;
428                 ret->root = root;
429         }
430         return ret;
431 }
432
433 static void radix_tree_node_rcu_free(struct rcu_head *head)
434 {
435         struct radix_tree_node *node =
436                         container_of(head, struct radix_tree_node, rcu_head);
437
438         /*
439          * Must only free zeroed nodes into the slab.  We can be left with
440          * non-NULL entries by radix_tree_free_nodes, so clear the entries
441          * and tags here.
442          */
443         memset(node->slots, 0, sizeof(node->slots));
444         memset(node->tags, 0, sizeof(node->tags));
445         INIT_LIST_HEAD(&node->private_list);
446
447         kmem_cache_free(radix_tree_node_cachep, node);
448 }
449
450 static inline void
451 radix_tree_node_free(struct radix_tree_node *node)
452 {
453         call_rcu(&node->rcu_head, radix_tree_node_rcu_free);
454 }
455
456 /*
457  * Load up this CPU's radix_tree_node buffer with sufficient objects to
458  * ensure that the addition of a single element in the tree cannot fail.  On
459  * success, return zero, with preemption disabled.  On error, return -ENOMEM
460  * with preemption not disabled.
461  *
462  * To make use of this facility, the radix tree must be initialised without
463  * __GFP_DIRECT_RECLAIM being passed to INIT_RADIX_TREE().
464  */
465 static int __radix_tree_preload(gfp_t gfp_mask, unsigned nr)
466 {
467         struct radix_tree_preload *rtp;
468         struct radix_tree_node *node;
469         int ret = -ENOMEM;
470
471         /*
472          * Nodes preloaded by one cgroup can be be used by another cgroup, so
473          * they should never be accounted to any particular memory cgroup.
474          */
475         gfp_mask &= ~__GFP_ACCOUNT;
476
477         preempt_disable();
478         rtp = this_cpu_ptr(&radix_tree_preloads);
479         while (rtp->nr < nr) {
480                 preempt_enable();
481                 node = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
482                 if (node == NULL)
483                         goto out;
484                 preempt_disable();
485                 rtp = this_cpu_ptr(&radix_tree_preloads);
486                 if (rtp->nr < nr) {
487                         node->parent = rtp->nodes;
488                         rtp->nodes = node;
489                         rtp->nr++;
490                 } else {
491                         kmem_cache_free(radix_tree_node_cachep, node);
492                 }
493         }
494         ret = 0;
495 out:
496         return ret;
497 }
498
499 /*
500  * Load up this CPU's radix_tree_node buffer with sufficient objects to
501  * ensure that the addition of a single element in the tree cannot fail.  On
502  * success, return zero, with preemption disabled.  On error, return -ENOMEM
503  * with preemption not disabled.
504  *
505  * To make use of this facility, the radix tree must be initialised without
506  * __GFP_DIRECT_RECLAIM being passed to INIT_RADIX_TREE().
507  */
508 int radix_tree_preload(gfp_t gfp_mask)
509 {
510         /* Warn on non-sensical use... */
511         WARN_ON_ONCE(!gfpflags_allow_blocking(gfp_mask));
512         return __radix_tree_preload(gfp_mask, RADIX_TREE_PRELOAD_SIZE);
513 }
514 EXPORT_SYMBOL(radix_tree_preload);
515
516 /*
517  * The same as above function, except we don't guarantee preloading happens.
518  * We do it, if we decide it helps. On success, return zero with preemption
519  * disabled. On error, return -ENOMEM with preemption not disabled.
520  */
521 int radix_tree_maybe_preload(gfp_t gfp_mask)
522 {
523         if (gfpflags_allow_blocking(gfp_mask))
524                 return __radix_tree_preload(gfp_mask, RADIX_TREE_PRELOAD_SIZE);
525         /* Preloading doesn't help anything with this gfp mask, skip it */
526         preempt_disable();
527         return 0;
528 }
529 EXPORT_SYMBOL(radix_tree_maybe_preload);
530
531 #ifdef CONFIG_RADIX_TREE_MULTIORDER
532 /*
533  * Preload with enough objects to ensure that we can split a single entry
534  * of order @old_order into many entries of size @new_order
535  */
536 int radix_tree_split_preload(unsigned int old_order, unsigned int new_order,
537                                                         gfp_t gfp_mask)
538 {
539         unsigned top = 1 << (old_order % RADIX_TREE_MAP_SHIFT);
540         unsigned layers = (old_order / RADIX_TREE_MAP_SHIFT) -
541                                 (new_order / RADIX_TREE_MAP_SHIFT);
542         unsigned nr = 0;
543
544         WARN_ON_ONCE(!gfpflags_allow_blocking(gfp_mask));
545         BUG_ON(new_order >= old_order);
546
547         while (layers--)
548                 nr = nr * RADIX_TREE_MAP_SIZE + 1;
549         return __radix_tree_preload(gfp_mask, top * nr);
550 }
551 #endif
552
553 /*
554  * The same as function above, but preload number of nodes required to insert
555  * (1 << order) continuous naturally-aligned elements.
556  */
557 int radix_tree_maybe_preload_order(gfp_t gfp_mask, int order)
558 {
559         unsigned long nr_subtrees;
560         int nr_nodes, subtree_height;
561
562         /* Preloading doesn't help anything with this gfp mask, skip it */
563         if (!gfpflags_allow_blocking(gfp_mask)) {
564                 preempt_disable();
565                 return 0;
566         }
567
568         /*
569          * Calculate number and height of fully populated subtrees it takes to
570          * store (1 << order) elements.
571          */
572         nr_subtrees = 1 << order;
573         for (subtree_height = 0; nr_subtrees > RADIX_TREE_MAP_SIZE;
574                         subtree_height++)
575                 nr_subtrees >>= RADIX_TREE_MAP_SHIFT;
576
577         /*
578          * The worst case is zero height tree with a single item at index 0 and
579          * then inserting items starting at ULONG_MAX - (1 << order).
580          *
581          * This requires RADIX_TREE_MAX_PATH nodes to build branch from root to
582          * 0-index item.
583          */
584         nr_nodes = RADIX_TREE_MAX_PATH;
585
586         /* Plus branch to fully populated subtrees. */
587         nr_nodes += RADIX_TREE_MAX_PATH - subtree_height;
588
589         /* Root node is shared. */
590         nr_nodes--;
591
592         /* Plus nodes required to build subtrees. */
593         nr_nodes += nr_subtrees * height_to_maxnodes[subtree_height];
594
595         return __radix_tree_preload(gfp_mask, nr_nodes);
596 }
597
598 static unsigned radix_tree_load_root(const struct radix_tree_root *root,
599                 struct radix_tree_node **nodep, unsigned long *maxindex)
600 {
601         struct radix_tree_node *node = rcu_dereference_raw(root->rnode);
602
603         *nodep = node;
604
605         if (likely(radix_tree_is_internal_node(node))) {
606                 node = entry_to_node(node);
607                 *maxindex = node_maxindex(node);
608                 return node->shift + RADIX_TREE_MAP_SHIFT;
609         }
610
611         *maxindex = 0;
612         return 0;
613 }
614
615 /*
616  *      Extend a radix tree so it can store key @index.
617  */
618 static int radix_tree_extend(struct radix_tree_root *root, gfp_t gfp,
619                                 unsigned long index, unsigned int shift)
620 {
621         struct radix_tree_node *slot;
622         unsigned int maxshift;
623         int tag;
624
625         /* Figure out what the shift should be.  */
626         maxshift = shift;
627         while (index > shift_maxindex(maxshift))
628                 maxshift += RADIX_TREE_MAP_SHIFT;
629
630         slot = root->rnode;
631         if (!slot && (!is_idr(root) || root_tag_get(root, IDR_FREE)))
632                 goto out;
633
634         do {
635                 struct radix_tree_node *node = radix_tree_node_alloc(gfp, NULL,
636                                                         root, shift, 0, 1, 0);
637                 if (!node)
638                         return -ENOMEM;
639
640                 if (is_idr(root)) {
641                         all_tag_set(node, IDR_FREE);
642                         if (!root_tag_get(root, IDR_FREE)) {
643                                 tag_clear(node, IDR_FREE, 0);
644                                 root_tag_set(root, IDR_FREE);
645                         }
646                 } else {
647                         /* Propagate the aggregated tag info to the new child */
648                         for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
649                                 if (root_tag_get(root, tag))
650                                         tag_set(node, tag, 0);
651                         }
652                 }
653
654                 BUG_ON(shift > BITS_PER_LONG);
655                 if (radix_tree_is_internal_node(slot)) {
656                         entry_to_node(slot)->parent = node;
657                 } else if (radix_tree_exceptional_entry(slot)) {
658                         /* Moving an exceptional root->rnode to a node */
659                         node->exceptional = 1;
660                 }
661                 node->slots[0] = slot;
662                 slot = node_to_entry(node);
663                 rcu_assign_pointer(root->rnode, slot);
664                 shift += RADIX_TREE_MAP_SHIFT;
665         } while (shift <= maxshift);
666 out:
667         return maxshift + RADIX_TREE_MAP_SHIFT;
668 }
669
670 /**
671  *      radix_tree_shrink    -    shrink radix tree to minimum height
672  *      @root           radix tree root
673  */
674 static inline bool radix_tree_shrink(struct radix_tree_root *root,
675                                      radix_tree_update_node_t update_node,
676                                      void *private)
677 {
678         bool shrunk = false;
679
680         for (;;) {
681                 struct radix_tree_node *node = root->rnode;
682                 struct radix_tree_node *child;
683
684                 if (!radix_tree_is_internal_node(node))
685                         break;
686                 node = entry_to_node(node);
687
688                 /*
689                  * The candidate node has more than one child, or its child
690                  * is not at the leftmost slot, or the child is a multiorder
691                  * entry, we cannot shrink.
692                  */
693                 if (node->count != 1)
694                         break;
695                 child = node->slots[0];
696                 if (!child)
697                         break;
698                 if (!radix_tree_is_internal_node(child) && node->shift)
699                         break;
700
701                 if (radix_tree_is_internal_node(child))
702                         entry_to_node(child)->parent = NULL;
703
704                 /*
705                  * We don't need rcu_assign_pointer(), since we are simply
706                  * moving the node from one part of the tree to another: if it
707                  * was safe to dereference the old pointer to it
708                  * (node->slots[0]), it will be safe to dereference the new
709                  * one (root->rnode) as far as dependent read barriers go.
710                  */
711                 root->rnode = child;
712                 if (is_idr(root) && !tag_get(node, IDR_FREE, 0))
713                         root_tag_clear(root, IDR_FREE);
714
715                 /*
716                  * We have a dilemma here. The node's slot[0] must not be
717                  * NULLed in case there are concurrent lookups expecting to
718                  * find the item. However if this was a bottom-level node,
719                  * then it may be subject to the slot pointer being visible
720                  * to callers dereferencing it. If item corresponding to
721                  * slot[0] is subsequently deleted, these callers would expect
722                  * their slot to become empty sooner or later.
723                  *
724                  * For example, lockless pagecache will look up a slot, deref
725                  * the page pointer, and if the page has 0 refcount it means it
726                  * was concurrently deleted from pagecache so try the deref
727                  * again. Fortunately there is already a requirement for logic
728                  * to retry the entire slot lookup -- the indirect pointer
729                  * problem (replacing direct root node with an indirect pointer
730                  * also results in a stale slot). So tag the slot as indirect
731                  * to force callers to retry.
732                  */
733                 node->count = 0;
734                 if (!radix_tree_is_internal_node(child)) {
735                         node->slots[0] = RADIX_TREE_RETRY;
736                         if (update_node)
737                                 update_node(node, private);
738                 }
739
740                 WARN_ON_ONCE(!list_empty(&node->private_list));
741                 radix_tree_node_free(node);
742                 shrunk = true;
743         }
744
745         return shrunk;
746 }
747
748 static bool delete_node(struct radix_tree_root *root,
749                         struct radix_tree_node *node,
750                         radix_tree_update_node_t update_node, void *private)
751 {
752         bool deleted = false;
753
754         do {
755                 struct radix_tree_node *parent;
756
757                 if (node->count) {
758                         if (node == entry_to_node(root->rnode))
759                                 deleted |= radix_tree_shrink(root, update_node,
760                                                                 private);
761                         return deleted;
762                 }
763
764                 parent = node->parent;
765                 if (parent) {
766                         parent->slots[node->offset] = NULL;
767                         parent->count--;
768                 } else {
769                         /*
770                          * Shouldn't the tags already have all been cleared
771                          * by the caller?
772                          */
773                         if (!is_idr(root))
774                                 root_tag_clear_all(root);
775                         root->rnode = NULL;
776                 }
777
778                 WARN_ON_ONCE(!list_empty(&node->private_list));
779                 radix_tree_node_free(node);
780                 deleted = true;
781
782                 node = parent;
783         } while (node);
784
785         return deleted;
786 }
787
788 /**
789  *      __radix_tree_create     -       create a slot in a radix tree
790  *      @root:          radix tree root
791  *      @index:         index key
792  *      @order:         index occupies 2^order aligned slots
793  *      @nodep:         returns node
794  *      @slotp:         returns slot
795  *
796  *      Create, if necessary, and return the node and slot for an item
797  *      at position @index in the radix tree @root.
798  *
799  *      Until there is more than one item in the tree, no nodes are
800  *      allocated and @root->rnode is used as a direct slot instead of
801  *      pointing to a node, in which case *@nodep will be NULL.
802  *
803  *      Returns -ENOMEM, or 0 for success.
804  */
805 int __radix_tree_create(struct radix_tree_root *root, unsigned long index,
806                         unsigned order, struct radix_tree_node **nodep,
807                         void ***slotp)
808 {
809         struct radix_tree_node *node = NULL, *child;
810         void **slot = (void **)&root->rnode;
811         unsigned long maxindex;
812         unsigned int shift, offset = 0;
813         unsigned long max = index | ((1UL << order) - 1);
814         gfp_t gfp = root_gfp_mask(root);
815
816         shift = radix_tree_load_root(root, &child, &maxindex);
817
818         /* Make sure the tree is high enough.  */
819         if (order > 0 && max == ((1UL << order) - 1))
820                 max++;
821         if (max > maxindex) {
822                 int error = radix_tree_extend(root, gfp, max, shift);
823                 if (error < 0)
824                         return error;
825                 shift = error;
826                 child = root->rnode;
827         }
828
829         while (shift > order) {
830                 shift -= RADIX_TREE_MAP_SHIFT;
831                 if (child == NULL) {
832                         /* Have to add a child node.  */
833                         child = radix_tree_node_alloc(gfp, node, root, shift,
834                                                         offset, 0, 0);
835                         if (!child)
836                                 return -ENOMEM;
837                         rcu_assign_pointer(*slot, node_to_entry(child));
838                         if (node)
839                                 node->count++;
840                 } else if (!radix_tree_is_internal_node(child))
841                         break;
842
843                 /* Go a level down */
844                 node = entry_to_node(child);
845                 offset = radix_tree_descend(node, &child, index);
846                 slot = &node->slots[offset];
847         }
848
849         if (nodep)
850                 *nodep = node;
851         if (slotp)
852                 *slotp = slot;
853         return 0;
854 }
855
856 /*
857  * Free any nodes below this node.  The tree is presumed to not need
858  * shrinking, and any user data in the tree is presumed to not need a
859  * destructor called on it.  If we need to add a destructor, we can
860  * add that functionality later.  Note that we may not clear tags or
861  * slots from the tree as an RCU walker may still have a pointer into
862  * this subtree.  We could replace the entries with RADIX_TREE_RETRY,
863  * but we'll still have to clear those in rcu_free.
864  */
865 static void radix_tree_free_nodes(struct radix_tree_node *node)
866 {
867         unsigned offset = 0;
868         struct radix_tree_node *child = entry_to_node(node);
869
870         for (;;) {
871                 void *entry = child->slots[offset];
872                 if (radix_tree_is_internal_node(entry) &&
873                                         !is_sibling_entry(child, entry)) {
874                         child = entry_to_node(entry);
875                         offset = 0;
876                         continue;
877                 }
878                 offset++;
879                 while (offset == RADIX_TREE_MAP_SIZE) {
880                         struct radix_tree_node *old = child;
881                         offset = child->offset + 1;
882                         child = child->parent;
883                         WARN_ON_ONCE(!list_empty(&old->private_list));
884                         radix_tree_node_free(old);
885                         if (old == entry_to_node(node))
886                                 return;
887                 }
888         }
889 }
890
891 #ifdef CONFIG_RADIX_TREE_MULTIORDER
892 static inline int insert_entries(struct radix_tree_node *node, void **slot,
893                                 void *item, unsigned order, bool replace)
894 {
895         struct radix_tree_node *child;
896         unsigned i, n, tag, offset, tags = 0;
897
898         if (node) {
899                 if (order > node->shift)
900                         n = 1 << (order - node->shift);
901                 else
902                         n = 1;
903                 offset = get_slot_offset(node, slot);
904         } else {
905                 n = 1;
906                 offset = 0;
907         }
908
909         if (n > 1) {
910                 offset = offset & ~(n - 1);
911                 slot = &node->slots[offset];
912         }
913         child = node_to_entry(slot);
914
915         for (i = 0; i < n; i++) {
916                 if (slot[i]) {
917                         if (replace) {
918                                 node->count--;
919                                 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
920                                         if (tag_get(node, tag, offset + i))
921                                                 tags |= 1 << tag;
922                         } else
923                                 return -EEXIST;
924                 }
925         }
926
927         for (i = 0; i < n; i++) {
928                 struct radix_tree_node *old = slot[i];
929                 if (i) {
930                         rcu_assign_pointer(slot[i], child);
931                         for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
932                                 if (tags & (1 << tag))
933                                         tag_clear(node, tag, offset + i);
934                 } else {
935                         rcu_assign_pointer(slot[i], item);
936                         for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
937                                 if (tags & (1 << tag))
938                                         tag_set(node, tag, offset);
939                 }
940                 if (radix_tree_is_internal_node(old) &&
941                                         !is_sibling_entry(node, old) &&
942                                         (old != RADIX_TREE_RETRY))
943                         radix_tree_free_nodes(old);
944                 if (radix_tree_exceptional_entry(old))
945                         node->exceptional--;
946         }
947         if (node) {
948                 node->count += n;
949                 if (radix_tree_exceptional_entry(item))
950                         node->exceptional += n;
951         }
952         return n;
953 }
954 #else
955 static inline int insert_entries(struct radix_tree_node *node, void **slot,
956                                 void *item, unsigned order, bool replace)
957 {
958         if (*slot)
959                 return -EEXIST;
960         rcu_assign_pointer(*slot, item);
961         if (node) {
962                 node->count++;
963                 if (radix_tree_exceptional_entry(item))
964                         node->exceptional++;
965         }
966         return 1;
967 }
968 #endif
969
970 /**
971  *      __radix_tree_insert    -    insert into a radix tree
972  *      @root:          radix tree root
973  *      @index:         index key
974  *      @order:         key covers the 2^order indices around index
975  *      @item:          item to insert
976  *
977  *      Insert an item into the radix tree at position @index.
978  */
979 int __radix_tree_insert(struct radix_tree_root *root, unsigned long index,
980                         unsigned order, void *item)
981 {
982         struct radix_tree_node *node;
983         void **slot;
984         int error;
985
986         BUG_ON(radix_tree_is_internal_node(item));
987
988         error = __radix_tree_create(root, index, order, &node, &slot);
989         if (error)
990                 return error;
991
992         error = insert_entries(node, slot, item, order, false);
993         if (error < 0)
994                 return error;
995
996         if (node) {
997                 unsigned offset = get_slot_offset(node, slot);
998                 BUG_ON(tag_get(node, 0, offset));
999                 BUG_ON(tag_get(node, 1, offset));
1000                 BUG_ON(tag_get(node, 2, offset));
1001         } else {
1002                 BUG_ON(root_tags_get(root));
1003         }
1004
1005         return 0;
1006 }
1007 EXPORT_SYMBOL(__radix_tree_insert);
1008
1009 /**
1010  *      __radix_tree_lookup     -       lookup an item in a radix tree
1011  *      @root:          radix tree root
1012  *      @index:         index key
1013  *      @nodep:         returns node
1014  *      @slotp:         returns slot
1015  *
1016  *      Lookup and return the item at position @index in the radix
1017  *      tree @root.
1018  *
1019  *      Until there is more than one item in the tree, no nodes are
1020  *      allocated and @root->rnode is used as a direct slot instead of
1021  *      pointing to a node, in which case *@nodep will be NULL.
1022  */
1023 void *__radix_tree_lookup(const struct radix_tree_root *root,
1024                           unsigned long index, struct radix_tree_node **nodep,
1025                           void ***slotp)
1026 {
1027         struct radix_tree_node *node, *parent;
1028         unsigned long maxindex;
1029         void **slot;
1030
1031  restart:
1032         parent = NULL;
1033         slot = (void **)&root->rnode;
1034         radix_tree_load_root(root, &node, &maxindex);
1035         if (index > maxindex)
1036                 return NULL;
1037
1038         while (radix_tree_is_internal_node(node)) {
1039                 unsigned offset;
1040
1041                 if (node == RADIX_TREE_RETRY)
1042                         goto restart;
1043                 parent = entry_to_node(node);
1044                 offset = radix_tree_descend(parent, &node, index);
1045                 slot = parent->slots + offset;
1046         }
1047
1048         if (nodep)
1049                 *nodep = parent;
1050         if (slotp)
1051                 *slotp = slot;
1052         return node;
1053 }
1054
1055 /**
1056  *      radix_tree_lookup_slot    -    lookup a slot in a radix tree
1057  *      @root:          radix tree root
1058  *      @index:         index key
1059  *
1060  *      Returns:  the slot corresponding to the position @index in the
1061  *      radix tree @root. This is useful for update-if-exists operations.
1062  *
1063  *      This function can be called under rcu_read_lock iff the slot is not
1064  *      modified by radix_tree_replace_slot, otherwise it must be called
1065  *      exclusive from other writers. Any dereference of the slot must be done
1066  *      using radix_tree_deref_slot.
1067  */
1068 void **radix_tree_lookup_slot(const struct radix_tree_root *root,
1069                                 unsigned long index)
1070 {
1071         void **slot;
1072
1073         if (!__radix_tree_lookup(root, index, NULL, &slot))
1074                 return NULL;
1075         return slot;
1076 }
1077 EXPORT_SYMBOL(radix_tree_lookup_slot);
1078
1079 /**
1080  *      radix_tree_lookup    -    perform lookup operation on a radix tree
1081  *      @root:          radix tree root
1082  *      @index:         index key
1083  *
1084  *      Lookup the item at the position @index in the radix tree @root.
1085  *
1086  *      This function can be called under rcu_read_lock, however the caller
1087  *      must manage lifetimes of leaf nodes (eg. RCU may also be used to free
1088  *      them safely). No RCU barriers are required to access or modify the
1089  *      returned item, however.
1090  */
1091 void *radix_tree_lookup(const struct radix_tree_root *root, unsigned long index)
1092 {
1093         return __radix_tree_lookup(root, index, NULL, NULL);
1094 }
1095 EXPORT_SYMBOL(radix_tree_lookup);
1096
1097 static inline void replace_sibling_entries(struct radix_tree_node *node,
1098                                 void **slot, int count, int exceptional)
1099 {
1100 #ifdef CONFIG_RADIX_TREE_MULTIORDER
1101         void *ptr = node_to_entry(slot);
1102         unsigned offset = get_slot_offset(node, slot) + 1;
1103
1104         while (offset < RADIX_TREE_MAP_SIZE) {
1105                 if (node->slots[offset] != ptr)
1106                         break;
1107                 if (count < 0) {
1108                         node->slots[offset] = NULL;
1109                         node->count--;
1110                 }
1111                 node->exceptional += exceptional;
1112                 offset++;
1113         }
1114 #endif
1115 }
1116
1117 static void replace_slot(void **slot, void *item, struct radix_tree_node *node,
1118                                 int count, int exceptional)
1119 {
1120         if (WARN_ON_ONCE(radix_tree_is_internal_node(item)))
1121                 return;
1122
1123         if (node && (count || exceptional)) {
1124                 node->count += count;
1125                 node->exceptional += exceptional;
1126                 replace_sibling_entries(node, slot, count, exceptional);
1127         }
1128
1129         rcu_assign_pointer(*slot, item);
1130 }
1131
1132 static bool node_tag_get(const struct radix_tree_root *root,
1133                                 const struct radix_tree_node *node,
1134                                 unsigned int tag, unsigned int offset)
1135 {
1136         if (node)
1137                 return tag_get(node, tag, offset);
1138         return root_tag_get(root, tag);
1139 }
1140
1141 /*
1142  * IDR users want to be able to store NULL in the tree, so if the slot isn't
1143  * free, don't adjust the count, even if it's transitioning between NULL and
1144  * non-NULL.  For the IDA, we mark slots as being IDR_FREE while they still
1145  * have empty bits, but it only stores NULL in slots when they're being
1146  * deleted.
1147  */
1148 static int calculate_count(struct radix_tree_root *root,
1149                                 struct radix_tree_node *node, void **slot,
1150                                 void *item, void *old)
1151 {
1152         if (is_idr(root)) {
1153                 unsigned offset = get_slot_offset(node, slot);
1154                 bool free = node_tag_get(root, node, IDR_FREE, offset);
1155                 if (!free)
1156                         return 0;
1157                 if (!old)
1158                         return 1;
1159         }
1160         return !!item - !!old;
1161 }
1162
1163 /**
1164  * __radix_tree_replace         - replace item in a slot
1165  * @root:               radix tree root
1166  * @node:               pointer to tree node
1167  * @slot:               pointer to slot in @node
1168  * @item:               new item to store in the slot.
1169  * @update_node:        callback for changing leaf nodes
1170  * @private:            private data to pass to @update_node
1171  *
1172  * For use with __radix_tree_lookup().  Caller must hold tree write locked
1173  * across slot lookup and replacement.
1174  */
1175 void __radix_tree_replace(struct radix_tree_root *root,
1176                           struct radix_tree_node *node,
1177                           void **slot, void *item,
1178                           radix_tree_update_node_t update_node, void *private)
1179 {
1180         void *old = rcu_dereference_raw(*slot);
1181         int exceptional = !!radix_tree_exceptional_entry(item) -
1182                                 !!radix_tree_exceptional_entry(old);
1183         int count = calculate_count(root, node, slot, item, old);
1184
1185         /*
1186          * This function supports replacing exceptional entries and
1187          * deleting entries, but that needs accounting against the
1188          * node unless the slot is root->rnode.
1189          */
1190         WARN_ON_ONCE(!node && (slot != (void **)&root->rnode) &&
1191                         (count || exceptional));
1192         replace_slot(slot, item, node, count, exceptional);
1193
1194         if (!node)
1195                 return;
1196
1197         if (update_node)
1198                 update_node(node, private);
1199
1200         delete_node(root, node, update_node, private);
1201 }
1202
1203 /**
1204  * radix_tree_replace_slot      - replace item in a slot
1205  * @root:       radix tree root
1206  * @slot:       pointer to slot
1207  * @item:       new item to store in the slot.
1208  *
1209  * For use with radix_tree_lookup_slot(), radix_tree_gang_lookup_slot(),
1210  * radix_tree_gang_lookup_tag_slot().  Caller must hold tree write locked
1211  * across slot lookup and replacement.
1212  *
1213  * NOTE: This cannot be used to switch between non-entries (empty slots),
1214  * regular entries, and exceptional entries, as that requires accounting
1215  * inside the radix tree node. When switching from one type of entry or
1216  * deleting, use __radix_tree_lookup() and __radix_tree_replace() or
1217  * radix_tree_iter_replace().
1218  */
1219 void radix_tree_replace_slot(struct radix_tree_root *root,
1220                              void **slot, void *item)
1221 {
1222         __radix_tree_replace(root, NULL, slot, item, NULL, NULL);
1223 }
1224
1225 /**
1226  * radix_tree_iter_replace - replace item in a slot
1227  * @root:       radix tree root
1228  * @slot:       pointer to slot
1229  * @item:       new item to store in the slot.
1230  *
1231  * For use with radix_tree_split() and radix_tree_for_each_slot().
1232  * Caller must hold tree write locked across split and replacement.
1233  */
1234 void radix_tree_iter_replace(struct radix_tree_root *root,
1235                 const struct radix_tree_iter *iter, void **slot, void *item)
1236 {
1237         __radix_tree_replace(root, iter->node, slot, item, NULL, NULL);
1238 }
1239
1240 #ifdef CONFIG_RADIX_TREE_MULTIORDER
1241 /**
1242  * radix_tree_join - replace multiple entries with one multiorder entry
1243  * @root: radix tree root
1244  * @index: an index inside the new entry
1245  * @order: order of the new entry
1246  * @item: new entry
1247  *
1248  * Call this function to replace several entries with one larger entry.
1249  * The existing entries are presumed to not need freeing as a result of
1250  * this call.
1251  *
1252  * The replacement entry will have all the tags set on it that were set
1253  * on any of the entries it is replacing.
1254  */
1255 int radix_tree_join(struct radix_tree_root *root, unsigned long index,
1256                         unsigned order, void *item)
1257 {
1258         struct radix_tree_node *node;
1259         void **slot;
1260         int error;
1261
1262         BUG_ON(radix_tree_is_internal_node(item));
1263
1264         error = __radix_tree_create(root, index, order, &node, &slot);
1265         if (!error)
1266                 error = insert_entries(node, slot, item, order, true);
1267         if (error > 0)
1268                 error = 0;
1269
1270         return error;
1271 }
1272
1273 /**
1274  * radix_tree_split - Split an entry into smaller entries
1275  * @root: radix tree root
1276  * @index: An index within the large entry
1277  * @order: Order of new entries
1278  *
1279  * Call this function as the first step in replacing a multiorder entry
1280  * with several entries of lower order.  After this function returns,
1281  * loop over the relevant portion of the tree using radix_tree_for_each_slot()
1282  * and call radix_tree_iter_replace() to set up each new entry.
1283  *
1284  * The tags from this entry are replicated to all the new entries.
1285  *
1286  * The radix tree should be locked against modification during the entire
1287  * replacement operation.  Lock-free lookups will see RADIX_TREE_RETRY which
1288  * should prompt RCU walkers to restart the lookup from the root.
1289  */
1290 int radix_tree_split(struct radix_tree_root *root, unsigned long index,
1291                                 unsigned order)
1292 {
1293         struct radix_tree_node *parent, *node, *child;
1294         void **slot;
1295         unsigned int offset, end;
1296         unsigned n, tag, tags = 0;
1297         gfp_t gfp = root_gfp_mask(root);
1298
1299         if (!__radix_tree_lookup(root, index, &parent, &slot))
1300                 return -ENOENT;
1301         if (!parent)
1302                 return -ENOENT;
1303
1304         offset = get_slot_offset(parent, slot);
1305
1306         for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
1307                 if (tag_get(parent, tag, offset))
1308                         tags |= 1 << tag;
1309
1310         for (end = offset + 1; end < RADIX_TREE_MAP_SIZE; end++) {
1311                 if (!is_sibling_entry(parent, parent->slots[end]))
1312                         break;
1313                 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
1314                         if (tags & (1 << tag))
1315                                 tag_set(parent, tag, end);
1316                 /* rcu_assign_pointer ensures tags are set before RETRY */
1317                 rcu_assign_pointer(parent->slots[end], RADIX_TREE_RETRY);
1318         }
1319         rcu_assign_pointer(parent->slots[offset], RADIX_TREE_RETRY);
1320         parent->exceptional -= (end - offset);
1321
1322         if (order == parent->shift)
1323                 return 0;
1324         if (order > parent->shift) {
1325                 while (offset < end)
1326                         offset += insert_entries(parent, &parent->slots[offset],
1327                                         RADIX_TREE_RETRY, order, true);
1328                 return 0;
1329         }
1330
1331         node = parent;
1332
1333         for (;;) {
1334                 if (node->shift > order) {
1335                         child = radix_tree_node_alloc(gfp, node, root,
1336                                         node->shift - RADIX_TREE_MAP_SHIFT,
1337                                         offset, 0, 0);
1338                         if (!child)
1339                                 goto nomem;
1340                         if (node != parent) {
1341                                 node->count++;
1342                                 node->slots[offset] = node_to_entry(child);
1343                                 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
1344                                         if (tags & (1 << tag))
1345                                                 tag_set(node, tag, offset);
1346                         }
1347
1348                         node = child;
1349                         offset = 0;
1350                         continue;
1351                 }
1352
1353                 n = insert_entries(node, &node->slots[offset],
1354                                         RADIX_TREE_RETRY, order, false);
1355                 BUG_ON(n > RADIX_TREE_MAP_SIZE);
1356
1357                 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
1358                         if (tags & (1 << tag))
1359                                 tag_set(node, tag, offset);
1360                 offset += n;
1361
1362                 while (offset == RADIX_TREE_MAP_SIZE) {
1363                         if (node == parent)
1364                                 break;
1365                         offset = node->offset;
1366                         child = node;
1367                         node = node->parent;
1368                         rcu_assign_pointer(node->slots[offset],
1369                                                 node_to_entry(child));
1370                         offset++;
1371                 }
1372                 if ((node == parent) && (offset == end))
1373                         return 0;
1374         }
1375
1376  nomem:
1377         /* Shouldn't happen; did user forget to preload? */
1378         /* TODO: free all the allocated nodes */
1379         WARN_ON(1);
1380         return -ENOMEM;
1381 }
1382 #endif
1383
1384 static void node_tag_set(struct radix_tree_root *root,
1385                                 struct radix_tree_node *node,
1386                                 unsigned int tag, unsigned int offset)
1387 {
1388         while (node) {
1389                 if (tag_get(node, tag, offset))
1390                         return;
1391                 tag_set(node, tag, offset);
1392                 offset = node->offset;
1393                 node = node->parent;
1394         }
1395
1396         if (!root_tag_get(root, tag))
1397                 root_tag_set(root, tag);
1398 }
1399
1400 /**
1401  *      radix_tree_tag_set - set a tag on a radix tree node
1402  *      @root:          radix tree root
1403  *      @index:         index key
1404  *      @tag:           tag index
1405  *
1406  *      Set the search tag (which must be < RADIX_TREE_MAX_TAGS)
1407  *      corresponding to @index in the radix tree.  From
1408  *      the root all the way down to the leaf node.
1409  *
1410  *      Returns the address of the tagged item.  Setting a tag on a not-present
1411  *      item is a bug.
1412  */
1413 void *radix_tree_tag_set(struct radix_tree_root *root,
1414                         unsigned long index, unsigned int tag)
1415 {
1416         struct radix_tree_node *node, *parent;
1417         unsigned long maxindex;
1418
1419         radix_tree_load_root(root, &node, &maxindex);
1420         BUG_ON(index > maxindex);
1421
1422         while (radix_tree_is_internal_node(node)) {
1423                 unsigned offset;
1424
1425                 parent = entry_to_node(node);
1426                 offset = radix_tree_descend(parent, &node, index);
1427                 BUG_ON(!node);
1428
1429                 if (!tag_get(parent, tag, offset))
1430                         tag_set(parent, tag, offset);
1431         }
1432
1433         /* set the root's tag bit */
1434         if (!root_tag_get(root, tag))
1435                 root_tag_set(root, tag);
1436
1437         return node;
1438 }
1439 EXPORT_SYMBOL(radix_tree_tag_set);
1440
1441 /**
1442  * radix_tree_iter_tag_set - set a tag on the current iterator entry
1443  * @root:       radix tree root
1444  * @iter:       iterator state
1445  * @tag:        tag to set
1446  */
1447 void radix_tree_iter_tag_set(struct radix_tree_root *root,
1448                         const struct radix_tree_iter *iter, unsigned int tag)
1449 {
1450         node_tag_set(root, iter->node, tag, iter_offset(iter));
1451 }
1452
1453 static void node_tag_clear(struct radix_tree_root *root,
1454                                 struct radix_tree_node *node,
1455                                 unsigned int tag, unsigned int offset)
1456 {
1457         while (node) {
1458                 if (!tag_get(node, tag, offset))
1459                         return;
1460                 tag_clear(node, tag, offset);
1461                 if (any_tag_set(node, tag))
1462                         return;
1463
1464                 offset = node->offset;
1465                 node = node->parent;
1466         }
1467
1468         /* clear the root's tag bit */
1469         if (root_tag_get(root, tag))
1470                 root_tag_clear(root, tag);
1471 }
1472
1473 /**
1474  *      radix_tree_tag_clear - clear a tag on a radix tree node
1475  *      @root:          radix tree root
1476  *      @index:         index key
1477  *      @tag:           tag index
1478  *
1479  *      Clear the search tag (which must be < RADIX_TREE_MAX_TAGS)
1480  *      corresponding to @index in the radix tree.  If this causes
1481  *      the leaf node to have no tags set then clear the tag in the
1482  *      next-to-leaf node, etc.
1483  *
1484  *      Returns the address of the tagged item on success, else NULL.  ie:
1485  *      has the same return value and semantics as radix_tree_lookup().
1486  */
1487 void *radix_tree_tag_clear(struct radix_tree_root *root,
1488                         unsigned long index, unsigned int tag)
1489 {
1490         struct radix_tree_node *node, *parent;
1491         unsigned long maxindex;
1492         int uninitialized_var(offset);
1493
1494         radix_tree_load_root(root, &node, &maxindex);
1495         if (index > maxindex)
1496                 return NULL;
1497
1498         parent = NULL;
1499
1500         while (radix_tree_is_internal_node(node)) {
1501                 parent = entry_to_node(node);
1502                 offset = radix_tree_descend(parent, &node, index);
1503         }
1504
1505         if (node)
1506                 node_tag_clear(root, parent, tag, offset);
1507
1508         return node;
1509 }
1510 EXPORT_SYMBOL(radix_tree_tag_clear);
1511
1512 /**
1513   * radix_tree_iter_tag_clear - clear a tag on the current iterator entry
1514   * @root: radix tree root
1515   * @iter: iterator state
1516   * @tag: tag to clear
1517   */
1518 void radix_tree_iter_tag_clear(struct radix_tree_root *root,
1519                         const struct radix_tree_iter *iter, unsigned int tag)
1520 {
1521         node_tag_clear(root, iter->node, tag, iter_offset(iter));
1522 }
1523
1524 /**
1525  * radix_tree_tag_get - get a tag on a radix tree node
1526  * @root:               radix tree root
1527  * @index:              index key
1528  * @tag:                tag index (< RADIX_TREE_MAX_TAGS)
1529  *
1530  * Return values:
1531  *
1532  *  0: tag not present or not set
1533  *  1: tag set
1534  *
1535  * Note that the return value of this function may not be relied on, even if
1536  * the RCU lock is held, unless tag modification and node deletion are excluded
1537  * from concurrency.
1538  */
1539 int radix_tree_tag_get(const struct radix_tree_root *root,
1540                         unsigned long index, unsigned int tag)
1541 {
1542         struct radix_tree_node *node, *parent;
1543         unsigned long maxindex;
1544
1545         if (!root_tag_get(root, tag))
1546                 return 0;
1547
1548         radix_tree_load_root(root, &node, &maxindex);
1549         if (index > maxindex)
1550                 return 0;
1551
1552         while (radix_tree_is_internal_node(node)) {
1553                 unsigned offset;
1554
1555                 parent = entry_to_node(node);
1556                 offset = radix_tree_descend(parent, &node, index);
1557
1558                 if (!tag_get(parent, tag, offset))
1559                         return 0;
1560                 if (node == RADIX_TREE_RETRY)
1561                         break;
1562         }
1563
1564         return 1;
1565 }
1566 EXPORT_SYMBOL(radix_tree_tag_get);
1567
1568 static inline void __set_iter_shift(struct radix_tree_iter *iter,
1569                                         unsigned int shift)
1570 {
1571 #ifdef CONFIG_RADIX_TREE_MULTIORDER
1572         iter->shift = shift;
1573 #endif
1574 }
1575
1576 /* Construct iter->tags bit-mask from node->tags[tag] array */
1577 static void set_iter_tags(struct radix_tree_iter *iter,
1578                                 struct radix_tree_node *node, unsigned offset,
1579                                 unsigned tag)
1580 {
1581         unsigned tag_long = offset / BITS_PER_LONG;
1582         unsigned tag_bit  = offset % BITS_PER_LONG;
1583
1584         if (!node) {
1585                 iter->tags = 1;
1586                 return;
1587         }
1588
1589         iter->tags = node->tags[tag][tag_long] >> tag_bit;
1590
1591         /* This never happens if RADIX_TREE_TAG_LONGS == 1 */
1592         if (tag_long < RADIX_TREE_TAG_LONGS - 1) {
1593                 /* Pick tags from next element */
1594                 if (tag_bit)
1595                         iter->tags |= node->tags[tag][tag_long + 1] <<
1596                                                 (BITS_PER_LONG - tag_bit);
1597                 /* Clip chunk size, here only BITS_PER_LONG tags */
1598                 iter->next_index = __radix_tree_iter_add(iter, BITS_PER_LONG);
1599         }
1600 }
1601
1602 #ifdef CONFIG_RADIX_TREE_MULTIORDER
1603 static void **skip_siblings(struct radix_tree_node **nodep,
1604                         void **slot, struct radix_tree_iter *iter)
1605 {
1606         void *sib = node_to_entry(slot - 1);
1607
1608         while (iter->index < iter->next_index) {
1609                 *nodep = rcu_dereference_raw(*slot);
1610                 if (*nodep && *nodep != sib)
1611                         return slot;
1612                 slot++;
1613                 iter->index = __radix_tree_iter_add(iter, 1);
1614                 iter->tags >>= 1;
1615         }
1616
1617         *nodep = NULL;
1618         return NULL;
1619 }
1620
1621 void ** __radix_tree_next_slot(void **slot, struct radix_tree_iter *iter,
1622                                         unsigned flags)
1623 {
1624         unsigned tag = flags & RADIX_TREE_ITER_TAG_MASK;
1625         struct radix_tree_node *node = rcu_dereference_raw(*slot);
1626
1627         slot = skip_siblings(&node, slot, iter);
1628
1629         while (radix_tree_is_internal_node(node)) {
1630                 unsigned offset;
1631                 unsigned long next_index;
1632
1633                 if (node == RADIX_TREE_RETRY)
1634                         return slot;
1635                 node = entry_to_node(node);
1636                 iter->node = node;
1637                 iter->shift = node->shift;
1638
1639                 if (flags & RADIX_TREE_ITER_TAGGED) {
1640                         offset = radix_tree_find_next_bit(node, tag, 0);
1641                         if (offset == RADIX_TREE_MAP_SIZE)
1642                                 return NULL;
1643                         slot = &node->slots[offset];
1644                         iter->index = __radix_tree_iter_add(iter, offset);
1645                         set_iter_tags(iter, node, offset, tag);
1646                         node = rcu_dereference_raw(*slot);
1647                 } else {
1648                         offset = 0;
1649                         slot = &node->slots[0];
1650                         for (;;) {
1651                                 node = rcu_dereference_raw(*slot);
1652                                 if (node)
1653                                         break;
1654                                 slot++;
1655                                 offset++;
1656                                 if (offset == RADIX_TREE_MAP_SIZE)
1657                                         return NULL;
1658                         }
1659                         iter->index = __radix_tree_iter_add(iter, offset);
1660                 }
1661                 if ((flags & RADIX_TREE_ITER_CONTIG) && (offset > 0))
1662                         goto none;
1663                 next_index = (iter->index | shift_maxindex(iter->shift)) + 1;
1664                 if (next_index < iter->next_index)
1665                         iter->next_index = next_index;
1666         }
1667
1668         return slot;
1669  none:
1670         iter->next_index = 0;
1671         return NULL;
1672 }
1673 EXPORT_SYMBOL(__radix_tree_next_slot);
1674 #else
1675 static void **skip_siblings(struct radix_tree_node **nodep,
1676                         void **slot, struct radix_tree_iter *iter)
1677 {
1678         return slot;
1679 }
1680 #endif
1681
1682 void **radix_tree_iter_resume(void **slot, struct radix_tree_iter *iter)
1683 {
1684         struct radix_tree_node *node;
1685
1686         slot++;
1687         iter->index = __radix_tree_iter_add(iter, 1);
1688         skip_siblings(&node, slot, iter);
1689         iter->next_index = iter->index;
1690         iter->tags = 0;
1691         return NULL;
1692 }
1693 EXPORT_SYMBOL(radix_tree_iter_resume);
1694
1695 /**
1696  * radix_tree_next_chunk - find next chunk of slots for iteration
1697  *
1698  * @root:       radix tree root
1699  * @iter:       iterator state
1700  * @flags:      RADIX_TREE_ITER_* flags and tag index
1701  * Returns:     pointer to chunk first slot, or NULL if iteration is over
1702  */
1703 void **radix_tree_next_chunk(const struct radix_tree_root *root,
1704                              struct radix_tree_iter *iter, unsigned flags)
1705 {
1706         unsigned tag = flags & RADIX_TREE_ITER_TAG_MASK;
1707         struct radix_tree_node *node, *child;
1708         unsigned long index, offset, maxindex;
1709
1710         if ((flags & RADIX_TREE_ITER_TAGGED) && !root_tag_get(root, tag))
1711                 return NULL;
1712
1713         /*
1714          * Catch next_index overflow after ~0UL. iter->index never overflows
1715          * during iterating; it can be zero only at the beginning.
1716          * And we cannot overflow iter->next_index in a single step,
1717          * because RADIX_TREE_MAP_SHIFT < BITS_PER_LONG.
1718          *
1719          * This condition also used by radix_tree_next_slot() to stop
1720          * contiguous iterating, and forbid switching to the next chunk.
1721          */
1722         index = iter->next_index;
1723         if (!index && iter->index)
1724                 return NULL;
1725
1726  restart:
1727         radix_tree_load_root(root, &child, &maxindex);
1728         if (index > maxindex)
1729                 return NULL;
1730         if (!child)
1731                 return NULL;
1732
1733         if (!radix_tree_is_internal_node(child)) {
1734                 /* Single-slot tree */
1735                 iter->index = index;
1736                 iter->next_index = maxindex + 1;
1737                 iter->tags = 1;
1738                 iter->node = NULL;
1739                 __set_iter_shift(iter, 0);
1740                 return (void **)&root->rnode;
1741         }
1742
1743         do {
1744                 node = entry_to_node(child);
1745                 offset = radix_tree_descend(node, &child, index);
1746
1747                 if ((flags & RADIX_TREE_ITER_TAGGED) ?
1748                                 !tag_get(node, tag, offset) : !child) {
1749                         /* Hole detected */
1750                         if (flags & RADIX_TREE_ITER_CONTIG)
1751                                 return NULL;
1752
1753                         if (flags & RADIX_TREE_ITER_TAGGED)
1754                                 offset = radix_tree_find_next_bit(node, tag,
1755                                                 offset + 1);
1756                         else
1757                                 while (++offset < RADIX_TREE_MAP_SIZE) {
1758                                         void *slot = node->slots[offset];
1759                                         if (is_sibling_entry(node, slot))
1760                                                 continue;
1761                                         if (slot)
1762                                                 break;
1763                                 }
1764                         index &= ~node_maxindex(node);
1765                         index += offset << node->shift;
1766                         /* Overflow after ~0UL */
1767                         if (!index)
1768                                 return NULL;
1769                         if (offset == RADIX_TREE_MAP_SIZE)
1770                                 goto restart;
1771                         child = rcu_dereference_raw(node->slots[offset]);
1772                 }
1773
1774                 if (!child)
1775                         goto restart;
1776                 if (child == RADIX_TREE_RETRY)
1777                         break;
1778         } while (radix_tree_is_internal_node(child));
1779
1780         /* Update the iterator state */
1781         iter->index = (index &~ node_maxindex(node)) | (offset << node->shift);
1782         iter->next_index = (index | node_maxindex(node)) + 1;
1783         iter->node = node;
1784         __set_iter_shift(iter, node->shift);
1785
1786         if (flags & RADIX_TREE_ITER_TAGGED)
1787                 set_iter_tags(iter, node, offset, tag);
1788
1789         return node->slots + offset;
1790 }
1791 EXPORT_SYMBOL(radix_tree_next_chunk);
1792
1793 /**
1794  *      radix_tree_gang_lookup - perform multiple lookup on a radix tree
1795  *      @root:          radix tree root
1796  *      @results:       where the results of the lookup are placed
1797  *      @first_index:   start the lookup from this key
1798  *      @max_items:     place up to this many items at *results
1799  *
1800  *      Performs an index-ascending scan of the tree for present items.  Places
1801  *      them at *@results and returns the number of items which were placed at
1802  *      *@results.
1803  *
1804  *      The implementation is naive.
1805  *
1806  *      Like radix_tree_lookup, radix_tree_gang_lookup may be called under
1807  *      rcu_read_lock. In this case, rather than the returned results being
1808  *      an atomic snapshot of the tree at a single point in time, the
1809  *      semantics of an RCU protected gang lookup are as though multiple
1810  *      radix_tree_lookups have been issued in individual locks, and results
1811  *      stored in 'results'.
1812  */
1813 unsigned int
1814 radix_tree_gang_lookup(const struct radix_tree_root *root, void **results,
1815                         unsigned long first_index, unsigned int max_items)
1816 {
1817         struct radix_tree_iter iter;
1818         void **slot;
1819         unsigned int ret = 0;
1820
1821         if (unlikely(!max_items))
1822                 return 0;
1823
1824         radix_tree_for_each_slot(slot, root, &iter, first_index) {
1825                 results[ret] = rcu_dereference_raw(*slot);
1826                 if (!results[ret])
1827                         continue;
1828                 if (radix_tree_is_internal_node(results[ret])) {
1829                         slot = radix_tree_iter_retry(&iter);
1830                         continue;
1831                 }
1832                 if (++ret == max_items)
1833                         break;
1834         }
1835
1836         return ret;
1837 }
1838 EXPORT_SYMBOL(radix_tree_gang_lookup);
1839
1840 /**
1841  *      radix_tree_gang_lookup_slot - perform multiple slot lookup on radix tree
1842  *      @root:          radix tree root
1843  *      @results:       where the results of the lookup are placed
1844  *      @indices:       where their indices should be placed (but usually NULL)
1845  *      @first_index:   start the lookup from this key
1846  *      @max_items:     place up to this many items at *results
1847  *
1848  *      Performs an index-ascending scan of the tree for present items.  Places
1849  *      their slots at *@results and returns the number of items which were
1850  *      placed at *@results.
1851  *
1852  *      The implementation is naive.
1853  *
1854  *      Like radix_tree_gang_lookup as far as RCU and locking goes. Slots must
1855  *      be dereferenced with radix_tree_deref_slot, and if using only RCU
1856  *      protection, radix_tree_deref_slot may fail requiring a retry.
1857  */
1858 unsigned int
1859 radix_tree_gang_lookup_slot(const struct radix_tree_root *root,
1860                         void ***results, unsigned long *indices,
1861                         unsigned long first_index, unsigned int max_items)
1862 {
1863         struct radix_tree_iter iter;
1864         void **slot;
1865         unsigned int ret = 0;
1866
1867         if (unlikely(!max_items))
1868                 return 0;
1869
1870         radix_tree_for_each_slot(slot, root, &iter, first_index) {
1871                 results[ret] = slot;
1872                 if (indices)
1873                         indices[ret] = iter.index;
1874                 if (++ret == max_items)
1875                         break;
1876         }
1877
1878         return ret;
1879 }
1880 EXPORT_SYMBOL(radix_tree_gang_lookup_slot);
1881
1882 /**
1883  *      radix_tree_gang_lookup_tag - perform multiple lookup on a radix tree
1884  *                                   based on a tag
1885  *      @root:          radix tree root
1886  *      @results:       where the results of the lookup are placed
1887  *      @first_index:   start the lookup from this key
1888  *      @max_items:     place up to this many items at *results
1889  *      @tag:           the tag index (< RADIX_TREE_MAX_TAGS)
1890  *
1891  *      Performs an index-ascending scan of the tree for present items which
1892  *      have the tag indexed by @tag set.  Places the items at *@results and
1893  *      returns the number of items which were placed at *@results.
1894  */
1895 unsigned int
1896 radix_tree_gang_lookup_tag(const struct radix_tree_root *root, void **results,
1897                 unsigned long first_index, unsigned int max_items,
1898                 unsigned int tag)
1899 {
1900         struct radix_tree_iter iter;
1901         void **slot;
1902         unsigned int ret = 0;
1903
1904         if (unlikely(!max_items))
1905                 return 0;
1906
1907         radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
1908                 results[ret] = rcu_dereference_raw(*slot);
1909                 if (!results[ret])
1910                         continue;
1911                 if (radix_tree_is_internal_node(results[ret])) {
1912                         slot = radix_tree_iter_retry(&iter);
1913                         continue;
1914                 }
1915                 if (++ret == max_items)
1916                         break;
1917         }
1918
1919         return ret;
1920 }
1921 EXPORT_SYMBOL(radix_tree_gang_lookup_tag);
1922
1923 /**
1924  *      radix_tree_gang_lookup_tag_slot - perform multiple slot lookup on a
1925  *                                        radix tree based on a tag
1926  *      @root:          radix tree root
1927  *      @results:       where the results of the lookup are placed
1928  *      @first_index:   start the lookup from this key
1929  *      @max_items:     place up to this many items at *results
1930  *      @tag:           the tag index (< RADIX_TREE_MAX_TAGS)
1931  *
1932  *      Performs an index-ascending scan of the tree for present items which
1933  *      have the tag indexed by @tag set.  Places the slots at *@results and
1934  *      returns the number of slots which were placed at *@results.
1935  */
1936 unsigned int
1937 radix_tree_gang_lookup_tag_slot(const struct radix_tree_root *root,
1938                 void ***results, unsigned long first_index,
1939                 unsigned int max_items, unsigned int tag)
1940 {
1941         struct radix_tree_iter iter;
1942         void **slot;
1943         unsigned int ret = 0;
1944
1945         if (unlikely(!max_items))
1946                 return 0;
1947
1948         radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
1949                 results[ret] = slot;
1950                 if (++ret == max_items)
1951                         break;
1952         }
1953
1954         return ret;
1955 }
1956 EXPORT_SYMBOL(radix_tree_gang_lookup_tag_slot);
1957
1958 /**
1959  *      __radix_tree_delete_node    -    try to free node after clearing a slot
1960  *      @root:          radix tree root
1961  *      @node:          node containing @index
1962  *      @update_node:   callback for changing leaf nodes
1963  *      @private:       private data to pass to @update_node
1964  *
1965  *      After clearing the slot at @index in @node from radix tree
1966  *      rooted at @root, call this function to attempt freeing the
1967  *      node and shrinking the tree.
1968  */
1969 void __radix_tree_delete_node(struct radix_tree_root *root,
1970                               struct radix_tree_node *node,
1971                               radix_tree_update_node_t update_node,
1972                               void *private)
1973 {
1974         delete_node(root, node, update_node, private);
1975 }
1976
1977 static bool __radix_tree_delete(struct radix_tree_root *root,
1978                                 struct radix_tree_node *node, void **slot)
1979 {
1980         void *old = rcu_dereference_raw(*slot);
1981         int exceptional = radix_tree_exceptional_entry(old) ? -1 : 0;
1982         unsigned offset = get_slot_offset(node, slot);
1983         int tag;
1984
1985         if (is_idr(root))
1986                 node_tag_set(root, node, IDR_FREE, offset);
1987         else
1988                 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
1989                         node_tag_clear(root, node, tag, offset);
1990
1991         replace_slot(slot, NULL, node, -1, exceptional);
1992         return node && delete_node(root, node, NULL, NULL);
1993 }
1994
1995 /**
1996  * radix_tree_iter_delete - delete the entry at this iterator position
1997  * @root: radix tree root
1998  * @iter: iterator state
1999  * @slot: pointer to slot
2000  *
2001  * Delete the entry at the position currently pointed to by the iterator.
2002  * This may result in the current node being freed; if it is, the iterator
2003  * is advanced so that it will not reference the freed memory.  This
2004  * function may be called without any locking if there are no other threads
2005  * which can access this tree.
2006  */
2007 void radix_tree_iter_delete(struct radix_tree_root *root,
2008                                 struct radix_tree_iter *iter, void **slot)
2009 {
2010         if (__radix_tree_delete(root, iter->node, slot))
2011                 iter->index = iter->next_index;
2012 }
2013
2014 /**
2015  * radix_tree_delete_item - delete an item from a radix tree
2016  * @root: radix tree root
2017  * @index: index key
2018  * @item: expected item
2019  *
2020  * Remove @item at @index from the radix tree rooted at @root.
2021  *
2022  * Return: the deleted entry, or %NULL if it was not present
2023  * or the entry at the given @index was not @item.
2024  */
2025 void *radix_tree_delete_item(struct radix_tree_root *root,
2026                              unsigned long index, void *item)
2027 {
2028         struct radix_tree_node *node = NULL;
2029         void **slot;
2030         void *entry;
2031
2032         entry = __radix_tree_lookup(root, index, &node, &slot);
2033         if (!entry && (!is_idr(root) || node_tag_get(root, node, IDR_FREE,
2034                                                 get_slot_offset(node, slot))))
2035                 return NULL;
2036
2037         if (item && entry != item)
2038                 return NULL;
2039
2040         __radix_tree_delete(root, node, slot);
2041
2042         return entry;
2043 }
2044 EXPORT_SYMBOL(radix_tree_delete_item);
2045
2046 /**
2047  * radix_tree_delete - delete an entry from a radix tree
2048  * @root: radix tree root
2049  * @index: index key
2050  *
2051  * Remove the entry at @index from the radix tree rooted at @root.
2052  *
2053  * Return: The deleted entry, or %NULL if it was not present.
2054  */
2055 void *radix_tree_delete(struct radix_tree_root *root, unsigned long index)
2056 {
2057         return radix_tree_delete_item(root, index, NULL);
2058 }
2059 EXPORT_SYMBOL(radix_tree_delete);
2060
2061 void radix_tree_clear_tags(struct radix_tree_root *root,
2062                            struct radix_tree_node *node,
2063                            void **slot)
2064 {
2065         if (node) {
2066                 unsigned int tag, offset = get_slot_offset(node, slot);
2067                 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++)
2068                         node_tag_clear(root, node, tag, offset);
2069         } else {
2070                 root_tag_clear_all(root);
2071         }
2072 }
2073
2074 /**
2075  *      radix_tree_tagged - test whether any items in the tree are tagged
2076  *      @root:          radix tree root
2077  *      @tag:           tag to test
2078  */
2079 int radix_tree_tagged(const struct radix_tree_root *root, unsigned int tag)
2080 {
2081         return root_tag_get(root, tag);
2082 }
2083 EXPORT_SYMBOL(radix_tree_tagged);
2084
2085 /**
2086  * idr_preload - preload for idr_alloc()
2087  * @gfp_mask: allocation mask to use for preloading
2088  *
2089  * Preallocate memory to use for the next call to idr_alloc().  This function
2090  * returns with preemption disabled.  It will be enabled by idr_preload_end().
2091  */
2092 void idr_preload(gfp_t gfp_mask)
2093 {
2094         __radix_tree_preload(gfp_mask, IDR_PRELOAD_SIZE);
2095 }
2096 EXPORT_SYMBOL(idr_preload);
2097
2098 /**
2099  * ida_pre_get - reserve resources for ida allocation
2100  * @ida: ida handle
2101  * @gfp: memory allocation flags
2102  *
2103  * This function should be called before calling ida_get_new_above().  If it
2104  * is unable to allocate memory, it will return %0.  On success, it returns %1.
2105  */
2106 int ida_pre_get(struct ida *ida, gfp_t gfp)
2107 {
2108         __radix_tree_preload(gfp, IDA_PRELOAD_SIZE);
2109         /*
2110          * The IDA API has no preload_end() equivalent.  Instead,
2111          * ida_get_new() can return -EAGAIN, prompting the caller
2112          * to return to the ida_pre_get() step.
2113          */
2114         preempt_enable();
2115
2116         if (!this_cpu_read(ida_bitmap)) {
2117                 struct ida_bitmap *bitmap = kmalloc(sizeof(*bitmap), gfp);
2118                 if (!bitmap)
2119                         return 0;
2120                 bitmap = this_cpu_cmpxchg(ida_bitmap, NULL, bitmap);
2121                 kfree(bitmap);
2122         }
2123
2124         return 1;
2125 }
2126 EXPORT_SYMBOL(ida_pre_get);
2127
2128 void **idr_get_free(struct radix_tree_root *root,
2129                         struct radix_tree_iter *iter, gfp_t gfp, int end)
2130 {
2131         struct radix_tree_node *node = NULL, *child;
2132         void **slot = (void **)&root->rnode;
2133         unsigned long maxindex, start = iter->next_index;
2134         unsigned long max = end > 0 ? end - 1 : INT_MAX;
2135         unsigned int shift, offset = 0;
2136
2137  grow:
2138         shift = radix_tree_load_root(root, &child, &maxindex);
2139         if (!radix_tree_tagged(root, IDR_FREE))
2140                 start = max(start, maxindex + 1);
2141         if (start > max)
2142                 return ERR_PTR(-ENOSPC);
2143
2144         if (start > maxindex) {
2145                 int error = radix_tree_extend(root, gfp, start, shift);
2146                 if (error < 0)
2147                         return ERR_PTR(error);
2148                 shift = error;
2149                 child = rcu_dereference_raw(root->rnode);
2150         }
2151
2152         while (shift) {
2153                 shift -= RADIX_TREE_MAP_SHIFT;
2154                 if (child == NULL) {
2155                         /* Have to add a child node.  */
2156                         child = radix_tree_node_alloc(gfp, node, root, shift,
2157                                                         offset, 0, 0);
2158                         if (!child)
2159                                 return ERR_PTR(-ENOMEM);
2160                         all_tag_set(child, IDR_FREE);
2161                         rcu_assign_pointer(*slot, node_to_entry(child));
2162                         if (node)
2163                                 node->count++;
2164                 } else if (!radix_tree_is_internal_node(child))
2165                         break;
2166
2167                 node = entry_to_node(child);
2168                 offset = radix_tree_descend(node, &child, start);
2169                 if (!tag_get(node, IDR_FREE, offset)) {
2170                         offset = radix_tree_find_next_bit(node, IDR_FREE,
2171                                                         offset + 1);
2172                         start = next_index(start, node, offset);
2173                         if (start > max)
2174                                 return ERR_PTR(-ENOSPC);
2175                         while (offset == RADIX_TREE_MAP_SIZE) {
2176                                 offset = node->offset + 1;
2177                                 node = node->parent;
2178                                 if (!node)
2179                                         goto grow;
2180                                 shift = node->shift;
2181                         }
2182                         child = rcu_dereference_raw(node->slots[offset]);
2183                 }
2184                 slot = &node->slots[offset];
2185         }
2186
2187         iter->index = start;
2188         if (node)
2189                 iter->next_index = 1 + min(max, (start | node_maxindex(node)));
2190         else
2191                 iter->next_index = 1;
2192         iter->node = node;
2193         __set_iter_shift(iter, shift);
2194         set_iter_tags(iter, node, offset, IDR_FREE);
2195
2196         return slot;
2197 }
2198
2199 /**
2200  * idr_destroy - release all internal memory from an IDR
2201  * @idr: idr handle
2202  *
2203  * After this function is called, the IDR is empty, and may be reused or
2204  * the data structure containing it may be freed.
2205  *
2206  * A typical clean-up sequence for objects stored in an idr tree will use
2207  * idr_for_each() to free all objects, if necessary, then idr_destroy() to
2208  * free the memory used to keep track of those objects.
2209  */
2210 void idr_destroy(struct idr *idr)
2211 {
2212         struct radix_tree_node *node = rcu_dereference_raw(idr->idr_rt.rnode);
2213         if (radix_tree_is_internal_node(node))
2214                 radix_tree_free_nodes(node);
2215         idr->idr_rt.rnode = NULL;
2216         root_tag_set(&idr->idr_rt, IDR_FREE);
2217 }
2218 EXPORT_SYMBOL(idr_destroy);
2219
2220 static void
2221 radix_tree_node_ctor(void *arg)
2222 {
2223         struct radix_tree_node *node = arg;
2224
2225         memset(node, 0, sizeof(*node));
2226         INIT_LIST_HEAD(&node->private_list);
2227 }
2228
2229 static __init unsigned long __maxindex(unsigned int height)
2230 {
2231         unsigned int width = height * RADIX_TREE_MAP_SHIFT;
2232         int shift = RADIX_TREE_INDEX_BITS - width;
2233
2234         if (shift < 0)
2235                 return ~0UL;
2236         if (shift >= BITS_PER_LONG)
2237                 return 0UL;
2238         return ~0UL >> shift;
2239 }
2240
2241 static __init void radix_tree_init_maxnodes(void)
2242 {
2243         unsigned long height_to_maxindex[RADIX_TREE_MAX_PATH + 1];
2244         unsigned int i, j;
2245
2246         for (i = 0; i < ARRAY_SIZE(height_to_maxindex); i++)
2247                 height_to_maxindex[i] = __maxindex(i);
2248         for (i = 0; i < ARRAY_SIZE(height_to_maxnodes); i++) {
2249                 for (j = i; j > 0; j--)
2250                         height_to_maxnodes[i] += height_to_maxindex[j - 1] + 1;
2251         }
2252 }
2253
2254 static int radix_tree_cpu_dead(unsigned int cpu)
2255 {
2256         struct radix_tree_preload *rtp;
2257         struct radix_tree_node *node;
2258
2259         /* Free per-cpu pool of preloaded nodes */
2260         rtp = &per_cpu(radix_tree_preloads, cpu);
2261         while (rtp->nr) {
2262                 node = rtp->nodes;
2263                 rtp->nodes = node->parent;
2264                 kmem_cache_free(radix_tree_node_cachep, node);
2265                 rtp->nr--;
2266         }
2267         kfree(per_cpu(ida_bitmap, cpu));
2268         per_cpu(ida_bitmap, cpu) = NULL;
2269         return 0;
2270 }
2271
2272 void __init radix_tree_init(void)
2273 {
2274         int ret;
2275         radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
2276                         sizeof(struct radix_tree_node), 0,
2277                         SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
2278                         radix_tree_node_ctor);
2279         radix_tree_init_maxnodes();
2280         ret = cpuhp_setup_state_nocalls(CPUHP_RADIX_DEAD, "lib/radix:dead",
2281                                         NULL, radix_tree_cpu_dead);
2282         WARN_ON(ret < 0);
2283 }