xref: /openbmc/linux/lib/idr.c (revision f32f004c)
10a835c4fSMatthew Wilcox #include <linux/bitmap.h>
2460488c5SMatthew Wilcox #include <linux/bug.h>
38bc3bcc9SPaul Gortmaker #include <linux/export.h>
41da177e4SLinus Torvalds #include <linux/idr.h>
50a835c4fSMatthew Wilcox #include <linux/slab.h>
688eca020SRusty Russell #include <linux/spinlock.h>
7b94078e6SMatthew Wilcox #include <linux/xarray.h>
81da177e4SLinus Torvalds 
9e096f6a7SMatthew Wilcox /**
10e096f6a7SMatthew Wilcox  * idr_alloc_u32() - Allocate an ID.
11e096f6a7SMatthew Wilcox  * @idr: IDR handle.
12e096f6a7SMatthew Wilcox  * @ptr: Pointer to be associated with the new ID.
13e096f6a7SMatthew Wilcox  * @nextid: Pointer to an ID.
14e096f6a7SMatthew Wilcox  * @max: The maximum ID to allocate (inclusive).
15e096f6a7SMatthew Wilcox  * @gfp: Memory allocation flags.
16e096f6a7SMatthew Wilcox  *
17e096f6a7SMatthew Wilcox  * Allocates an unused ID in the range specified by @nextid and @max.
18e096f6a7SMatthew Wilcox  * Note that @max is inclusive whereas the @end parameter to idr_alloc()
19460488c5SMatthew Wilcox  * is exclusive.  The new ID is assigned to @nextid before the pointer
20460488c5SMatthew Wilcox  * is inserted into the IDR, so if @nextid points into the object pointed
21460488c5SMatthew Wilcox  * to by @ptr, a concurrent lookup will not find an uninitialised ID.
22e096f6a7SMatthew Wilcox  *
23e096f6a7SMatthew Wilcox  * The caller should provide their own locking to ensure that two
24e096f6a7SMatthew Wilcox  * concurrent modifications to the IDR are not possible.  Read-only
25e096f6a7SMatthew Wilcox  * accesses to the IDR may be done under the RCU read lock or may
26e096f6a7SMatthew Wilcox  * exclude simultaneous writers.
27e096f6a7SMatthew Wilcox  *
28e096f6a7SMatthew Wilcox  * Return: 0 if an ID was allocated, -ENOMEM if memory allocation failed,
29e096f6a7SMatthew Wilcox  * or -ENOSPC if no free IDs could be found.  If an error occurred,
30e096f6a7SMatthew Wilcox  * @nextid is unchanged.
31e096f6a7SMatthew Wilcox  */
32e096f6a7SMatthew Wilcox int idr_alloc_u32(struct idr *idr, void *ptr, u32 *nextid,
33e096f6a7SMatthew Wilcox 			unsigned long max, gfp_t gfp)
34e096f6a7SMatthew Wilcox {
350a835c4fSMatthew Wilcox 	struct radix_tree_iter iter;
36388f79fdSChris Mi 	void __rcu **slot;
374b0ad076SMatthew Wilcox 	unsigned int base = idr->idr_base;
384b0ad076SMatthew Wilcox 	unsigned int id = *nextid;
39d5c7409fSTejun Heo 
40f8d5d0ccSMatthew Wilcox 	if (WARN_ON_ONCE(!(idr->idr_rt.xa_flags & ROOT_IS_IDR)))
41f8d5d0ccSMatthew Wilcox 		idr->idr_rt.xa_flags |= IDR_RT_MARKER;
42d5c7409fSTejun Heo 
436ce711f2SMatthew Wilcox 	id = (id < base) ? 0 : id - base;
446ce711f2SMatthew Wilcox 	radix_tree_iter_init(&iter, id);
456ce711f2SMatthew Wilcox 	slot = idr_get_free(&idr->idr_rt, &iter, gfp, max - base);
460a835c4fSMatthew Wilcox 	if (IS_ERR(slot))
470a835c4fSMatthew Wilcox 		return PTR_ERR(slot);
48d5c7409fSTejun Heo 
496ce711f2SMatthew Wilcox 	*nextid = iter.index + base;
50460488c5SMatthew Wilcox 	/* there is a memory barrier inside radix_tree_iter_replace() */
510a835c4fSMatthew Wilcox 	radix_tree_iter_replace(&idr->idr_rt, &iter, slot, ptr);
520a835c4fSMatthew Wilcox 	radix_tree_iter_tag_clear(&idr->idr_rt, &iter, IDR_FREE);
53388f79fdSChris Mi 
54388f79fdSChris Mi 	return 0;
55d5c7409fSTejun Heo }
56460488c5SMatthew Wilcox EXPORT_SYMBOL_GPL(idr_alloc_u32);
57d5c7409fSTejun Heo 
583e6628c4SJeff Layton /**
59460488c5SMatthew Wilcox  * idr_alloc() - Allocate an ID.
60460488c5SMatthew Wilcox  * @idr: IDR handle.
61460488c5SMatthew Wilcox  * @ptr: Pointer to be associated with the new ID.
62460488c5SMatthew Wilcox  * @start: The minimum ID (inclusive).
63460488c5SMatthew Wilcox  * @end: The maximum ID (exclusive).
64460488c5SMatthew Wilcox  * @gfp: Memory allocation flags.
653e6628c4SJeff Layton  *
66460488c5SMatthew Wilcox  * Allocates an unused ID in the range specified by @start and @end.  If
67460488c5SMatthew Wilcox  * @end is <= 0, it is treated as one larger than %INT_MAX.  This allows
68460488c5SMatthew Wilcox  * callers to use @start + N as @end as long as N is within integer range.
69460488c5SMatthew Wilcox  *
70460488c5SMatthew Wilcox  * The caller should provide their own locking to ensure that two
71460488c5SMatthew Wilcox  * concurrent modifications to the IDR are not possible.  Read-only
72460488c5SMatthew Wilcox  * accesses to the IDR may be done under the RCU read lock or may
73460488c5SMatthew Wilcox  * exclude simultaneous writers.
74460488c5SMatthew Wilcox  *
75460488c5SMatthew Wilcox  * Return: The newly allocated ID, -ENOMEM if memory allocation failed,
76460488c5SMatthew Wilcox  * or -ENOSPC if no free IDs could be found.
77460488c5SMatthew Wilcox  */
78460488c5SMatthew Wilcox int idr_alloc(struct idr *idr, void *ptr, int start, int end, gfp_t gfp)
79460488c5SMatthew Wilcox {
80460488c5SMatthew Wilcox 	u32 id = start;
81460488c5SMatthew Wilcox 	int ret;
82460488c5SMatthew Wilcox 
83460488c5SMatthew Wilcox 	if (WARN_ON_ONCE(start < 0))
84460488c5SMatthew Wilcox 		return -EINVAL;
85460488c5SMatthew Wilcox 
86460488c5SMatthew Wilcox 	ret = idr_alloc_u32(idr, ptr, &id, end > 0 ? end - 1 : INT_MAX, gfp);
87460488c5SMatthew Wilcox 	if (ret)
88460488c5SMatthew Wilcox 		return ret;
89460488c5SMatthew Wilcox 
90460488c5SMatthew Wilcox 	return id;
91460488c5SMatthew Wilcox }
92460488c5SMatthew Wilcox EXPORT_SYMBOL_GPL(idr_alloc);
93460488c5SMatthew Wilcox 
94460488c5SMatthew Wilcox /**
95460488c5SMatthew Wilcox  * idr_alloc_cyclic() - Allocate an ID cyclically.
96460488c5SMatthew Wilcox  * @idr: IDR handle.
97460488c5SMatthew Wilcox  * @ptr: Pointer to be associated with the new ID.
98460488c5SMatthew Wilcox  * @start: The minimum ID (inclusive).
99460488c5SMatthew Wilcox  * @end: The maximum ID (exclusive).
100460488c5SMatthew Wilcox  * @gfp: Memory allocation flags.
101460488c5SMatthew Wilcox  *
102460488c5SMatthew Wilcox  * Allocates an unused ID in the range specified by @nextid and @end.  If
103460488c5SMatthew Wilcox  * @end is <= 0, it is treated as one larger than %INT_MAX.  This allows
104460488c5SMatthew Wilcox  * callers to use @start + N as @end as long as N is within integer range.
105460488c5SMatthew Wilcox  * The search for an unused ID will start at the last ID allocated and will
106460488c5SMatthew Wilcox  * wrap around to @start if no free IDs are found before reaching @end.
107460488c5SMatthew Wilcox  *
108460488c5SMatthew Wilcox  * The caller should provide their own locking to ensure that two
109460488c5SMatthew Wilcox  * concurrent modifications to the IDR are not possible.  Read-only
110460488c5SMatthew Wilcox  * accesses to the IDR may be done under the RCU read lock or may
111460488c5SMatthew Wilcox  * exclude simultaneous writers.
112460488c5SMatthew Wilcox  *
113460488c5SMatthew Wilcox  * Return: The newly allocated ID, -ENOMEM if memory allocation failed,
114460488c5SMatthew Wilcox  * or -ENOSPC if no free IDs could be found.
1153e6628c4SJeff Layton  */
1160a835c4fSMatthew Wilcox int idr_alloc_cyclic(struct idr *idr, void *ptr, int start, int end, gfp_t gfp)
1173e6628c4SJeff Layton {
118460488c5SMatthew Wilcox 	u32 id = idr->idr_next;
119460488c5SMatthew Wilcox 	int err, max = end > 0 ? end - 1 : INT_MAX;
1203e6628c4SJeff Layton 
121460488c5SMatthew Wilcox 	if ((int)id < start)
122460488c5SMatthew Wilcox 		id = start;
1233e6628c4SJeff Layton 
124460488c5SMatthew Wilcox 	err = idr_alloc_u32(idr, ptr, &id, max, gfp);
125460488c5SMatthew Wilcox 	if ((err == -ENOSPC) && (id > start)) {
126460488c5SMatthew Wilcox 		id = start;
127460488c5SMatthew Wilcox 		err = idr_alloc_u32(idr, ptr, &id, max, gfp);
128460488c5SMatthew Wilcox 	}
129460488c5SMatthew Wilcox 	if (err)
130460488c5SMatthew Wilcox 		return err;
1310a835c4fSMatthew Wilcox 
132460488c5SMatthew Wilcox 	idr->idr_next = id + 1;
1333e6628c4SJeff Layton 	return id;
1343e6628c4SJeff Layton }
1353e6628c4SJeff Layton EXPORT_SYMBOL(idr_alloc_cyclic);
1363e6628c4SJeff Layton 
1375806f07cSJeff Mahoney /**
1386ce711f2SMatthew Wilcox  * idr_remove() - Remove an ID from the IDR.
1396ce711f2SMatthew Wilcox  * @idr: IDR handle.
1406ce711f2SMatthew Wilcox  * @id: Pointer ID.
1416ce711f2SMatthew Wilcox  *
1426ce711f2SMatthew Wilcox  * Removes this ID from the IDR.  If the ID was not previously in the IDR,
1436ce711f2SMatthew Wilcox  * this function returns %NULL.
1446ce711f2SMatthew Wilcox  *
1456ce711f2SMatthew Wilcox  * Since this function modifies the IDR, the caller should provide their
1466ce711f2SMatthew Wilcox  * own locking to ensure that concurrent modification of the same IDR is
1476ce711f2SMatthew Wilcox  * not possible.
1486ce711f2SMatthew Wilcox  *
1496ce711f2SMatthew Wilcox  * Return: The pointer formerly associated with this ID.
1506ce711f2SMatthew Wilcox  */
1516ce711f2SMatthew Wilcox void *idr_remove(struct idr *idr, unsigned long id)
1526ce711f2SMatthew Wilcox {
1536ce711f2SMatthew Wilcox 	return radix_tree_delete_item(&idr->idr_rt, id - idr->idr_base, NULL);
1546ce711f2SMatthew Wilcox }
1556ce711f2SMatthew Wilcox EXPORT_SYMBOL_GPL(idr_remove);
1566ce711f2SMatthew Wilcox 
1576ce711f2SMatthew Wilcox /**
1586ce711f2SMatthew Wilcox  * idr_find() - Return pointer for given ID.
1596ce711f2SMatthew Wilcox  * @idr: IDR handle.
1606ce711f2SMatthew Wilcox  * @id: Pointer ID.
1616ce711f2SMatthew Wilcox  *
1626ce711f2SMatthew Wilcox  * Looks up the pointer associated with this ID.  A %NULL pointer may
1636ce711f2SMatthew Wilcox  * indicate that @id is not allocated or that the %NULL pointer was
1646ce711f2SMatthew Wilcox  * associated with this ID.
1656ce711f2SMatthew Wilcox  *
1666ce711f2SMatthew Wilcox  * This function can be called under rcu_read_lock(), given that the leaf
1676ce711f2SMatthew Wilcox  * pointers lifetimes are correctly managed.
1686ce711f2SMatthew Wilcox  *
1696ce711f2SMatthew Wilcox  * Return: The pointer associated with this ID.
1706ce711f2SMatthew Wilcox  */
1716ce711f2SMatthew Wilcox void *idr_find(const struct idr *idr, unsigned long id)
1726ce711f2SMatthew Wilcox {
1736ce711f2SMatthew Wilcox 	return radix_tree_lookup(&idr->idr_rt, id - idr->idr_base);
1746ce711f2SMatthew Wilcox }
1756ce711f2SMatthew Wilcox EXPORT_SYMBOL_GPL(idr_find);
1766ce711f2SMatthew Wilcox 
1776ce711f2SMatthew Wilcox /**
1787a457577SMatthew Wilcox  * idr_for_each() - Iterate through all stored pointers.
1797a457577SMatthew Wilcox  * @idr: IDR handle.
1807a457577SMatthew Wilcox  * @fn: Function to be called for each pointer.
1817a457577SMatthew Wilcox  * @data: Data passed to callback function.
18296d7fa42SKristian Hoegsberg  *
1830a835c4fSMatthew Wilcox  * The callback function will be called for each entry in @idr, passing
1847a457577SMatthew Wilcox  * the ID, the entry and @data.
18596d7fa42SKristian Hoegsberg  *
1860a835c4fSMatthew Wilcox  * If @fn returns anything other than %0, the iteration stops and that
1870a835c4fSMatthew Wilcox  * value is returned from this function.
18896d7fa42SKristian Hoegsberg  *
1890a835c4fSMatthew Wilcox  * idr_for_each() can be called concurrently with idr_alloc() and
1900a835c4fSMatthew Wilcox  * idr_remove() if protected by RCU.  Newly added entries may not be
1910a835c4fSMatthew Wilcox  * seen and deleted entries may be seen, but adding and removing entries
1920a835c4fSMatthew Wilcox  * will not cause other entries to be skipped, nor spurious ones to be seen.
19396d7fa42SKristian Hoegsberg  */
1940a835c4fSMatthew Wilcox int idr_for_each(const struct idr *idr,
19596d7fa42SKristian Hoegsberg 		int (*fn)(int id, void *p, void *data), void *data)
19696d7fa42SKristian Hoegsberg {
1970a835c4fSMatthew Wilcox 	struct radix_tree_iter iter;
1987e73eb0bSMatthew Wilcox 	void __rcu **slot;
1996ce711f2SMatthew Wilcox 	int base = idr->idr_base;
20096d7fa42SKristian Hoegsberg 
2010a835c4fSMatthew Wilcox 	radix_tree_for_each_slot(slot, &idr->idr_rt, &iter, 0) {
20272fd6c7bSMatthew Wilcox 		int ret;
2034b0ad076SMatthew Wilcox 		unsigned long id = iter.index + base;
20472fd6c7bSMatthew Wilcox 
2054b0ad076SMatthew Wilcox 		if (WARN_ON_ONCE(id > INT_MAX))
20672fd6c7bSMatthew Wilcox 			break;
2074b0ad076SMatthew Wilcox 		ret = fn(id, rcu_dereference_raw(*slot), data);
2080a835c4fSMatthew Wilcox 		if (ret)
2090a835c4fSMatthew Wilcox 			return ret;
21096d7fa42SKristian Hoegsberg 	}
21196d7fa42SKristian Hoegsberg 
2120a835c4fSMatthew Wilcox 	return 0;
21396d7fa42SKristian Hoegsberg }
21496d7fa42SKristian Hoegsberg EXPORT_SYMBOL(idr_for_each);
21596d7fa42SKristian Hoegsberg 
21696d7fa42SKristian Hoegsberg /**
2177a457577SMatthew Wilcox  * idr_get_next() - Find next populated entry.
2187a457577SMatthew Wilcox  * @idr: IDR handle.
2197a457577SMatthew Wilcox  * @nextid: Pointer to an ID.
22038460b48SKAMEZAWA Hiroyuki  *
2210a835c4fSMatthew Wilcox  * Returns the next populated entry in the tree with an ID greater than
2220a835c4fSMatthew Wilcox  * or equal to the value pointed to by @nextid.  On exit, @nextid is updated
2230a835c4fSMatthew Wilcox  * to the ID of the found value.  To use in a loop, the value pointed to by
2240a835c4fSMatthew Wilcox  * nextid must be incremented by the user.
22538460b48SKAMEZAWA Hiroyuki  */
2260a835c4fSMatthew Wilcox void *idr_get_next(struct idr *idr, int *nextid)
22738460b48SKAMEZAWA Hiroyuki {
2280a835c4fSMatthew Wilcox 	struct radix_tree_iter iter;
2297e73eb0bSMatthew Wilcox 	void __rcu **slot;
2304b0ad076SMatthew Wilcox 	unsigned long base = idr->idr_base;
2314b0ad076SMatthew Wilcox 	unsigned long id = *nextid;
23238460b48SKAMEZAWA Hiroyuki 
2336ce711f2SMatthew Wilcox 	id = (id < base) ? 0 : id - base;
2346ce711f2SMatthew Wilcox 	slot = radix_tree_iter_find(&idr->idr_rt, &iter, id);
2350a835c4fSMatthew Wilcox 	if (!slot)
23638460b48SKAMEZAWA Hiroyuki 		return NULL;
2376ce711f2SMatthew Wilcox 	id = iter.index + base;
23838460b48SKAMEZAWA Hiroyuki 
2396ce711f2SMatthew Wilcox 	if (WARN_ON_ONCE(id > INT_MAX))
24072fd6c7bSMatthew Wilcox 		return NULL;
24172fd6c7bSMatthew Wilcox 
2426ce711f2SMatthew Wilcox 	*nextid = id;
2430a835c4fSMatthew Wilcox 	return rcu_dereference_raw(*slot);
24438460b48SKAMEZAWA Hiroyuki }
2454d1ee80fSBen Hutchings EXPORT_SYMBOL(idr_get_next);
24638460b48SKAMEZAWA Hiroyuki 
2477a457577SMatthew Wilcox /**
2487a457577SMatthew Wilcox  * idr_get_next_ul() - Find next populated entry.
2497a457577SMatthew Wilcox  * @idr: IDR handle.
2507a457577SMatthew Wilcox  * @nextid: Pointer to an ID.
2517a457577SMatthew Wilcox  *
2527a457577SMatthew Wilcox  * Returns the next populated entry in the tree with an ID greater than
2537a457577SMatthew Wilcox  * or equal to the value pointed to by @nextid.  On exit, @nextid is updated
2547a457577SMatthew Wilcox  * to the ID of the found value.  To use in a loop, the value pointed to by
2557a457577SMatthew Wilcox  * nextid must be incremented by the user.
2567a457577SMatthew Wilcox  */
2577a457577SMatthew Wilcox void *idr_get_next_ul(struct idr *idr, unsigned long *nextid)
258388f79fdSChris Mi {
259388f79fdSChris Mi 	struct radix_tree_iter iter;
260388f79fdSChris Mi 	void __rcu **slot;
2616ce711f2SMatthew Wilcox 	unsigned long base = idr->idr_base;
2626ce711f2SMatthew Wilcox 	unsigned long id = *nextid;
263388f79fdSChris Mi 
2646ce711f2SMatthew Wilcox 	id = (id < base) ? 0 : id - base;
2656ce711f2SMatthew Wilcox 	slot = radix_tree_iter_find(&idr->idr_rt, &iter, id);
266388f79fdSChris Mi 	if (!slot)
267388f79fdSChris Mi 		return NULL;
268388f79fdSChris Mi 
2696ce711f2SMatthew Wilcox 	*nextid = iter.index + base;
270388f79fdSChris Mi 	return rcu_dereference_raw(*slot);
271388f79fdSChris Mi }
2727a457577SMatthew Wilcox EXPORT_SYMBOL(idr_get_next_ul);
273388f79fdSChris Mi 
27438460b48SKAMEZAWA Hiroyuki /**
275460488c5SMatthew Wilcox  * idr_replace() - replace pointer for given ID.
276460488c5SMatthew Wilcox  * @idr: IDR handle.
277460488c5SMatthew Wilcox  * @ptr: New pointer to associate with the ID.
278460488c5SMatthew Wilcox  * @id: ID to change.
2795806f07cSJeff Mahoney  *
2800a835c4fSMatthew Wilcox  * Replace the pointer registered with an ID and return the old value.
2810a835c4fSMatthew Wilcox  * This function can be called under the RCU read lock concurrently with
2820a835c4fSMatthew Wilcox  * idr_alloc() and idr_remove() (as long as the ID being removed is not
2830a835c4fSMatthew Wilcox  * the one being replaced!).
2845806f07cSJeff Mahoney  *
285a70e43a5SEric Biggers  * Returns: the old value on success.  %-ENOENT indicates that @id was not
286234a4624SMatthew Wilcox  * found.  %-EINVAL indicates that @ptr was not valid.
2875806f07cSJeff Mahoney  */
288234a4624SMatthew Wilcox void *idr_replace(struct idr *idr, void *ptr, unsigned long id)
289388f79fdSChris Mi {
2900a835c4fSMatthew Wilcox 	struct radix_tree_node *node;
2917e73eb0bSMatthew Wilcox 	void __rcu **slot = NULL;
2920a835c4fSMatthew Wilcox 	void *entry;
2935806f07cSJeff Mahoney 
2946ce711f2SMatthew Wilcox 	id -= idr->idr_base;
295e8c8d1bcSTejun Heo 
2960a835c4fSMatthew Wilcox 	entry = __radix_tree_lookup(&idr->idr_rt, id, &node, &slot);
2970a835c4fSMatthew Wilcox 	if (!slot || radix_tree_tag_get(&idr->idr_rt, id, IDR_FREE))
298b93804b2SLai Jiangshan 		return ERR_PTR(-ENOENT);
2996ff2d39bSManfred Spraul 
300c7df8ad2SMel Gorman 	__radix_tree_replace(&idr->idr_rt, node, slot, ptr, NULL);
3015806f07cSJeff Mahoney 
3020a835c4fSMatthew Wilcox 	return entry;
3035806f07cSJeff Mahoney }
304234a4624SMatthew Wilcox EXPORT_SYMBOL(idr_replace);
3055806f07cSJeff Mahoney 
30656083ab1SRandy Dunlap /**
30756083ab1SRandy Dunlap  * DOC: IDA description
30872dba584STejun Heo  *
3090a835c4fSMatthew Wilcox  * The IDA is an ID allocator which does not provide the ability to
3100a835c4fSMatthew Wilcox  * associate an ID with a pointer.  As such, it only needs to store one
3110a835c4fSMatthew Wilcox  * bit per ID, and so is more space efficient than an IDR.  To use an IDA,
3120a835c4fSMatthew Wilcox  * define it using DEFINE_IDA() (or embed a &struct ida in a data structure,
3130a835c4fSMatthew Wilcox  * then initialise it using ida_init()).  To allocate a new ID, call
3145ade60ddSMatthew Wilcox  * ida_alloc(), ida_alloc_min(), ida_alloc_max() or ida_alloc_range().
3155ade60ddSMatthew Wilcox  * To free an ID, call ida_free().
31672dba584STejun Heo  *
317b03f8e43SMatthew Wilcox  * ida_destroy() can be used to dispose of an IDA without needing to
318b03f8e43SMatthew Wilcox  * free the individual IDs in it.  You can use ida_is_empty() to find
319b03f8e43SMatthew Wilcox  * out whether the IDA has any IDs currently allocated.
3200a835c4fSMatthew Wilcox  *
321f32f004cSMatthew Wilcox  * The IDA handles its own locking.  It is safe to call any of the IDA
322f32f004cSMatthew Wilcox  * functions without synchronisation in your code.
323f32f004cSMatthew Wilcox  *
3240a835c4fSMatthew Wilcox  * IDs are currently limited to the range [0-INT_MAX].  If this is an awkward
3250a835c4fSMatthew Wilcox  * limitation, it should be quite straightforward to raise the maximum.
32672dba584STejun Heo  */
32772dba584STejun Heo 
328d37cacc5SMatthew Wilcox /*
329d37cacc5SMatthew Wilcox  * Developer's notes:
330d37cacc5SMatthew Wilcox  *
331f32f004cSMatthew Wilcox  * The IDA uses the functionality provided by the XArray to store bitmaps in
332f32f004cSMatthew Wilcox  * each entry.  The XA_FREE_MARK is only cleared when all bits in the bitmap
333f32f004cSMatthew Wilcox  * have been set.
334d37cacc5SMatthew Wilcox  *
335f32f004cSMatthew Wilcox  * I considered telling the XArray that each slot is an order-10 node
336f32f004cSMatthew Wilcox  * and indexing by bit number, but the XArray can't allow a single multi-index
337f32f004cSMatthew Wilcox  * entry in the head, which would significantly increase memory consumption
338f32f004cSMatthew Wilcox  * for the IDA.  So instead we divide the index by the number of bits in the
339f32f004cSMatthew Wilcox  * leaf bitmap before doing a radix tree lookup.
340d37cacc5SMatthew Wilcox  *
341d37cacc5SMatthew Wilcox  * As an optimisation, if there are only a few low bits set in any given
3423159f943SMatthew Wilcox  * leaf, instead of allocating a 128-byte bitmap, we store the bits
343f32f004cSMatthew Wilcox  * as a value entry.  Value entries never have the XA_FREE_MARK cleared
344f32f004cSMatthew Wilcox  * because we can always convert them into a bitmap entry.
345d37cacc5SMatthew Wilcox  *
346f32f004cSMatthew Wilcox  * It would be possible to optimise further; once we've run out of a
347f32f004cSMatthew Wilcox  * single 128-byte bitmap, we currently switch to a 576-byte node, put
348f32f004cSMatthew Wilcox  * the 128-byte bitmap in the first entry and then start allocating extra
349f32f004cSMatthew Wilcox  * 128-byte entries.  We could instead use the 512 bytes of the node's
350f32f004cSMatthew Wilcox  * data as a bitmap before moving to that scheme.  I do not believe this
351f32f004cSMatthew Wilcox  * is a worthwhile optimisation; Rasmus Villemoes surveyed the current
352f32f004cSMatthew Wilcox  * users of the IDA and almost none of them use more than 1024 entries.
353f32f004cSMatthew Wilcox  * Those that do use more than the 8192 IDs that the 512 bytes would
354f32f004cSMatthew Wilcox  * provide.
355d37cacc5SMatthew Wilcox  *
356f32f004cSMatthew Wilcox  * The IDA always uses a lock to alloc/free.  If we add a 'test_bit'
357d37cacc5SMatthew Wilcox  * equivalent, it will still need locking.  Going to RCU lookup would require
358d37cacc5SMatthew Wilcox  * using RCU to free bitmaps, and that's not trivial without embedding an
359d37cacc5SMatthew Wilcox  * RCU head in the bitmap, which adds a 2-pointer overhead to each 128-byte
360d37cacc5SMatthew Wilcox  * bitmap, which is excessive.
361d37cacc5SMatthew Wilcox  */
362d37cacc5SMatthew Wilcox 
36372dba584STejun Heo /**
3645ade60ddSMatthew Wilcox  * ida_alloc_range() - Allocate an unused ID.
3655ade60ddSMatthew Wilcox  * @ida: IDA handle.
3665ade60ddSMatthew Wilcox  * @min: Lowest ID to allocate.
3675ade60ddSMatthew Wilcox  * @max: Highest ID to allocate.
3685ade60ddSMatthew Wilcox  * @gfp: Memory allocation flags.
36988eca020SRusty Russell  *
3705ade60ddSMatthew Wilcox  * Allocate an ID between @min and @max, inclusive.  The allocated ID will
3715ade60ddSMatthew Wilcox  * not exceed %INT_MAX, even if @max is larger.
37288eca020SRusty Russell  *
3735ade60ddSMatthew Wilcox  * Context: Any context.
3745ade60ddSMatthew Wilcox  * Return: The allocated ID, or %-ENOMEM if memory could not be allocated,
3755ade60ddSMatthew Wilcox  * or %-ENOSPC if there are no free IDs.
37688eca020SRusty Russell  */
3775ade60ddSMatthew Wilcox int ida_alloc_range(struct ida *ida, unsigned int min, unsigned int max,
3785ade60ddSMatthew Wilcox 			gfp_t gfp)
37988eca020SRusty Russell {
380f32f004cSMatthew Wilcox 	XA_STATE(xas, &ida->xa, min / IDA_BITMAP_BITS);
381f32f004cSMatthew Wilcox 	unsigned bit = min % IDA_BITMAP_BITS;
38246cbc1d3STejun Heo 	unsigned long flags;
383f32f004cSMatthew Wilcox 	struct ida_bitmap *bitmap, *alloc = NULL;
38488eca020SRusty Russell 
3855ade60ddSMatthew Wilcox 	if ((int)min < 0)
3865ade60ddSMatthew Wilcox 		return -ENOSPC;
38788eca020SRusty Russell 
3885ade60ddSMatthew Wilcox 	if ((int)max < 0)
3895ade60ddSMatthew Wilcox 		max = INT_MAX;
39088eca020SRusty Russell 
391f32f004cSMatthew Wilcox retry:
392f32f004cSMatthew Wilcox 	xas_lock_irqsave(&xas, flags);
393f32f004cSMatthew Wilcox next:
394f32f004cSMatthew Wilcox 	bitmap = xas_find_marked(&xas, max / IDA_BITMAP_BITS, XA_FREE_MARK);
395f32f004cSMatthew Wilcox 	if (xas.xa_index > min / IDA_BITMAP_BITS)
396f32f004cSMatthew Wilcox 		bit = 0;
397f32f004cSMatthew Wilcox 	if (xas.xa_index * IDA_BITMAP_BITS + bit > max)
398f32f004cSMatthew Wilcox 		goto nospc;
39988eca020SRusty Russell 
400f32f004cSMatthew Wilcox 	if (xa_is_value(bitmap)) {
401f32f004cSMatthew Wilcox 		unsigned long tmp = xa_to_value(bitmap);
402f32f004cSMatthew Wilcox 
403f32f004cSMatthew Wilcox 		if (bit < BITS_PER_XA_VALUE) {
404f32f004cSMatthew Wilcox 			bit = find_next_zero_bit(&tmp, BITS_PER_XA_VALUE, bit);
405f32f004cSMatthew Wilcox 			if (xas.xa_index * IDA_BITMAP_BITS + bit > max)
406f32f004cSMatthew Wilcox 				goto nospc;
407f32f004cSMatthew Wilcox 			if (bit < BITS_PER_XA_VALUE) {
408f32f004cSMatthew Wilcox 				tmp |= 1UL << bit;
409f32f004cSMatthew Wilcox 				xas_store(&xas, xa_mk_value(tmp));
410f32f004cSMatthew Wilcox 				goto out;
411f32f004cSMatthew Wilcox 			}
412f32f004cSMatthew Wilcox 		}
413f32f004cSMatthew Wilcox 		bitmap = alloc;
414f32f004cSMatthew Wilcox 		if (!bitmap)
415f32f004cSMatthew Wilcox 			bitmap = kzalloc(sizeof(*bitmap), GFP_NOWAIT);
416f32f004cSMatthew Wilcox 		if (!bitmap)
417f32f004cSMatthew Wilcox 			goto alloc;
418f32f004cSMatthew Wilcox 		bitmap->bitmap[0] = tmp;
419f32f004cSMatthew Wilcox 		xas_store(&xas, bitmap);
420f32f004cSMatthew Wilcox 		if (xas_error(&xas)) {
421f32f004cSMatthew Wilcox 			bitmap->bitmap[0] = 0;
422f32f004cSMatthew Wilcox 			goto out;
423f32f004cSMatthew Wilcox 		}
424f32f004cSMatthew Wilcox 	}
425f32f004cSMatthew Wilcox 
426f32f004cSMatthew Wilcox 	if (bitmap) {
427f32f004cSMatthew Wilcox 		bit = find_next_zero_bit(bitmap->bitmap, IDA_BITMAP_BITS, bit);
428f32f004cSMatthew Wilcox 		if (xas.xa_index * IDA_BITMAP_BITS + bit > max)
429f32f004cSMatthew Wilcox 			goto nospc;
430f32f004cSMatthew Wilcox 		if (bit == IDA_BITMAP_BITS)
431f32f004cSMatthew Wilcox 			goto next;
432f32f004cSMatthew Wilcox 
433f32f004cSMatthew Wilcox 		__set_bit(bit, bitmap->bitmap);
434f32f004cSMatthew Wilcox 		if (bitmap_full(bitmap->bitmap, IDA_BITMAP_BITS))
435f32f004cSMatthew Wilcox 			xas_clear_mark(&xas, XA_FREE_MARK);
436f32f004cSMatthew Wilcox 	} else {
437f32f004cSMatthew Wilcox 		if (bit < BITS_PER_XA_VALUE) {
438f32f004cSMatthew Wilcox 			bitmap = xa_mk_value(1UL << bit);
439f32f004cSMatthew Wilcox 		} else {
440f32f004cSMatthew Wilcox 			bitmap = alloc;
441f32f004cSMatthew Wilcox 			if (!bitmap)
442f32f004cSMatthew Wilcox 				bitmap = kzalloc(sizeof(*bitmap), GFP_NOWAIT);
443f32f004cSMatthew Wilcox 			if (!bitmap)
444f32f004cSMatthew Wilcox 				goto alloc;
445f32f004cSMatthew Wilcox 			__set_bit(bit, bitmap->bitmap);
446f32f004cSMatthew Wilcox 		}
447f32f004cSMatthew Wilcox 		xas_store(&xas, bitmap);
448f32f004cSMatthew Wilcox 	}
449f32f004cSMatthew Wilcox out:
450f32f004cSMatthew Wilcox 	xas_unlock_irqrestore(&xas, flags);
451f32f004cSMatthew Wilcox 	if (xas_nomem(&xas, gfp)) {
452f32f004cSMatthew Wilcox 		xas.xa_index = min / IDA_BITMAP_BITS;
453f32f004cSMatthew Wilcox 		bit = min % IDA_BITMAP_BITS;
454f32f004cSMatthew Wilcox 		goto retry;
455f32f004cSMatthew Wilcox 	}
456f32f004cSMatthew Wilcox 	if (bitmap != alloc)
457f32f004cSMatthew Wilcox 		kfree(alloc);
458f32f004cSMatthew Wilcox 	if (xas_error(&xas))
459f32f004cSMatthew Wilcox 		return xas_error(&xas);
460f32f004cSMatthew Wilcox 	return xas.xa_index * IDA_BITMAP_BITS + bit;
461f32f004cSMatthew Wilcox alloc:
462f32f004cSMatthew Wilcox 	xas_unlock_irqrestore(&xas, flags);
463f32f004cSMatthew Wilcox 	alloc = kzalloc(sizeof(*bitmap), gfp);
464f32f004cSMatthew Wilcox 	if (!alloc)
4655ade60ddSMatthew Wilcox 		return -ENOMEM;
466f32f004cSMatthew Wilcox 	xas_set(&xas, min / IDA_BITMAP_BITS);
467f32f004cSMatthew Wilcox 	bit = min % IDA_BITMAP_BITS;
468f32f004cSMatthew Wilcox 	goto retry;
469f32f004cSMatthew Wilcox nospc:
470f32f004cSMatthew Wilcox 	xas_unlock_irqrestore(&xas, flags);
471f32f004cSMatthew Wilcox 	return -ENOSPC;
47288eca020SRusty Russell }
4735ade60ddSMatthew Wilcox EXPORT_SYMBOL(ida_alloc_range);
47488eca020SRusty Russell 
47588eca020SRusty Russell /**
4765ade60ddSMatthew Wilcox  * ida_free() - Release an allocated ID.
4775ade60ddSMatthew Wilcox  * @ida: IDA handle.
4785ade60ddSMatthew Wilcox  * @id: Previously allocated ID.
479a2ef9471SDaniel Vetter  *
4805ade60ddSMatthew Wilcox  * Context: Any context.
48188eca020SRusty Russell  */
4825ade60ddSMatthew Wilcox void ida_free(struct ida *ida, unsigned int id)
48388eca020SRusty Russell {
484f32f004cSMatthew Wilcox 	XA_STATE(xas, &ida->xa, id / IDA_BITMAP_BITS);
485f32f004cSMatthew Wilcox 	unsigned bit = id % IDA_BITMAP_BITS;
486f32f004cSMatthew Wilcox 	struct ida_bitmap *bitmap;
48746cbc1d3STejun Heo 	unsigned long flags;
48846cbc1d3STejun Heo 
48988eca020SRusty Russell 	BUG_ON((int)id < 0);
490f32f004cSMatthew Wilcox 
491f32f004cSMatthew Wilcox 	xas_lock_irqsave(&xas, flags);
492f32f004cSMatthew Wilcox 	bitmap = xas_load(&xas);
493f32f004cSMatthew Wilcox 
494f32f004cSMatthew Wilcox 	if (xa_is_value(bitmap)) {
495f32f004cSMatthew Wilcox 		unsigned long v = xa_to_value(bitmap);
496f32f004cSMatthew Wilcox 		if (bit >= BITS_PER_XA_VALUE)
497f32f004cSMatthew Wilcox 			goto err;
498f32f004cSMatthew Wilcox 		if (!(v & (1UL << bit)))
499f32f004cSMatthew Wilcox 			goto err;
500f32f004cSMatthew Wilcox 		v &= ~(1UL << bit);
501f32f004cSMatthew Wilcox 		if (!v)
502f32f004cSMatthew Wilcox 			goto delete;
503f32f004cSMatthew Wilcox 		xas_store(&xas, xa_mk_value(v));
504f32f004cSMatthew Wilcox 	} else {
505f32f004cSMatthew Wilcox 		if (!test_bit(bit, bitmap->bitmap))
506f32f004cSMatthew Wilcox 			goto err;
507f32f004cSMatthew Wilcox 		__clear_bit(bit, bitmap->bitmap);
508f32f004cSMatthew Wilcox 		xas_set_mark(&xas, XA_FREE_MARK);
509f32f004cSMatthew Wilcox 		if (bitmap_empty(bitmap->bitmap, IDA_BITMAP_BITS)) {
510f32f004cSMatthew Wilcox 			kfree(bitmap);
511f32f004cSMatthew Wilcox delete:
512f32f004cSMatthew Wilcox 			xas_store(&xas, NULL);
513f32f004cSMatthew Wilcox 		}
514f32f004cSMatthew Wilcox 	}
515f32f004cSMatthew Wilcox 	xas_unlock_irqrestore(&xas, flags);
516f32f004cSMatthew Wilcox 	return;
517f32f004cSMatthew Wilcox  err:
518f32f004cSMatthew Wilcox 	xas_unlock_irqrestore(&xas, flags);
519f32f004cSMatthew Wilcox 	WARN(1, "ida_free called for id=%d which is not allocated.\n", id);
52088eca020SRusty Russell }
5215ade60ddSMatthew Wilcox EXPORT_SYMBOL(ida_free);
522f32f004cSMatthew Wilcox 
523f32f004cSMatthew Wilcox /**
524f32f004cSMatthew Wilcox  * ida_destroy() - Free all IDs.
525f32f004cSMatthew Wilcox  * @ida: IDA handle.
526f32f004cSMatthew Wilcox  *
527f32f004cSMatthew Wilcox  * Calling this function frees all IDs and releases all resources used
528f32f004cSMatthew Wilcox  * by an IDA.  When this call returns, the IDA is empty and can be reused
529f32f004cSMatthew Wilcox  * or freed.  If the IDA is already empty, there is no need to call this
530f32f004cSMatthew Wilcox  * function.
531f32f004cSMatthew Wilcox  *
532f32f004cSMatthew Wilcox  * Context: Any context.
533f32f004cSMatthew Wilcox  */
534f32f004cSMatthew Wilcox void ida_destroy(struct ida *ida)
535f32f004cSMatthew Wilcox {
536f32f004cSMatthew Wilcox 	XA_STATE(xas, &ida->xa, 0);
537f32f004cSMatthew Wilcox 	struct ida_bitmap *bitmap;
538f32f004cSMatthew Wilcox 	unsigned long flags;
539f32f004cSMatthew Wilcox 
540f32f004cSMatthew Wilcox 	xas_lock_irqsave(&xas, flags);
541f32f004cSMatthew Wilcox 	xas_for_each(&xas, bitmap, ULONG_MAX) {
542f32f004cSMatthew Wilcox 		if (!xa_is_value(bitmap))
543f32f004cSMatthew Wilcox 			kfree(bitmap);
544f32f004cSMatthew Wilcox 		xas_store(&xas, NULL);
545f32f004cSMatthew Wilcox 	}
546f32f004cSMatthew Wilcox 	xas_unlock_irqrestore(&xas, flags);
547f32f004cSMatthew Wilcox }
548f32f004cSMatthew Wilcox EXPORT_SYMBOL(ida_destroy);
549f32f004cSMatthew Wilcox 
550f32f004cSMatthew Wilcox #ifndef __KERNEL__
551f32f004cSMatthew Wilcox extern void xa_dump_index(unsigned long index, unsigned int shift);
552f32f004cSMatthew Wilcox #define IDA_CHUNK_SHIFT		ilog2(IDA_BITMAP_BITS)
553f32f004cSMatthew Wilcox 
554f32f004cSMatthew Wilcox static void ida_dump_entry(void *entry, unsigned long index)
555f32f004cSMatthew Wilcox {
556f32f004cSMatthew Wilcox 	unsigned long i;
557f32f004cSMatthew Wilcox 
558f32f004cSMatthew Wilcox 	if (!entry)
559f32f004cSMatthew Wilcox 		return;
560f32f004cSMatthew Wilcox 
561f32f004cSMatthew Wilcox 	if (xa_is_node(entry)) {
562f32f004cSMatthew Wilcox 		struct xa_node *node = xa_to_node(entry);
563f32f004cSMatthew Wilcox 		unsigned int shift = node->shift + IDA_CHUNK_SHIFT +
564f32f004cSMatthew Wilcox 			XA_CHUNK_SHIFT;
565f32f004cSMatthew Wilcox 
566f32f004cSMatthew Wilcox 		xa_dump_index(index * IDA_BITMAP_BITS, shift);
567f32f004cSMatthew Wilcox 		xa_dump_node(node);
568f32f004cSMatthew Wilcox 		for (i = 0; i < XA_CHUNK_SIZE; i++)
569f32f004cSMatthew Wilcox 			ida_dump_entry(node->slots[i],
570f32f004cSMatthew Wilcox 					index | (i << node->shift));
571f32f004cSMatthew Wilcox 	} else if (xa_is_value(entry)) {
572f32f004cSMatthew Wilcox 		xa_dump_index(index * IDA_BITMAP_BITS, ilog2(BITS_PER_LONG));
573f32f004cSMatthew Wilcox 		pr_cont("value: data %lx [%px]\n", xa_to_value(entry), entry);
574f32f004cSMatthew Wilcox 	} else {
575f32f004cSMatthew Wilcox 		struct ida_bitmap *bitmap = entry;
576f32f004cSMatthew Wilcox 
577f32f004cSMatthew Wilcox 		xa_dump_index(index * IDA_BITMAP_BITS, IDA_CHUNK_SHIFT);
578f32f004cSMatthew Wilcox 		pr_cont("bitmap: %p data", bitmap);
579f32f004cSMatthew Wilcox 		for (i = 0; i < IDA_BITMAP_LONGS; i++)
580f32f004cSMatthew Wilcox 			pr_cont(" %lx", bitmap->bitmap[i]);
581f32f004cSMatthew Wilcox 		pr_cont("\n");
582f32f004cSMatthew Wilcox 	}
583f32f004cSMatthew Wilcox }
584f32f004cSMatthew Wilcox 
585f32f004cSMatthew Wilcox static void ida_dump(struct ida *ida)
586f32f004cSMatthew Wilcox {
587f32f004cSMatthew Wilcox 	struct xarray *xa = &ida->xa;
588f32f004cSMatthew Wilcox 	pr_debug("ida: %p node %p free %d\n", ida, xa->xa_head,
589f32f004cSMatthew Wilcox 				xa->xa_flags >> ROOT_TAG_SHIFT);
590f32f004cSMatthew Wilcox 	ida_dump_entry(xa->xa_head, 0);
591f32f004cSMatthew Wilcox }
592f32f004cSMatthew Wilcox #endif
593