idr.c 29 KB

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