idr.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. /*
  2. * 2002-10-18 written by Jim Houston jim.houston@ccur.com
  3. * Copyright (C) 2002 by Concurrent Computer Corporation
  4. * Distributed under the GNU GPL license version 2.
  5. *
  6. * Modified by George Anzinger to reuse immediately and to use
  7. * find bit instructions. Also removed _irq on spinlocks.
  8. *
  9. * Modified by Nadia Derbey to make it RCU safe.
  10. *
  11. * Small id to pointer translation service.
  12. *
  13. * It uses a radix tree like structure as a sparse array indexed
  14. * by the id to obtain the pointer. The bitmap makes allocating
  15. * a new id quick.
  16. *
  17. * You call it to allocate an id (an int) an associate with that id a
  18. * pointer or what ever, we treat it as a (void *). You can pass this
  19. * id to a user for him to pass back at a later time. You then pass
  20. * that id to this code and it returns your pointer.
  21. * You can release ids at any time. When all ids are released, most of
  22. * the memory is returned (we keep MAX_IDR_FREE) in a local pool so we
  23. * don't need to go to the memory "store" during an id allocate, just
  24. * so you don't need to be too concerned about locking and conflicts
  25. * with the slab allocator.
  26. */
  27. #ifndef TEST // to test in user space...
  28. #include <linux/slab.h>
  29. #include <linux/init.h>
  30. #include <linux/export.h>
  31. #endif
  32. #include <linux/err.h>
  33. #include <linux/string.h>
  34. #include <linux/idr.h>
  35. #include <linux/spinlock.h>
  36. #include <linux/percpu.h>
  37. #include <linux/hardirq.h>
  38. #define MAX_IDR_SHIFT (sizeof(int) * 8 - 1)
  39. #define MAX_IDR_BIT (1U << MAX_IDR_SHIFT)
  40. /* Leave the possibility of an incomplete final layer */
  41. #define MAX_IDR_LEVEL ((MAX_IDR_SHIFT + IDR_BITS - 1) / IDR_BITS)
  42. /* Number of id_layer structs to leave in free list */
  43. #define MAX_IDR_FREE (MAX_IDR_LEVEL * 2)
  44. static struct kmem_cache *idr_layer_cache;
  45. static DEFINE_PER_CPU(struct idr_layer *, idr_preload_head);
  46. static DEFINE_PER_CPU(int, idr_preload_cnt);
  47. static DEFINE_SPINLOCK(simple_ida_lock);
  48. /* the maximum ID which can be allocated given idr->layers */
  49. static int idr_max(int layers)
  50. {
  51. int bits = min_t(int, layers * IDR_BITS, MAX_IDR_SHIFT);
  52. return (1 << bits) - 1;
  53. }
  54. static struct idr_layer *get_from_free_list(struct idr *idp)
  55. {
  56. struct idr_layer *p;
  57. unsigned long flags;
  58. spin_lock_irqsave(&idp->lock, flags);
  59. if ((p = idp->id_free)) {
  60. idp->id_free = p->ary[0];
  61. idp->id_free_cnt--;
  62. p->ary[0] = NULL;
  63. }
  64. spin_unlock_irqrestore(&idp->lock, flags);
  65. return(p);
  66. }
  67. /**
  68. * idr_layer_alloc - allocate a new idr_layer
  69. * @gfp_mask: allocation mask
  70. * @layer_idr: optional idr to allocate from
  71. *
  72. * If @layer_idr is %NULL, directly allocate one using @gfp_mask or fetch
  73. * one from the per-cpu preload buffer. If @layer_idr is not %NULL, fetch
  74. * an idr_layer from @idr->id_free.
  75. *
  76. * @layer_idr is to maintain backward compatibility with the old alloc
  77. * interface - idr_pre_get() and idr_get_new*() - and will be removed
  78. * together with per-pool preload buffer.
  79. */
  80. static struct idr_layer *idr_layer_alloc(gfp_t gfp_mask, struct idr *layer_idr)
  81. {
  82. struct idr_layer *new;
  83. /* this is the old path, bypass to get_from_free_list() */
  84. if (layer_idr)
  85. return get_from_free_list(layer_idr);
  86. /* try to allocate directly from kmem_cache */
  87. new = kmem_cache_zalloc(idr_layer_cache, gfp_mask);
  88. if (new)
  89. return new;
  90. /*
  91. * Try to fetch one from the per-cpu preload buffer if in process
  92. * context. See idr_preload() for details.
  93. */
  94. if (in_interrupt())
  95. return NULL;
  96. preempt_disable();
  97. new = __this_cpu_read(idr_preload_head);
  98. if (new) {
  99. __this_cpu_write(idr_preload_head, new->ary[0]);
  100. __this_cpu_dec(idr_preload_cnt);
  101. new->ary[0] = NULL;
  102. }
  103. preempt_enable();
  104. return new;
  105. }
  106. static void idr_layer_rcu_free(struct rcu_head *head)
  107. {
  108. struct idr_layer *layer;
  109. layer = container_of(head, struct idr_layer, rcu_head);
  110. kmem_cache_free(idr_layer_cache, layer);
  111. }
  112. static inline void free_layer(struct idr_layer *p)
  113. {
  114. call_rcu(&p->rcu_head, idr_layer_rcu_free);
  115. }
  116. /* only called when idp->lock is held */
  117. static void __move_to_free_list(struct idr *idp, struct idr_layer *p)
  118. {
  119. p->ary[0] = idp->id_free;
  120. idp->id_free = p;
  121. idp->id_free_cnt++;
  122. }
  123. static void move_to_free_list(struct idr *idp, struct idr_layer *p)
  124. {
  125. unsigned long flags;
  126. /*
  127. * Depends on the return element being zeroed.
  128. */
  129. spin_lock_irqsave(&idp->lock, flags);
  130. __move_to_free_list(idp, p);
  131. spin_unlock_irqrestore(&idp->lock, flags);
  132. }
  133. static void idr_mark_full(struct idr_layer **pa, int id)
  134. {
  135. struct idr_layer *p = pa[0];
  136. int l = 0;
  137. __set_bit(id & IDR_MASK, &p->bitmap);
  138. /*
  139. * If this layer is full mark the bit in the layer above to
  140. * show that this part of the radix tree is full. This may
  141. * complete the layer above and require walking up the radix
  142. * tree.
  143. */
  144. while (p->bitmap == IDR_FULL) {
  145. if (!(p = pa[++l]))
  146. break;
  147. id = id >> IDR_BITS;
  148. __set_bit((id & IDR_MASK), &p->bitmap);
  149. }
  150. }
  151. /**
  152. * idr_pre_get - reserve resources for idr allocation
  153. * @idp: idr handle
  154. * @gfp_mask: memory allocation flags
  155. *
  156. * This function should be called prior to calling the idr_get_new* functions.
  157. * It preallocates enough memory to satisfy the worst possible allocation. The
  158. * caller should pass in GFP_KERNEL if possible. This of course requires that
  159. * no spinning locks be held.
  160. *
  161. * If the system is REALLY out of memory this function returns %0,
  162. * otherwise %1.
  163. */
  164. int idr_pre_get(struct idr *idp, gfp_t gfp_mask)
  165. {
  166. while (idp->id_free_cnt < MAX_IDR_FREE) {
  167. struct idr_layer *new;
  168. new = kmem_cache_zalloc(idr_layer_cache, gfp_mask);
  169. if (new == NULL)
  170. return (0);
  171. move_to_free_list(idp, new);
  172. }
  173. return 1;
  174. }
  175. EXPORT_SYMBOL(idr_pre_get);
  176. /**
  177. * sub_alloc - try to allocate an id without growing the tree depth
  178. * @idp: idr handle
  179. * @starting_id: id to start search at
  180. * @id: pointer to the allocated handle
  181. * @pa: idr_layer[MAX_IDR_LEVEL] used as backtrack buffer
  182. * @gfp_mask: allocation mask for idr_layer_alloc()
  183. * @layer_idr: optional idr passed to idr_layer_alloc()
  184. *
  185. * Allocate an id in range [@starting_id, INT_MAX] from @idp without
  186. * growing its depth. Returns
  187. *
  188. * the allocated id >= 0 if successful,
  189. * -EAGAIN if the tree needs to grow for allocation to succeed,
  190. * -ENOSPC if the id space is exhausted,
  191. * -ENOMEM if more idr_layers need to be allocated.
  192. */
  193. static int sub_alloc(struct idr *idp, int *starting_id, struct idr_layer **pa,
  194. gfp_t gfp_mask, struct idr *layer_idr)
  195. {
  196. int n, m, sh;
  197. struct idr_layer *p, *new;
  198. int l, id, oid;
  199. unsigned long bm;
  200. id = *starting_id;
  201. restart:
  202. p = idp->top;
  203. l = idp->layers;
  204. pa[l--] = NULL;
  205. while (1) {
  206. /*
  207. * We run around this while until we reach the leaf node...
  208. */
  209. n = (id >> (IDR_BITS*l)) & IDR_MASK;
  210. bm = ~p->bitmap;
  211. m = find_next_bit(&bm, IDR_SIZE, n);
  212. if (m == IDR_SIZE) {
  213. /* no space available go back to previous layer. */
  214. l++;
  215. oid = id;
  216. id = (id | ((1 << (IDR_BITS * l)) - 1)) + 1;
  217. /* if already at the top layer, we need to grow */
  218. if (id >= 1 << (idp->layers * IDR_BITS)) {
  219. *starting_id = id;
  220. return -EAGAIN;
  221. }
  222. p = pa[l];
  223. BUG_ON(!p);
  224. /* If we need to go up one layer, continue the
  225. * loop; otherwise, restart from the top.
  226. */
  227. sh = IDR_BITS * (l + 1);
  228. if (oid >> sh == id >> sh)
  229. continue;
  230. else
  231. goto restart;
  232. }
  233. if (m != n) {
  234. sh = IDR_BITS*l;
  235. id = ((id >> sh) ^ n ^ m) << sh;
  236. }
  237. if ((id >= MAX_IDR_BIT) || (id < 0))
  238. return -ENOSPC;
  239. if (l == 0)
  240. break;
  241. /*
  242. * Create the layer below if it is missing.
  243. */
  244. if (!p->ary[m]) {
  245. new = idr_layer_alloc(gfp_mask, layer_idr);
  246. if (!new)
  247. return -ENOMEM;
  248. new->layer = l-1;
  249. rcu_assign_pointer(p->ary[m], new);
  250. p->count++;
  251. }
  252. pa[l--] = p;
  253. p = p->ary[m];
  254. }
  255. pa[l] = p;
  256. return id;
  257. }
  258. static int idr_get_empty_slot(struct idr *idp, int starting_id,
  259. struct idr_layer **pa, gfp_t gfp_mask,
  260. struct idr *layer_idr)
  261. {
  262. struct idr_layer *p, *new;
  263. int layers, v, id;
  264. unsigned long flags;
  265. id = starting_id;
  266. build_up:
  267. p = idp->top;
  268. layers = idp->layers;
  269. if (unlikely(!p)) {
  270. if (!(p = idr_layer_alloc(gfp_mask, layer_idr)))
  271. return -ENOMEM;
  272. p->layer = 0;
  273. layers = 1;
  274. }
  275. /*
  276. * Add a new layer to the top of the tree if the requested
  277. * id is larger than the currently allocated space.
  278. */
  279. while (id > idr_max(layers)) {
  280. layers++;
  281. if (!p->count) {
  282. /* special case: if the tree is currently empty,
  283. * then we grow the tree by moving the top node
  284. * upwards.
  285. */
  286. p->layer++;
  287. continue;
  288. }
  289. if (!(new = idr_layer_alloc(gfp_mask, layer_idr))) {
  290. /*
  291. * The allocation failed. If we built part of
  292. * the structure tear it down.
  293. */
  294. spin_lock_irqsave(&idp->lock, flags);
  295. for (new = p; p && p != idp->top; new = p) {
  296. p = p->ary[0];
  297. new->ary[0] = NULL;
  298. new->bitmap = new->count = 0;
  299. __move_to_free_list(idp, new);
  300. }
  301. spin_unlock_irqrestore(&idp->lock, flags);
  302. return -ENOMEM;
  303. }
  304. new->ary[0] = p;
  305. new->count = 1;
  306. new->layer = layers-1;
  307. if (p->bitmap == IDR_FULL)
  308. __set_bit(0, &new->bitmap);
  309. p = new;
  310. }
  311. rcu_assign_pointer(idp->top, p);
  312. idp->layers = layers;
  313. v = sub_alloc(idp, &id, pa, gfp_mask, layer_idr);
  314. if (v == -EAGAIN)
  315. goto build_up;
  316. return(v);
  317. }
  318. /*
  319. * @id and @pa are from a successful allocation from idr_get_empty_slot().
  320. * Install the user pointer @ptr and mark the slot full.
  321. */
  322. static void idr_fill_slot(void *ptr, int id, struct idr_layer **pa)
  323. {
  324. rcu_assign_pointer(pa[0]->ary[id & IDR_MASK], (struct idr_layer *)ptr);
  325. pa[0]->count++;
  326. idr_mark_full(pa, id);
  327. }
  328. /**
  329. * idr_get_new_above - allocate new idr entry above or equal to a start id
  330. * @idp: idr handle
  331. * @ptr: pointer you want associated with the id
  332. * @starting_id: id to start search at
  333. * @id: pointer to the allocated handle
  334. *
  335. * This is the allocate id function. It should be called with any
  336. * required locks.
  337. *
  338. * If allocation from IDR's private freelist fails, idr_get_new_above() will
  339. * return %-EAGAIN. The caller should retry the idr_pre_get() call to refill
  340. * IDR's preallocation and then retry the idr_get_new_above() call.
  341. *
  342. * If the idr is full idr_get_new_above() will return %-ENOSPC.
  343. *
  344. * @id returns a value in the range @starting_id ... %0x7fffffff
  345. */
  346. int idr_get_new_above(struct idr *idp, void *ptr, int starting_id, int *id)
  347. {
  348. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  349. int rv;
  350. rv = idr_get_empty_slot(idp, starting_id, pa, 0, idp);
  351. if (rv < 0)
  352. return rv == -ENOMEM ? -EAGAIN : rv;
  353. idr_fill_slot(ptr, rv, pa);
  354. *id = rv;
  355. return 0;
  356. }
  357. EXPORT_SYMBOL(idr_get_new_above);
  358. /**
  359. * idr_preload - preload for idr_alloc()
  360. * @gfp_mask: allocation mask to use for preloading
  361. *
  362. * Preload per-cpu layer buffer for idr_alloc(). Can only be used from
  363. * process context and each idr_preload() invocation should be matched with
  364. * idr_preload_end(). Note that preemption is disabled while preloaded.
  365. *
  366. * The first idr_alloc() in the preloaded section can be treated as if it
  367. * were invoked with @gfp_mask used for preloading. This allows using more
  368. * permissive allocation masks for idrs protected by spinlocks.
  369. *
  370. * For example, if idr_alloc() below fails, the failure can be treated as
  371. * if idr_alloc() were called with GFP_KERNEL rather than GFP_NOWAIT.
  372. *
  373. * idr_preload(GFP_KERNEL);
  374. * spin_lock(lock);
  375. *
  376. * id = idr_alloc(idr, ptr, start, end, GFP_NOWAIT);
  377. *
  378. * spin_unlock(lock);
  379. * idr_preload_end();
  380. * if (id < 0)
  381. * error;
  382. */
  383. void idr_preload(gfp_t gfp_mask)
  384. {
  385. /*
  386. * Consuming preload buffer from non-process context breaks preload
  387. * allocation guarantee. Disallow usage from those contexts.
  388. */
  389. WARN_ON_ONCE(in_interrupt());
  390. might_sleep_if(gfp_mask & __GFP_WAIT);
  391. preempt_disable();
  392. /*
  393. * idr_alloc() is likely to succeed w/o full idr_layer buffer and
  394. * return value from idr_alloc() needs to be checked for failure
  395. * anyway. Silently give up if allocation fails. The caller can
  396. * treat failures from idr_alloc() as if idr_alloc() were called
  397. * with @gfp_mask which should be enough.
  398. */
  399. while (__this_cpu_read(idr_preload_cnt) < MAX_IDR_FREE) {
  400. struct idr_layer *new;
  401. preempt_enable();
  402. new = kmem_cache_zalloc(idr_layer_cache, gfp_mask);
  403. preempt_disable();
  404. if (!new)
  405. break;
  406. /* link the new one to per-cpu preload list */
  407. new->ary[0] = __this_cpu_read(idr_preload_head);
  408. __this_cpu_write(idr_preload_head, new);
  409. __this_cpu_inc(idr_preload_cnt);
  410. }
  411. }
  412. EXPORT_SYMBOL(idr_preload);
  413. /**
  414. * idr_alloc - allocate new idr entry
  415. * @idr: the (initialized) idr
  416. * @ptr: pointer to be associated with the new id
  417. * @start: the minimum id (inclusive)
  418. * @end: the maximum id (exclusive, <= 0 for max)
  419. * @gfp_mask: memory allocation flags
  420. *
  421. * Allocate an id in [start, end) and associate it with @ptr. If no ID is
  422. * available in the specified range, returns -ENOSPC. On memory allocation
  423. * failure, returns -ENOMEM.
  424. *
  425. * Note that @end is treated as max when <= 0. This is to always allow
  426. * using @start + N as @end as long as N is inside integer range.
  427. *
  428. * The user is responsible for exclusively synchronizing all operations
  429. * which may modify @idr. However, read-only accesses such as idr_find()
  430. * or iteration can be performed under RCU read lock provided the user
  431. * destroys @ptr in RCU-safe way after removal from idr.
  432. */
  433. int idr_alloc(struct idr *idr, void *ptr, int start, int end, gfp_t gfp_mask)
  434. {
  435. int max = end > 0 ? end - 1 : INT_MAX; /* inclusive upper limit */
  436. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  437. int id;
  438. might_sleep_if(gfp_mask & __GFP_WAIT);
  439. /* sanity checks */
  440. if (WARN_ON_ONCE(start < 0))
  441. return -EINVAL;
  442. if (unlikely(max < start))
  443. return -ENOSPC;
  444. /* allocate id */
  445. id = idr_get_empty_slot(idr, start, pa, gfp_mask, NULL);
  446. if (unlikely(id < 0))
  447. return id;
  448. if (unlikely(id > max))
  449. return -ENOSPC;
  450. idr_fill_slot(ptr, id, pa);
  451. return id;
  452. }
  453. EXPORT_SYMBOL_GPL(idr_alloc);
  454. static void idr_remove_warning(int id)
  455. {
  456. printk(KERN_WARNING
  457. "idr_remove called for id=%d which is not allocated.\n", id);
  458. dump_stack();
  459. }
  460. static void sub_remove(struct idr *idp, int shift, int id)
  461. {
  462. struct idr_layer *p = idp->top;
  463. struct idr_layer **pa[MAX_IDR_LEVEL + 1];
  464. struct idr_layer ***paa = &pa[0];
  465. struct idr_layer *to_free;
  466. int n;
  467. *paa = NULL;
  468. *++paa = &idp->top;
  469. while ((shift > 0) && p) {
  470. n = (id >> shift) & IDR_MASK;
  471. __clear_bit(n, &p->bitmap);
  472. *++paa = &p->ary[n];
  473. p = p->ary[n];
  474. shift -= IDR_BITS;
  475. }
  476. n = id & IDR_MASK;
  477. if (likely(p != NULL && test_bit(n, &p->bitmap))){
  478. __clear_bit(n, &p->bitmap);
  479. rcu_assign_pointer(p->ary[n], NULL);
  480. to_free = NULL;
  481. while(*paa && ! --((**paa)->count)){
  482. if (to_free)
  483. free_layer(to_free);
  484. to_free = **paa;
  485. **paa-- = NULL;
  486. }
  487. if (!*paa)
  488. idp->layers = 0;
  489. if (to_free)
  490. free_layer(to_free);
  491. } else
  492. idr_remove_warning(id);
  493. }
  494. /**
  495. * idr_remove - remove the given id and free its slot
  496. * @idp: idr handle
  497. * @id: unique key
  498. */
  499. void idr_remove(struct idr *idp, int id)
  500. {
  501. struct idr_layer *p;
  502. struct idr_layer *to_free;
  503. if (WARN_ON_ONCE(id < 0))
  504. return;
  505. sub_remove(idp, (idp->layers - 1) * IDR_BITS, id);
  506. if (idp->top && idp->top->count == 1 && (idp->layers > 1) &&
  507. idp->top->ary[0]) {
  508. /*
  509. * Single child at leftmost slot: we can shrink the tree.
  510. * This level is not needed anymore since when layers are
  511. * inserted, they are inserted at the top of the existing
  512. * tree.
  513. */
  514. to_free = idp->top;
  515. p = idp->top->ary[0];
  516. rcu_assign_pointer(idp->top, p);
  517. --idp->layers;
  518. to_free->bitmap = to_free->count = 0;
  519. free_layer(to_free);
  520. }
  521. while (idp->id_free_cnt >= MAX_IDR_FREE) {
  522. p = get_from_free_list(idp);
  523. /*
  524. * Note: we don't call the rcu callback here, since the only
  525. * layers that fall into the freelist are those that have been
  526. * preallocated.
  527. */
  528. kmem_cache_free(idr_layer_cache, p);
  529. }
  530. return;
  531. }
  532. EXPORT_SYMBOL(idr_remove);
  533. void __idr_remove_all(struct idr *idp)
  534. {
  535. int n, id, max;
  536. int bt_mask;
  537. struct idr_layer *p;
  538. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  539. struct idr_layer **paa = &pa[0];
  540. n = idp->layers * IDR_BITS;
  541. p = idp->top;
  542. rcu_assign_pointer(idp->top, NULL);
  543. max = idr_max(idp->layers);
  544. id = 0;
  545. while (id >= 0 && id <= max) {
  546. while (n > IDR_BITS && p) {
  547. n -= IDR_BITS;
  548. *paa++ = p;
  549. p = p->ary[(id >> n) & IDR_MASK];
  550. }
  551. bt_mask = id;
  552. id += 1 << n;
  553. /* Get the highest bit that the above add changed from 0->1. */
  554. while (n < fls(id ^ bt_mask)) {
  555. if (p)
  556. free_layer(p);
  557. n += IDR_BITS;
  558. p = *--paa;
  559. }
  560. }
  561. idp->layers = 0;
  562. }
  563. EXPORT_SYMBOL(__idr_remove_all);
  564. /**
  565. * idr_destroy - release all cached layers within an idr tree
  566. * @idp: idr handle
  567. *
  568. * Free all id mappings and all idp_layers. After this function, @idp is
  569. * completely unused and can be freed / recycled. The caller is
  570. * responsible for ensuring that no one else accesses @idp during or after
  571. * idr_destroy().
  572. *
  573. * A typical clean-up sequence for objects stored in an idr tree will use
  574. * idr_for_each() to free all objects, if necessay, then idr_destroy() to
  575. * free up the id mappings and cached idr_layers.
  576. */
  577. void idr_destroy(struct idr *idp)
  578. {
  579. __idr_remove_all(idp);
  580. while (idp->id_free_cnt) {
  581. struct idr_layer *p = get_from_free_list(idp);
  582. kmem_cache_free(idr_layer_cache, p);
  583. }
  584. }
  585. EXPORT_SYMBOL(idr_destroy);
  586. /**
  587. * idr_find - return pointer for given id
  588. * @idp: idr handle
  589. * @id: lookup key
  590. *
  591. * Return the pointer given the id it has been registered with. A %NULL
  592. * return indicates that @id is not valid or you passed %NULL in
  593. * idr_get_new().
  594. *
  595. * This function can be called under rcu_read_lock(), given that the leaf
  596. * pointers lifetimes are correctly managed.
  597. */
  598. void *idr_find(struct idr *idp, int id)
  599. {
  600. int n;
  601. struct idr_layer *p;
  602. if (WARN_ON_ONCE(id < 0))
  603. return NULL;
  604. p = rcu_dereference_raw(idp->top);
  605. if (!p)
  606. return NULL;
  607. n = (p->layer+1) * IDR_BITS;
  608. if (id > idr_max(p->layer + 1))
  609. return NULL;
  610. BUG_ON(n == 0);
  611. while (n > 0 && p) {
  612. n -= IDR_BITS;
  613. BUG_ON(n != p->layer*IDR_BITS);
  614. p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
  615. }
  616. return((void *)p);
  617. }
  618. EXPORT_SYMBOL(idr_find);
  619. /**
  620. * idr_for_each - iterate through all stored pointers
  621. * @idp: idr handle
  622. * @fn: function to be called for each pointer
  623. * @data: data passed back to callback function
  624. *
  625. * Iterate over the pointers registered with the given idr. The
  626. * callback function will be called for each pointer currently
  627. * registered, passing the id, the pointer and the data pointer passed
  628. * to this function. It is not safe to modify the idr tree while in
  629. * the callback, so functions such as idr_get_new and idr_remove are
  630. * not allowed.
  631. *
  632. * We check the return of @fn each time. If it returns anything other
  633. * than %0, we break out and return that value.
  634. *
  635. * The caller must serialize idr_for_each() vs idr_get_new() and idr_remove().
  636. */
  637. int idr_for_each(struct idr *idp,
  638. int (*fn)(int id, void *p, void *data), void *data)
  639. {
  640. int n, id, max, error = 0;
  641. struct idr_layer *p;
  642. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  643. struct idr_layer **paa = &pa[0];
  644. n = idp->layers * IDR_BITS;
  645. p = rcu_dereference_raw(idp->top);
  646. max = idr_max(idp->layers);
  647. id = 0;
  648. while (id >= 0 && id <= max) {
  649. while (n > 0 && p) {
  650. n -= IDR_BITS;
  651. *paa++ = p;
  652. p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
  653. }
  654. if (p) {
  655. error = fn(id, (void *)p, data);
  656. if (error)
  657. break;
  658. }
  659. id += 1 << n;
  660. while (n < fls(id)) {
  661. n += IDR_BITS;
  662. p = *--paa;
  663. }
  664. }
  665. return error;
  666. }
  667. EXPORT_SYMBOL(idr_for_each);
  668. /**
  669. * idr_get_next - lookup next object of id to given id.
  670. * @idp: idr handle
  671. * @nextidp: pointer to lookup key
  672. *
  673. * Returns pointer to registered object with id, which is next number to
  674. * given id. After being looked up, *@nextidp will be updated for the next
  675. * iteration.
  676. *
  677. * This function can be called under rcu_read_lock(), given that the leaf
  678. * pointers lifetimes are correctly managed.
  679. */
  680. void *idr_get_next(struct idr *idp, int *nextidp)
  681. {
  682. struct idr_layer *p, *pa[MAX_IDR_LEVEL + 1];
  683. struct idr_layer **paa = &pa[0];
  684. int id = *nextidp;
  685. int n, max;
  686. /* find first ent */
  687. p = rcu_dereference_raw(idp->top);
  688. if (!p)
  689. return NULL;
  690. n = (p->layer + 1) * IDR_BITS;
  691. max = idr_max(p->layer + 1);
  692. while (id >= 0 && id <= max) {
  693. while (n > 0 && p) {
  694. n -= IDR_BITS;
  695. *paa++ = p;
  696. p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
  697. }
  698. if (p) {
  699. *nextidp = id;
  700. return p;
  701. }
  702. /*
  703. * Proceed to the next layer at the current level. Unlike
  704. * idr_for_each(), @id isn't guaranteed to be aligned to
  705. * layer boundary at this point and adding 1 << n may
  706. * incorrectly skip IDs. Make sure we jump to the
  707. * beginning of the next layer using round_up().
  708. */
  709. id = round_up(id + 1, 1 << n);
  710. while (n < fls(id)) {
  711. n += IDR_BITS;
  712. p = *--paa;
  713. }
  714. }
  715. return NULL;
  716. }
  717. EXPORT_SYMBOL(idr_get_next);
  718. /**
  719. * idr_replace - replace pointer for given id
  720. * @idp: idr handle
  721. * @ptr: pointer you want associated with the id
  722. * @id: lookup key
  723. *
  724. * Replace the pointer registered with an id and return the old value.
  725. * A %-ENOENT return indicates that @id was not found.
  726. * A %-EINVAL return indicates that @id was not within valid constraints.
  727. *
  728. * The caller must serialize with writers.
  729. */
  730. void *idr_replace(struct idr *idp, void *ptr, int id)
  731. {
  732. int n;
  733. struct idr_layer *p, *old_p;
  734. if (WARN_ON_ONCE(id < 0))
  735. return ERR_PTR(-EINVAL);
  736. p = idp->top;
  737. if (!p)
  738. return ERR_PTR(-EINVAL);
  739. n = (p->layer+1) * IDR_BITS;
  740. if (id >= (1 << n))
  741. return ERR_PTR(-EINVAL);
  742. n -= IDR_BITS;
  743. while ((n > 0) && p) {
  744. p = p->ary[(id >> n) & IDR_MASK];
  745. n -= IDR_BITS;
  746. }
  747. n = id & IDR_MASK;
  748. if (unlikely(p == NULL || !test_bit(n, &p->bitmap)))
  749. return ERR_PTR(-ENOENT);
  750. old_p = p->ary[n];
  751. rcu_assign_pointer(p->ary[n], ptr);
  752. return old_p;
  753. }
  754. EXPORT_SYMBOL(idr_replace);
  755. void __init idr_init_cache(void)
  756. {
  757. idr_layer_cache = kmem_cache_create("idr_layer_cache",
  758. sizeof(struct idr_layer), 0, SLAB_PANIC, NULL);
  759. }
  760. /**
  761. * idr_init - initialize idr handle
  762. * @idp: idr handle
  763. *
  764. * This function is use to set up the handle (@idp) that you will pass
  765. * to the rest of the functions.
  766. */
  767. void idr_init(struct idr *idp)
  768. {
  769. memset(idp, 0, sizeof(struct idr));
  770. spin_lock_init(&idp->lock);
  771. }
  772. EXPORT_SYMBOL(idr_init);
  773. /**
  774. * DOC: IDA description
  775. * IDA - IDR based ID allocator
  776. *
  777. * This is id allocator without id -> pointer translation. Memory
  778. * usage is much lower than full blown idr because each id only
  779. * occupies a bit. ida uses a custom leaf node which contains
  780. * IDA_BITMAP_BITS slots.
  781. *
  782. * 2007-04-25 written by Tejun Heo <htejun@gmail.com>
  783. */
  784. static void free_bitmap(struct ida *ida, struct ida_bitmap *bitmap)
  785. {
  786. unsigned long flags;
  787. if (!ida->free_bitmap) {
  788. spin_lock_irqsave(&ida->idr.lock, flags);
  789. if (!ida->free_bitmap) {
  790. ida->free_bitmap = bitmap;
  791. bitmap = NULL;
  792. }
  793. spin_unlock_irqrestore(&ida->idr.lock, flags);
  794. }
  795. kfree(bitmap);
  796. }
  797. /**
  798. * ida_pre_get - reserve resources for ida allocation
  799. * @ida: ida handle
  800. * @gfp_mask: memory allocation flag
  801. *
  802. * This function should be called prior to locking and calling the
  803. * following function. It preallocates enough memory to satisfy the
  804. * worst possible allocation.
  805. *
  806. * If the system is REALLY out of memory this function returns %0,
  807. * otherwise %1.
  808. */
  809. int ida_pre_get(struct ida *ida, gfp_t gfp_mask)
  810. {
  811. /* allocate idr_layers */
  812. if (!idr_pre_get(&ida->idr, gfp_mask))
  813. return 0;
  814. /* allocate free_bitmap */
  815. if (!ida->free_bitmap) {
  816. struct ida_bitmap *bitmap;
  817. bitmap = kmalloc(sizeof(struct ida_bitmap), gfp_mask);
  818. if (!bitmap)
  819. return 0;
  820. free_bitmap(ida, bitmap);
  821. }
  822. return 1;
  823. }
  824. EXPORT_SYMBOL(ida_pre_get);
  825. /**
  826. * ida_get_new_above - allocate new ID above or equal to a start id
  827. * @ida: ida handle
  828. * @starting_id: id to start search at
  829. * @p_id: pointer to the allocated handle
  830. *
  831. * Allocate new ID above or equal to @starting_id. It should be called
  832. * with any required locks.
  833. *
  834. * If memory is required, it will return %-EAGAIN, you should unlock
  835. * and go back to the ida_pre_get() call. If the ida is full, it will
  836. * return %-ENOSPC.
  837. *
  838. * @p_id returns a value in the range @starting_id ... %0x7fffffff.
  839. */
  840. int ida_get_new_above(struct ida *ida, int starting_id, int *p_id)
  841. {
  842. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  843. struct ida_bitmap *bitmap;
  844. unsigned long flags;
  845. int idr_id = starting_id / IDA_BITMAP_BITS;
  846. int offset = starting_id % IDA_BITMAP_BITS;
  847. int t, id;
  848. restart:
  849. /* get vacant slot */
  850. t = idr_get_empty_slot(&ida->idr, idr_id, pa, 0, &ida->idr);
  851. if (t < 0)
  852. return t == -ENOMEM ? -EAGAIN : t;
  853. if (t * IDA_BITMAP_BITS >= MAX_IDR_BIT)
  854. return -ENOSPC;
  855. if (t != idr_id)
  856. offset = 0;
  857. idr_id = t;
  858. /* if bitmap isn't there, create a new one */
  859. bitmap = (void *)pa[0]->ary[idr_id & IDR_MASK];
  860. if (!bitmap) {
  861. spin_lock_irqsave(&ida->idr.lock, flags);
  862. bitmap = ida->free_bitmap;
  863. ida->free_bitmap = NULL;
  864. spin_unlock_irqrestore(&ida->idr.lock, flags);
  865. if (!bitmap)
  866. return -EAGAIN;
  867. memset(bitmap, 0, sizeof(struct ida_bitmap));
  868. rcu_assign_pointer(pa[0]->ary[idr_id & IDR_MASK],
  869. (void *)bitmap);
  870. pa[0]->count++;
  871. }
  872. /* lookup for empty slot */
  873. t = find_next_zero_bit(bitmap->bitmap, IDA_BITMAP_BITS, offset);
  874. if (t == IDA_BITMAP_BITS) {
  875. /* no empty slot after offset, continue to the next chunk */
  876. idr_id++;
  877. offset = 0;
  878. goto restart;
  879. }
  880. id = idr_id * IDA_BITMAP_BITS + t;
  881. if (id >= MAX_IDR_BIT)
  882. return -ENOSPC;
  883. __set_bit(t, bitmap->bitmap);
  884. if (++bitmap->nr_busy == IDA_BITMAP_BITS)
  885. idr_mark_full(pa, idr_id);
  886. *p_id = id;
  887. /* Each leaf node can handle nearly a thousand slots and the
  888. * whole idea of ida is to have small memory foot print.
  889. * Throw away extra resources one by one after each successful
  890. * allocation.
  891. */
  892. if (ida->idr.id_free_cnt || ida->free_bitmap) {
  893. struct idr_layer *p = get_from_free_list(&ida->idr);
  894. if (p)
  895. kmem_cache_free(idr_layer_cache, p);
  896. }
  897. return 0;
  898. }
  899. EXPORT_SYMBOL(ida_get_new_above);
  900. /**
  901. * ida_remove - remove the given ID
  902. * @ida: ida handle
  903. * @id: ID to free
  904. */
  905. void ida_remove(struct ida *ida, int id)
  906. {
  907. struct idr_layer *p = ida->idr.top;
  908. int shift = (ida->idr.layers - 1) * IDR_BITS;
  909. int idr_id = id / IDA_BITMAP_BITS;
  910. int offset = id % IDA_BITMAP_BITS;
  911. int n;
  912. struct ida_bitmap *bitmap;
  913. /* clear full bits while looking up the leaf idr_layer */
  914. while ((shift > 0) && p) {
  915. n = (idr_id >> shift) & IDR_MASK;
  916. __clear_bit(n, &p->bitmap);
  917. p = p->ary[n];
  918. shift -= IDR_BITS;
  919. }
  920. if (p == NULL)
  921. goto err;
  922. n = idr_id & IDR_MASK;
  923. __clear_bit(n, &p->bitmap);
  924. bitmap = (void *)p->ary[n];
  925. if (!test_bit(offset, bitmap->bitmap))
  926. goto err;
  927. /* update bitmap and remove it if empty */
  928. __clear_bit(offset, bitmap->bitmap);
  929. if (--bitmap->nr_busy == 0) {
  930. __set_bit(n, &p->bitmap); /* to please idr_remove() */
  931. idr_remove(&ida->idr, idr_id);
  932. free_bitmap(ida, bitmap);
  933. }
  934. return;
  935. err:
  936. printk(KERN_WARNING
  937. "ida_remove called for id=%d which is not allocated.\n", id);
  938. }
  939. EXPORT_SYMBOL(ida_remove);
  940. /**
  941. * ida_destroy - release all cached layers within an ida tree
  942. * @ida: ida handle
  943. */
  944. void ida_destroy(struct ida *ida)
  945. {
  946. idr_destroy(&ida->idr);
  947. kfree(ida->free_bitmap);
  948. }
  949. EXPORT_SYMBOL(ida_destroy);
  950. /**
  951. * ida_simple_get - get a new id.
  952. * @ida: the (initialized) ida.
  953. * @start: the minimum id (inclusive, < 0x8000000)
  954. * @end: the maximum id (exclusive, < 0x8000000 or 0)
  955. * @gfp_mask: memory allocation flags
  956. *
  957. * Allocates an id in the range start <= id < end, or returns -ENOSPC.
  958. * On memory allocation failure, returns -ENOMEM.
  959. *
  960. * Use ida_simple_remove() to get rid of an id.
  961. */
  962. int ida_simple_get(struct ida *ida, unsigned int start, unsigned int end,
  963. gfp_t gfp_mask)
  964. {
  965. int ret, id;
  966. unsigned int max;
  967. unsigned long flags;
  968. BUG_ON((int)start < 0);
  969. BUG_ON((int)end < 0);
  970. if (end == 0)
  971. max = 0x80000000;
  972. else {
  973. BUG_ON(end < start);
  974. max = end - 1;
  975. }
  976. again:
  977. if (!ida_pre_get(ida, gfp_mask))
  978. return -ENOMEM;
  979. spin_lock_irqsave(&simple_ida_lock, flags);
  980. ret = ida_get_new_above(ida, start, &id);
  981. if (!ret) {
  982. if (id > max) {
  983. ida_remove(ida, id);
  984. ret = -ENOSPC;
  985. } else {
  986. ret = id;
  987. }
  988. }
  989. spin_unlock_irqrestore(&simple_ida_lock, flags);
  990. if (unlikely(ret == -EAGAIN))
  991. goto again;
  992. return ret;
  993. }
  994. EXPORT_SYMBOL(ida_simple_get);
  995. /**
  996. * ida_simple_remove - remove an allocated id.
  997. * @ida: the (initialized) ida.
  998. * @id: the id returned by ida_simple_get.
  999. */
  1000. void ida_simple_remove(struct ida *ida, unsigned int id)
  1001. {
  1002. unsigned long flags;
  1003. BUG_ON((int)id < 0);
  1004. spin_lock_irqsave(&simple_ida_lock, flags);
  1005. ida_remove(ida, id);
  1006. spin_unlock_irqrestore(&simple_ida_lock, flags);
  1007. }
  1008. EXPORT_SYMBOL(ida_simple_remove);
  1009. /**
  1010. * ida_init - initialize ida handle
  1011. * @ida: ida handle
  1012. *
  1013. * This function is use to set up the handle (@ida) that you will pass
  1014. * to the rest of the functions.
  1015. */
  1016. void ida_init(struct ida *ida)
  1017. {
  1018. memset(ida, 0, sizeof(struct ida));
  1019. idr_init(&ida->idr);
  1020. }
  1021. EXPORT_SYMBOL(ida_init);