idr.c 29 KB

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