idr.c 29 KB

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