xref: /linux/include/linux/maple_tree.h (revision 49bda4826843be0ef97a162009a29ea3a63f3935)
1 /* SPDX-License-Identifier: GPL-2.0+ */
2 #ifndef _LINUX_MAPLE_TREE_H
3 #define _LINUX_MAPLE_TREE_H
4 /*
5  * Maple Tree - An RCU-safe adaptive tree for storing ranges
6  * Copyright (c) 2018-2022 Oracle
7  * Authors:     Liam R. Howlett <liam@infradead.org>
8  *              Matthew Wilcox <willy@infradead.org>
9  */
10 
11 #include <linux/kernel.h>
12 #include <linux/rcupdate.h>
13 #include <linux/spinlock.h>
14 
15 /*
16  * Allocated nodes are mutable until they have been inserted into the tree,
17  * at which time they cannot change their type until they have been removed
18  * from the tree and an RCU grace period has passed.
19  *
20  * Removed nodes have their ->parent set to point to themselves.  RCU readers
21  * check ->parent before relying on the value that they loaded from the
22  * slots array.  This lets us reuse the slots array for the RCU head.
23  *
24  * Nodes in the tree point to their parent unless bit 0 is set.
25  */
26 #if defined(CONFIG_64BIT) || defined(BUILD_VDSO32_64)
27 /* 64bit sizes */
28 #define MAPLE_NODE_SLOTS	31	/* 256 bytes including ->parent */
29 #define MAPLE_RANGE64_SLOTS	16	/* 256 bytes */
30 #define MAPLE_ARANGE64_SLOTS	10	/* 240 bytes */
31 #else
32 /* 32bit sizes */
33 #define MAPLE_NODE_SLOTS	63	/* 256 bytes including ->parent */
34 #define MAPLE_RANGE64_SLOTS	32	/* 256 bytes */
35 #define MAPLE_ARANGE64_SLOTS	21	/* 240 bytes */
36 #endif /* defined(CONFIG_64BIT) || defined(BUILD_VDSO32_64) */
37 
38 #define MAPLE_NODE_MASK		255UL
39 
40 /*
41  * The node->parent of the root node has bit 0 set and the rest of the pointer
42  * is a pointer to the tree itself.  No more bits are available in this pointer
43  * (on m68k, the data structure may only be 2-byte aligned).
44  *
45  * Internal non-root nodes can only have maple_range_* nodes as parents.  The
46  * parent pointer is 256B aligned like all other tree nodes.  When storing a 32
47  * or 64 bit values, the offset can fit into 4 bits.  The 16 bit values need an
48  * extra bit to store the offset.  This extra bit comes from a reuse of the last
49  * bit in the node type.  This is possible by using bit 1 to indicate if bit 2
50  * is part of the type or the slot.
51  *
52  * Once the type is decided, the decision of an allocation range type or a
53  * range type is done by examining the immutable tree flag for the
54  * MT_FLAGS_ALLOC_RANGE flag.
55  *
56  *  Node types:
57  *   0b??1 = Root
58  *   0b?00 = 16 bit nodes
59  *   0b010 = 32 bit nodes
60  *   0b110 = 64 bit nodes
61  *
62  *  Slot size and location in the parent pointer:
63  *   type  : slot location
64  *   0b??1 : Root
65  *   0b?00 : 16 bit values, type in 0-1, slot in 2-6
66  *   0b010 : 32 bit values, type in 0-2, slot in 3-6
67  *   0b110 : 64 bit values, type in 0-2, slot in 3-6
68  */
69 
70 /*
71  * This metadata is used to optimize the gap updating code and in reverse
72  * searching for gaps or any other code that needs to find the end of the data.
73  */
74 struct maple_metadata {
75 	unsigned char end;	/* end of data */
76 	unsigned char gap;	/* offset of largest gap */
77 };
78 
79 /*
80  * Leaf nodes do not store pointers to nodes, they store user data.  Users may
81  * store almost any bit pattern.  As noted above, the optimisation of storing an
82  * entry at 0 in the root pointer cannot be done for data which have the bottom
83  * two bits set to '10'.  We also reserve values with the bottom two bits set to
84  * '10' which are below 4096 (ie 2, 6, 10 .. 4094) for internal use.  Some APIs
85  * return errnos as a negative errno shifted right by two bits and the bottom
86  * two bits set to '10', and while choosing to store these values in the array
87  * is not an error, it may lead to confusion if you're testing for an error with
88  * mas_is_err().
89  *
90  * Non-leaf nodes store the type of the node pointed to (enum maple_type in bits
91  * 3-6), bit 2 is reserved.  That leaves bits 0-1 unused for now.
92  *
93  * In regular B-Tree terms, pivots are called keys.  The term pivot is used to
94  * indicate that the tree is specifying ranges,  Pivots may appear in the
95  * subtree with an entry attached to the value whereas keys are unique to a
96  * specific position of a B-tree.  Pivot values are inclusive of the slot with
97  * the same index.
98  */
99 
100 struct maple_range_64 {
101 	struct maple_pnode *parent;
102 	unsigned long pivot[MAPLE_RANGE64_SLOTS - 1];
103 	union {
104 		void __rcu *slot[MAPLE_RANGE64_SLOTS];
105 		struct {
106 			void __rcu *pad[MAPLE_RANGE64_SLOTS - 1];
107 			struct maple_metadata meta;
108 		};
109 	};
110 };
111 
112 /*
113  * At tree creation time, the user can specify that they're willing to trade off
114  * storing fewer entries in a tree in return for storing more information in
115  * each node.
116  *
117  * The maple tree supports recording the largest range of NULL entries available
118  * in this node, also called gaps.  This optimises the tree for allocating a
119  * range.
120  */
121 struct maple_arange_64 {
122 	struct maple_pnode *parent;
123 	unsigned long pivot[MAPLE_ARANGE64_SLOTS - 1];
124 	void __rcu *slot[MAPLE_ARANGE64_SLOTS];
125 	unsigned long gap[MAPLE_ARANGE64_SLOTS];
126 	struct maple_metadata meta;
127 };
128 
129 struct maple_topiary {
130 	struct maple_pnode *parent;
131 	struct maple_enode *next; /* Overlaps the pivot */
132 };
133 
134 enum maple_type {
135 	maple_dense,
136 	maple_leaf_64,
137 	maple_range_64,
138 	maple_arange_64,
139 	maple_copy,
140 };
141 
142 enum store_type {
143 	wr_invalid,
144 	wr_new_root,
145 	wr_store_root,
146 	wr_exact_fit,
147 	wr_spanning_store,
148 	wr_split_store,
149 	wr_rebalance,
150 	wr_append,
151 	wr_node_store,
152 	wr_slot_store,
153 };
154 
155 struct maple_copy {
156 	/*
157 	 * min, max, and pivots are values
158 	 * start, end, split are indexes into arrays
159 	 * data is a size
160 	 */
161 
162 	struct {
163 		struct maple_node *node;
164 		unsigned long max;
165 		enum maple_type mt;
166 	} dst[3];
167 	struct {
168 		struct maple_node *node;
169 		unsigned long max;
170 		unsigned char start;
171 		unsigned char end;
172 		enum maple_type mt;
173 	} src[4];
174 	/* Simulated node */
175 	void __rcu *slot[3];
176 	unsigned long gap[3];
177 	unsigned long min;
178 	union {
179 		unsigned long pivot[3];
180 		struct {
181 			void *_pad[2];
182 			unsigned long max;
183 		};
184 	};
185 	unsigned char end;
186 
187 	/*Avoid passing these around */
188 	unsigned char s_count;
189 	unsigned char d_count;
190 	unsigned char split;
191 	unsigned char data;
192 	unsigned char height;
193 };
194 
195 /**
196  * DOC: Maple tree flags
197  *
198  * * MT_FLAGS_ALLOC_RANGE	- Track gaps in this tree
199  * * MT_FLAGS_USE_RCU		- Operate in RCU mode
200  * * MT_FLAGS_HEIGHT_OFFSET	- The position of the tree height in the flags
201  * * MT_FLAGS_HEIGHT_MASK	- The mask for the maple tree height value
202  * * MT_FLAGS_LOCK_MASK		- How the mt_lock is used
203  * * MT_FLAGS_LOCK_IRQ		- Acquired irq-safe
204  * * MT_FLAGS_LOCK_BH		- Acquired bh-safe
205  * * MT_FLAGS_LOCK_EXTERN	- mt_lock is not used
206  *
207  * MAPLE_HEIGHT_MAX	The largest height that can be stored
208  */
209 #define MT_FLAGS_ALLOC_RANGE	0x01
210 #define MT_FLAGS_USE_RCU	0x02
211 #define MT_FLAGS_HEIGHT_OFFSET	0x02
212 #define MT_FLAGS_HEIGHT_MASK	0x7C
213 #define MT_FLAGS_LOCK_MASK	0x300
214 #define MT_FLAGS_LOCK_IRQ	0x100
215 #define MT_FLAGS_LOCK_BH	0x200
216 #define MT_FLAGS_LOCK_EXTERN	0x300
217 #define MT_FLAGS_ALLOC_WRAPPED	0x0800
218 
219 #define MAPLE_HEIGHT_MAX	31
220 
221 
222 #define MAPLE_NODE_TYPE_MASK	0x0F
223 #define MAPLE_NODE_TYPE_SHIFT	0x03
224 
225 #define MAPLE_RESERVED_RANGE	4096
226 
227 #ifdef CONFIG_LOCKDEP
228 #define mt_lock_is_held(mt)                                             \
229 	(!(mt)->ma_external_lock || lock_is_held((mt)->ma_external_lock))
230 
231 #define mt_write_lock_is_held(mt)					\
232 	(!(mt)->ma_external_lock ||					\
233 	 lock_is_held_type((mt)->ma_external_lock, 0))
234 
235 #define mt_set_external_lock(mt, lock)					\
236 	(mt)->ma_external_lock = &(lock)->dep_map
237 
238 #define mt_on_stack(mt)			(mt).ma_external_lock = NULL
239 #else
240 #define mt_lock_is_held(mt)		1
241 #define mt_write_lock_is_held(mt)	1
242 #define mt_set_external_lock(mt, lock)	do { } while (0)
243 #define mt_on_stack(mt)			do { } while (0)
244 #endif
245 
246 /*
247  * If the tree contains a single entry at index 0, it is usually stored in
248  * tree->ma_root.  To optimise for the page cache, an entry which ends in '00',
249  * '01' or '11' is stored in the root, but an entry which ends in '10' will be
250  * stored in a node.  Bits 3-6 are used to store enum maple_type.
251  *
252  * The flags are used both to store some immutable information about this tree
253  * (set at tree creation time) and dynamic information set under the spinlock.
254  *
255  * Another use of flags are to indicate global states of the tree.  This is the
256  * case with the MT_FLAGS_USE_RCU flag, which indicates the tree is currently in
257  * RCU mode.  This mode was added to allow the tree to reuse nodes instead of
258  * re-allocating and RCU freeing nodes when there is a single user.
259  */
260 struct maple_tree {
261 	union {
262 		spinlock_t		ma_lock;
263 #ifdef CONFIG_LOCKDEP
264 		struct lockdep_map	*ma_external_lock;
265 #endif
266 	};
267 	unsigned int	ma_flags;
268 	void __rcu      *ma_root;
269 };
270 
271 /**
272  * MTREE_INIT() - Initialize a maple tree
273  * @name: The maple tree name
274  * @__flags: The maple tree flags
275  *
276  */
277 #define MTREE_INIT(name, __flags) {					\
278 	.ma_lock = __SPIN_LOCK_UNLOCKED((name).ma_lock),		\
279 	.ma_flags = __flags,						\
280 	.ma_root = NULL,						\
281 }
282 
283 /**
284  * MTREE_INIT_EXT() - Initialize a maple tree with an external lock.
285  * @name: The tree name
286  * @__flags: The maple tree flags
287  * @__lock: The external lock
288  */
289 #ifdef CONFIG_LOCKDEP
290 #define MTREE_INIT_EXT(name, __flags, __lock) {				\
291 	.ma_external_lock = &(__lock).dep_map,				\
292 	.ma_flags = (__flags),						\
293 	.ma_root = NULL,						\
294 }
295 #else
296 #define MTREE_INIT_EXT(name, __flags, __lock)	MTREE_INIT(name, __flags)
297 #endif
298 
299 #define DEFINE_MTREE(name)						\
300 	struct maple_tree name = MTREE_INIT(name, 0)
301 
302 #define mtree_lock(mt)		spin_lock((&(mt)->ma_lock))
303 #define mtree_lock_nested(mas, subclass) \
304 		spin_lock_nested((&(mt)->ma_lock), subclass)
305 #define mtree_unlock(mt)	spin_unlock((&(mt)->ma_lock))
306 
307 /*
308  * The Maple Tree squeezes various bits in at various points which aren't
309  * necessarily obvious.  Usually, this is done by observing that pointers are
310  * N-byte aligned and thus the bottom log_2(N) bits are available for use.  We
311  * don't use the high bits of pointers to store additional information because
312  * we don't know what bits are unused on any given architecture.
313  *
314  * Nodes are 256 bytes in size and are also aligned to 256 bytes, giving us 8
315  * low bits for our own purposes.  Nodes are currently of 4 types:
316  * 1. Single pointer (Range is 0-0)
317  * 2. Non-leaf Allocation Range nodes
318  * 3. Non-leaf Range nodes
319  * 4. Leaf Range nodes All nodes consist of a number of node slots,
320  *    pivots, and a parent pointer.
321  */
322 
323 struct maple_node {
324 	union {
325 		struct {
326 			struct maple_pnode *parent;
327 			void __rcu *slot[MAPLE_NODE_SLOTS];
328 		};
329 		struct {
330 			void *pad;
331 			struct rcu_head rcu;
332 			struct maple_enode *piv_parent;
333 			unsigned char parent_slot;
334 			enum maple_type type;
335 			unsigned char slot_len;
336 			unsigned int ma_flags;
337 		};
338 		struct maple_range_64 mr64;
339 		struct maple_arange_64 ma64;
340 		struct maple_copy cp;
341 	};
342 };
343 
344 /*
345  * More complicated stores can cause two nodes to become one or three and
346  * potentially alter the height of the tree.  Either half of the tree may need
347  * to be rebalanced against the other.  The ma_topiary struct is used to track
348  * which nodes have been 'cut' from the tree so that the change can be done
349  * safely at a later date.  This is done to support RCU.
350  */
351 struct ma_topiary {
352 	struct maple_enode *head;
353 	struct maple_enode *tail;
354 	struct maple_tree *mtree;
355 };
356 
357 void *mtree_load(struct maple_tree *mt, unsigned long index);
358 
359 int mtree_insert(struct maple_tree *mt, unsigned long index,
360 		void *entry, gfp_t gfp);
361 int mtree_insert_range(struct maple_tree *mt, unsigned long first,
362 		unsigned long last, void *entry, gfp_t gfp);
363 int mtree_alloc_range(struct maple_tree *mt, unsigned long *startp,
364 		void *entry, unsigned long size, unsigned long min,
365 		unsigned long max, gfp_t gfp);
366 int mtree_alloc_cyclic(struct maple_tree *mt, unsigned long *startp,
367 		void *entry, unsigned long range_lo, unsigned long range_hi,
368 		unsigned long *next, gfp_t gfp);
369 int mtree_alloc_rrange(struct maple_tree *mt, unsigned long *startp,
370 		void *entry, unsigned long size, unsigned long min,
371 		unsigned long max, gfp_t gfp);
372 
373 int mtree_store_range(struct maple_tree *mt, unsigned long first,
374 		      unsigned long last, void *entry, gfp_t gfp);
375 int mtree_store(struct maple_tree *mt, unsigned long index,
376 		void *entry, gfp_t gfp);
377 void *mtree_erase(struct maple_tree *mt, unsigned long index);
378 
379 int mtree_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp);
380 int __mt_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp);
381 
382 void mtree_destroy(struct maple_tree *mt);
383 void __mt_destroy(struct maple_tree *mt);
384 
385 /**
386  * mtree_empty() - Determine if a tree has any present entries.
387  * @mt: Maple Tree.
388  *
389  * Context: Any context.
390  * Return: %true if the tree contains only NULL pointers.
391  */
mtree_empty(const struct maple_tree * mt)392 static inline bool mtree_empty(const struct maple_tree *mt)
393 {
394 	return mt->ma_root == NULL;
395 }
396 
397 /* Advanced API */
398 
399 /*
400  * Maple State Status
401  * ma_active means the maple state is pointing to a node and offset and can
402  * continue operating on the tree.
403  * ma_start means we have not searched the tree.
404  * ma_root means we have searched the tree and the entry we found lives in
405  * the root of the tree (ie it has index 0, length 1 and is the only entry in
406  * the tree).
407  * ma_none means we have searched the tree and there is no node in the
408  * tree for this entry.  For example, we searched for index 1 in an empty
409  * tree.  Or we have a tree which points to a full leaf node and we
410  * searched for an entry which is larger than can be contained in that
411  * leaf node.
412  * ma_pause means the data within the maple state may be stale, restart the
413  * operation
414  * ma_overflow means the search has reached the upper limit of the search
415  * ma_underflow means the search has reached the lower limit of the search
416  * ma_error means there was an error, check the node for the error number.
417  */
418 enum maple_status {
419 	ma_active,
420 	ma_start,
421 	ma_root,
422 	ma_none,
423 	ma_pause,
424 	ma_overflow,
425 	ma_underflow,
426 	ma_error,
427 };
428 
429 /*
430  * The maple state is defined in the struct ma_state and is used to keep track
431  * of information during operations, and even between operations when using the
432  * advanced API.
433  *
434  * If state->node has bit 0 set then it references a tree location which is not
435  * a node (eg the root).  If bit 1 is set, the rest of the bits are a negative
436  * errno.  Bit 2 (the 'unallocated slots' bit) is clear.  Bits 3-6 indicate the
437  * node type.
438  *
439  * state->alloc either has a request number of nodes or an allocated node.  If
440  * stat->alloc has a requested number of nodes, the first bit will be set (0x1)
441  * and the remaining bits are the value.  If state->alloc is a node, then the
442  * node will be of type maple_alloc.  maple_alloc has MAPLE_NODE_SLOTS - 1 for
443  * storing more allocated nodes, a total number of nodes allocated, and the
444  * node_count in this node.  node_count is the number of allocated nodes in this
445  * node.  The scaling beyond MAPLE_NODE_SLOTS - 1 is handled by storing further
446  * nodes into state->alloc->slot[0]'s node.  Nodes are taken from state->alloc
447  * by removing a node from the state->alloc node until state->alloc->node_count
448  * is 1, when state->alloc is returned and the state->alloc->slot[0] is promoted
449  * to state->alloc.  Nodes are pushed onto state->alloc by putting the current
450  * state->alloc into the pushed node's slot[0].
451  *
452  * The state also contains the implied min/max of the state->node, the depth of
453  * this search, and the offset. The implied min/max are either from the parent
454  * node or are 0-oo for the root node.  The depth is incremented or decremented
455  * every time a node is walked down or up.  The offset is the slot/pivot of
456  * interest in the node - either for reading or writing.
457  *
458  * When returning a value the maple state index and last respectively contain
459  * the start and end of the range for the entry.  Ranges are inclusive in the
460  * Maple Tree.
461  *
462  * The status of the state is used to determine how the next action should treat
463  * the state.  For instance, if the status is ma_start then the next action
464  * should start at the root of the tree and walk down.  If the status is
465  * ma_pause then the node may be stale data and should be discarded.  If the
466  * status is ma_overflow, then the last action hit the upper limit.
467  *
468  */
469 struct ma_state {
470 	struct maple_tree *tree;	/* The tree we're operating in */
471 	unsigned long index;		/* The index we're operating on - range start */
472 	unsigned long last;		/* The last index we're operating on - range end */
473 	struct maple_enode *node;	/* The node containing this entry */
474 	unsigned long min;		/* The minimum index of this node - implied pivot min */
475 	unsigned long max;		/* The maximum index of this node - implied pivot max */
476 	struct slab_sheaf *sheaf;	/* Allocated nodes for this operation */
477 	struct maple_node *alloc;	/* A single allocated node for fast path writes */
478 	unsigned long node_request;	/* The number of nodes to allocate for this operation */
479 	enum maple_status status;	/* The status of the state (active, start, none, etc) */
480 	unsigned char depth;		/* depth of tree descent during write */
481 	unsigned char offset;
482 	unsigned char mas_flags;
483 	unsigned char end;		/* The end of the node */
484 	enum store_type store_type;	/* The type of store needed for this operation */
485 #ifdef CONFIG_LOCKDEP
486 	u32 ld_seq;
487 #ifdef CONFIG_RCU_STRICT_GRACE_PERIOD
488 	unsigned long rcu_gp;
489 #endif /* CONFIG_RCU_STRICT_GRACE_PERIOD */
490 #endif /* CONFIG_LOCKDEP */
491 };
492 
493 struct ma_wr_state {
494 	struct ma_state *mas;
495 	struct maple_node *node;	/* Decoded mas->node */
496 	unsigned long r_min;		/* range min */
497 	unsigned long r_max;		/* range max */
498 	enum maple_type type;		/* mas->node type */
499 	unsigned char offset_end;	/* The offset where the write ends */
500 	unsigned long *pivots;		/* mas->node->pivots pointer */
501 	unsigned long end_piv;		/* The pivot at the offset end */
502 	void __rcu **slots;		/* mas->node->slots pointer */
503 	void *entry;			/* The entry to write */
504 	void *content;			/* The existing entry that is being overwritten */
505 	unsigned char vacant_height;	/* Height of lowest node with free space */
506 	unsigned char sufficient_height;/* Height of lowest node with min sufficiency + 1 nodes */
507 };
508 
509 #define mas_lock(mas)           spin_lock(&((mas)->tree->ma_lock))
510 #define mas_lock_nested(mas, subclass) \
511 		spin_lock_nested(&((mas)->tree->ma_lock), subclass)
512 #define mas_unlock(mas)         spin_unlock(&((mas)->tree->ma_lock))
513 
514 /*
515  * Special values for ma_state.node.
516  * MA_ERROR represents an errno.  After dropping the lock and attempting
517  * to resolve the error, the walk would have to be restarted from the
518  * top of the tree as the tree may have been modified.
519  */
520 #define MA_ERROR(err) \
521 		((struct maple_enode *)(((unsigned long)err << 2) | 2UL))
522 
523 /*
524  * When changing MA_STATE, remember to also change rust/kernel/maple_tree.rs
525  */
526 #define MA_STATE(name, mt, first, end)					\
527 	struct ma_state name = {					\
528 		.tree = mt,						\
529 		.index = first,						\
530 		.last = end,						\
531 		.node = NULL,						\
532 		.status = ma_start,					\
533 		.min = 0,						\
534 		.max = ULONG_MAX,					\
535 		.sheaf = NULL,						\
536 		.alloc = NULL,						\
537 		.node_request = 0,					\
538 		.mas_flags = 0,						\
539 		.store_type = wr_invalid,				\
540 	}
541 
542 #define MA_WR_STATE(name, ma_state, wr_entry)				\
543 	struct ma_wr_state name = {					\
544 		.mas = ma_state,					\
545 		.content = NULL,					\
546 		.entry = wr_entry,					\
547 		.vacant_height = 0,					\
548 		.sufficient_height = 0					\
549 	}
550 
551 #define MA_TOPIARY(name, tree)						\
552 	struct ma_topiary name = {					\
553 		.head = NULL,						\
554 		.tail = NULL,						\
555 		.mtree = tree,						\
556 	}
557 
558 void *mas_walk(struct ma_state *mas);
559 void *mas_store(struct ma_state *mas, void *entry);
560 void *mas_erase(struct ma_state *mas);
561 int mas_store_gfp(struct ma_state *mas, void *entry, gfp_t gfp);
562 void mas_store_prealloc(struct ma_state *mas, void *entry);
563 void *mas_find(struct ma_state *mas, unsigned long max);
564 void *mas_find_range(struct ma_state *mas, unsigned long max);
565 void *mas_find_rev(struct ma_state *mas, unsigned long min);
566 void *mas_find_range_rev(struct ma_state *mas, unsigned long max);
567 int mas_preallocate(struct ma_state *mas, void *entry, gfp_t gfp);
568 int mas_alloc_cyclic(struct ma_state *mas, unsigned long *startp,
569 		void *entry, unsigned long range_lo, unsigned long range_hi,
570 		unsigned long *next, gfp_t gfp);
571 
572 bool mas_nomem(struct ma_state *mas, gfp_t gfp);
573 bool mas_nomem_nofail(struct ma_state *mas, unsigned long index,
574 		      unsigned long last);
575 void mas_pause(struct ma_state *mas);
576 void maple_tree_init(void);
577 void mas_destroy(struct ma_state *mas);
578 
579 void *mas_prev(struct ma_state *mas, unsigned long min);
580 void *mas_prev_range(struct ma_state *mas, unsigned long min);
581 void *mas_next(struct ma_state *mas, unsigned long max);
582 void *mas_next_range(struct ma_state *mas, unsigned long max);
583 
584 int mas_empty_area(struct ma_state *mas, unsigned long min, unsigned long max,
585 		   unsigned long size);
586 /*
587  * This finds an empty area from the highest address to the lowest.
588  * AKA "Topdown" version,
589  */
590 int mas_empty_area_rev(struct ma_state *mas, unsigned long min,
591 		       unsigned long max, unsigned long size);
592 
mas_init(struct ma_state * mas,struct maple_tree * tree,unsigned long addr)593 static inline void mas_init(struct ma_state *mas, struct maple_tree *tree,
594 			    unsigned long addr)
595 {
596 	memset(mas, 0, sizeof(struct ma_state));
597 	mas->tree = tree;
598 	mas->index = mas->last = addr;
599 	mas->max = ULONG_MAX;
600 	mas->status = ma_start;
601 	mas->node = NULL;
602 }
603 
mas_is_active(struct ma_state * mas)604 static inline bool mas_is_active(struct ma_state *mas)
605 {
606 	return mas->status == ma_active;
607 }
608 
mas_is_err(struct ma_state * mas)609 static inline bool mas_is_err(struct ma_state *mas)
610 {
611 	return mas->status == ma_error;
612 }
613 
614 /**
615  * mas_reset() - Reset a Maple Tree operation state.
616  * @mas: Maple Tree operation state.
617  *
618  * Resets the error or walk state of the @mas so future walks of the
619  * array will start from the root.  Use this if you have dropped the
620  * lock and want to reuse the ma_state.
621  *
622  * Context: Any context.
623  */
mas_reset(struct ma_state * mas)624 static __always_inline void mas_reset(struct ma_state *mas)
625 {
626 	mas->status = ma_start;
627 	mas->node = NULL;
628 }
629 
630 /**
631  * mas_for_each() - Iterate over a range of the maple tree.
632  * @__mas: Maple Tree operation state (maple_state)
633  * @__entry: Entry retrieved from the tree
634  * @__max: maximum index to retrieve from the tree
635  *
636  * When returned, mas->index and mas->last will hold the entire range for the
637  * entry.
638  *
639  * Note: may return the zero entry.
640  */
641 #define mas_for_each(__mas, __entry, __max) \
642 	while (((__entry) = mas_find((__mas), (__max))) != NULL)
643 
644 /**
645  * mas_for_each_rev() - Iterate over a range of the maple tree in reverse order.
646  * @__mas: Maple Tree operation state (maple_state)
647  * @__entry: Entry retrieved from the tree
648  * @__min: minimum index to retrieve from the tree
649  *
650  * When returned, mas->index and mas->last will hold the entire range for the
651  * entry.
652  *
653  * Note: may return the zero entry.
654  */
655 #define mas_for_each_rev(__mas, __entry, __min) \
656 	while (((__entry) = mas_find_rev((__mas), (__min))) != NULL)
657 
658 #ifdef CONFIG_DEBUG_MAPLE_TREE
659 enum mt_dump_format {
660 	mt_dump_dec,
661 	mt_dump_hex,
662 };
663 
664 extern atomic_t maple_tree_tests_run;
665 extern atomic_t maple_tree_tests_passed;
666 
667 void mt_dump(const struct maple_tree *mt, enum mt_dump_format format);
668 void mas_dump(const struct ma_state *mas);
669 void mas_wr_dump(const struct ma_wr_state *wr_mas);
670 void mt_validate(struct maple_tree *mt);
671 void mt_cache_shrink(void);
672 #define MT_BUG_ON(__tree, __x) do {					\
673 	atomic_inc(&maple_tree_tests_run);				\
674 	if (__x) {							\
675 		pr_info("BUG at %s:%d (%u)\n",				\
676 		__func__, __LINE__, __x);				\
677 		mt_dump(__tree, mt_dump_hex);				\
678 		pr_info("Pass: %u Run:%u\n",				\
679 			atomic_read(&maple_tree_tests_passed),		\
680 			atomic_read(&maple_tree_tests_run));		\
681 		dump_stack();						\
682 	} else {							\
683 		atomic_inc(&maple_tree_tests_passed);			\
684 	}								\
685 } while (0)
686 
687 #define MAS_BUG_ON(__mas, __x) do {					\
688 	atomic_inc(&maple_tree_tests_run);				\
689 	if (__x) {							\
690 		pr_info("BUG at %s:%d (%u)\n",				\
691 		__func__, __LINE__, __x);				\
692 		mas_dump(__mas);					\
693 		mt_dump((__mas)->tree, mt_dump_hex);			\
694 		pr_info("Pass: %u Run:%u\n",				\
695 			atomic_read(&maple_tree_tests_passed),		\
696 			atomic_read(&maple_tree_tests_run));		\
697 		dump_stack();						\
698 	} else {							\
699 		atomic_inc(&maple_tree_tests_passed);			\
700 	}								\
701 } while (0)
702 
703 #define MAS_WR_BUG_ON(__wrmas, __x) do {				\
704 	atomic_inc(&maple_tree_tests_run);				\
705 	if (__x) {							\
706 		pr_info("BUG at %s:%d (%u)\n",				\
707 		__func__, __LINE__, __x);				\
708 		mas_wr_dump(__wrmas);					\
709 		mas_dump((__wrmas)->mas);				\
710 		mt_dump((__wrmas)->mas->tree, mt_dump_hex);		\
711 		pr_info("Pass: %u Run:%u\n",				\
712 			atomic_read(&maple_tree_tests_passed),		\
713 			atomic_read(&maple_tree_tests_run));		\
714 		dump_stack();						\
715 	} else {							\
716 		atomic_inc(&maple_tree_tests_passed);			\
717 	}								\
718 } while (0)
719 
720 #define MT_WARN_ON(__tree, __x)  ({					\
721 	int ret = !!(__x);						\
722 	atomic_inc(&maple_tree_tests_run);				\
723 	if (ret) {							\
724 		pr_info("WARN at %s:%d (%u)\n",				\
725 		__func__, __LINE__, __x);				\
726 		mt_dump(__tree, mt_dump_hex);				\
727 		pr_info("Pass: %u Run:%u\n",				\
728 			atomic_read(&maple_tree_tests_passed),		\
729 			atomic_read(&maple_tree_tests_run));		\
730 		dump_stack();						\
731 	} else {							\
732 		atomic_inc(&maple_tree_tests_passed);			\
733 	}								\
734 	unlikely(ret);							\
735 })
736 
737 #define MAS_WARN_ON(__mas, __x) ({					\
738 	int ret = !!(__x);						\
739 	atomic_inc(&maple_tree_tests_run);				\
740 	if (ret) {							\
741 		pr_info("WARN at %s:%d (%u)\n",				\
742 		__func__, __LINE__, __x);				\
743 		mas_dump(__mas);					\
744 		mt_dump((__mas)->tree, mt_dump_hex);			\
745 		pr_info("Pass: %u Run:%u\n",				\
746 			atomic_read(&maple_tree_tests_passed),		\
747 			atomic_read(&maple_tree_tests_run));		\
748 		dump_stack();						\
749 	} else {							\
750 		atomic_inc(&maple_tree_tests_passed);			\
751 	}								\
752 	unlikely(ret);							\
753 })
754 
755 #define MAS_WR_WARN_ON(__wrmas, __x) ({					\
756 	int ret = !!(__x);						\
757 	atomic_inc(&maple_tree_tests_run);				\
758 	if (ret) {							\
759 		pr_info("WARN at %s:%d (%u)\n",				\
760 		__func__, __LINE__, __x);				\
761 		mas_wr_dump(__wrmas);					\
762 		mas_dump((__wrmas)->mas);				\
763 		mt_dump((__wrmas)->mas->tree, mt_dump_hex);		\
764 		pr_info("Pass: %u Run:%u\n",				\
765 			atomic_read(&maple_tree_tests_passed),		\
766 			atomic_read(&maple_tree_tests_run));		\
767 		dump_stack();						\
768 	} else {							\
769 		atomic_inc(&maple_tree_tests_passed);			\
770 	}								\
771 	unlikely(ret);							\
772 })
773 #else
774 #define MT_BUG_ON(__tree, __x)		BUG_ON(__x)
775 #define MAS_BUG_ON(__mas, __x)		BUG_ON(__x)
776 #define MAS_WR_BUG_ON(__mas, __x)	BUG_ON(__x)
777 #define MT_WARN_ON(__tree, __x)		WARN_ON(__x)
778 #define MAS_WARN_ON(__mas, __x)		WARN_ON(__x)
779 #define MAS_WR_WARN_ON(__mas, __x)	WARN_ON(__x)
780 #endif /* CONFIG_DEBUG_MAPLE_TREE */
781 
782 /**
783  * __mas_set_range() - Set up Maple Tree operation state to a sub-range of the
784  * current location.
785  * @mas: Maple Tree operation state.
786  * @start: New start of range in the Maple Tree.
787  * @last: New end of range in the Maple Tree.
788  *
789  * set the internal maple state values to a sub-range.
790  * Please use mas_set_range() if you do not know where you are in the tree.
791  */
__mas_set_range(struct ma_state * mas,unsigned long start,unsigned long last)792 static inline void __mas_set_range(struct ma_state *mas, unsigned long start,
793 		unsigned long last)
794 {
795 	/* Ensure the range starts within the current slot */
796 	MAS_WARN_ON(mas, mas_is_active(mas) &&
797 		   (mas->index > start || mas->last < start));
798 	mas->index = start;
799 	mas->last = last;
800 }
801 
802 /**
803  * mas_set_range() - Set up Maple Tree operation state for a different index.
804  * @mas: Maple Tree operation state.
805  * @start: New start of range in the Maple Tree.
806  * @last: New end of range in the Maple Tree.
807  *
808  * Move the operation state to refer to a different range.  This will
809  * have the effect of starting a walk from the top; see mas_next()
810  * to move to an adjacent index.
811  */
812 static inline
mas_set_range(struct ma_state * mas,unsigned long start,unsigned long last)813 void mas_set_range(struct ma_state *mas, unsigned long start, unsigned long last)
814 {
815 	mas_reset(mas);
816 	__mas_set_range(mas, start, last);
817 }
818 
819 /**
820  * mas_set() - Set up Maple Tree operation state for a different index.
821  * @mas: Maple Tree operation state.
822  * @index: New index into the Maple Tree.
823  *
824  * Move the operation state to refer to a different index.  This will
825  * have the effect of starting a walk from the top; see mas_next()
826  * to move to an adjacent index.
827  */
mas_set(struct ma_state * mas,unsigned long index)828 static inline void mas_set(struct ma_state *mas, unsigned long index)
829 {
830 
831 	mas_set_range(mas, index, index);
832 }
833 
mt_external_lock(const struct maple_tree * mt)834 static inline bool mt_external_lock(const struct maple_tree *mt)
835 {
836 	return (mt->ma_flags & MT_FLAGS_LOCK_MASK) == MT_FLAGS_LOCK_EXTERN;
837 }
838 
839 /**
840  * mt_init_flags() - Initialise an empty maple tree with flags.
841  * @mt: Maple Tree
842  * @flags: maple tree flags.
843  *
844  * If you need to initialise a Maple Tree with special flags (eg, an
845  * allocation tree), use this function.
846  *
847  * Context: Any context.
848  */
mt_init_flags(struct maple_tree * mt,unsigned int flags)849 static inline void mt_init_flags(struct maple_tree *mt, unsigned int flags)
850 {
851 	mt->ma_flags = flags;
852 	if (!mt_external_lock(mt))
853 		spin_lock_init(&mt->ma_lock);
854 	rcu_assign_pointer(mt->ma_root, NULL);
855 }
856 
857 /**
858  * mt_init() - Initialise an empty maple tree.
859  * @mt: Maple Tree
860  *
861  * An empty Maple Tree.
862  *
863  * Context: Any context.
864  */
mt_init(struct maple_tree * mt)865 static inline void mt_init(struct maple_tree *mt)
866 {
867 	mt_init_flags(mt, 0);
868 }
869 
mt_in_rcu(struct maple_tree * mt)870 static inline bool mt_in_rcu(struct maple_tree *mt)
871 {
872 	return mt->ma_flags & MT_FLAGS_USE_RCU;
873 }
874 
875 /**
876  * mt_clear_in_rcu() - Switch the tree to non-RCU mode.
877  * @mt: The Maple Tree
878  */
mt_clear_in_rcu(struct maple_tree * mt)879 static inline void mt_clear_in_rcu(struct maple_tree *mt)
880 {
881 	if (!mt_in_rcu(mt))
882 		return;
883 
884 	if (mt_external_lock(mt)) {
885 		WARN_ON(!mt_lock_is_held(mt));
886 		mt->ma_flags &= ~MT_FLAGS_USE_RCU;
887 	} else {
888 		mtree_lock(mt);
889 		mt->ma_flags &= ~MT_FLAGS_USE_RCU;
890 		mtree_unlock(mt);
891 	}
892 }
893 
894 /**
895  * mt_set_in_rcu() - Switch the tree to RCU safe mode.
896  * @mt: The Maple Tree
897  */
mt_set_in_rcu(struct maple_tree * mt)898 static inline void mt_set_in_rcu(struct maple_tree *mt)
899 {
900 	if (mt_in_rcu(mt))
901 		return;
902 
903 	if (mt_external_lock(mt)) {
904 		WARN_ON(!mt_lock_is_held(mt));
905 		mt->ma_flags |= MT_FLAGS_USE_RCU;
906 	} else {
907 		mtree_lock(mt);
908 		mt->ma_flags |= MT_FLAGS_USE_RCU;
909 		mtree_unlock(mt);
910 	}
911 }
912 
mt_height(const struct maple_tree * mt)913 static inline unsigned int mt_height(const struct maple_tree *mt)
914 {
915 	return (mt->ma_flags & MT_FLAGS_HEIGHT_MASK) >> MT_FLAGS_HEIGHT_OFFSET;
916 }
917 
918 void *mt_find(struct maple_tree *mt, unsigned long *index, unsigned long max);
919 void *mt_find_after(struct maple_tree *mt, unsigned long *index,
920 		    unsigned long max);
921 void *mt_prev(struct maple_tree *mt, unsigned long index,  unsigned long min);
922 void *mt_next(struct maple_tree *mt, unsigned long index, unsigned long max);
923 
924 /**
925  * mt_for_each - Iterate over each entry starting at index until max.
926  * @__tree: The Maple Tree
927  * @__entry: The current entry
928  * @__index: The index to start the search from. Subsequently used as iterator.
929  * @__max: The maximum limit for @index
930  *
931  * This iterator skips all entries, which resolve to a NULL pointer,
932  * e.g. entries which has been reserved with XA_ZERO_ENTRY.
933  */
934 #define mt_for_each(__tree, __entry, __index, __max) \
935 	for (__entry = mt_find(__tree, &(__index), __max); \
936 		__entry; __entry = mt_find_after(__tree, &(__index), __max))
937 
938 #endif /*_LINUX_MAPLE_TREE_H */
939