idr.c 28 KB

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