idr.c 29 KB

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