Back to home page

LXR

 
 

    


0001 /*
0002  * 2002-10-18  written by Jim Houston jim.houston@ccur.com
0003  *  Copyright (C) 2002 by Concurrent Computer Corporation
0004  *  Distributed under the GNU GPL license version 2.
0005  *
0006  * Modified by George Anzinger to reuse immediately and to use
0007  * find bit instructions.  Also removed _irq on spinlocks.
0008  *
0009  * Modified by Nadia Derbey to make it RCU safe.
0010  *
0011  * Small id to pointer translation service.
0012  *
0013  * It uses a radix tree like structure as a sparse array indexed
0014  * by the id to obtain the pointer.  The bitmap makes allocating
0015  * a new id quick.
0016  *
0017  * You call it to allocate an id (an int) an associate with that id a
0018  * pointer or what ever, we treat it as a (void *).  You can pass this
0019  * id to a user for him to pass back at a later time.  You then pass
0020  * that id to this code and it returns your pointer.
0021  */
0022 
0023 #ifndef TEST                        // to test in user space...
0024 #include <linux/slab.h>
0025 #include <linux/init.h>
0026 #include <linux/export.h>
0027 #endif
0028 #include <linux/err.h>
0029 #include <linux/string.h>
0030 #include <linux/idr.h>
0031 #include <linux/spinlock.h>
0032 #include <linux/percpu.h>
0033 
0034 #define MAX_IDR_SHIFT       (sizeof(int) * 8 - 1)
0035 #define MAX_IDR_BIT     (1U << MAX_IDR_SHIFT)
0036 
0037 /* Leave the possibility of an incomplete final layer */
0038 #define MAX_IDR_LEVEL ((MAX_IDR_SHIFT + IDR_BITS - 1) / IDR_BITS)
0039 
0040 /* Number of id_layer structs to leave in free list */
0041 #define MAX_IDR_FREE (MAX_IDR_LEVEL * 2)
0042 
0043 static struct kmem_cache *idr_layer_cache;
0044 static DEFINE_PER_CPU(struct idr_layer *, idr_preload_head);
0045 static DEFINE_PER_CPU(int, idr_preload_cnt);
0046 static DEFINE_SPINLOCK(simple_ida_lock);
0047 
0048 /* the maximum ID which can be allocated given idr->layers */
0049 static int idr_max(int layers)
0050 {
0051     int bits = min_t(int, layers * IDR_BITS, MAX_IDR_SHIFT);
0052 
0053     return (1 << bits) - 1;
0054 }
0055 
0056 /*
0057  * Prefix mask for an idr_layer at @layer.  For layer 0, the prefix mask is
0058  * all bits except for the lower IDR_BITS.  For layer 1, 2 * IDR_BITS, and
0059  * so on.
0060  */
0061 static int idr_layer_prefix_mask(int layer)
0062 {
0063     return ~idr_max(layer + 1);
0064 }
0065 
0066 static struct idr_layer *get_from_free_list(struct idr *idp)
0067 {
0068     struct idr_layer *p;
0069     unsigned long flags;
0070 
0071     spin_lock_irqsave(&idp->lock, flags);
0072     if ((p = idp->id_free)) {
0073         idp->id_free = p->ary[0];
0074         idp->id_free_cnt--;
0075         p->ary[0] = NULL;
0076     }
0077     spin_unlock_irqrestore(&idp->lock, flags);
0078     return(p);
0079 }
0080 
0081 /**
0082  * idr_layer_alloc - allocate a new idr_layer
0083  * @gfp_mask: allocation mask
0084  * @layer_idr: optional idr to allocate from
0085  *
0086  * If @layer_idr is %NULL, directly allocate one using @gfp_mask or fetch
0087  * one from the per-cpu preload buffer.  If @layer_idr is not %NULL, fetch
0088  * an idr_layer from @idr->id_free.
0089  *
0090  * @layer_idr is to maintain backward compatibility with the old alloc
0091  * interface - idr_pre_get() and idr_get_new*() - and will be removed
0092  * together with per-pool preload buffer.
0093  */
0094 static struct idr_layer *idr_layer_alloc(gfp_t gfp_mask, struct idr *layer_idr)
0095 {
0096     struct idr_layer *new;
0097 
0098     /* this is the old path, bypass to get_from_free_list() */
0099     if (layer_idr)
0100         return get_from_free_list(layer_idr);
0101 
0102     /*
0103      * Try to allocate directly from kmem_cache.  We want to try this
0104      * before preload buffer; otherwise, non-preloading idr_alloc()
0105      * users will end up taking advantage of preloading ones.  As the
0106      * following is allowed to fail for preloaded cases, suppress
0107      * warning this time.
0108      */
0109     new = kmem_cache_zalloc(idr_layer_cache, gfp_mask | __GFP_NOWARN);
0110     if (new)
0111         return new;
0112 
0113     /*
0114      * Try to fetch one from the per-cpu preload buffer if in process
0115      * context.  See idr_preload() for details.
0116      */
0117     if (!in_interrupt()) {
0118         preempt_disable();
0119         new = __this_cpu_read(idr_preload_head);
0120         if (new) {
0121             __this_cpu_write(idr_preload_head, new->ary[0]);
0122             __this_cpu_dec(idr_preload_cnt);
0123             new->ary[0] = NULL;
0124         }
0125         preempt_enable();
0126         if (new)
0127             return new;
0128     }
0129 
0130     /*
0131      * Both failed.  Try kmem_cache again w/o adding __GFP_NOWARN so
0132      * that memory allocation failure warning is printed as intended.
0133      */
0134     return kmem_cache_zalloc(idr_layer_cache, gfp_mask);
0135 }
0136 
0137 static void idr_layer_rcu_free(struct rcu_head *head)
0138 {
0139     struct idr_layer *layer;
0140 
0141     layer = container_of(head, struct idr_layer, rcu_head);
0142     kmem_cache_free(idr_layer_cache, layer);
0143 }
0144 
0145 static inline void free_layer(struct idr *idr, struct idr_layer *p)
0146 {
0147     if (idr->hint == p)
0148         RCU_INIT_POINTER(idr->hint, NULL);
0149     call_rcu(&p->rcu_head, idr_layer_rcu_free);
0150 }
0151 
0152 /* only called when idp->lock is held */
0153 static void __move_to_free_list(struct idr *idp, struct idr_layer *p)
0154 {
0155     p->ary[0] = idp->id_free;
0156     idp->id_free = p;
0157     idp->id_free_cnt++;
0158 }
0159 
0160 static void move_to_free_list(struct idr *idp, struct idr_layer *p)
0161 {
0162     unsigned long flags;
0163 
0164     /*
0165      * Depends on the return element being zeroed.
0166      */
0167     spin_lock_irqsave(&idp->lock, flags);
0168     __move_to_free_list(idp, p);
0169     spin_unlock_irqrestore(&idp->lock, flags);
0170 }
0171 
0172 static void idr_mark_full(struct idr_layer **pa, int id)
0173 {
0174     struct idr_layer *p = pa[0];
0175     int l = 0;
0176 
0177     __set_bit(id & IDR_MASK, p->bitmap);
0178     /*
0179      * If this layer is full mark the bit in the layer above to
0180      * show that this part of the radix tree is full.  This may
0181      * complete the layer above and require walking up the radix
0182      * tree.
0183      */
0184     while (bitmap_full(p->bitmap, IDR_SIZE)) {
0185         if (!(p = pa[++l]))
0186             break;
0187         id = id >> IDR_BITS;
0188         __set_bit((id & IDR_MASK), p->bitmap);
0189     }
0190 }
0191 
0192 static int __idr_pre_get(struct idr *idp, gfp_t gfp_mask)
0193 {
0194     while (idp->id_free_cnt < MAX_IDR_FREE) {
0195         struct idr_layer *new;
0196         new = kmem_cache_zalloc(idr_layer_cache, gfp_mask);
0197         if (new == NULL)
0198             return (0);
0199         move_to_free_list(idp, new);
0200     }
0201     return 1;
0202 }
0203 
0204 /**
0205  * sub_alloc - try to allocate an id without growing the tree depth
0206  * @idp: idr handle
0207  * @starting_id: id to start search at
0208  * @pa: idr_layer[MAX_IDR_LEVEL] used as backtrack buffer
0209  * @gfp_mask: allocation mask for idr_layer_alloc()
0210  * @layer_idr: optional idr passed to idr_layer_alloc()
0211  *
0212  * Allocate an id in range [@starting_id, INT_MAX] from @idp without
0213  * growing its depth.  Returns
0214  *
0215  *  the allocated id >= 0 if successful,
0216  *  -EAGAIN if the tree needs to grow for allocation to succeed,
0217  *  -ENOSPC if the id space is exhausted,
0218  *  -ENOMEM if more idr_layers need to be allocated.
0219  */
0220 static int sub_alloc(struct idr *idp, int *starting_id, struct idr_layer **pa,
0221              gfp_t gfp_mask, struct idr *layer_idr)
0222 {
0223     int n, m, sh;
0224     struct idr_layer *p, *new;
0225     int l, id, oid;
0226 
0227     id = *starting_id;
0228  restart:
0229     p = idp->top;
0230     l = idp->layers;
0231     pa[l--] = NULL;
0232     while (1) {
0233         /*
0234          * We run around this while until we reach the leaf node...
0235          */
0236         n = (id >> (IDR_BITS*l)) & IDR_MASK;
0237         m = find_next_zero_bit(p->bitmap, IDR_SIZE, n);
0238         if (m == IDR_SIZE) {
0239             /* no space available go back to previous layer. */
0240             l++;
0241             oid = id;
0242             id = (id | ((1 << (IDR_BITS * l)) - 1)) + 1;
0243 
0244             /* if already at the top layer, we need to grow */
0245             if (id > idr_max(idp->layers)) {
0246                 *starting_id = id;
0247                 return -EAGAIN;
0248             }
0249             p = pa[l];
0250             BUG_ON(!p);
0251 
0252             /* If we need to go up one layer, continue the
0253              * loop; otherwise, restart from the top.
0254              */
0255             sh = IDR_BITS * (l + 1);
0256             if (oid >> sh == id >> sh)
0257                 continue;
0258             else
0259                 goto restart;
0260         }
0261         if (m != n) {
0262             sh = IDR_BITS*l;
0263             id = ((id >> sh) ^ n ^ m) << sh;
0264         }
0265         if ((id >= MAX_IDR_BIT) || (id < 0))
0266             return -ENOSPC;
0267         if (l == 0)
0268             break;
0269         /*
0270          * Create the layer below if it is missing.
0271          */
0272         if (!p->ary[m]) {
0273             new = idr_layer_alloc(gfp_mask, layer_idr);
0274             if (!new)
0275                 return -ENOMEM;
0276             new->layer = l-1;
0277             new->prefix = id & idr_layer_prefix_mask(new->layer);
0278             rcu_assign_pointer(p->ary[m], new);
0279             p->count++;
0280         }
0281         pa[l--] = p;
0282         p = p->ary[m];
0283     }
0284 
0285     pa[l] = p;
0286     return id;
0287 }
0288 
0289 static int idr_get_empty_slot(struct idr *idp, int starting_id,
0290                   struct idr_layer **pa, gfp_t gfp_mask,
0291                   struct idr *layer_idr)
0292 {
0293     struct idr_layer *p, *new;
0294     int layers, v, id;
0295     unsigned long flags;
0296 
0297     id = starting_id;
0298 build_up:
0299     p = idp->top;
0300     layers = idp->layers;
0301     if (unlikely(!p)) {
0302         if (!(p = idr_layer_alloc(gfp_mask, layer_idr)))
0303             return -ENOMEM;
0304         p->layer = 0;
0305         layers = 1;
0306     }
0307     /*
0308      * Add a new layer to the top of the tree if the requested
0309      * id is larger than the currently allocated space.
0310      */
0311     while (id > idr_max(layers)) {
0312         layers++;
0313         if (!p->count) {
0314             /* special case: if the tree is currently empty,
0315              * then we grow the tree by moving the top node
0316              * upwards.
0317              */
0318             p->layer++;
0319             WARN_ON_ONCE(p->prefix);
0320             continue;
0321         }
0322         if (!(new = idr_layer_alloc(gfp_mask, layer_idr))) {
0323             /*
0324              * The allocation failed.  If we built part of
0325              * the structure tear it down.
0326              */
0327             spin_lock_irqsave(&idp->lock, flags);
0328             for (new = p; p && p != idp->top; new = p) {
0329                 p = p->ary[0];
0330                 new->ary[0] = NULL;
0331                 new->count = 0;
0332                 bitmap_clear(new->bitmap, 0, IDR_SIZE);
0333                 __move_to_free_list(idp, new);
0334             }
0335             spin_unlock_irqrestore(&idp->lock, flags);
0336             return -ENOMEM;
0337         }
0338         new->ary[0] = p;
0339         new->count = 1;
0340         new->layer = layers-1;
0341         new->prefix = id & idr_layer_prefix_mask(new->layer);
0342         if (bitmap_full(p->bitmap, IDR_SIZE))
0343             __set_bit(0, new->bitmap);
0344         p = new;
0345     }
0346     rcu_assign_pointer(idp->top, p);
0347     idp->layers = layers;
0348     v = sub_alloc(idp, &id, pa, gfp_mask, layer_idr);
0349     if (v == -EAGAIN)
0350         goto build_up;
0351     return(v);
0352 }
0353 
0354 /*
0355  * @id and @pa are from a successful allocation from idr_get_empty_slot().
0356  * Install the user pointer @ptr and mark the slot full.
0357  */
0358 static void idr_fill_slot(struct idr *idr, void *ptr, int id,
0359               struct idr_layer **pa)
0360 {
0361     /* update hint used for lookup, cleared from free_layer() */
0362     rcu_assign_pointer(idr->hint, pa[0]);
0363 
0364     rcu_assign_pointer(pa[0]->ary[id & IDR_MASK], (struct idr_layer *)ptr);
0365     pa[0]->count++;
0366     idr_mark_full(pa, id);
0367 }
0368 
0369 
0370 /**
0371  * idr_preload - preload for idr_alloc()
0372  * @gfp_mask: allocation mask to use for preloading
0373  *
0374  * Preload per-cpu layer buffer for idr_alloc().  Can only be used from
0375  * process context and each idr_preload() invocation should be matched with
0376  * idr_preload_end().  Note that preemption is disabled while preloaded.
0377  *
0378  * The first idr_alloc() in the preloaded section can be treated as if it
0379  * were invoked with @gfp_mask used for preloading.  This allows using more
0380  * permissive allocation masks for idrs protected by spinlocks.
0381  *
0382  * For example, if idr_alloc() below fails, the failure can be treated as
0383  * if idr_alloc() were called with GFP_KERNEL rather than GFP_NOWAIT.
0384  *
0385  *  idr_preload(GFP_KERNEL);
0386  *  spin_lock(lock);
0387  *
0388  *  id = idr_alloc(idr, ptr, start, end, GFP_NOWAIT);
0389  *
0390  *  spin_unlock(lock);
0391  *  idr_preload_end();
0392  *  if (id < 0)
0393  *      error;
0394  */
0395 void idr_preload(gfp_t gfp_mask)
0396 {
0397     /*
0398      * Consuming preload buffer from non-process context breaks preload
0399      * allocation guarantee.  Disallow usage from those contexts.
0400      */
0401     WARN_ON_ONCE(in_interrupt());
0402     might_sleep_if(gfpflags_allow_blocking(gfp_mask));
0403 
0404     preempt_disable();
0405 
0406     /*
0407      * idr_alloc() is likely to succeed w/o full idr_layer buffer and
0408      * return value from idr_alloc() needs to be checked for failure
0409      * anyway.  Silently give up if allocation fails.  The caller can
0410      * treat failures from idr_alloc() as if idr_alloc() were called
0411      * with @gfp_mask which should be enough.
0412      */
0413     while (__this_cpu_read(idr_preload_cnt) < MAX_IDR_FREE) {
0414         struct idr_layer *new;
0415 
0416         preempt_enable();
0417         new = kmem_cache_zalloc(idr_layer_cache, gfp_mask);
0418         preempt_disable();
0419         if (!new)
0420             break;
0421 
0422         /* link the new one to per-cpu preload list */
0423         new->ary[0] = __this_cpu_read(idr_preload_head);
0424         __this_cpu_write(idr_preload_head, new);
0425         __this_cpu_inc(idr_preload_cnt);
0426     }
0427 }
0428 EXPORT_SYMBOL(idr_preload);
0429 
0430 /**
0431  * idr_alloc - allocate new idr entry
0432  * @idr: the (initialized) idr
0433  * @ptr: pointer to be associated with the new id
0434  * @start: the minimum id (inclusive)
0435  * @end: the maximum id (exclusive, <= 0 for max)
0436  * @gfp_mask: memory allocation flags
0437  *
0438  * Allocate an id in [start, end) and associate it with @ptr.  If no ID is
0439  * available in the specified range, returns -ENOSPC.  On memory allocation
0440  * failure, returns -ENOMEM.
0441  *
0442  * Note that @end is treated as max when <= 0.  This is to always allow
0443  * using @start + N as @end as long as N is inside integer range.
0444  *
0445  * The user is responsible for exclusively synchronizing all operations
0446  * which may modify @idr.  However, read-only accesses such as idr_find()
0447  * or iteration can be performed under RCU read lock provided the user
0448  * destroys @ptr in RCU-safe way after removal from idr.
0449  */
0450 int idr_alloc(struct idr *idr, void *ptr, int start, int end, gfp_t gfp_mask)
0451 {
0452     int max = end > 0 ? end - 1 : INT_MAX;  /* inclusive upper limit */
0453     struct idr_layer *pa[MAX_IDR_LEVEL + 1];
0454     int id;
0455 
0456     might_sleep_if(gfpflags_allow_blocking(gfp_mask));
0457 
0458     /* sanity checks */
0459     if (WARN_ON_ONCE(start < 0))
0460         return -EINVAL;
0461     if (unlikely(max < start))
0462         return -ENOSPC;
0463 
0464     /* allocate id */
0465     id = idr_get_empty_slot(idr, start, pa, gfp_mask, NULL);
0466     if (unlikely(id < 0))
0467         return id;
0468     if (unlikely(id > max))
0469         return -ENOSPC;
0470 
0471     idr_fill_slot(idr, ptr, id, pa);
0472     return id;
0473 }
0474 EXPORT_SYMBOL_GPL(idr_alloc);
0475 
0476 /**
0477  * idr_alloc_cyclic - allocate new idr entry in a cyclical fashion
0478  * @idr: the (initialized) idr
0479  * @ptr: pointer to be associated with the new id
0480  * @start: the minimum id (inclusive)
0481  * @end: the maximum id (exclusive, <= 0 for max)
0482  * @gfp_mask: memory allocation flags
0483  *
0484  * Essentially the same as idr_alloc, but prefers to allocate progressively
0485  * higher ids if it can. If the "cur" counter wraps, then it will start again
0486  * at the "start" end of the range and allocate one that has already been used.
0487  */
0488 int idr_alloc_cyclic(struct idr *idr, void *ptr, int start, int end,
0489             gfp_t gfp_mask)
0490 {
0491     int id;
0492 
0493     id = idr_alloc(idr, ptr, max(start, idr->cur), end, gfp_mask);
0494     if (id == -ENOSPC)
0495         id = idr_alloc(idr, ptr, start, end, gfp_mask);
0496 
0497     if (likely(id >= 0))
0498         idr->cur = id + 1;
0499     return id;
0500 }
0501 EXPORT_SYMBOL(idr_alloc_cyclic);
0502 
0503 static void idr_remove_warning(int id)
0504 {
0505     WARN(1, "idr_remove called for id=%d which is not allocated.\n", id);
0506 }
0507 
0508 static void sub_remove(struct idr *idp, int shift, int id)
0509 {
0510     struct idr_layer *p = idp->top;
0511     struct idr_layer **pa[MAX_IDR_LEVEL + 1];
0512     struct idr_layer ***paa = &pa[0];
0513     struct idr_layer *to_free;
0514     int n;
0515 
0516     *paa = NULL;
0517     *++paa = &idp->top;
0518 
0519     while ((shift > 0) && p) {
0520         n = (id >> shift) & IDR_MASK;
0521         __clear_bit(n, p->bitmap);
0522         *++paa = &p->ary[n];
0523         p = p->ary[n];
0524         shift -= IDR_BITS;
0525     }
0526     n = id & IDR_MASK;
0527     if (likely(p != NULL && test_bit(n, p->bitmap))) {
0528         __clear_bit(n, p->bitmap);
0529         RCU_INIT_POINTER(p->ary[n], NULL);
0530         to_free = NULL;
0531         while(*paa && ! --((**paa)->count)){
0532             if (to_free)
0533                 free_layer(idp, to_free);
0534             to_free = **paa;
0535             **paa-- = NULL;
0536         }
0537         if (!*paa)
0538             idp->layers = 0;
0539         if (to_free)
0540             free_layer(idp, to_free);
0541     } else
0542         idr_remove_warning(id);
0543 }
0544 
0545 /**
0546  * idr_remove - remove the given id and free its slot
0547  * @idp: idr handle
0548  * @id: unique key
0549  */
0550 void idr_remove(struct idr *idp, int id)
0551 {
0552     struct idr_layer *p;
0553     struct idr_layer *to_free;
0554 
0555     if (id < 0)
0556         return;
0557 
0558     if (id > idr_max(idp->layers)) {
0559         idr_remove_warning(id);
0560         return;
0561     }
0562 
0563     sub_remove(idp, (idp->layers - 1) * IDR_BITS, id);
0564     if (idp->top && idp->top->count == 1 && (idp->layers > 1) &&
0565         idp->top->ary[0]) {
0566         /*
0567          * Single child at leftmost slot: we can shrink the tree.
0568          * This level is not needed anymore since when layers are
0569          * inserted, they are inserted at the top of the existing
0570          * tree.
0571          */
0572         to_free = idp->top;
0573         p = idp->top->ary[0];
0574         rcu_assign_pointer(idp->top, p);
0575         --idp->layers;
0576         to_free->count = 0;
0577         bitmap_clear(to_free->bitmap, 0, IDR_SIZE);
0578         free_layer(idp, to_free);
0579     }
0580 }
0581 EXPORT_SYMBOL(idr_remove);
0582 
0583 static void __idr_remove_all(struct idr *idp)
0584 {
0585     int n, id, max;
0586     int bt_mask;
0587     struct idr_layer *p;
0588     struct idr_layer *pa[MAX_IDR_LEVEL + 1];
0589     struct idr_layer **paa = &pa[0];
0590 
0591     n = idp->layers * IDR_BITS;
0592     *paa = idp->top;
0593     RCU_INIT_POINTER(idp->top, NULL);
0594     max = idr_max(idp->layers);
0595 
0596     id = 0;
0597     while (id >= 0 && id <= max) {
0598         p = *paa;
0599         while (n > IDR_BITS && p) {
0600             n -= IDR_BITS;
0601             p = p->ary[(id >> n) & IDR_MASK];
0602             *++paa = p;
0603         }
0604 
0605         bt_mask = id;
0606         id += 1 << n;
0607         /* Get the highest bit that the above add changed from 0->1. */
0608         while (n < fls(id ^ bt_mask)) {
0609             if (*paa)
0610                 free_layer(idp, *paa);
0611             n += IDR_BITS;
0612             --paa;
0613         }
0614     }
0615     idp->layers = 0;
0616 }
0617 
0618 /**
0619  * idr_destroy - release all cached layers within an idr tree
0620  * @idp: idr handle
0621  *
0622  * Free all id mappings and all idp_layers.  After this function, @idp is
0623  * completely unused and can be freed / recycled.  The caller is
0624  * responsible for ensuring that no one else accesses @idp during or after
0625  * idr_destroy().
0626  *
0627  * A typical clean-up sequence for objects stored in an idr tree will use
0628  * idr_for_each() to free all objects, if necessary, then idr_destroy() to
0629  * free up the id mappings and cached idr_layers.
0630  */
0631 void idr_destroy(struct idr *idp)
0632 {
0633     __idr_remove_all(idp);
0634 
0635     while (idp->id_free_cnt) {
0636         struct idr_layer *p = get_from_free_list(idp);
0637         kmem_cache_free(idr_layer_cache, p);
0638     }
0639 }
0640 EXPORT_SYMBOL(idr_destroy);
0641 
0642 void *idr_find_slowpath(struct idr *idp, int id)
0643 {
0644     int n;
0645     struct idr_layer *p;
0646 
0647     if (id < 0)
0648         return NULL;
0649 
0650     p = rcu_dereference_raw(idp->top);
0651     if (!p)
0652         return NULL;
0653     n = (p->layer+1) * IDR_BITS;
0654 
0655     if (id > idr_max(p->layer + 1))
0656         return NULL;
0657     BUG_ON(n == 0);
0658 
0659     while (n > 0 && p) {
0660         n -= IDR_BITS;
0661         BUG_ON(n != p->layer*IDR_BITS);
0662         p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
0663     }
0664     return((void *)p);
0665 }
0666 EXPORT_SYMBOL(idr_find_slowpath);
0667 
0668 /**
0669  * idr_for_each - iterate through all stored pointers
0670  * @idp: idr handle
0671  * @fn: function to be called for each pointer
0672  * @data: data passed back to callback function
0673  *
0674  * Iterate over the pointers registered with the given idr.  The
0675  * callback function will be called for each pointer currently
0676  * registered, passing the id, the pointer and the data pointer passed
0677  * to this function.  It is not safe to modify the idr tree while in
0678  * the callback, so functions such as idr_get_new and idr_remove are
0679  * not allowed.
0680  *
0681  * We check the return of @fn each time. If it returns anything other
0682  * than %0, we break out and return that value.
0683  *
0684  * The caller must serialize idr_for_each() vs idr_get_new() and idr_remove().
0685  */
0686 int idr_for_each(struct idr *idp,
0687          int (*fn)(int id, void *p, void *data), void *data)
0688 {
0689     int n, id, max, error = 0;
0690     struct idr_layer *p;
0691     struct idr_layer *pa[MAX_IDR_LEVEL + 1];
0692     struct idr_layer **paa = &pa[0];
0693 
0694     n = idp->layers * IDR_BITS;
0695     *paa = rcu_dereference_raw(idp->top);
0696     max = idr_max(idp->layers);
0697 
0698     id = 0;
0699     while (id >= 0 && id <= max) {
0700         p = *paa;
0701         while (n > 0 && p) {
0702             n -= IDR_BITS;
0703             p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
0704             *++paa = p;
0705         }
0706 
0707         if (p) {
0708             error = fn(id, (void *)p, data);
0709             if (error)
0710                 break;
0711         }
0712 
0713         id += 1 << n;
0714         while (n < fls(id)) {
0715             n += IDR_BITS;
0716             --paa;
0717         }
0718     }
0719 
0720     return error;
0721 }
0722 EXPORT_SYMBOL(idr_for_each);
0723 
0724 /**
0725  * idr_get_next - lookup next object of id to given id.
0726  * @idp: idr handle
0727  * @nextidp:  pointer to lookup key
0728  *
0729  * Returns pointer to registered object with id, which is next number to
0730  * given id. After being looked up, *@nextidp will be updated for the next
0731  * iteration.
0732  *
0733  * This function can be called under rcu_read_lock(), given that the leaf
0734  * pointers lifetimes are correctly managed.
0735  */
0736 void *idr_get_next(struct idr *idp, int *nextidp)
0737 {
0738     struct idr_layer *p, *pa[MAX_IDR_LEVEL + 1];
0739     struct idr_layer **paa = &pa[0];
0740     int id = *nextidp;
0741     int n, max;
0742 
0743     /* find first ent */
0744     p = *paa = rcu_dereference_raw(idp->top);
0745     if (!p)
0746         return NULL;
0747     n = (p->layer + 1) * IDR_BITS;
0748     max = idr_max(p->layer + 1);
0749 
0750     while (id >= 0 && id <= max) {
0751         p = *paa;
0752         while (n > 0 && p) {
0753             n -= IDR_BITS;
0754             p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
0755             *++paa = p;
0756         }
0757 
0758         if (p) {
0759             *nextidp = id;
0760             return p;
0761         }
0762 
0763         /*
0764          * Proceed to the next layer at the current level.  Unlike
0765          * idr_for_each(), @id isn't guaranteed to be aligned to
0766          * layer boundary at this point and adding 1 << n may
0767          * incorrectly skip IDs.  Make sure we jump to the
0768          * beginning of the next layer using round_up().
0769          */
0770         id = round_up(id + 1, 1 << n);
0771         while (n < fls(id)) {
0772             n += IDR_BITS;
0773             --paa;
0774         }
0775     }
0776     return NULL;
0777 }
0778 EXPORT_SYMBOL(idr_get_next);
0779 
0780 
0781 /**
0782  * idr_replace - replace pointer for given id
0783  * @idp: idr handle
0784  * @ptr: pointer you want associated with the id
0785  * @id: lookup key
0786  *
0787  * Replace the pointer registered with an id and return the old value.
0788  * A %-ENOENT return indicates that @id was not found.
0789  * A %-EINVAL return indicates that @id was not within valid constraints.
0790  *
0791  * The caller must serialize with writers.
0792  */
0793 void *idr_replace(struct idr *idp, void *ptr, int id)
0794 {
0795     int n;
0796     struct idr_layer *p, *old_p;
0797 
0798     if (id < 0)
0799         return ERR_PTR(-EINVAL);
0800 
0801     p = idp->top;
0802     if (!p)
0803         return ERR_PTR(-ENOENT);
0804 
0805     if (id > idr_max(p->layer + 1))
0806         return ERR_PTR(-ENOENT);
0807 
0808     n = p->layer * IDR_BITS;
0809     while ((n > 0) && p) {
0810         p = p->ary[(id >> n) & IDR_MASK];
0811         n -= IDR_BITS;
0812     }
0813 
0814     n = id & IDR_MASK;
0815     if (unlikely(p == NULL || !test_bit(n, p->bitmap)))
0816         return ERR_PTR(-ENOENT);
0817 
0818     old_p = p->ary[n];
0819     rcu_assign_pointer(p->ary[n], ptr);
0820 
0821     return old_p;
0822 }
0823 EXPORT_SYMBOL(idr_replace);
0824 
0825 void __init idr_init_cache(void)
0826 {
0827     idr_layer_cache = kmem_cache_create("idr_layer_cache",
0828                 sizeof(struct idr_layer), 0, SLAB_PANIC, NULL);
0829 }
0830 
0831 /**
0832  * idr_init - initialize idr handle
0833  * @idp:    idr handle
0834  *
0835  * This function is use to set up the handle (@idp) that you will pass
0836  * to the rest of the functions.
0837  */
0838 void idr_init(struct idr *idp)
0839 {
0840     memset(idp, 0, sizeof(struct idr));
0841     spin_lock_init(&idp->lock);
0842 }
0843 EXPORT_SYMBOL(idr_init);
0844 
0845 static int idr_has_entry(int id, void *p, void *data)
0846 {
0847     return 1;
0848 }
0849 
0850 bool idr_is_empty(struct idr *idp)
0851 {
0852     return !idr_for_each(idp, idr_has_entry, NULL);
0853 }
0854 EXPORT_SYMBOL(idr_is_empty);
0855 
0856 /**
0857  * DOC: IDA description
0858  * IDA - IDR based ID allocator
0859  *
0860  * This is id allocator without id -> pointer translation.  Memory
0861  * usage is much lower than full blown idr because each id only
0862  * occupies a bit.  ida uses a custom leaf node which contains
0863  * IDA_BITMAP_BITS slots.
0864  *
0865  * 2007-04-25  written by Tejun Heo <htejun@gmail.com>
0866  */
0867 
0868 static void free_bitmap(struct ida *ida, struct ida_bitmap *bitmap)
0869 {
0870     unsigned long flags;
0871 
0872     if (!ida->free_bitmap) {
0873         spin_lock_irqsave(&ida->idr.lock, flags);
0874         if (!ida->free_bitmap) {
0875             ida->free_bitmap = bitmap;
0876             bitmap = NULL;
0877         }
0878         spin_unlock_irqrestore(&ida->idr.lock, flags);
0879     }
0880 
0881     kfree(bitmap);
0882 }
0883 
0884 /**
0885  * ida_pre_get - reserve resources for ida allocation
0886  * @ida:    ida handle
0887  * @gfp_mask:   memory allocation flag
0888  *
0889  * This function should be called prior to locking and calling the
0890  * following function.  It preallocates enough memory to satisfy the
0891  * worst possible allocation.
0892  *
0893  * If the system is REALLY out of memory this function returns %0,
0894  * otherwise %1.
0895  */
0896 int ida_pre_get(struct ida *ida, gfp_t gfp_mask)
0897 {
0898     /* allocate idr_layers */
0899     if (!__idr_pre_get(&ida->idr, gfp_mask))
0900         return 0;
0901 
0902     /* allocate free_bitmap */
0903     if (!ida->free_bitmap) {
0904         struct ida_bitmap *bitmap;
0905 
0906         bitmap = kmalloc(sizeof(struct ida_bitmap), gfp_mask);
0907         if (!bitmap)
0908             return 0;
0909 
0910         free_bitmap(ida, bitmap);
0911     }
0912 
0913     return 1;
0914 }
0915 EXPORT_SYMBOL(ida_pre_get);
0916 
0917 /**
0918  * ida_get_new_above - allocate new ID above or equal to a start id
0919  * @ida:    ida handle
0920  * @starting_id: id to start search at
0921  * @p_id:   pointer to the allocated handle
0922  *
0923  * Allocate new ID above or equal to @starting_id.  It should be called
0924  * with any required locks.
0925  *
0926  * If memory is required, it will return %-EAGAIN, you should unlock
0927  * and go back to the ida_pre_get() call.  If the ida is full, it will
0928  * return %-ENOSPC.
0929  *
0930  * Note that callers must ensure that concurrent access to @ida is not possible.
0931  * See ida_simple_get() for a varaint which takes care of locking.
0932  *
0933  * @p_id returns a value in the range @starting_id ... %0x7fffffff.
0934  */
0935 int ida_get_new_above(struct ida *ida, int starting_id, int *p_id)
0936 {
0937     struct idr_layer *pa[MAX_IDR_LEVEL + 1];
0938     struct ida_bitmap *bitmap;
0939     unsigned long flags;
0940     int idr_id = starting_id / IDA_BITMAP_BITS;
0941     int offset = starting_id % IDA_BITMAP_BITS;
0942     int t, id;
0943 
0944  restart:
0945     /* get vacant slot */
0946     t = idr_get_empty_slot(&ida->idr, idr_id, pa, 0, &ida->idr);
0947     if (t < 0)
0948         return t == -ENOMEM ? -EAGAIN : t;
0949 
0950     if (t * IDA_BITMAP_BITS >= MAX_IDR_BIT)
0951         return -ENOSPC;
0952 
0953     if (t != idr_id)
0954         offset = 0;
0955     idr_id = t;
0956 
0957     /* if bitmap isn't there, create a new one */
0958     bitmap = (void *)pa[0]->ary[idr_id & IDR_MASK];
0959     if (!bitmap) {
0960         spin_lock_irqsave(&ida->idr.lock, flags);
0961         bitmap = ida->free_bitmap;
0962         ida->free_bitmap = NULL;
0963         spin_unlock_irqrestore(&ida->idr.lock, flags);
0964 
0965         if (!bitmap)
0966             return -EAGAIN;
0967 
0968         memset(bitmap, 0, sizeof(struct ida_bitmap));
0969         rcu_assign_pointer(pa[0]->ary[idr_id & IDR_MASK],
0970                 (void *)bitmap);
0971         pa[0]->count++;
0972     }
0973 
0974     /* lookup for empty slot */
0975     t = find_next_zero_bit(bitmap->bitmap, IDA_BITMAP_BITS, offset);
0976     if (t == IDA_BITMAP_BITS) {
0977         /* no empty slot after offset, continue to the next chunk */
0978         idr_id++;
0979         offset = 0;
0980         goto restart;
0981     }
0982 
0983     id = idr_id * IDA_BITMAP_BITS + t;
0984     if (id >= MAX_IDR_BIT)
0985         return -ENOSPC;
0986 
0987     __set_bit(t, bitmap->bitmap);
0988     if (++bitmap->nr_busy == IDA_BITMAP_BITS)
0989         idr_mark_full(pa, idr_id);
0990 
0991     *p_id = id;
0992 
0993     /* Each leaf node can handle nearly a thousand slots and the
0994      * whole idea of ida is to have small memory foot print.
0995      * Throw away extra resources one by one after each successful
0996      * allocation.
0997      */
0998     if (ida->idr.id_free_cnt || ida->free_bitmap) {
0999         struct idr_layer *p = get_from_free_list(&ida->idr);
1000         if (p)
1001             kmem_cache_free(idr_layer_cache, p);
1002     }
1003 
1004     return 0;
1005 }
1006 EXPORT_SYMBOL(ida_get_new_above);
1007 
1008 /**
1009  * ida_remove - remove the given ID
1010  * @ida:    ida handle
1011  * @id:     ID to free
1012  */
1013 void ida_remove(struct ida *ida, int id)
1014 {
1015     struct idr_layer *p = ida->idr.top;
1016     int shift = (ida->idr.layers - 1) * IDR_BITS;
1017     int idr_id = id / IDA_BITMAP_BITS;
1018     int offset = id % IDA_BITMAP_BITS;
1019     int n;
1020     struct ida_bitmap *bitmap;
1021 
1022     if (idr_id > idr_max(ida->idr.layers))
1023         goto err;
1024 
1025     /* clear full bits while looking up the leaf idr_layer */
1026     while ((shift > 0) && p) {
1027         n = (idr_id >> shift) & IDR_MASK;
1028         __clear_bit(n, p->bitmap);
1029         p = p->ary[n];
1030         shift -= IDR_BITS;
1031     }
1032 
1033     if (p == NULL)
1034         goto err;
1035 
1036     n = idr_id & IDR_MASK;
1037     __clear_bit(n, p->bitmap);
1038 
1039     bitmap = (void *)p->ary[n];
1040     if (!bitmap || !test_bit(offset, bitmap->bitmap))
1041         goto err;
1042 
1043     /* update bitmap and remove it if empty */
1044     __clear_bit(offset, bitmap->bitmap);
1045     if (--bitmap->nr_busy == 0) {
1046         __set_bit(n, p->bitmap);    /* to please idr_remove() */
1047         idr_remove(&ida->idr, idr_id);
1048         free_bitmap(ida, bitmap);
1049     }
1050 
1051     return;
1052 
1053  err:
1054     WARN(1, "ida_remove called for id=%d which is not allocated.\n", id);
1055 }
1056 EXPORT_SYMBOL(ida_remove);
1057 
1058 /**
1059  * ida_destroy - release all cached layers within an ida tree
1060  * @ida:        ida handle
1061  */
1062 void ida_destroy(struct ida *ida)
1063 {
1064     idr_destroy(&ida->idr);
1065     kfree(ida->free_bitmap);
1066 }
1067 EXPORT_SYMBOL(ida_destroy);
1068 
1069 /**
1070  * ida_simple_get - get a new id.
1071  * @ida: the (initialized) ida.
1072  * @start: the minimum id (inclusive, < 0x8000000)
1073  * @end: the maximum id (exclusive, < 0x8000000 or 0)
1074  * @gfp_mask: memory allocation flags
1075  *
1076  * Allocates an id in the range start <= id < end, or returns -ENOSPC.
1077  * On memory allocation failure, returns -ENOMEM.
1078  *
1079  * Compared to ida_get_new_above() this function does its own locking, and
1080  * should be used unless there are special requirements.
1081  *
1082  * Use ida_simple_remove() to get rid of an id.
1083  */
1084 int ida_simple_get(struct ida *ida, unsigned int start, unsigned int end,
1085            gfp_t gfp_mask)
1086 {
1087     int ret, id;
1088     unsigned int max;
1089     unsigned long flags;
1090 
1091     BUG_ON((int)start < 0);
1092     BUG_ON((int)end < 0);
1093 
1094     if (end == 0)
1095         max = 0x80000000;
1096     else {
1097         BUG_ON(end < start);
1098         max = end - 1;
1099     }
1100 
1101 again:
1102     if (!ida_pre_get(ida, gfp_mask))
1103         return -ENOMEM;
1104 
1105     spin_lock_irqsave(&simple_ida_lock, flags);
1106     ret = ida_get_new_above(ida, start, &id);
1107     if (!ret) {
1108         if (id > max) {
1109             ida_remove(ida, id);
1110             ret = -ENOSPC;
1111         } else {
1112             ret = id;
1113         }
1114     }
1115     spin_unlock_irqrestore(&simple_ida_lock, flags);
1116 
1117     if (unlikely(ret == -EAGAIN))
1118         goto again;
1119 
1120     return ret;
1121 }
1122 EXPORT_SYMBOL(ida_simple_get);
1123 
1124 /**
1125  * ida_simple_remove - remove an allocated id.
1126  * @ida: the (initialized) ida.
1127  * @id: the id returned by ida_simple_get.
1128  *
1129  * Use to release an id allocated with ida_simple_get().
1130  *
1131  * Compared to ida_remove() this function does its own locking, and should be
1132  * used unless there are special requirements.
1133  */
1134 void ida_simple_remove(struct ida *ida, unsigned int id)
1135 {
1136     unsigned long flags;
1137 
1138     BUG_ON((int)id < 0);
1139     spin_lock_irqsave(&simple_ida_lock, flags);
1140     ida_remove(ida, id);
1141     spin_unlock_irqrestore(&simple_ida_lock, flags);
1142 }
1143 EXPORT_SYMBOL(ida_simple_remove);
1144 
1145 /**
1146  * ida_init - initialize ida handle
1147  * @ida:    ida handle
1148  *
1149  * This function is use to set up the handle (@ida) that you will pass
1150  * to the rest of the functions.
1151  */
1152 void ida_init(struct ida *ida)
1153 {
1154     memset(ida, 0, sizeof(struct ida));
1155     idr_init(&ida->idr);
1156 
1157 }
1158 EXPORT_SYMBOL(ida_init);