idr.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. #include <linux/bitmap.h>
  2. #include <linux/bug.h>
  3. #include <linux/export.h>
  4. #include <linux/idr.h>
  5. #include <linux/slab.h>
  6. #include <linux/spinlock.h>
  7. #include <linux/xarray.h>
  8. DEFINE_PER_CPU(struct ida_bitmap *, ida_bitmap);
  9. /**
  10. * idr_alloc_u32() - Allocate an ID.
  11. * @idr: IDR handle.
  12. * @ptr: Pointer to be associated with the new ID.
  13. * @nextid: Pointer to an ID.
  14. * @max: The maximum ID to allocate (inclusive).
  15. * @gfp: Memory allocation flags.
  16. *
  17. * Allocates an unused ID in the range specified by @nextid and @max.
  18. * Note that @max is inclusive whereas the @end parameter to idr_alloc()
  19. * is exclusive. The new ID is assigned to @nextid before the pointer
  20. * is inserted into the IDR, so if @nextid points into the object pointed
  21. * to by @ptr, a concurrent lookup will not find an uninitialised ID.
  22. *
  23. * The caller should provide their own locking to ensure that two
  24. * concurrent modifications to the IDR are not possible. Read-only
  25. * accesses to the IDR may be done under the RCU read lock or may
  26. * exclude simultaneous writers.
  27. *
  28. * Return: 0 if an ID was allocated, -ENOMEM if memory allocation failed,
  29. * or -ENOSPC if no free IDs could be found. If an error occurred,
  30. * @nextid is unchanged.
  31. */
  32. int idr_alloc_u32(struct idr *idr, void *ptr, u32 *nextid,
  33. unsigned long max, gfp_t gfp)
  34. {
  35. struct radix_tree_iter iter;
  36. void __rcu **slot;
  37. unsigned int base = idr->idr_base;
  38. unsigned int id = *nextid;
  39. if (WARN_ON_ONCE(radix_tree_is_internal_node(ptr)))
  40. return -EINVAL;
  41. if (WARN_ON_ONCE(!(idr->idr_rt.gfp_mask & ROOT_IS_IDR)))
  42. idr->idr_rt.gfp_mask |= IDR_RT_MARKER;
  43. id = (id < base) ? 0 : id - base;
  44. radix_tree_iter_init(&iter, id);
  45. slot = idr_get_free(&idr->idr_rt, &iter, gfp, max - base);
  46. if (IS_ERR(slot))
  47. return PTR_ERR(slot);
  48. *nextid = iter.index + base;
  49. /* there is a memory barrier inside radix_tree_iter_replace() */
  50. radix_tree_iter_replace(&idr->idr_rt, &iter, slot, ptr);
  51. radix_tree_iter_tag_clear(&idr->idr_rt, &iter, IDR_FREE);
  52. return 0;
  53. }
  54. EXPORT_SYMBOL_GPL(idr_alloc_u32);
  55. /**
  56. * idr_alloc() - Allocate an ID.
  57. * @idr: IDR handle.
  58. * @ptr: Pointer to be associated with the new ID.
  59. * @start: The minimum ID (inclusive).
  60. * @end: The maximum ID (exclusive).
  61. * @gfp: Memory allocation flags.
  62. *
  63. * Allocates an unused ID in the range specified by @start and @end. If
  64. * @end is <= 0, it is treated as one larger than %INT_MAX. This allows
  65. * callers to use @start + N as @end as long as N is within integer range.
  66. *
  67. * The caller should provide their own locking to ensure that two
  68. * concurrent modifications to the IDR are not possible. Read-only
  69. * accesses to the IDR may be done under the RCU read lock or may
  70. * exclude simultaneous writers.
  71. *
  72. * Return: The newly allocated ID, -ENOMEM if memory allocation failed,
  73. * or -ENOSPC if no free IDs could be found.
  74. */
  75. int idr_alloc(struct idr *idr, void *ptr, int start, int end, gfp_t gfp)
  76. {
  77. u32 id = start;
  78. int ret;
  79. if (WARN_ON_ONCE(start < 0))
  80. return -EINVAL;
  81. ret = idr_alloc_u32(idr, ptr, &id, end > 0 ? end - 1 : INT_MAX, gfp);
  82. if (ret)
  83. return ret;
  84. return id;
  85. }
  86. EXPORT_SYMBOL_GPL(idr_alloc);
  87. /**
  88. * idr_alloc_cyclic() - Allocate an ID cyclically.
  89. * @idr: IDR handle.
  90. * @ptr: Pointer to be associated with the new ID.
  91. * @start: The minimum ID (inclusive).
  92. * @end: The maximum ID (exclusive).
  93. * @gfp: Memory allocation flags.
  94. *
  95. * Allocates an unused ID in the range specified by @nextid and @end. If
  96. * @end is <= 0, it is treated as one larger than %INT_MAX. This allows
  97. * callers to use @start + N as @end as long as N is within integer range.
  98. * The search for an unused ID will start at the last ID allocated and will
  99. * wrap around to @start if no free IDs are found before reaching @end.
  100. *
  101. * The caller should provide their own locking to ensure that two
  102. * concurrent modifications to the IDR are not possible. Read-only
  103. * accesses to the IDR may be done under the RCU read lock or may
  104. * exclude simultaneous writers.
  105. *
  106. * Return: The newly allocated ID, -ENOMEM if memory allocation failed,
  107. * or -ENOSPC if no free IDs could be found.
  108. */
  109. int idr_alloc_cyclic(struct idr *idr, void *ptr, int start, int end, gfp_t gfp)
  110. {
  111. u32 id = idr->idr_next;
  112. int err, max = end > 0 ? end - 1 : INT_MAX;
  113. if ((int)id < start)
  114. id = start;
  115. err = idr_alloc_u32(idr, ptr, &id, max, gfp);
  116. if ((err == -ENOSPC) && (id > start)) {
  117. id = start;
  118. err = idr_alloc_u32(idr, ptr, &id, max, gfp);
  119. }
  120. if (err)
  121. return err;
  122. idr->idr_next = id + 1;
  123. return id;
  124. }
  125. EXPORT_SYMBOL(idr_alloc_cyclic);
  126. /**
  127. * idr_remove() - Remove an ID from the IDR.
  128. * @idr: IDR handle.
  129. * @id: Pointer ID.
  130. *
  131. * Removes this ID from the IDR. If the ID was not previously in the IDR,
  132. * this function returns %NULL.
  133. *
  134. * Since this function modifies the IDR, the caller should provide their
  135. * own locking to ensure that concurrent modification of the same IDR is
  136. * not possible.
  137. *
  138. * Return: The pointer formerly associated with this ID.
  139. */
  140. void *idr_remove(struct idr *idr, unsigned long id)
  141. {
  142. return radix_tree_delete_item(&idr->idr_rt, id - idr->idr_base, NULL);
  143. }
  144. EXPORT_SYMBOL_GPL(idr_remove);
  145. /**
  146. * idr_find() - Return pointer for given ID.
  147. * @idr: IDR handle.
  148. * @id: Pointer ID.
  149. *
  150. * Looks up the pointer associated with this ID. A %NULL pointer may
  151. * indicate that @id is not allocated or that the %NULL pointer was
  152. * associated with this ID.
  153. *
  154. * This function can be called under rcu_read_lock(), given that the leaf
  155. * pointers lifetimes are correctly managed.
  156. *
  157. * Return: The pointer associated with this ID.
  158. */
  159. void *idr_find(const struct idr *idr, unsigned long id)
  160. {
  161. return radix_tree_lookup(&idr->idr_rt, id - idr->idr_base);
  162. }
  163. EXPORT_SYMBOL_GPL(idr_find);
  164. /**
  165. * idr_for_each() - Iterate through all stored pointers.
  166. * @idr: IDR handle.
  167. * @fn: Function to be called for each pointer.
  168. * @data: Data passed to callback function.
  169. *
  170. * The callback function will be called for each entry in @idr, passing
  171. * the ID, the entry and @data.
  172. *
  173. * If @fn returns anything other than %0, the iteration stops and that
  174. * value is returned from this function.
  175. *
  176. * idr_for_each() can be called concurrently with idr_alloc() and
  177. * idr_remove() if protected by RCU. Newly added entries may not be
  178. * seen and deleted entries may be seen, but adding and removing entries
  179. * will not cause other entries to be skipped, nor spurious ones to be seen.
  180. */
  181. int idr_for_each(const struct idr *idr,
  182. int (*fn)(int id, void *p, void *data), void *data)
  183. {
  184. struct radix_tree_iter iter;
  185. void __rcu **slot;
  186. int base = idr->idr_base;
  187. radix_tree_for_each_slot(slot, &idr->idr_rt, &iter, 0) {
  188. int ret;
  189. unsigned long id = iter.index + base;
  190. if (WARN_ON_ONCE(id > INT_MAX))
  191. break;
  192. ret = fn(id, rcu_dereference_raw(*slot), data);
  193. if (ret)
  194. return ret;
  195. }
  196. return 0;
  197. }
  198. EXPORT_SYMBOL(idr_for_each);
  199. /**
  200. * idr_get_next_ul() - Find next populated entry.
  201. * @idr: IDR handle.
  202. * @nextid: Pointer to an ID.
  203. *
  204. * Returns the next populated entry in the tree with an ID greater than
  205. * or equal to the value pointed to by @nextid. On exit, @nextid is updated
  206. * to the ID of the found value. To use in a loop, the value pointed to by
  207. * nextid must be incremented by the user.
  208. */
  209. void *idr_get_next_ul(struct idr *idr, unsigned long *nextid)
  210. {
  211. struct radix_tree_iter iter;
  212. void __rcu **slot;
  213. void *entry = NULL;
  214. unsigned long base = idr->idr_base;
  215. unsigned long id = *nextid;
  216. id = (id < base) ? 0 : id - base;
  217. radix_tree_for_each_slot(slot, &idr->idr_rt, &iter, id) {
  218. entry = rcu_dereference_raw(*slot);
  219. if (!entry)
  220. continue;
  221. if (!radix_tree_deref_retry(entry))
  222. break;
  223. if (slot != (void *)&idr->idr_rt.rnode &&
  224. entry != (void *)RADIX_TREE_INTERNAL_NODE)
  225. break;
  226. slot = radix_tree_iter_retry(&iter);
  227. }
  228. if (!slot)
  229. return NULL;
  230. *nextid = iter.index + base;
  231. return entry;
  232. }
  233. EXPORT_SYMBOL(idr_get_next_ul);
  234. /**
  235. * idr_get_next() - Find next populated entry.
  236. * @idr: IDR handle.
  237. * @nextid: Pointer to an ID.
  238. *
  239. * Returns the next populated entry in the tree with an ID greater than
  240. * or equal to the value pointed to by @nextid. On exit, @nextid is updated
  241. * to the ID of the found value. To use in a loop, the value pointed to by
  242. * nextid must be incremented by the user.
  243. */
  244. void *idr_get_next(struct idr *idr, int *nextid)
  245. {
  246. unsigned long id = *nextid;
  247. void *entry = idr_get_next_ul(idr, &id);
  248. if (WARN_ON_ONCE(id > INT_MAX))
  249. return NULL;
  250. *nextid = id;
  251. return entry;
  252. }
  253. EXPORT_SYMBOL(idr_get_next);
  254. /**
  255. * idr_replace() - replace pointer for given ID.
  256. * @idr: IDR handle.
  257. * @ptr: New pointer to associate with the ID.
  258. * @id: ID to change.
  259. *
  260. * Replace the pointer registered with an ID and return the old value.
  261. * This function can be called under the RCU read lock concurrently with
  262. * idr_alloc() and idr_remove() (as long as the ID being removed is not
  263. * the one being replaced!).
  264. *
  265. * Returns: the old value on success. %-ENOENT indicates that @id was not
  266. * found. %-EINVAL indicates that @ptr was not valid.
  267. */
  268. void *idr_replace(struct idr *idr, void *ptr, unsigned long id)
  269. {
  270. struct radix_tree_node *node;
  271. void __rcu **slot = NULL;
  272. void *entry;
  273. if (WARN_ON_ONCE(radix_tree_is_internal_node(ptr)))
  274. return ERR_PTR(-EINVAL);
  275. id -= idr->idr_base;
  276. entry = __radix_tree_lookup(&idr->idr_rt, id, &node, &slot);
  277. if (!slot || radix_tree_tag_get(&idr->idr_rt, id, IDR_FREE))
  278. return ERR_PTR(-ENOENT);
  279. __radix_tree_replace(&idr->idr_rt, node, slot, ptr, NULL);
  280. return entry;
  281. }
  282. EXPORT_SYMBOL(idr_replace);
  283. /**
  284. * DOC: IDA description
  285. *
  286. * The IDA is an ID allocator which does not provide the ability to
  287. * associate an ID with a pointer. As such, it only needs to store one
  288. * bit per ID, and so is more space efficient than an IDR. To use an IDA,
  289. * define it using DEFINE_IDA() (or embed a &struct ida in a data structure,
  290. * then initialise it using ida_init()). To allocate a new ID, call
  291. * ida_alloc(), ida_alloc_min(), ida_alloc_max() or ida_alloc_range().
  292. * To free an ID, call ida_free().
  293. *
  294. * ida_destroy() can be used to dispose of an IDA without needing to
  295. * free the individual IDs in it. You can use ida_is_empty() to find
  296. * out whether the IDA has any IDs currently allocated.
  297. *
  298. * IDs are currently limited to the range [0-INT_MAX]. If this is an awkward
  299. * limitation, it should be quite straightforward to raise the maximum.
  300. */
  301. /*
  302. * Developer's notes:
  303. *
  304. * The IDA uses the functionality provided by the IDR & radix tree to store
  305. * bitmaps in each entry. The IDR_FREE tag means there is at least one bit
  306. * free, unlike the IDR where it means at least one entry is free.
  307. *
  308. * I considered telling the radix tree that each slot is an order-10 node
  309. * and storing the bit numbers in the radix tree, but the radix tree can't
  310. * allow a single multiorder entry at index 0, which would significantly
  311. * increase memory consumption for the IDA. So instead we divide the index
  312. * by the number of bits in the leaf bitmap before doing a radix tree lookup.
  313. *
  314. * As an optimisation, if there are only a few low bits set in any given
  315. * leaf, instead of allocating a 128-byte bitmap, we use the 'exceptional
  316. * entry' functionality of the radix tree to store BITS_PER_LONG - 2 bits
  317. * directly in the entry. By being really tricksy, we could store
  318. * BITS_PER_LONG - 1 bits, but there're diminishing returns after optimising
  319. * for 0-3 allocated IDs.
  320. *
  321. * We allow the radix tree 'exceptional' count to get out of date. Nothing
  322. * in the IDA nor the radix tree code checks it. If it becomes important
  323. * to maintain an accurate exceptional count, switch the rcu_assign_pointer()
  324. * calls to radix_tree_iter_replace() which will correct the exceptional
  325. * count.
  326. *
  327. * The IDA always requires a lock to alloc/free. If we add a 'test_bit'
  328. * equivalent, it will still need locking. Going to RCU lookup would require
  329. * using RCU to free bitmaps, and that's not trivial without embedding an
  330. * RCU head in the bitmap, which adds a 2-pointer overhead to each 128-byte
  331. * bitmap, which is excessive.
  332. */
  333. #define IDA_MAX (0x80000000U / IDA_BITMAP_BITS - 1)
  334. static int ida_get_new_above(struct ida *ida, int start)
  335. {
  336. struct radix_tree_root *root = &ida->ida_rt;
  337. void __rcu **slot;
  338. struct radix_tree_iter iter;
  339. struct ida_bitmap *bitmap;
  340. unsigned long index;
  341. unsigned bit, ebit;
  342. int new;
  343. index = start / IDA_BITMAP_BITS;
  344. bit = start % IDA_BITMAP_BITS;
  345. ebit = bit + RADIX_TREE_EXCEPTIONAL_SHIFT;
  346. slot = radix_tree_iter_init(&iter, index);
  347. for (;;) {
  348. if (slot)
  349. slot = radix_tree_next_slot(slot, &iter,
  350. RADIX_TREE_ITER_TAGGED);
  351. if (!slot) {
  352. slot = idr_get_free(root, &iter, GFP_NOWAIT, IDA_MAX);
  353. if (IS_ERR(slot)) {
  354. if (slot == ERR_PTR(-ENOMEM))
  355. return -EAGAIN;
  356. return PTR_ERR(slot);
  357. }
  358. }
  359. if (iter.index > index) {
  360. bit = 0;
  361. ebit = RADIX_TREE_EXCEPTIONAL_SHIFT;
  362. }
  363. new = iter.index * IDA_BITMAP_BITS;
  364. bitmap = rcu_dereference_raw(*slot);
  365. if (radix_tree_exception(bitmap)) {
  366. unsigned long tmp = (unsigned long)bitmap;
  367. ebit = find_next_zero_bit(&tmp, BITS_PER_LONG, ebit);
  368. if (ebit < BITS_PER_LONG) {
  369. tmp |= 1UL << ebit;
  370. rcu_assign_pointer(*slot, (void *)tmp);
  371. return new + ebit -
  372. RADIX_TREE_EXCEPTIONAL_SHIFT;
  373. }
  374. bitmap = this_cpu_xchg(ida_bitmap, NULL);
  375. if (!bitmap)
  376. return -EAGAIN;
  377. bitmap->bitmap[0] = tmp >> RADIX_TREE_EXCEPTIONAL_SHIFT;
  378. rcu_assign_pointer(*slot, bitmap);
  379. }
  380. if (bitmap) {
  381. bit = find_next_zero_bit(bitmap->bitmap,
  382. IDA_BITMAP_BITS, bit);
  383. new += bit;
  384. if (new < 0)
  385. return -ENOSPC;
  386. if (bit == IDA_BITMAP_BITS)
  387. continue;
  388. __set_bit(bit, bitmap->bitmap);
  389. if (bitmap_full(bitmap->bitmap, IDA_BITMAP_BITS))
  390. radix_tree_iter_tag_clear(root, &iter,
  391. IDR_FREE);
  392. } else {
  393. new += bit;
  394. if (new < 0)
  395. return -ENOSPC;
  396. if (ebit < BITS_PER_LONG) {
  397. bitmap = (void *)((1UL << ebit) |
  398. RADIX_TREE_EXCEPTIONAL_ENTRY);
  399. radix_tree_iter_replace(root, &iter, slot,
  400. bitmap);
  401. return new;
  402. }
  403. bitmap = this_cpu_xchg(ida_bitmap, NULL);
  404. if (!bitmap)
  405. return -EAGAIN;
  406. __set_bit(bit, bitmap->bitmap);
  407. radix_tree_iter_replace(root, &iter, slot, bitmap);
  408. }
  409. return new;
  410. }
  411. }
  412. static void ida_remove(struct ida *ida, int id)
  413. {
  414. unsigned long index = id / IDA_BITMAP_BITS;
  415. unsigned offset = id % IDA_BITMAP_BITS;
  416. struct ida_bitmap *bitmap;
  417. unsigned long *btmp;
  418. struct radix_tree_iter iter;
  419. void __rcu **slot;
  420. slot = radix_tree_iter_lookup(&ida->ida_rt, &iter, index);
  421. if (!slot)
  422. goto err;
  423. bitmap = rcu_dereference_raw(*slot);
  424. if (radix_tree_exception(bitmap)) {
  425. btmp = (unsigned long *)slot;
  426. offset += RADIX_TREE_EXCEPTIONAL_SHIFT;
  427. if (offset >= BITS_PER_LONG)
  428. goto err;
  429. } else {
  430. btmp = bitmap->bitmap;
  431. }
  432. if (!test_bit(offset, btmp))
  433. goto err;
  434. __clear_bit(offset, btmp);
  435. radix_tree_iter_tag_set(&ida->ida_rt, &iter, IDR_FREE);
  436. if (radix_tree_exception(bitmap)) {
  437. if (rcu_dereference_raw(*slot) ==
  438. (void *)RADIX_TREE_EXCEPTIONAL_ENTRY)
  439. radix_tree_iter_delete(&ida->ida_rt, &iter, slot);
  440. } else if (bitmap_empty(btmp, IDA_BITMAP_BITS)) {
  441. kfree(bitmap);
  442. radix_tree_iter_delete(&ida->ida_rt, &iter, slot);
  443. }
  444. return;
  445. err:
  446. WARN(1, "ida_free called for id=%d which is not allocated.\n", id);
  447. }
  448. /**
  449. * ida_destroy() - Free all IDs.
  450. * @ida: IDA handle.
  451. *
  452. * Calling this function frees all IDs and releases all resources used
  453. * by an IDA. When this call returns, the IDA is empty and can be reused
  454. * or freed. If the IDA is already empty, there is no need to call this
  455. * function.
  456. *
  457. * Context: Any context.
  458. */
  459. void ida_destroy(struct ida *ida)
  460. {
  461. unsigned long flags;
  462. struct radix_tree_iter iter;
  463. void __rcu **slot;
  464. xa_lock_irqsave(&ida->ida_rt, flags);
  465. radix_tree_for_each_slot(slot, &ida->ida_rt, &iter, 0) {
  466. struct ida_bitmap *bitmap = rcu_dereference_raw(*slot);
  467. if (!radix_tree_exception(bitmap))
  468. kfree(bitmap);
  469. radix_tree_iter_delete(&ida->ida_rt, &iter, slot);
  470. }
  471. xa_unlock_irqrestore(&ida->ida_rt, flags);
  472. }
  473. EXPORT_SYMBOL(ida_destroy);
  474. /**
  475. * ida_alloc_range() - Allocate an unused ID.
  476. * @ida: IDA handle.
  477. * @min: Lowest ID to allocate.
  478. * @max: Highest ID to allocate.
  479. * @gfp: Memory allocation flags.
  480. *
  481. * Allocate an ID between @min and @max, inclusive. The allocated ID will
  482. * not exceed %INT_MAX, even if @max is larger.
  483. *
  484. * Context: Any context.
  485. * Return: The allocated ID, or %-ENOMEM if memory could not be allocated,
  486. * or %-ENOSPC if there are no free IDs.
  487. */
  488. int ida_alloc_range(struct ida *ida, unsigned int min, unsigned int max,
  489. gfp_t gfp)
  490. {
  491. int id = 0;
  492. unsigned long flags;
  493. if ((int)min < 0)
  494. return -ENOSPC;
  495. if ((int)max < 0)
  496. max = INT_MAX;
  497. again:
  498. xa_lock_irqsave(&ida->ida_rt, flags);
  499. id = ida_get_new_above(ida, min);
  500. if (id > (int)max) {
  501. ida_remove(ida, id);
  502. id = -ENOSPC;
  503. }
  504. xa_unlock_irqrestore(&ida->ida_rt, flags);
  505. if (unlikely(id == -EAGAIN)) {
  506. if (!ida_pre_get(ida, gfp))
  507. return -ENOMEM;
  508. goto again;
  509. }
  510. return id;
  511. }
  512. EXPORT_SYMBOL(ida_alloc_range);
  513. /**
  514. * ida_free() - Release an allocated ID.
  515. * @ida: IDA handle.
  516. * @id: Previously allocated ID.
  517. *
  518. * Context: Any context.
  519. */
  520. void ida_free(struct ida *ida, unsigned int id)
  521. {
  522. unsigned long flags;
  523. BUG_ON((int)id < 0);
  524. xa_lock_irqsave(&ida->ida_rt, flags);
  525. ida_remove(ida, id);
  526. xa_unlock_irqrestore(&ida->ida_rt, flags);
  527. }
  528. EXPORT_SYMBOL(ida_free);