idr.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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. static void idr_remove_warning(int id)
  451. {
  452. printk(KERN_WARNING
  453. "idr_remove called for id=%d which is not allocated.\n", id);
  454. dump_stack();
  455. }
  456. static void sub_remove(struct idr *idp, int shift, int id)
  457. {
  458. struct idr_layer *p = idp->top;
  459. struct idr_layer **pa[MAX_IDR_LEVEL + 1];
  460. struct idr_layer ***paa = &pa[0];
  461. struct idr_layer *to_free;
  462. int n;
  463. *paa = NULL;
  464. *++paa = &idp->top;
  465. while ((shift > 0) && p) {
  466. n = (id >> shift) & IDR_MASK;
  467. __clear_bit(n, p->bitmap);
  468. *++paa = &p->ary[n];
  469. p = p->ary[n];
  470. shift -= IDR_BITS;
  471. }
  472. n = id & IDR_MASK;
  473. if (likely(p != NULL && test_bit(n, p->bitmap))) {
  474. __clear_bit(n, p->bitmap);
  475. rcu_assign_pointer(p->ary[n], NULL);
  476. to_free = NULL;
  477. while(*paa && ! --((**paa)->count)){
  478. if (to_free)
  479. free_layer(idp, to_free);
  480. to_free = **paa;
  481. **paa-- = NULL;
  482. }
  483. if (!*paa)
  484. idp->layers = 0;
  485. if (to_free)
  486. free_layer(idp, to_free);
  487. } else
  488. idr_remove_warning(id);
  489. }
  490. /**
  491. * idr_remove - remove the given id and free its slot
  492. * @idp: idr handle
  493. * @id: unique key
  494. */
  495. void idr_remove(struct idr *idp, int id)
  496. {
  497. struct idr_layer *p;
  498. struct idr_layer *to_free;
  499. if (id < 0)
  500. return;
  501. sub_remove(idp, (idp->layers - 1) * IDR_BITS, id);
  502. if (idp->top && idp->top->count == 1 && (idp->layers > 1) &&
  503. idp->top->ary[0]) {
  504. /*
  505. * Single child at leftmost slot: we can shrink the tree.
  506. * This level is not needed anymore since when layers are
  507. * inserted, they are inserted at the top of the existing
  508. * tree.
  509. */
  510. to_free = idp->top;
  511. p = idp->top->ary[0];
  512. rcu_assign_pointer(idp->top, p);
  513. --idp->layers;
  514. to_free->count = 0;
  515. bitmap_clear(to_free->bitmap, 0, IDR_SIZE);
  516. free_layer(idp, to_free);
  517. }
  518. while (idp->id_free_cnt >= MAX_IDR_FREE) {
  519. p = get_from_free_list(idp);
  520. /*
  521. * Note: we don't call the rcu callback here, since the only
  522. * layers that fall into the freelist are those that have been
  523. * preallocated.
  524. */
  525. kmem_cache_free(idr_layer_cache, p);
  526. }
  527. return;
  528. }
  529. EXPORT_SYMBOL(idr_remove);
  530. void __idr_remove_all(struct idr *idp)
  531. {
  532. int n, id, max;
  533. int bt_mask;
  534. struct idr_layer *p;
  535. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  536. struct idr_layer **paa = &pa[0];
  537. n = idp->layers * IDR_BITS;
  538. p = idp->top;
  539. rcu_assign_pointer(idp->top, NULL);
  540. max = idr_max(idp->layers);
  541. id = 0;
  542. while (id >= 0 && id <= max) {
  543. while (n > IDR_BITS && p) {
  544. n -= IDR_BITS;
  545. *paa++ = p;
  546. p = p->ary[(id >> n) & IDR_MASK];
  547. }
  548. bt_mask = id;
  549. id += 1 << n;
  550. /* Get the highest bit that the above add changed from 0->1. */
  551. while (n < fls(id ^ bt_mask)) {
  552. if (p)
  553. free_layer(idp, p);
  554. n += IDR_BITS;
  555. p = *--paa;
  556. }
  557. }
  558. idp->layers = 0;
  559. }
  560. EXPORT_SYMBOL(__idr_remove_all);
  561. /**
  562. * idr_destroy - release all cached layers within an idr tree
  563. * @idp: idr handle
  564. *
  565. * Free all id mappings and all idp_layers. After this function, @idp is
  566. * completely unused and can be freed / recycled. The caller is
  567. * responsible for ensuring that no one else accesses @idp during or after
  568. * idr_destroy().
  569. *
  570. * A typical clean-up sequence for objects stored in an idr tree will use
  571. * idr_for_each() to free all objects, if necessay, then idr_destroy() to
  572. * free up the id mappings and cached idr_layers.
  573. */
  574. void idr_destroy(struct idr *idp)
  575. {
  576. __idr_remove_all(idp);
  577. while (idp->id_free_cnt) {
  578. struct idr_layer *p = get_from_free_list(idp);
  579. kmem_cache_free(idr_layer_cache, p);
  580. }
  581. }
  582. EXPORT_SYMBOL(idr_destroy);
  583. void *idr_find_slowpath(struct idr *idp, int id)
  584. {
  585. int n;
  586. struct idr_layer *p;
  587. if (id < 0)
  588. return NULL;
  589. p = rcu_dereference_raw(idp->top);
  590. if (!p)
  591. return NULL;
  592. n = (p->layer+1) * IDR_BITS;
  593. if (id > idr_max(p->layer + 1))
  594. return NULL;
  595. BUG_ON(n == 0);
  596. while (n > 0 && p) {
  597. n -= IDR_BITS;
  598. BUG_ON(n != p->layer*IDR_BITS);
  599. p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
  600. }
  601. return((void *)p);
  602. }
  603. EXPORT_SYMBOL(idr_find_slowpath);
  604. /**
  605. * idr_for_each - iterate through all stored pointers
  606. * @idp: idr handle
  607. * @fn: function to be called for each pointer
  608. * @data: data passed back to callback function
  609. *
  610. * Iterate over the pointers registered with the given idr. The
  611. * callback function will be called for each pointer currently
  612. * registered, passing the id, the pointer and the data pointer passed
  613. * to this function. It is not safe to modify the idr tree while in
  614. * the callback, so functions such as idr_get_new and idr_remove are
  615. * not allowed.
  616. *
  617. * We check the return of @fn each time. If it returns anything other
  618. * than %0, we break out and return that value.
  619. *
  620. * The caller must serialize idr_for_each() vs idr_get_new() and idr_remove().
  621. */
  622. int idr_for_each(struct idr *idp,
  623. int (*fn)(int id, void *p, void *data), void *data)
  624. {
  625. int n, id, max, error = 0;
  626. struct idr_layer *p;
  627. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  628. struct idr_layer **paa = &pa[0];
  629. n = idp->layers * IDR_BITS;
  630. p = rcu_dereference_raw(idp->top);
  631. max = idr_max(idp->layers);
  632. id = 0;
  633. while (id >= 0 && id <= max) {
  634. while (n > 0 && p) {
  635. n -= IDR_BITS;
  636. *paa++ = p;
  637. p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
  638. }
  639. if (p) {
  640. error = fn(id, (void *)p, data);
  641. if (error)
  642. break;
  643. }
  644. id += 1 << n;
  645. while (n < fls(id)) {
  646. n += IDR_BITS;
  647. p = *--paa;
  648. }
  649. }
  650. return error;
  651. }
  652. EXPORT_SYMBOL(idr_for_each);
  653. /**
  654. * idr_get_next - lookup next object of id to given id.
  655. * @idp: idr handle
  656. * @nextidp: pointer to lookup key
  657. *
  658. * Returns pointer to registered object with id, which is next number to
  659. * given id. After being looked up, *@nextidp will be updated for the next
  660. * iteration.
  661. *
  662. * This function can be called under rcu_read_lock(), given that the leaf
  663. * pointers lifetimes are correctly managed.
  664. */
  665. void *idr_get_next(struct idr *idp, int *nextidp)
  666. {
  667. struct idr_layer *p, *pa[MAX_IDR_LEVEL + 1];
  668. struct idr_layer **paa = &pa[0];
  669. int id = *nextidp;
  670. int n, max;
  671. /* find first ent */
  672. p = rcu_dereference_raw(idp->top);
  673. if (!p)
  674. return NULL;
  675. n = (p->layer + 1) * IDR_BITS;
  676. max = idr_max(p->layer + 1);
  677. while (id >= 0 && id <= max) {
  678. while (n > 0 && p) {
  679. n -= IDR_BITS;
  680. *paa++ = p;
  681. p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
  682. }
  683. if (p) {
  684. *nextidp = id;
  685. return p;
  686. }
  687. /*
  688. * Proceed to the next layer at the current level. Unlike
  689. * idr_for_each(), @id isn't guaranteed to be aligned to
  690. * layer boundary at this point and adding 1 << n may
  691. * incorrectly skip IDs. Make sure we jump to the
  692. * beginning of the next layer using round_up().
  693. */
  694. id = round_up(id + 1, 1 << n);
  695. while (n < fls(id)) {
  696. n += IDR_BITS;
  697. p = *--paa;
  698. }
  699. }
  700. return NULL;
  701. }
  702. EXPORT_SYMBOL(idr_get_next);
  703. /**
  704. * idr_replace - replace pointer for given id
  705. * @idp: idr handle
  706. * @ptr: pointer you want associated with the id
  707. * @id: lookup key
  708. *
  709. * Replace the pointer registered with an id and return the old value.
  710. * A %-ENOENT return indicates that @id was not found.
  711. * A %-EINVAL return indicates that @id was not within valid constraints.
  712. *
  713. * The caller must serialize with writers.
  714. */
  715. void *idr_replace(struct idr *idp, void *ptr, int id)
  716. {
  717. int n;
  718. struct idr_layer *p, *old_p;
  719. if (id < 0)
  720. return ERR_PTR(-EINVAL);
  721. p = idp->top;
  722. if (!p)
  723. return ERR_PTR(-EINVAL);
  724. n = (p->layer+1) * IDR_BITS;
  725. if (id >= (1 << n))
  726. return ERR_PTR(-EINVAL);
  727. n -= IDR_BITS;
  728. while ((n > 0) && p) {
  729. p = p->ary[(id >> n) & IDR_MASK];
  730. n -= IDR_BITS;
  731. }
  732. n = id & IDR_MASK;
  733. if (unlikely(p == NULL || !test_bit(n, p->bitmap)))
  734. return ERR_PTR(-ENOENT);
  735. old_p = p->ary[n];
  736. rcu_assign_pointer(p->ary[n], ptr);
  737. return old_p;
  738. }
  739. EXPORT_SYMBOL(idr_replace);
  740. void __init idr_init_cache(void)
  741. {
  742. idr_layer_cache = kmem_cache_create("idr_layer_cache",
  743. sizeof(struct idr_layer), 0, SLAB_PANIC, NULL);
  744. }
  745. /**
  746. * idr_init - initialize idr handle
  747. * @idp: idr handle
  748. *
  749. * This function is use to set up the handle (@idp) that you will pass
  750. * to the rest of the functions.
  751. */
  752. void idr_init(struct idr *idp)
  753. {
  754. memset(idp, 0, sizeof(struct idr));
  755. spin_lock_init(&idp->lock);
  756. }
  757. EXPORT_SYMBOL(idr_init);
  758. /**
  759. * DOC: IDA description
  760. * IDA - IDR based ID allocator
  761. *
  762. * This is id allocator without id -> pointer translation. Memory
  763. * usage is much lower than full blown idr because each id only
  764. * occupies a bit. ida uses a custom leaf node which contains
  765. * IDA_BITMAP_BITS slots.
  766. *
  767. * 2007-04-25 written by Tejun Heo <htejun@gmail.com>
  768. */
  769. static void free_bitmap(struct ida *ida, struct ida_bitmap *bitmap)
  770. {
  771. unsigned long flags;
  772. if (!ida->free_bitmap) {
  773. spin_lock_irqsave(&ida->idr.lock, flags);
  774. if (!ida->free_bitmap) {
  775. ida->free_bitmap = bitmap;
  776. bitmap = NULL;
  777. }
  778. spin_unlock_irqrestore(&ida->idr.lock, flags);
  779. }
  780. kfree(bitmap);
  781. }
  782. /**
  783. * ida_pre_get - reserve resources for ida allocation
  784. * @ida: ida handle
  785. * @gfp_mask: memory allocation flag
  786. *
  787. * This function should be called prior to locking and calling the
  788. * following function. It preallocates enough memory to satisfy the
  789. * worst possible allocation.
  790. *
  791. * If the system is REALLY out of memory this function returns %0,
  792. * otherwise %1.
  793. */
  794. int ida_pre_get(struct ida *ida, gfp_t gfp_mask)
  795. {
  796. /* allocate idr_layers */
  797. if (!__idr_pre_get(&ida->idr, gfp_mask))
  798. return 0;
  799. /* allocate free_bitmap */
  800. if (!ida->free_bitmap) {
  801. struct ida_bitmap *bitmap;
  802. bitmap = kmalloc(sizeof(struct ida_bitmap), gfp_mask);
  803. if (!bitmap)
  804. return 0;
  805. free_bitmap(ida, bitmap);
  806. }
  807. return 1;
  808. }
  809. EXPORT_SYMBOL(ida_pre_get);
  810. /**
  811. * ida_get_new_above - allocate new ID above or equal to a start id
  812. * @ida: ida handle
  813. * @starting_id: id to start search at
  814. * @p_id: pointer to the allocated handle
  815. *
  816. * Allocate new ID above or equal to @starting_id. It should be called
  817. * with any required locks.
  818. *
  819. * If memory is required, it will return %-EAGAIN, you should unlock
  820. * and go back to the ida_pre_get() call. If the ida is full, it will
  821. * return %-ENOSPC.
  822. *
  823. * @p_id returns a value in the range @starting_id ... %0x7fffffff.
  824. */
  825. int ida_get_new_above(struct ida *ida, int starting_id, int *p_id)
  826. {
  827. struct idr_layer *pa[MAX_IDR_LEVEL + 1];
  828. struct ida_bitmap *bitmap;
  829. unsigned long flags;
  830. int idr_id = starting_id / IDA_BITMAP_BITS;
  831. int offset = starting_id % IDA_BITMAP_BITS;
  832. int t, id;
  833. restart:
  834. /* get vacant slot */
  835. t = idr_get_empty_slot(&ida->idr, idr_id, pa, 0, &ida->idr);
  836. if (t < 0)
  837. return t == -ENOMEM ? -EAGAIN : t;
  838. if (t * IDA_BITMAP_BITS >= MAX_IDR_BIT)
  839. return -ENOSPC;
  840. if (t != idr_id)
  841. offset = 0;
  842. idr_id = t;
  843. /* if bitmap isn't there, create a new one */
  844. bitmap = (void *)pa[0]->ary[idr_id & IDR_MASK];
  845. if (!bitmap) {
  846. spin_lock_irqsave(&ida->idr.lock, flags);
  847. bitmap = ida->free_bitmap;
  848. ida->free_bitmap = NULL;
  849. spin_unlock_irqrestore(&ida->idr.lock, flags);
  850. if (!bitmap)
  851. return -EAGAIN;
  852. memset(bitmap, 0, sizeof(struct ida_bitmap));
  853. rcu_assign_pointer(pa[0]->ary[idr_id & IDR_MASK],
  854. (void *)bitmap);
  855. pa[0]->count++;
  856. }
  857. /* lookup for empty slot */
  858. t = find_next_zero_bit(bitmap->bitmap, IDA_BITMAP_BITS, offset);
  859. if (t == IDA_BITMAP_BITS) {
  860. /* no empty slot after offset, continue to the next chunk */
  861. idr_id++;
  862. offset = 0;
  863. goto restart;
  864. }
  865. id = idr_id * IDA_BITMAP_BITS + t;
  866. if (id >= MAX_IDR_BIT)
  867. return -ENOSPC;
  868. __set_bit(t, bitmap->bitmap);
  869. if (++bitmap->nr_busy == IDA_BITMAP_BITS)
  870. idr_mark_full(pa, idr_id);
  871. *p_id = id;
  872. /* Each leaf node can handle nearly a thousand slots and the
  873. * whole idea of ida is to have small memory foot print.
  874. * Throw away extra resources one by one after each successful
  875. * allocation.
  876. */
  877. if (ida->idr.id_free_cnt || ida->free_bitmap) {
  878. struct idr_layer *p = get_from_free_list(&ida->idr);
  879. if (p)
  880. kmem_cache_free(idr_layer_cache, p);
  881. }
  882. return 0;
  883. }
  884. EXPORT_SYMBOL(ida_get_new_above);
  885. /**
  886. * ida_remove - remove the given ID
  887. * @ida: ida handle
  888. * @id: ID to free
  889. */
  890. void ida_remove(struct ida *ida, int id)
  891. {
  892. struct idr_layer *p = ida->idr.top;
  893. int shift = (ida->idr.layers - 1) * IDR_BITS;
  894. int idr_id = id / IDA_BITMAP_BITS;
  895. int offset = id % IDA_BITMAP_BITS;
  896. int n;
  897. struct ida_bitmap *bitmap;
  898. /* clear full bits while looking up the leaf idr_layer */
  899. while ((shift > 0) && p) {
  900. n = (idr_id >> shift) & IDR_MASK;
  901. __clear_bit(n, p->bitmap);
  902. p = p->ary[n];
  903. shift -= IDR_BITS;
  904. }
  905. if (p == NULL)
  906. goto err;
  907. n = idr_id & IDR_MASK;
  908. __clear_bit(n, p->bitmap);
  909. bitmap = (void *)p->ary[n];
  910. if (!test_bit(offset, bitmap->bitmap))
  911. goto err;
  912. /* update bitmap and remove it if empty */
  913. __clear_bit(offset, bitmap->bitmap);
  914. if (--bitmap->nr_busy == 0) {
  915. __set_bit(n, p->bitmap); /* to please idr_remove() */
  916. idr_remove(&ida->idr, idr_id);
  917. free_bitmap(ida, bitmap);
  918. }
  919. return;
  920. err:
  921. printk(KERN_WARNING
  922. "ida_remove called for id=%d which is not allocated.\n", id);
  923. }
  924. EXPORT_SYMBOL(ida_remove);
  925. /**
  926. * ida_destroy - release all cached layers within an ida tree
  927. * @ida: ida handle
  928. */
  929. void ida_destroy(struct ida *ida)
  930. {
  931. idr_destroy(&ida->idr);
  932. kfree(ida->free_bitmap);
  933. }
  934. EXPORT_SYMBOL(ida_destroy);
  935. /**
  936. * ida_simple_get - get a new id.
  937. * @ida: the (initialized) ida.
  938. * @start: the minimum id (inclusive, < 0x8000000)
  939. * @end: the maximum id (exclusive, < 0x8000000 or 0)
  940. * @gfp_mask: memory allocation flags
  941. *
  942. * Allocates an id in the range start <= id < end, or returns -ENOSPC.
  943. * On memory allocation failure, returns -ENOMEM.
  944. *
  945. * Use ida_simple_remove() to get rid of an id.
  946. */
  947. int ida_simple_get(struct ida *ida, unsigned int start, unsigned int end,
  948. gfp_t gfp_mask)
  949. {
  950. int ret, id;
  951. unsigned int max;
  952. unsigned long flags;
  953. BUG_ON((int)start < 0);
  954. BUG_ON((int)end < 0);
  955. if (end == 0)
  956. max = 0x80000000;
  957. else {
  958. BUG_ON(end < start);
  959. max = end - 1;
  960. }
  961. again:
  962. if (!ida_pre_get(ida, gfp_mask))
  963. return -ENOMEM;
  964. spin_lock_irqsave(&simple_ida_lock, flags);
  965. ret = ida_get_new_above(ida, start, &id);
  966. if (!ret) {
  967. if (id > max) {
  968. ida_remove(ida, id);
  969. ret = -ENOSPC;
  970. } else {
  971. ret = id;
  972. }
  973. }
  974. spin_unlock_irqrestore(&simple_ida_lock, flags);
  975. if (unlikely(ret == -EAGAIN))
  976. goto again;
  977. return ret;
  978. }
  979. EXPORT_SYMBOL(ida_simple_get);
  980. /**
  981. * ida_simple_remove - remove an allocated id.
  982. * @ida: the (initialized) ida.
  983. * @id: the id returned by ida_simple_get.
  984. */
  985. void ida_simple_remove(struct ida *ida, unsigned int id)
  986. {
  987. unsigned long flags;
  988. BUG_ON((int)id < 0);
  989. spin_lock_irqsave(&simple_ida_lock, flags);
  990. ida_remove(ida, id);
  991. spin_unlock_irqrestore(&simple_ida_lock, flags);
  992. }
  993. EXPORT_SYMBOL(ida_simple_remove);
  994. /**
  995. * ida_init - initialize ida handle
  996. * @ida: ida handle
  997. *
  998. * This function is use to set up the handle (@ida) that you will pass
  999. * to the rest of the functions.
  1000. */
  1001. void ida_init(struct ida *ida)
  1002. {
  1003. memset(ida, 0, sizeof(struct ida));
  1004. idr_init(&ida->idr);
  1005. }
  1006. EXPORT_SYMBOL(ida_init);