xref: /linux-6.15/include/linux/radix-tree.h (revision 13b251bd)
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/preempt.h>
26 #include <linux/types.h>
27 #include <linux/bug.h>
28 #include <linux/kernel.h>
29 #include <linux/rcupdate.h>
30 
31 /*
32  * The bottom two bits of the slot determine how the remaining bits in the
33  * slot are interpreted:
34  *
35  * 00 - data pointer
36  * 01 - internal entry
37  * 10 - exceptional entry
38  * 11 - this bit combination is currently unused/reserved
39  *
40  * The internal entry may be a pointer to the next level in the tree, a
41  * sibling entry, or an indicator that the entry in this slot has been moved
42  * to another location in the tree and the lookup should be restarted.  While
43  * NULL fits the 'data pointer' pattern, it means that there is no entry in
44  * the tree for this index (no matter what level of the tree it is found at).
45  * This means that you cannot store NULL in the tree as a value for the index.
46  */
47 #define RADIX_TREE_ENTRY_MASK		3UL
48 #define RADIX_TREE_INTERNAL_NODE	1UL
49 
50 /*
51  * Most users of the radix tree store pointers but shmem/tmpfs stores swap
52  * entries in the same tree.  They are marked as exceptional entries to
53  * distinguish them from pointers to struct page.
54  * EXCEPTIONAL_ENTRY tests the bit, EXCEPTIONAL_SHIFT shifts content past it.
55  */
56 #define RADIX_TREE_EXCEPTIONAL_ENTRY	2
57 #define RADIX_TREE_EXCEPTIONAL_SHIFT	2
58 
59 static inline bool radix_tree_is_internal_node(void *ptr)
60 {
61 	return ((unsigned long)ptr & RADIX_TREE_ENTRY_MASK) ==
62 				RADIX_TREE_INTERNAL_NODE;
63 }
64 
65 /*** radix-tree API starts here ***/
66 
67 #define RADIX_TREE_MAX_TAGS 3
68 
69 #ifndef RADIX_TREE_MAP_SHIFT
70 #define RADIX_TREE_MAP_SHIFT	(CONFIG_BASE_SMALL ? 4 : 6)
71 #endif
72 
73 #define RADIX_TREE_MAP_SIZE	(1UL << RADIX_TREE_MAP_SHIFT)
74 #define RADIX_TREE_MAP_MASK	(RADIX_TREE_MAP_SIZE-1)
75 
76 #define RADIX_TREE_TAG_LONGS	\
77 	((RADIX_TREE_MAP_SIZE + BITS_PER_LONG - 1) / BITS_PER_LONG)
78 
79 #define RADIX_TREE_INDEX_BITS  (8 /* CHAR_BIT */ * sizeof(unsigned long))
80 #define RADIX_TREE_MAX_PATH (DIV_ROUND_UP(RADIX_TREE_INDEX_BITS, \
81 					  RADIX_TREE_MAP_SHIFT))
82 
83 struct radix_tree_node {
84 	unsigned char	shift;		/* Bits remaining in each slot */
85 	unsigned char	offset;		/* Slot offset in parent */
86 	unsigned char	count;		/* Total entry count */
87 	unsigned char	exceptional;	/* Exceptional entry count */
88 	union {
89 		struct {
90 			/* Used when ascending tree */
91 			struct radix_tree_node *parent;
92 			/* For tree user */
93 			void *private_data;
94 		};
95 		/* Used when freeing node */
96 		struct rcu_head	rcu_head;
97 	};
98 	/* For tree user */
99 	struct list_head private_list;
100 	void __rcu	*slots[RADIX_TREE_MAP_SIZE];
101 	unsigned long	tags[RADIX_TREE_MAX_TAGS][RADIX_TREE_TAG_LONGS];
102 };
103 
104 /* root tags are stored in gfp_mask, shifted by __GFP_BITS_SHIFT */
105 struct radix_tree_root {
106 	gfp_t			gfp_mask;
107 	struct radix_tree_node	__rcu *rnode;
108 };
109 
110 #define RADIX_TREE_INIT(mask)	{					\
111 	.gfp_mask = (mask),						\
112 	.rnode = NULL,							\
113 }
114 
115 #define RADIX_TREE(name, mask) \
116 	struct radix_tree_root name = RADIX_TREE_INIT(mask)
117 
118 #define INIT_RADIX_TREE(root, mask)					\
119 do {									\
120 	(root)->gfp_mask = (mask);					\
121 	(root)->rnode = NULL;						\
122 } while (0)
123 
124 static inline bool radix_tree_empty(struct radix_tree_root *root)
125 {
126 	return root->rnode == NULL;
127 }
128 
129 /**
130  * Radix-tree synchronization
131  *
132  * The radix-tree API requires that users provide all synchronisation (with
133  * specific exceptions, noted below).
134  *
135  * Synchronization of access to the data items being stored in the tree, and
136  * management of their lifetimes must be completely managed by API users.
137  *
138  * For API usage, in general,
139  * - any function _modifying_ the tree or tags (inserting or deleting
140  *   items, setting or clearing tags) must exclude other modifications, and
141  *   exclude any functions reading the tree.
142  * - any function _reading_ the tree or tags (looking up items or tags,
143  *   gang lookups) must exclude modifications to the tree, but may occur
144  *   concurrently with other readers.
145  *
146  * The notable exceptions to this rule are the following functions:
147  * __radix_tree_lookup
148  * radix_tree_lookup
149  * radix_tree_lookup_slot
150  * radix_tree_tag_get
151  * radix_tree_gang_lookup
152  * radix_tree_gang_lookup_slot
153  * radix_tree_gang_lookup_tag
154  * radix_tree_gang_lookup_tag_slot
155  * radix_tree_tagged
156  *
157  * The first 8 functions are able to be called locklessly, using RCU. The
158  * caller must ensure calls to these functions are made within rcu_read_lock()
159  * regions. Other readers (lock-free or otherwise) and modifications may be
160  * running concurrently.
161  *
162  * It is still required that the caller manage the synchronization and lifetimes
163  * of the items. So if RCU lock-free lookups are used, typically this would mean
164  * that the items have their own locks, or are amenable to lock-free access; and
165  * that the items are freed by RCU (or only freed after having been deleted from
166  * the radix tree *and* a synchronize_rcu() grace period).
167  *
168  * (Note, rcu_assign_pointer and rcu_dereference are not needed to control
169  * access to data items when inserting into or looking up from the radix tree)
170  *
171  * Note that the value returned by radix_tree_tag_get() may not be relied upon
172  * if only the RCU read lock is held.  Functions to set/clear tags and to
173  * delete nodes running concurrently with it may affect its result such that
174  * two consecutive reads in the same locked section may return different
175  * values.  If reliability is required, modification functions must also be
176  * excluded from concurrency.
177  *
178  * radix_tree_tagged is able to be called without locking or RCU.
179  */
180 
181 /**
182  * radix_tree_deref_slot	- dereference a slot
183  * @pslot:	pointer to slot, returned by radix_tree_lookup_slot
184  * Returns:	item that was stored in that slot with any direct pointer flag
185  *		removed.
186  *
187  * For use with radix_tree_lookup_slot().  Caller must hold tree at least read
188  * locked across slot lookup and dereference. Not required if write lock is
189  * held (ie. items cannot be concurrently inserted).
190  *
191  * radix_tree_deref_retry must be used to confirm validity of the pointer if
192  * only the read lock is held.
193  */
194 static inline void *radix_tree_deref_slot(void **pslot)
195 {
196 	return rcu_dereference(*pslot);
197 }
198 
199 /**
200  * radix_tree_deref_slot_protected	- dereference a slot without RCU lock but with tree lock held
201  * @pslot:	pointer to slot, returned by radix_tree_lookup_slot
202  * Returns:	item that was stored in that slot with any direct pointer flag
203  *		removed.
204  *
205  * Similar to radix_tree_deref_slot but only used during migration when a pages
206  * mapping is being moved. The caller does not hold the RCU read lock but it
207  * must hold the tree lock to prevent parallel updates.
208  */
209 static inline void *radix_tree_deref_slot_protected(void **pslot,
210 							spinlock_t *treelock)
211 {
212 	return rcu_dereference_protected(*pslot, lockdep_is_held(treelock));
213 }
214 
215 /**
216  * radix_tree_deref_retry	- check radix_tree_deref_slot
217  * @arg:	pointer returned by radix_tree_deref_slot
218  * Returns:	0 if retry is not required, otherwise retry is required
219  *
220  * radix_tree_deref_retry must be used with radix_tree_deref_slot.
221  */
222 static inline int radix_tree_deref_retry(void *arg)
223 {
224 	return unlikely(radix_tree_is_internal_node(arg));
225 }
226 
227 /**
228  * radix_tree_exceptional_entry	- radix_tree_deref_slot gave exceptional entry?
229  * @arg:	value returned by radix_tree_deref_slot
230  * Returns:	0 if well-aligned pointer, non-0 if exceptional entry.
231  */
232 static inline int radix_tree_exceptional_entry(void *arg)
233 {
234 	/* Not unlikely because radix_tree_exception often tested first */
235 	return (unsigned long)arg & RADIX_TREE_EXCEPTIONAL_ENTRY;
236 }
237 
238 /**
239  * radix_tree_exception	- radix_tree_deref_slot returned either exception?
240  * @arg:	value returned by radix_tree_deref_slot
241  * Returns:	0 if well-aligned pointer, non-0 if either kind of exception.
242  */
243 static inline int radix_tree_exception(void *arg)
244 {
245 	return unlikely((unsigned long)arg & RADIX_TREE_ENTRY_MASK);
246 }
247 
248 int __radix_tree_create(struct radix_tree_root *root, unsigned long index,
249 			unsigned order, struct radix_tree_node **nodep,
250 			void ***slotp);
251 int __radix_tree_insert(struct radix_tree_root *, unsigned long index,
252 			unsigned order, void *);
253 static inline int radix_tree_insert(struct radix_tree_root *root,
254 			unsigned long index, void *entry)
255 {
256 	return __radix_tree_insert(root, index, 0, entry);
257 }
258 void *__radix_tree_lookup(struct radix_tree_root *root, unsigned long index,
259 			  struct radix_tree_node **nodep, void ***slotp);
260 void *radix_tree_lookup(struct radix_tree_root *, unsigned long);
261 void **radix_tree_lookup_slot(struct radix_tree_root *, unsigned long);
262 typedef void (*radix_tree_update_node_t)(struct radix_tree_node *, void *);
263 void __radix_tree_replace(struct radix_tree_root *root,
264 			  struct radix_tree_node *node,
265 			  void **slot, void *item,
266 			  radix_tree_update_node_t update_node, void *private);
267 void radix_tree_replace_slot(struct radix_tree_root *root,
268 			     void **slot, void *item);
269 void __radix_tree_delete_node(struct radix_tree_root *root,
270 			      struct radix_tree_node *node);
271 void *radix_tree_delete_item(struct radix_tree_root *, unsigned long, void *);
272 void *radix_tree_delete(struct radix_tree_root *, unsigned long);
273 void radix_tree_clear_tags(struct radix_tree_root *root,
274 			   struct radix_tree_node *node,
275 			   void **slot);
276 unsigned int radix_tree_gang_lookup(struct radix_tree_root *root,
277 			void **results, unsigned long first_index,
278 			unsigned int max_items);
279 unsigned int radix_tree_gang_lookup_slot(struct radix_tree_root *root,
280 			void ***results, unsigned long *indices,
281 			unsigned long first_index, unsigned int max_items);
282 int radix_tree_preload(gfp_t gfp_mask);
283 int radix_tree_maybe_preload(gfp_t gfp_mask);
284 int radix_tree_maybe_preload_order(gfp_t gfp_mask, int order);
285 void radix_tree_init(void);
286 void *radix_tree_tag_set(struct radix_tree_root *root,
287 			unsigned long index, unsigned int tag);
288 void *radix_tree_tag_clear(struct radix_tree_root *root,
289 			unsigned long index, unsigned int tag);
290 int radix_tree_tag_get(struct radix_tree_root *root,
291 			unsigned long index, unsigned int tag);
292 unsigned int
293 radix_tree_gang_lookup_tag(struct radix_tree_root *root, void **results,
294 		unsigned long first_index, unsigned int max_items,
295 		unsigned int tag);
296 unsigned int
297 radix_tree_gang_lookup_tag_slot(struct radix_tree_root *root, void ***results,
298 		unsigned long first_index, unsigned int max_items,
299 		unsigned int tag);
300 unsigned long radix_tree_range_tag_if_tagged(struct radix_tree_root *root,
301 		unsigned long *first_indexp, unsigned long last_index,
302 		unsigned long nr_to_tag,
303 		unsigned int fromtag, unsigned int totag);
304 int radix_tree_tagged(struct radix_tree_root *root, unsigned int tag);
305 unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item);
306 
307 static inline void radix_tree_preload_end(void)
308 {
309 	preempt_enable();
310 }
311 
312 /**
313  * struct radix_tree_iter - radix tree iterator state
314  *
315  * @index:	index of current slot
316  * @next_index:	one beyond the last index for this chunk
317  * @tags:	bit-mask for tag-iterating
318  * @shift:	shift for the node that holds our slots
319  *
320  * This radix tree iterator works in terms of "chunks" of slots.  A chunk is a
321  * subinterval of slots contained within one radix tree leaf node.  It is
322  * described by a pointer to its first slot and a struct radix_tree_iter
323  * which holds the chunk's position in the tree and its size.  For tagged
324  * iteration radix_tree_iter also holds the slots' bit-mask for one chosen
325  * radix tree tag.
326  */
327 struct radix_tree_iter {
328 	unsigned long	index;
329 	unsigned long	next_index;
330 	unsigned long	tags;
331 #ifdef CONFIG_RADIX_TREE_MULTIORDER
332 	unsigned int	shift;
333 #endif
334 };
335 
336 static inline unsigned int iter_shift(struct radix_tree_iter *iter)
337 {
338 #ifdef CONFIG_RADIX_TREE_MULTIORDER
339 	return iter->shift;
340 #else
341 	return 0;
342 #endif
343 }
344 
345 #define RADIX_TREE_ITER_TAG_MASK	0x00FF	/* tag index in lower byte */
346 #define RADIX_TREE_ITER_TAGGED		0x0100	/* lookup tagged slots */
347 #define RADIX_TREE_ITER_CONTIG		0x0200	/* stop at first hole */
348 
349 /**
350  * radix_tree_iter_init - initialize radix tree iterator
351  *
352  * @iter:	pointer to iterator state
353  * @start:	iteration starting index
354  * Returns:	NULL
355  */
356 static __always_inline void **
357 radix_tree_iter_init(struct radix_tree_iter *iter, unsigned long start)
358 {
359 	/*
360 	 * Leave iter->tags uninitialized. radix_tree_next_chunk() will fill it
361 	 * in the case of a successful tagged chunk lookup.  If the lookup was
362 	 * unsuccessful or non-tagged then nobody cares about ->tags.
363 	 *
364 	 * Set index to zero to bypass next_index overflow protection.
365 	 * See the comment in radix_tree_next_chunk() for details.
366 	 */
367 	iter->index = 0;
368 	iter->next_index = start;
369 	return NULL;
370 }
371 
372 /**
373  * radix_tree_next_chunk - find next chunk of slots for iteration
374  *
375  * @root:	radix tree root
376  * @iter:	iterator state
377  * @flags:	RADIX_TREE_ITER_* flags and tag index
378  * Returns:	pointer to chunk first slot, or NULL if there no more left
379  *
380  * This function looks up the next chunk in the radix tree starting from
381  * @iter->next_index.  It returns a pointer to the chunk's first slot.
382  * Also it fills @iter with data about chunk: position in the tree (index),
383  * its end (next_index), and constructs a bit mask for tagged iterating (tags).
384  */
385 void **radix_tree_next_chunk(struct radix_tree_root *root,
386 			     struct radix_tree_iter *iter, unsigned flags);
387 
388 /**
389  * radix_tree_iter_retry - retry this chunk of the iteration
390  * @iter:	iterator state
391  *
392  * If we iterate over a tree protected only by the RCU lock, a race
393  * against deletion or creation may result in seeing a slot for which
394  * radix_tree_deref_retry() returns true.  If so, call this function
395  * and continue the iteration.
396  */
397 static inline __must_check
398 void **radix_tree_iter_retry(struct radix_tree_iter *iter)
399 {
400 	iter->next_index = iter->index;
401 	iter->tags = 0;
402 	return NULL;
403 }
404 
405 static inline unsigned long
406 __radix_tree_iter_add(struct radix_tree_iter *iter, unsigned long slots)
407 {
408 	return iter->index + (slots << iter_shift(iter));
409 }
410 
411 /**
412  * radix_tree_iter_next - resume iterating when the chunk may be invalid
413  * @iter:	iterator state
414  *
415  * If the iterator needs to release then reacquire a lock, the chunk may
416  * have been invalidated by an insertion or deletion.  Call this function
417  * to continue the iteration from the next index.
418  */
419 static inline __must_check
420 void **radix_tree_iter_next(struct radix_tree_iter *iter)
421 {
422 	iter->next_index = __radix_tree_iter_add(iter, 1);
423 	iter->tags = 0;
424 	return NULL;
425 }
426 
427 /**
428  * radix_tree_chunk_size - get current chunk size
429  *
430  * @iter:	pointer to radix tree iterator
431  * Returns:	current chunk size
432  */
433 static __always_inline long
434 radix_tree_chunk_size(struct radix_tree_iter *iter)
435 {
436 	return (iter->next_index - iter->index) >> iter_shift(iter);
437 }
438 
439 static inline struct radix_tree_node *entry_to_node(void *ptr)
440 {
441 	return (void *)((unsigned long)ptr & ~RADIX_TREE_INTERNAL_NODE);
442 }
443 
444 /**
445  * radix_tree_next_slot - find next slot in chunk
446  *
447  * @slot:	pointer to current slot
448  * @iter:	pointer to interator state
449  * @flags:	RADIX_TREE_ITER_*, should be constant
450  * Returns:	pointer to next slot, or NULL if there no more left
451  *
452  * This function updates @iter->index in the case of a successful lookup.
453  * For tagged lookup it also eats @iter->tags.
454  *
455  * There are several cases where 'slot' can be passed in as NULL to this
456  * function.  These cases result from the use of radix_tree_iter_next() or
457  * radix_tree_iter_retry().  In these cases we don't end up dereferencing
458  * 'slot' because either:
459  * a) we are doing tagged iteration and iter->tags has been set to 0, or
460  * b) we are doing non-tagged iteration, and iter->index and iter->next_index
461  *    have been set up so that radix_tree_chunk_size() returns 1 or 0.
462  */
463 static __always_inline void **
464 radix_tree_next_slot(void **slot, struct radix_tree_iter *iter, unsigned flags)
465 {
466 	if (flags & RADIX_TREE_ITER_TAGGED) {
467 		void *canon = slot;
468 
469 		iter->tags >>= 1;
470 		if (unlikely(!iter->tags))
471 			return NULL;
472 		while (IS_ENABLED(CONFIG_RADIX_TREE_MULTIORDER) &&
473 					radix_tree_is_internal_node(slot[1])) {
474 			if (entry_to_node(slot[1]) == canon) {
475 				iter->tags >>= 1;
476 				iter->index = __radix_tree_iter_add(iter, 1);
477 				slot++;
478 				continue;
479 			}
480 			iter->next_index = __radix_tree_iter_add(iter, 1);
481 			return NULL;
482 		}
483 		if (likely(iter->tags & 1ul)) {
484 			iter->index = __radix_tree_iter_add(iter, 1);
485 			return slot + 1;
486 		}
487 		if (!(flags & RADIX_TREE_ITER_CONTIG)) {
488 			unsigned offset = __ffs(iter->tags);
489 
490 			iter->tags >>= offset;
491 			iter->index = __radix_tree_iter_add(iter, offset + 1);
492 			return slot + offset + 1;
493 		}
494 	} else {
495 		long count = radix_tree_chunk_size(iter);
496 		void *canon = slot;
497 
498 		while (--count > 0) {
499 			slot++;
500 			iter->index = __radix_tree_iter_add(iter, 1);
501 
502 			if (IS_ENABLED(CONFIG_RADIX_TREE_MULTIORDER) &&
503 			    radix_tree_is_internal_node(*slot)) {
504 				if (entry_to_node(*slot) == canon)
505 					continue;
506 				iter->next_index = iter->index;
507 				break;
508 			}
509 
510 			if (likely(*slot))
511 				return slot;
512 			if (flags & RADIX_TREE_ITER_CONTIG) {
513 				/* forbid switching to the next chunk */
514 				iter->next_index = 0;
515 				break;
516 			}
517 		}
518 	}
519 	return NULL;
520 }
521 
522 /**
523  * radix_tree_for_each_slot - iterate over non-empty slots
524  *
525  * @slot:	the void** variable for pointer to slot
526  * @root:	the struct radix_tree_root pointer
527  * @iter:	the struct radix_tree_iter pointer
528  * @start:	iteration starting index
529  *
530  * @slot points to radix tree slot, @iter->index contains its index.
531  */
532 #define radix_tree_for_each_slot(slot, root, iter, start)		\
533 	for (slot = radix_tree_iter_init(iter, start) ;			\
534 	     slot || (slot = radix_tree_next_chunk(root, iter, 0)) ;	\
535 	     slot = radix_tree_next_slot(slot, iter, 0))
536 
537 /**
538  * radix_tree_for_each_contig - iterate over contiguous slots
539  *
540  * @slot:	the void** variable for pointer to slot
541  * @root:	the struct radix_tree_root pointer
542  * @iter:	the struct radix_tree_iter pointer
543  * @start:	iteration starting index
544  *
545  * @slot points to radix tree slot, @iter->index contains its index.
546  */
547 #define radix_tree_for_each_contig(slot, root, iter, start)		\
548 	for (slot = radix_tree_iter_init(iter, start) ;			\
549 	     slot || (slot = radix_tree_next_chunk(root, iter,		\
550 				RADIX_TREE_ITER_CONTIG)) ;		\
551 	     slot = radix_tree_next_slot(slot, iter,			\
552 				RADIX_TREE_ITER_CONTIG))
553 
554 /**
555  * radix_tree_for_each_tagged - iterate over tagged slots
556  *
557  * @slot:	the void** variable for pointer to slot
558  * @root:	the struct radix_tree_root pointer
559  * @iter:	the struct radix_tree_iter pointer
560  * @start:	iteration starting index
561  * @tag:	tag index
562  *
563  * @slot points to radix tree slot, @iter->index contains its index.
564  */
565 #define radix_tree_for_each_tagged(slot, root, iter, start, tag)	\
566 	for (slot = radix_tree_iter_init(iter, start) ;			\
567 	     slot || (slot = radix_tree_next_chunk(root, iter,		\
568 			      RADIX_TREE_ITER_TAGGED | tag)) ;		\
569 	     slot = radix_tree_next_slot(slot, iter,			\
570 				RADIX_TREE_ITER_TAGGED))
571 
572 #endif /* _LINUX_RADIX_TREE_H */
573