ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / lib / idr.c
1 /*
2  * linux/kernel/id.c
3  *
4  * 2002-10-18  written by Jim Houston jim.houston@ccur.com
5  *      Copyright (C) 2002 by Concurrent Computer Corporation
6  *      Distributed under the GNU GPL license version 2.
7  *
8  * Small id to pointer translation service.  
9  *
10  * It uses a radix tree like structure as a sparse array indexed 
11  * by the id to obtain the pointer.  The bitmap makes allocating
12  * a new id quick.  
13
14  * Modified by George Anzinger to reuse immediately and to use
15  * find bit instructions.  Also removed _irq on spinlocks.
16
17  * So here is what this bit of code does:
18
19  * You call it to allocate an id (an int) an associate with that id a
20  * pointer or what ever, we treat it as a (void *).  You can pass this
21  * id to a user for him to pass back at a later time.  You then pass
22  * that id to this code and it returns your pointer.
23
24  * You can release ids at any time. When all ids are released, most of 
25  * the memory is returned (we keep IDR_FREE_MAX) in a local pool so we
26  * don't need to go to the memory "store" during an id allocate, just 
27  * so you don't need to be too concerned about locking and conflicts
28  * with the slab allocator.
29
30  * A word on reuse.  We reuse empty id slots as soon as we can, always
31  * using the lowest one available.  But we also merge a counter in the
32  * high bits of the id.  The counter is RESERVED_ID_BITS (8 at this time)
33  * long.  This means that if you allocate and release the same id in a 
34  * loop we will reuse an id after about 256 times around the loop.  The
35  * word about is used here as we will NOT return a valid id of -1 so if
36  * you loop on the largest possible id (and that is 24 bits, wow!) we
37  * will kick the counter to avoid -1.  (Paranoid?  You bet!)
38  *
39  * What you need to do is, since we don't keep the counter as part of
40  * id / ptr pair, to keep a copy of it in the pointed to structure
41  * (or else where) so that when you ask for a ptr you can varify that
42  * the returned ptr is correct by comparing the id it contains with the one
43  * you asked for.  In other words, we only did half the reuse protection.
44  * Since the code depends on your code doing this check, we ignore high
45  * order bits in the id, not just the count, but bits that would, if used,
46  * index outside of the allocated ids.  In other words, if the largest id
47  * currently allocated is 32 a look up will only look at the low 5 bits of
48  * the id.  Since you will want to keep this id in the structure anyway
49  * (if for no other reason than to be able to eliminate the id when the
50  * structure is found in some other way) this seems reasonable.  If you
51  * really think otherwise, the code to check these bits here, it is just
52  * disabled with a #if 0.
53
54
55  * So here are the complete details:
56
57  *  include <linux/idr.h>
58
59  * void idr_init(struct idr *idp)
60
61  *   This function is use to set up the handle (idp) that you will pass
62  *   to the rest of the functions.  The structure is defined in the
63  *   header.
64
65  * int idr_pre_get(struct idr *idp, unsigned gfp_mask)
66
67  *   This function should be called prior to locking and calling the
68  *   following function.  It pre allocates enough memory to satisfy the
69  *   worst possible allocation.  Unless gfp_mask is GFP_ATOMIC, it can
70  *   sleep, so must not be called with any spinlocks held.  If the system is
71  *   REALLY out of memory this function returns 0, other wise 1.
72
73  * int idr_get_new(struct idr *idp, void *ptr);
74  
75  *   This is the allocate id function.  It should be called with any
76  *   required locks.  In fact, in the SMP case, you MUST lock prior to
77  *   calling this function to avoid possible out of memory problems.  If
78  *   memory is required, it will return a -1, in which case you should
79  *   unlock and go back to the idr_pre_get() call.  ptr is the pointer
80  *   you want associated with the id.  In other words:
81
82  * void *idr_find(struct idr *idp, int id);
83  
84  *   returns the "ptr", given the id.  A NULL return indicates that the
85  *   id is not valid (or you passed NULL in the idr_get_new(), shame on
86  *   you).  This function must be called with a spinlock that prevents
87  *   calling either idr_get_new() or idr_remove() or idr_find() while it
88  *   is working.
89
90  * void idr_remove(struct idr *idp, int id);
91
92  *   removes the given id, freeing that slot and any memory that may
93  *   now be unused.  See idr_find() for locking restrictions.
94
95  */
96
97
98
99 #ifndef TEST                        // to test in user space...
100 #include <linux/slab.h>
101 #include <linux/init.h>
102 #include <linux/module.h>
103 #endif
104 #include <linux/string.h>
105 #include <linux/idr.h>
106
107
108 static kmem_cache_t *idr_layer_cache;
109
110
111
112 static struct idr_layer *alloc_layer(struct idr *idp)
113 {
114         struct idr_layer *p;
115
116         spin_lock(&idp->lock);
117         if (!(p = idp->id_free))
118                 BUG();
119         idp->id_free = p->ary[0];
120         idp->id_free_cnt--;
121         p->ary[0] = 0;
122         spin_unlock(&idp->lock);
123         return(p);
124 }
125
126 static void free_layer(struct idr *idp, struct idr_layer *p)
127 {
128         /*
129          * Depends on the return element being zeroed.
130          */
131         spin_lock(&idp->lock);
132         p->ary[0] = idp->id_free;
133         idp->id_free = p;
134         idp->id_free_cnt++;
135         spin_unlock(&idp->lock);
136 }
137
138 int idr_pre_get(struct idr *idp, unsigned gfp_mask)
139 {
140         while (idp->id_free_cnt < IDR_FREE_MAX) {
141                 struct idr_layer *new;
142                 new = kmem_cache_alloc(idr_layer_cache, gfp_mask);
143                 if(new == NULL)
144                         return (0);
145                 free_layer(idp, new);
146         }
147         return 1;
148 }
149 EXPORT_SYMBOL(idr_pre_get);
150
151 static int sub_alloc(struct idr *idp, void *ptr, int *starting_id)
152 {
153         int n, m, sh;
154         struct idr_layer *p, *new;
155         struct idr_layer *pa[MAX_LEVEL];
156         int l, id;
157         long bm;
158
159         id = *starting_id;
160         p = idp->top;
161         l = idp->layers;
162         pa[l--] = NULL;
163         while (1) {
164                 /*
165                  * We run around this while until we reach the leaf node...
166                  */
167                 n = (id >> (IDR_BITS*l)) & IDR_MASK;
168                 bm = ~p->bitmap;
169                 m = find_next_bit(&bm, IDR_SIZE, n);
170                 if (m == IDR_SIZE) {
171                         /* no space available go back to previous layer. */
172                         l++;
173                         id = (id | ((1 << (IDR_BITS*l))-1)) + 1;
174                         if (!(p = pa[l])) {
175                                 *starting_id = id;
176                                 return -2;
177                         }
178                         continue;
179                 }
180                 if (m != n) {
181                         sh = IDR_BITS*l;
182                         id = ((id >> sh) ^ n ^ m) << sh;
183                 }
184                 if (id >= MAX_ID_BIT)
185                         return -1;
186                 if (l == 0)
187                         break;
188                 /*
189                  * Create the layer below if it is missing.
190                  */
191                 if (!p->ary[m]) {
192                         if (!(new = alloc_layer(idp)))
193                                 return -1;
194                         p->ary[m] = new;
195                         p->count++;
196                 }
197                 pa[l--] = p;
198                 p = p->ary[m];
199         }
200         /*
201          * We have reached the leaf node, plant the
202          * users pointer and return the raw id.
203          */
204         p->ary[m] = (struct idr_layer *)ptr;
205         __set_bit(m, &p->bitmap);
206         p->count++;
207         /*
208          * If this layer is full mark the bit in the layer above
209          * to show that this part of the radix tree is full.
210          * This may complete the layer above and require walking
211          * up the radix tree.
212          */
213         n = id;
214         while (p->bitmap == IDR_FULL) {
215                 if (!(p = pa[++l]))
216                         break;
217                 n = n >> IDR_BITS;
218                 __set_bit((n & IDR_MASK), &p->bitmap);
219         }
220         return(id);
221 }
222
223 int idr_get_new_above(struct idr *idp, void *ptr, int starting_id)
224 {
225         struct idr_layer *p, *new;
226         int layers, v, id;
227         
228         id = starting_id;
229 build_up:
230         p = idp->top;
231         layers = idp->layers;
232         if (unlikely(!p)) {
233                 if (!(p = alloc_layer(idp)))
234                         return -1;
235                 layers = 1;
236         }
237         /*
238          * Add a new layer to the top of the tree if the requested
239          * id is larger than the currently allocated space.
240          */
241         while (id >= (1 << (layers*IDR_BITS))) {
242                 layers++;
243                 if (!p->count)
244                         continue;
245                 if (!(new = alloc_layer(idp))) {
246                         /*
247                          * The allocation failed.  If we built part of
248                          * the structure tear it down.
249                          */
250                         for (new = p; p && p != idp->top; new = p) {
251                                 p = p->ary[0];
252                                 new->ary[0] = 0;
253                                 new->bitmap = new->count = 0;
254                                 free_layer(idp, new);
255                         }
256                         return -1;
257                 }
258                 new->ary[0] = p;
259                 new->count = 1;
260                 if (p->bitmap == IDR_FULL)
261                         __set_bit(0, &new->bitmap);
262                 p = new;
263         }
264         idp->top = p;
265         idp->layers = layers;
266         v = sub_alloc(idp, ptr, &id);
267         if (v == -2)
268                 goto build_up;
269         if ( likely(v >= 0 )) {
270                 idp->count++;
271                 v += (idp->count << MAX_ID_SHIFT);
272                 if ( unlikely( v == -1 ))
273                      v += (1L << MAX_ID_SHIFT);
274         }
275         return(v);
276 }
277 EXPORT_SYMBOL(idr_get_new_above);
278
279 int idr_get_new(struct idr *idp, void *ptr)
280 {
281         return idr_get_new_above(idp, ptr, 0);
282 }
283 EXPORT_SYMBOL(idr_get_new);
284
285
286 static void sub_remove(struct idr *idp, int shift, int id)
287 {
288         struct idr_layer *p = idp->top;
289         struct idr_layer **pa[MAX_LEVEL];
290         struct idr_layer ***paa = &pa[0];
291
292         *paa = NULL;
293         *++paa = &idp->top;
294
295         while ((shift > 0) && p) {
296                 int n = (id >> shift) & IDR_MASK;
297                 __clear_bit(n, &p->bitmap);
298                 *++paa = &p->ary[n];
299                 p = p->ary[n];
300                 shift -= IDR_BITS;
301         }
302         if (likely(p != NULL)){
303                 int n = id & IDR_MASK;
304                 __clear_bit(n, &p->bitmap);
305                 p->ary[n] = NULL;
306                 while(*paa && ! --((**paa)->count)){
307                         free_layer(idp, **paa);
308                         **paa-- = NULL;
309                 }
310                 if ( ! *paa )
311                         idp->layers = 0;
312         }
313 }
314 void idr_remove(struct idr *idp, int id)
315 {
316         struct idr_layer *p;
317
318         sub_remove(idp, (idp->layers - 1) * IDR_BITS, id);
319         if ( idp->top && idp->top->count == 1 && 
320              (idp->layers > 1) &&
321              idp->top->ary[0]){  // We can drop a layer
322
323                 p = idp->top->ary[0];
324                 idp->top->bitmap = idp->top->count = 0;
325                 free_layer(idp, idp->top);
326                 idp->top = p;
327                 --idp->layers;
328         }
329         while (idp->id_free_cnt >= IDR_FREE_MAX) {
330                 
331                 p = alloc_layer(idp);
332                 kmem_cache_free(idr_layer_cache, p);
333                 return;
334         }
335 }
336 EXPORT_SYMBOL(idr_remove);
337
338 void *idr_find(struct idr *idp, int id)
339 {
340         int n;
341         struct idr_layer *p;
342
343         n = idp->layers * IDR_BITS;
344         p = idp->top;
345 #if 0
346         /*
347          * This tests to see if bits outside the current tree are
348          * present.  If so, tain't one of ours!
349          */
350         if ( unlikely( (id & ~(~0 << MAX_ID_SHIFT)) >> (n + IDR_BITS)))
351              return NULL;
352 #endif
353         while (n > 0 && p) {
354                 n -= IDR_BITS;
355                 p = p->ary[(id >> n) & IDR_MASK];
356         }
357         return((void *)p);
358 }
359 EXPORT_SYMBOL(idr_find);
360
361 static void idr_cache_ctor(void * idr_layer, 
362                            kmem_cache_t *idr_layer_cache, unsigned long flags)
363 {
364         memset(idr_layer, 0, sizeof(struct idr_layer));
365 }
366
367 static  int init_id_cache(void)
368 {
369         if (!idr_layer_cache)
370                 idr_layer_cache = kmem_cache_create("idr_layer_cache", 
371                         sizeof(struct idr_layer), 0, 0, idr_cache_ctor, 0);
372         return 0;
373 }
374
375 void idr_init(struct idr *idp)
376 {
377         init_id_cache();
378         memset(idp, 0, sizeof(struct idr));
379         spin_lock_init(&idp->lock);
380 }
381 EXPORT_SYMBOL(idr_init);
382