idr.c 29 KB

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