idr.c 28 KB

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