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