xref: /linux-6.15/include/linux/radix-tree.h (revision 228cd2db)
1 /*
2  * Copyright (C) 2001 Momchil Velikov
3  * Portions Copyright (C) 2001 Christoph Hellwig
4  * Copyright (C) 2006 Nick Piggin
5  * Copyright (C) 2012 Konstantin Khlebnikov
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License as
9  * published by the Free Software Foundation; either version 2, or (at
10  * your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21 #ifndef _LINUX_RADIX_TREE_H
22 #define _LINUX_RADIX_TREE_H
23 
24 #include <linux/bitops.h>
25 #include <linux/kernel.h>
26 #include <linux/list.h>
27 #include <linux/preempt.h>
28 #include <linux/rcupdate.h>
29 #include <linux/spinlock.h>
30 #include <linux/types.h>
31 #include <linux/xarray.h>
32 
33 /* Keep unconverted code working */
34 #define radix_tree_root		xarray
35 #define radix_tree_node		xa_node
36 
37 /*
38  * The bottom two bits of the slot determine how the remaining bits in the
39  * slot are interpreted:
40  *
41  * 00 - data pointer
42  * 10 - internal entry
43  * x1 - value entry
44  *
45  * The internal entry may be a pointer to the next level in the tree, a
46  * sibling entry, or an indicator that the entry in this slot has been moved
47  * to another location in the tree and the lookup should be restarted.  While
48  * NULL fits the 'data pointer' pattern, it means that there is no entry in
49  * the tree for this index (no matter what level of the tree it is found at).
50  * This means that storing a NULL entry in the tree is the same as deleting
51  * the entry from the tree.
52  */
53 #define RADIX_TREE_ENTRY_MASK		3UL
54 #define RADIX_TREE_INTERNAL_NODE	2UL
55 
56 static inline bool radix_tree_is_internal_node(void *ptr)
57 {
58 	return ((unsigned long)ptr & RADIX_TREE_ENTRY_MASK) ==
59 				RADIX_TREE_INTERNAL_NODE;
60 }
61 
62 /*** radix-tree API starts here ***/
63 
64 #define RADIX_TREE_MAP_SHIFT	XA_CHUNK_SHIFT
65 #define RADIX_TREE_MAP_SIZE	(1UL << RADIX_TREE_MAP_SHIFT)
66 #define RADIX_TREE_MAP_MASK	(RADIX_TREE_MAP_SIZE-1)
67 
68 #define RADIX_TREE_MAX_TAGS	XA_MAX_MARKS
69 #define RADIX_TREE_TAG_LONGS	XA_MARK_LONGS
70 
71 #define RADIX_TREE_INDEX_BITS  (8 /* CHAR_BIT */ * sizeof(unsigned long))
72 #define RADIX_TREE_MAX_PATH (DIV_ROUND_UP(RADIX_TREE_INDEX_BITS, \
73 					  RADIX_TREE_MAP_SHIFT))
74 
75 /* The IDR tag is stored in the low bits of xa_flags */
76 #define ROOT_IS_IDR	((__force gfp_t)4)
77 /* The top bits of xa_flags are used to store the root tags */
78 #define ROOT_TAG_SHIFT	(__GFP_BITS_SHIFT)
79 
80 #define RADIX_TREE_INIT(name, mask)	XARRAY_INIT(name, mask)
81 
82 #define RADIX_TREE(name, mask) \
83 	struct radix_tree_root name = RADIX_TREE_INIT(name, mask)
84 
85 #define INIT_RADIX_TREE(root, mask) xa_init_flags(root, mask)
86 
87 static inline bool radix_tree_empty(const struct radix_tree_root *root)
88 {
89 	return root->xa_head == NULL;
90 }
91 
92 /**
93  * struct radix_tree_iter - radix tree iterator state
94  *
95  * @index:	index of current slot
96  * @next_index:	one beyond the last index for this chunk
97  * @tags:	bit-mask for tag-iterating
98  * @node:	node that contains current slot
99  *
100  * This radix tree iterator works in terms of "chunks" of slots.  A chunk is a
101  * subinterval of slots contained within one radix tree leaf node.  It is
102  * described by a pointer to its first slot and a struct radix_tree_iter
103  * which holds the chunk's position in the tree and its size.  For tagged
104  * iteration radix_tree_iter also holds the slots' bit-mask for one chosen
105  * radix tree tag.
106  */
107 struct radix_tree_iter {
108 	unsigned long	index;
109 	unsigned long	next_index;
110 	unsigned long	tags;
111 	struct radix_tree_node *node;
112 };
113 
114 /**
115  * Radix-tree synchronization
116  *
117  * The radix-tree API requires that users provide all synchronisation (with
118  * specific exceptions, noted below).
119  *
120  * Synchronization of access to the data items being stored in the tree, and
121  * management of their lifetimes must be completely managed by API users.
122  *
123  * For API usage, in general,
124  * - any function _modifying_ the tree or tags (inserting or deleting
125  *   items, setting or clearing tags) must exclude other modifications, and
126  *   exclude any functions reading the tree.
127  * - any function _reading_ the tree or tags (looking up items or tags,
128  *   gang lookups) must exclude modifications to the tree, but may occur
129  *   concurrently with other readers.
130  *
131  * The notable exceptions to this rule are the following functions:
132  * __radix_tree_lookup
133  * radix_tree_lookup
134  * radix_tree_lookup_slot
135  * radix_tree_tag_get
136  * radix_tree_gang_lookup
137  * radix_tree_gang_lookup_tag
138  * radix_tree_gang_lookup_tag_slot
139  * radix_tree_tagged
140  *
141  * The first 7 functions are able to be called locklessly, using RCU. The
142  * caller must ensure calls to these functions are made within rcu_read_lock()
143  * regions. Other readers (lock-free or otherwise) and modifications may be
144  * running concurrently.
145  *
146  * It is still required that the caller manage the synchronization and lifetimes
147  * of the items. So if RCU lock-free lookups are used, typically this would mean
148  * that the items have their own locks, or are amenable to lock-free access; and
149  * that the items are freed by RCU (or only freed after having been deleted from
150  * the radix tree *and* a synchronize_rcu() grace period).
151  *
152  * (Note, rcu_assign_pointer and rcu_dereference are not needed to control
153  * access to data items when inserting into or looking up from the radix tree)
154  *
155  * Note that the value returned by radix_tree_tag_get() may not be relied upon
156  * if only the RCU read lock is held.  Functions to set/clear tags and to
157  * delete nodes running concurrently with it may affect its result such that
158  * two consecutive reads in the same locked section may return different
159  * values.  If reliability is required, modification functions must also be
160  * excluded from concurrency.
161  *
162  * radix_tree_tagged is able to be called without locking or RCU.
163  */
164 
165 /**
166  * radix_tree_deref_slot - dereference a slot
167  * @slot: slot pointer, returned by radix_tree_lookup_slot
168  *
169  * For use with radix_tree_lookup_slot().  Caller must hold tree at least read
170  * locked across slot lookup and dereference. Not required if write lock is
171  * held (ie. items cannot be concurrently inserted).
172  *
173  * radix_tree_deref_retry must be used to confirm validity of the pointer if
174  * only the read lock is held.
175  *
176  * Return: entry stored in that slot.
177  */
178 static inline void *radix_tree_deref_slot(void __rcu **slot)
179 {
180 	return rcu_dereference(*slot);
181 }
182 
183 /**
184  * radix_tree_deref_slot_protected - dereference a slot with tree lock held
185  * @slot: slot pointer, returned by radix_tree_lookup_slot
186  *
187  * Similar to radix_tree_deref_slot.  The caller does not hold the RCU read
188  * lock but it must hold the tree lock to prevent parallel updates.
189  *
190  * Return: entry stored in that slot.
191  */
192 static inline void *radix_tree_deref_slot_protected(void __rcu **slot,
193 							spinlock_t *treelock)
194 {
195 	return rcu_dereference_protected(*slot, lockdep_is_held(treelock));
196 }
197 
198 /**
199  * radix_tree_deref_retry	- check radix_tree_deref_slot
200  * @arg:	pointer returned by radix_tree_deref_slot
201  * Returns:	0 if retry is not required, otherwise retry is required
202  *
203  * radix_tree_deref_retry must be used with radix_tree_deref_slot.
204  */
205 static inline int radix_tree_deref_retry(void *arg)
206 {
207 	return unlikely(radix_tree_is_internal_node(arg));
208 }
209 
210 /**
211  * radix_tree_exception	- radix_tree_deref_slot returned either exception?
212  * @arg:	value returned by radix_tree_deref_slot
213  * Returns:	0 if well-aligned pointer, non-0 if either kind of exception.
214  */
215 static inline int radix_tree_exception(void *arg)
216 {
217 	return unlikely((unsigned long)arg & RADIX_TREE_ENTRY_MASK);
218 }
219 
220 int radix_tree_insert(struct radix_tree_root *, unsigned long index,
221 			void *);
222 void *__radix_tree_lookup(const struct radix_tree_root *, unsigned long index,
223 			  struct radix_tree_node **nodep, void __rcu ***slotp);
224 void *radix_tree_lookup(const struct radix_tree_root *, unsigned long);
225 void __rcu **radix_tree_lookup_slot(const struct radix_tree_root *,
226 					unsigned long index);
227 void __radix_tree_replace(struct radix_tree_root *, struct radix_tree_node *,
228 			  void __rcu **slot, void *entry);
229 void radix_tree_iter_replace(struct radix_tree_root *,
230 		const struct radix_tree_iter *, void __rcu **slot, void *entry);
231 void radix_tree_replace_slot(struct radix_tree_root *,
232 			     void __rcu **slot, void *entry);
233 void radix_tree_iter_delete(struct radix_tree_root *,
234 			struct radix_tree_iter *iter, void __rcu **slot);
235 void *radix_tree_delete_item(struct radix_tree_root *, unsigned long, void *);
236 void *radix_tree_delete(struct radix_tree_root *, unsigned long);
237 unsigned int radix_tree_gang_lookup(const struct radix_tree_root *,
238 			void **results, unsigned long first_index,
239 			unsigned int max_items);
240 int radix_tree_preload(gfp_t gfp_mask);
241 int radix_tree_maybe_preload(gfp_t gfp_mask);
242 void radix_tree_init(void);
243 void *radix_tree_tag_set(struct radix_tree_root *,
244 			unsigned long index, unsigned int tag);
245 void *radix_tree_tag_clear(struct radix_tree_root *,
246 			unsigned long index, unsigned int tag);
247 int radix_tree_tag_get(const struct radix_tree_root *,
248 			unsigned long index, unsigned int tag);
249 void radix_tree_iter_tag_clear(struct radix_tree_root *,
250 		const struct radix_tree_iter *iter, unsigned int tag);
251 unsigned int radix_tree_gang_lookup_tag(const struct radix_tree_root *,
252 		void **results, unsigned long first_index,
253 		unsigned int max_items, unsigned int tag);
254 unsigned int radix_tree_gang_lookup_tag_slot(const struct radix_tree_root *,
255 		void __rcu ***results, unsigned long first_index,
256 		unsigned int max_items, unsigned int tag);
257 int radix_tree_tagged(const struct radix_tree_root *, unsigned int tag);
258 
259 static inline void radix_tree_preload_end(void)
260 {
261 	preempt_enable();
262 }
263 
264 void __rcu **idr_get_free(struct radix_tree_root *root,
265 			      struct radix_tree_iter *iter, gfp_t gfp,
266 			      unsigned long max);
267 
268 enum {
269 	RADIX_TREE_ITER_TAG_MASK = 0x0f,	/* tag index in lower nybble */
270 	RADIX_TREE_ITER_TAGGED   = 0x10,	/* lookup tagged slots */
271 	RADIX_TREE_ITER_CONTIG   = 0x20,	/* stop at first hole */
272 };
273 
274 /**
275  * radix_tree_iter_init - initialize radix tree iterator
276  *
277  * @iter:	pointer to iterator state
278  * @start:	iteration starting index
279  * Returns:	NULL
280  */
281 static __always_inline void __rcu **
282 radix_tree_iter_init(struct radix_tree_iter *iter, unsigned long start)
283 {
284 	/*
285 	 * Leave iter->tags uninitialized. radix_tree_next_chunk() will fill it
286 	 * in the case of a successful tagged chunk lookup.  If the lookup was
287 	 * unsuccessful or non-tagged then nobody cares about ->tags.
288 	 *
289 	 * Set index to zero to bypass next_index overflow protection.
290 	 * See the comment in radix_tree_next_chunk() for details.
291 	 */
292 	iter->index = 0;
293 	iter->next_index = start;
294 	return NULL;
295 }
296 
297 /**
298  * radix_tree_next_chunk - find next chunk of slots for iteration
299  *
300  * @root:	radix tree root
301  * @iter:	iterator state
302  * @flags:	RADIX_TREE_ITER_* flags and tag index
303  * Returns:	pointer to chunk first slot, or NULL if there no more left
304  *
305  * This function looks up the next chunk in the radix tree starting from
306  * @iter->next_index.  It returns a pointer to the chunk's first slot.
307  * Also it fills @iter with data about chunk: position in the tree (index),
308  * its end (next_index), and constructs a bit mask for tagged iterating (tags).
309  */
310 void __rcu **radix_tree_next_chunk(const struct radix_tree_root *,
311 			     struct radix_tree_iter *iter, unsigned flags);
312 
313 /**
314  * radix_tree_iter_lookup - look up an index in the radix tree
315  * @root: radix tree root
316  * @iter: iterator state
317  * @index: key to look up
318  *
319  * If @index is present in the radix tree, this function returns the slot
320  * containing it and updates @iter to describe the entry.  If @index is not
321  * present, it returns NULL.
322  */
323 static inline void __rcu **
324 radix_tree_iter_lookup(const struct radix_tree_root *root,
325 			struct radix_tree_iter *iter, unsigned long index)
326 {
327 	radix_tree_iter_init(iter, index);
328 	return radix_tree_next_chunk(root, iter, RADIX_TREE_ITER_CONTIG);
329 }
330 
331 /**
332  * radix_tree_iter_find - find a present entry
333  * @root: radix tree root
334  * @iter: iterator state
335  * @index: start location
336  *
337  * This function returns the slot containing the entry with the lowest index
338  * which is at least @index.  If @index is larger than any present entry, this
339  * function returns NULL.  The @iter is updated to describe the entry found.
340  */
341 static inline void __rcu **
342 radix_tree_iter_find(const struct radix_tree_root *root,
343 			struct radix_tree_iter *iter, unsigned long index)
344 {
345 	radix_tree_iter_init(iter, index);
346 	return radix_tree_next_chunk(root, iter, 0);
347 }
348 
349 /**
350  * radix_tree_iter_retry - retry this chunk of the iteration
351  * @iter:	iterator state
352  *
353  * If we iterate over a tree protected only by the RCU lock, a race
354  * against deletion or creation may result in seeing a slot for which
355  * radix_tree_deref_retry() returns true.  If so, call this function
356  * and continue the iteration.
357  */
358 static inline __must_check
359 void __rcu **radix_tree_iter_retry(struct radix_tree_iter *iter)
360 {
361 	iter->next_index = iter->index;
362 	iter->tags = 0;
363 	return NULL;
364 }
365 
366 static inline unsigned long
367 __radix_tree_iter_add(struct radix_tree_iter *iter, unsigned long slots)
368 {
369 	return iter->index + slots;
370 }
371 
372 /**
373  * radix_tree_iter_resume - resume iterating when the chunk may be invalid
374  * @slot: pointer to current slot
375  * @iter: iterator state
376  * Returns: New slot pointer
377  *
378  * If the iterator needs to release then reacquire a lock, the chunk may
379  * have been invalidated by an insertion or deletion.  Call this function
380  * before releasing the lock to continue the iteration from the next index.
381  */
382 void __rcu **__must_check radix_tree_iter_resume(void __rcu **slot,
383 					struct radix_tree_iter *iter);
384 
385 /**
386  * radix_tree_chunk_size - get current chunk size
387  *
388  * @iter:	pointer to radix tree iterator
389  * Returns:	current chunk size
390  */
391 static __always_inline long
392 radix_tree_chunk_size(struct radix_tree_iter *iter)
393 {
394 	return iter->next_index - iter->index;
395 }
396 
397 /**
398  * radix_tree_next_slot - find next slot in chunk
399  *
400  * @slot:	pointer to current slot
401  * @iter:	pointer to interator state
402  * @flags:	RADIX_TREE_ITER_*, should be constant
403  * Returns:	pointer to next slot, or NULL if there no more left
404  *
405  * This function updates @iter->index in the case of a successful lookup.
406  * For tagged lookup it also eats @iter->tags.
407  *
408  * There are several cases where 'slot' can be passed in as NULL to this
409  * function.  These cases result from the use of radix_tree_iter_resume() or
410  * radix_tree_iter_retry().  In these cases we don't end up dereferencing
411  * 'slot' because either:
412  * a) we are doing tagged iteration and iter->tags has been set to 0, or
413  * b) we are doing non-tagged iteration, and iter->index and iter->next_index
414  *    have been set up so that radix_tree_chunk_size() returns 1 or 0.
415  */
416 static __always_inline void __rcu **radix_tree_next_slot(void __rcu **slot,
417 				struct radix_tree_iter *iter, unsigned flags)
418 {
419 	if (flags & RADIX_TREE_ITER_TAGGED) {
420 		iter->tags >>= 1;
421 		if (unlikely(!iter->tags))
422 			return NULL;
423 		if (likely(iter->tags & 1ul)) {
424 			iter->index = __radix_tree_iter_add(iter, 1);
425 			slot++;
426 			goto found;
427 		}
428 		if (!(flags & RADIX_TREE_ITER_CONTIG)) {
429 			unsigned offset = __ffs(iter->tags);
430 
431 			iter->tags >>= offset++;
432 			iter->index = __radix_tree_iter_add(iter, offset);
433 			slot += offset;
434 			goto found;
435 		}
436 	} else {
437 		long count = radix_tree_chunk_size(iter);
438 
439 		while (--count > 0) {
440 			slot++;
441 			iter->index = __radix_tree_iter_add(iter, 1);
442 
443 			if (likely(*slot))
444 				goto found;
445 			if (flags & RADIX_TREE_ITER_CONTIG) {
446 				/* forbid switching to the next chunk */
447 				iter->next_index = 0;
448 				break;
449 			}
450 		}
451 	}
452 	return NULL;
453 
454  found:
455 	return slot;
456 }
457 
458 /**
459  * radix_tree_for_each_slot - iterate over non-empty slots
460  *
461  * @slot:	the void** variable for pointer to slot
462  * @root:	the struct radix_tree_root pointer
463  * @iter:	the struct radix_tree_iter pointer
464  * @start:	iteration starting index
465  *
466  * @slot points to radix tree slot, @iter->index contains its index.
467  */
468 #define radix_tree_for_each_slot(slot, root, iter, start)		\
469 	for (slot = radix_tree_iter_init(iter, start) ;			\
470 	     slot || (slot = radix_tree_next_chunk(root, iter, 0)) ;	\
471 	     slot = radix_tree_next_slot(slot, iter, 0))
472 
473 /**
474  * radix_tree_for_each_tagged - iterate over tagged slots
475  *
476  * @slot:	the void** variable for pointer to slot
477  * @root:	the struct radix_tree_root pointer
478  * @iter:	the struct radix_tree_iter pointer
479  * @start:	iteration starting index
480  * @tag:	tag index
481  *
482  * @slot points to radix tree slot, @iter->index contains its index.
483  */
484 #define radix_tree_for_each_tagged(slot, root, iter, start, tag)	\
485 	for (slot = radix_tree_iter_init(iter, start) ;			\
486 	     slot || (slot = radix_tree_next_chunk(root, iter,		\
487 			      RADIX_TREE_ITER_TAGGED | tag)) ;		\
488 	     slot = radix_tree_next_slot(slot, iter,			\
489 				RADIX_TREE_ITER_TAGGED | tag))
490 
491 #endif /* _LINUX_RADIX_TREE_H */
492