xref: /linux-6.15/lib/maple_tree.c (revision 12833a73)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Maple Tree implementation
4  * Copyright (c) 2018-2022 Oracle Corporation
5  * Authors: Liam R. Howlett <[email protected]>
6  *	    Matthew Wilcox <[email protected]>
7  * Copyright (c) 2023 ByteDance
8  * Author: Peng Zhang <[email protected]>
9  */
10 
11 /*
12  * DOC: Interesting implementation details of the Maple Tree
13  *
14  * Each node type has a number of slots for entries and a number of slots for
15  * pivots.  In the case of dense nodes, the pivots are implied by the position
16  * and are simply the slot index + the minimum of the node.
17  *
18  * In regular B-Tree terms, pivots are called keys.  The term pivot is used to
19  * indicate that the tree is specifying ranges.  Pivots may appear in the
20  * subtree with an entry attached to the value whereas keys are unique to a
21  * specific position of a B-tree.  Pivot values are inclusive of the slot with
22  * the same index.
23  *
24  *
25  * The following illustrates the layout of a range64 nodes slots and pivots.
26  *
27  *
28  *  Slots -> | 0 | 1 | 2 | ... | 12 | 13 | 14 | 15 |
29  *           ┬   ┬   ┬   ┬     ┬    ┬    ┬    ┬    ┬
30  *           │   │   │   │     │    │    │    │    └─ Implied maximum
31  *           │   │   │   │     │    │    │    └─ Pivot 14
32  *           │   │   │   │     │    │    └─ Pivot 13
33  *           │   │   │   │     │    └─ Pivot 12
34  *           │   │   │   │     └─ Pivot 11
35  *           │   │   │   └─ Pivot 2
36  *           │   │   └─ Pivot 1
37  *           │   └─ Pivot 0
38  *           └─  Implied minimum
39  *
40  * Slot contents:
41  *  Internal (non-leaf) nodes contain pointers to other nodes.
42  *  Leaf nodes contain entries.
43  *
44  * The location of interest is often referred to as an offset.  All offsets have
45  * a slot, but the last offset has an implied pivot from the node above (or
46  * UINT_MAX for the root node.
47  *
48  * Ranges complicate certain write activities.  When modifying any of
49  * the B-tree variants, it is known that one entry will either be added or
50  * deleted.  When modifying the Maple Tree, one store operation may overwrite
51  * the entire data set, or one half of the tree, or the middle half of the tree.
52  *
53  */
54 
55 
56 #include <linux/maple_tree.h>
57 #include <linux/xarray.h>
58 #include <linux/types.h>
59 #include <linux/export.h>
60 #include <linux/slab.h>
61 #include <linux/limits.h>
62 #include <asm/barrier.h>
63 
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/maple_tree.h>
66 
67 #define MA_ROOT_PARENT 1
68 
69 /*
70  * Maple state flags
71  * * MA_STATE_BULK		- Bulk insert mode
72  * * MA_STATE_REBALANCE		- Indicate a rebalance during bulk insert
73  * * MA_STATE_PREALLOC		- Preallocated nodes, WARN_ON allocation
74  */
75 #define MA_STATE_BULK		1
76 #define MA_STATE_REBALANCE	2
77 #define MA_STATE_PREALLOC	4
78 
79 #define ma_parent_ptr(x) ((struct maple_pnode *)(x))
80 #define mas_tree_parent(x) ((unsigned long)(x->tree) | MA_ROOT_PARENT)
81 #define ma_mnode_ptr(x) ((struct maple_node *)(x))
82 #define ma_enode_ptr(x) ((struct maple_enode *)(x))
83 static struct kmem_cache *maple_node_cache;
84 
85 #ifdef CONFIG_DEBUG_MAPLE_TREE
86 static const unsigned long mt_max[] = {
87 	[maple_dense]		= MAPLE_NODE_SLOTS,
88 	[maple_leaf_64]		= ULONG_MAX,
89 	[maple_range_64]	= ULONG_MAX,
90 	[maple_arange_64]	= ULONG_MAX,
91 };
92 #define mt_node_max(x) mt_max[mte_node_type(x)]
93 #endif
94 
95 static const unsigned char mt_slots[] = {
96 	[maple_dense]		= MAPLE_NODE_SLOTS,
97 	[maple_leaf_64]		= MAPLE_RANGE64_SLOTS,
98 	[maple_range_64]	= MAPLE_RANGE64_SLOTS,
99 	[maple_arange_64]	= MAPLE_ARANGE64_SLOTS,
100 };
101 #define mt_slot_count(x) mt_slots[mte_node_type(x)]
102 
103 static const unsigned char mt_pivots[] = {
104 	[maple_dense]		= 0,
105 	[maple_leaf_64]		= MAPLE_RANGE64_SLOTS - 1,
106 	[maple_range_64]	= MAPLE_RANGE64_SLOTS - 1,
107 	[maple_arange_64]	= MAPLE_ARANGE64_SLOTS - 1,
108 };
109 #define mt_pivot_count(x) mt_pivots[mte_node_type(x)]
110 
111 static const unsigned char mt_min_slots[] = {
112 	[maple_dense]		= MAPLE_NODE_SLOTS / 2,
113 	[maple_leaf_64]		= (MAPLE_RANGE64_SLOTS / 2) - 2,
114 	[maple_range_64]	= (MAPLE_RANGE64_SLOTS / 2) - 2,
115 	[maple_arange_64]	= (MAPLE_ARANGE64_SLOTS / 2) - 1,
116 };
117 #define mt_min_slot_count(x) mt_min_slots[mte_node_type(x)]
118 
119 #define MAPLE_BIG_NODE_SLOTS	(MAPLE_RANGE64_SLOTS * 2 + 2)
120 #define MAPLE_BIG_NODE_GAPS	(MAPLE_ARANGE64_SLOTS * 2 + 1)
121 
122 struct maple_big_node {
123 	unsigned long pivot[MAPLE_BIG_NODE_SLOTS - 1];
124 	union {
125 		struct maple_enode *slot[MAPLE_BIG_NODE_SLOTS];
126 		struct {
127 			unsigned long padding[MAPLE_BIG_NODE_GAPS];
128 			unsigned long gap[MAPLE_BIG_NODE_GAPS];
129 		};
130 	};
131 	unsigned char b_end;
132 	enum maple_type type;
133 };
134 
135 /*
136  * The maple_subtree_state is used to build a tree to replace a segment of an
137  * existing tree in a more atomic way.  Any walkers of the older tree will hit a
138  * dead node and restart on updates.
139  */
140 struct maple_subtree_state {
141 	struct ma_state *orig_l;	/* Original left side of subtree */
142 	struct ma_state *orig_r;	/* Original right side of subtree */
143 	struct ma_state *l;		/* New left side of subtree */
144 	struct ma_state *m;		/* New middle of subtree (rare) */
145 	struct ma_state *r;		/* New right side of subtree */
146 	struct ma_topiary *free;	/* nodes to be freed */
147 	struct ma_topiary *destroy;	/* Nodes to be destroyed (walked and freed) */
148 	struct maple_big_node *bn;
149 };
150 
151 #ifdef CONFIG_KASAN_STACK
152 /* Prevent mas_wr_bnode() from exceeding the stack frame limit */
153 #define noinline_for_kasan noinline_for_stack
154 #else
155 #define noinline_for_kasan inline
156 #endif
157 
158 /* Functions */
159 static inline struct maple_node *mt_alloc_one(gfp_t gfp)
160 {
161 	return kmem_cache_alloc(maple_node_cache, gfp);
162 }
163 
164 static inline int mt_alloc_bulk(gfp_t gfp, size_t size, void **nodes)
165 {
166 	return kmem_cache_alloc_bulk(maple_node_cache, gfp, size, nodes);
167 }
168 
169 static inline void mt_free_one(struct maple_node *node)
170 {
171 	kmem_cache_free(maple_node_cache, node);
172 }
173 
174 static inline void mt_free_bulk(size_t size, void __rcu **nodes)
175 {
176 	kmem_cache_free_bulk(maple_node_cache, size, (void **)nodes);
177 }
178 
179 static void mt_free_rcu(struct rcu_head *head)
180 {
181 	struct maple_node *node = container_of(head, struct maple_node, rcu);
182 
183 	kmem_cache_free(maple_node_cache, node);
184 }
185 
186 /*
187  * ma_free_rcu() - Use rcu callback to free a maple node
188  * @node: The node to free
189  *
190  * The maple tree uses the parent pointer to indicate this node is no longer in
191  * use and will be freed.
192  */
193 static void ma_free_rcu(struct maple_node *node)
194 {
195 	WARN_ON(node->parent != ma_parent_ptr(node));
196 	call_rcu(&node->rcu, mt_free_rcu);
197 }
198 
199 static void mas_set_height(struct ma_state *mas)
200 {
201 	unsigned int new_flags = mas->tree->ma_flags;
202 
203 	new_flags &= ~MT_FLAGS_HEIGHT_MASK;
204 	MAS_BUG_ON(mas, mas->depth > MAPLE_HEIGHT_MAX);
205 	new_flags |= mas->depth << MT_FLAGS_HEIGHT_OFFSET;
206 	mas->tree->ma_flags = new_flags;
207 }
208 
209 static unsigned int mas_mt_height(struct ma_state *mas)
210 {
211 	return mt_height(mas->tree);
212 }
213 
214 static inline unsigned int mt_attr(struct maple_tree *mt)
215 {
216 	return mt->ma_flags & ~MT_FLAGS_HEIGHT_MASK;
217 }
218 
219 static __always_inline enum maple_type mte_node_type(
220 		const struct maple_enode *entry)
221 {
222 	return ((unsigned long)entry >> MAPLE_NODE_TYPE_SHIFT) &
223 		MAPLE_NODE_TYPE_MASK;
224 }
225 
226 static __always_inline bool ma_is_dense(const enum maple_type type)
227 {
228 	return type < maple_leaf_64;
229 }
230 
231 static __always_inline bool ma_is_leaf(const enum maple_type type)
232 {
233 	return type < maple_range_64;
234 }
235 
236 static __always_inline bool mte_is_leaf(const struct maple_enode *entry)
237 {
238 	return ma_is_leaf(mte_node_type(entry));
239 }
240 
241 /*
242  * We also reserve values with the bottom two bits set to '10' which are
243  * below 4096
244  */
245 static __always_inline bool mt_is_reserved(const void *entry)
246 {
247 	return ((unsigned long)entry < MAPLE_RESERVED_RANGE) &&
248 		xa_is_internal(entry);
249 }
250 
251 static __always_inline void mas_set_err(struct ma_state *mas, long err)
252 {
253 	mas->node = MA_ERROR(err);
254 	mas->status = ma_error;
255 }
256 
257 static __always_inline bool mas_is_ptr(const struct ma_state *mas)
258 {
259 	return mas->status == ma_root;
260 }
261 
262 static __always_inline bool mas_is_start(const struct ma_state *mas)
263 {
264 	return mas->status == ma_start;
265 }
266 
267 static __always_inline bool mas_is_none(const struct ma_state *mas)
268 {
269 	return mas->status == ma_none;
270 }
271 
272 static __always_inline bool mas_is_paused(const struct ma_state *mas)
273 {
274 	return mas->status == ma_pause;
275 }
276 
277 static __always_inline bool mas_is_overflow(struct ma_state *mas)
278 {
279 	return mas->status == ma_overflow;
280 }
281 
282 static inline bool mas_is_underflow(struct ma_state *mas)
283 {
284 	return mas->status == ma_underflow;
285 }
286 
287 static __always_inline struct maple_node *mte_to_node(
288 		const struct maple_enode *entry)
289 {
290 	return (struct maple_node *)((unsigned long)entry & ~MAPLE_NODE_MASK);
291 }
292 
293 /*
294  * mte_to_mat() - Convert a maple encoded node to a maple topiary node.
295  * @entry: The maple encoded node
296  *
297  * Return: a maple topiary pointer
298  */
299 static inline struct maple_topiary *mte_to_mat(const struct maple_enode *entry)
300 {
301 	return (struct maple_topiary *)
302 		((unsigned long)entry & ~MAPLE_NODE_MASK);
303 }
304 
305 /*
306  * mas_mn() - Get the maple state node.
307  * @mas: The maple state
308  *
309  * Return: the maple node (not encoded - bare pointer).
310  */
311 static inline struct maple_node *mas_mn(const struct ma_state *mas)
312 {
313 	return mte_to_node(mas->node);
314 }
315 
316 /*
317  * mte_set_node_dead() - Set a maple encoded node as dead.
318  * @mn: The maple encoded node.
319  */
320 static inline void mte_set_node_dead(struct maple_enode *mn)
321 {
322 	mte_to_node(mn)->parent = ma_parent_ptr(mte_to_node(mn));
323 	smp_wmb(); /* Needed for RCU */
324 }
325 
326 /* Bit 1 indicates the root is a node */
327 #define MAPLE_ROOT_NODE			0x02
328 /* maple_type stored bit 3-6 */
329 #define MAPLE_ENODE_TYPE_SHIFT		0x03
330 /* Bit 2 means a NULL somewhere below */
331 #define MAPLE_ENODE_NULL		0x04
332 
333 static inline struct maple_enode *mt_mk_node(const struct maple_node *node,
334 					     enum maple_type type)
335 {
336 	return (void *)((unsigned long)node |
337 			(type << MAPLE_ENODE_TYPE_SHIFT) | MAPLE_ENODE_NULL);
338 }
339 
340 static inline void *mte_mk_root(const struct maple_enode *node)
341 {
342 	return (void *)((unsigned long)node | MAPLE_ROOT_NODE);
343 }
344 
345 static inline void *mte_safe_root(const struct maple_enode *node)
346 {
347 	return (void *)((unsigned long)node & ~MAPLE_ROOT_NODE);
348 }
349 
350 static inline void __maybe_unused *mte_set_full(const struct maple_enode *node)
351 {
352 	return (void *)((unsigned long)node & ~MAPLE_ENODE_NULL);
353 }
354 
355 static inline void __maybe_unused *mte_clear_full(const struct maple_enode *node)
356 {
357 	return (void *)((unsigned long)node | MAPLE_ENODE_NULL);
358 }
359 
360 static inline bool __maybe_unused mte_has_null(const struct maple_enode *node)
361 {
362 	return (unsigned long)node & MAPLE_ENODE_NULL;
363 }
364 
365 static __always_inline bool ma_is_root(struct maple_node *node)
366 {
367 	return ((unsigned long)node->parent & MA_ROOT_PARENT);
368 }
369 
370 static __always_inline bool mte_is_root(const struct maple_enode *node)
371 {
372 	return ma_is_root(mte_to_node(node));
373 }
374 
375 static inline bool mas_is_root_limits(const struct ma_state *mas)
376 {
377 	return !mas->min && mas->max == ULONG_MAX;
378 }
379 
380 static __always_inline bool mt_is_alloc(struct maple_tree *mt)
381 {
382 	return (mt->ma_flags & MT_FLAGS_ALLOC_RANGE);
383 }
384 
385 /*
386  * The Parent Pointer
387  * Excluding root, the parent pointer is 256B aligned like all other tree nodes.
388  * When storing a 32 or 64 bit values, the offset can fit into 5 bits.  The 16
389  * bit values need an extra bit to store the offset.  This extra bit comes from
390  * a reuse of the last bit in the node type.  This is possible by using bit 1 to
391  * indicate if bit 2 is part of the type or the slot.
392  *
393  * Note types:
394  *  0x??1 = Root
395  *  0x?00 = 16 bit nodes
396  *  0x010 = 32 bit nodes
397  *  0x110 = 64 bit nodes
398  *
399  * Slot size and alignment
400  *  0b??1 : Root
401  *  0b?00 : 16 bit values, type in 0-1, slot in 2-7
402  *  0b010 : 32 bit values, type in 0-2, slot in 3-7
403  *  0b110 : 64 bit values, type in 0-2, slot in 3-7
404  */
405 
406 #define MAPLE_PARENT_ROOT		0x01
407 
408 #define MAPLE_PARENT_SLOT_SHIFT		0x03
409 #define MAPLE_PARENT_SLOT_MASK		0xF8
410 
411 #define MAPLE_PARENT_16B_SLOT_SHIFT	0x02
412 #define MAPLE_PARENT_16B_SLOT_MASK	0xFC
413 
414 #define MAPLE_PARENT_RANGE64		0x06
415 #define MAPLE_PARENT_RANGE32		0x04
416 #define MAPLE_PARENT_NOT_RANGE16	0x02
417 
418 /*
419  * mte_parent_shift() - Get the parent shift for the slot storage.
420  * @parent: The parent pointer cast as an unsigned long
421  * Return: The shift into that pointer to the star to of the slot
422  */
423 static inline unsigned long mte_parent_shift(unsigned long parent)
424 {
425 	/* Note bit 1 == 0 means 16B */
426 	if (likely(parent & MAPLE_PARENT_NOT_RANGE16))
427 		return MAPLE_PARENT_SLOT_SHIFT;
428 
429 	return MAPLE_PARENT_16B_SLOT_SHIFT;
430 }
431 
432 /*
433  * mte_parent_slot_mask() - Get the slot mask for the parent.
434  * @parent: The parent pointer cast as an unsigned long.
435  * Return: The slot mask for that parent.
436  */
437 static inline unsigned long mte_parent_slot_mask(unsigned long parent)
438 {
439 	/* Note bit 1 == 0 means 16B */
440 	if (likely(parent & MAPLE_PARENT_NOT_RANGE16))
441 		return MAPLE_PARENT_SLOT_MASK;
442 
443 	return MAPLE_PARENT_16B_SLOT_MASK;
444 }
445 
446 /*
447  * mas_parent_type() - Return the maple_type of the parent from the stored
448  * parent type.
449  * @mas: The maple state
450  * @enode: The maple_enode to extract the parent's enum
451  * Return: The node->parent maple_type
452  */
453 static inline
454 enum maple_type mas_parent_type(struct ma_state *mas, struct maple_enode *enode)
455 {
456 	unsigned long p_type;
457 
458 	p_type = (unsigned long)mte_to_node(enode)->parent;
459 	if (WARN_ON(p_type & MAPLE_PARENT_ROOT))
460 		return 0;
461 
462 	p_type &= MAPLE_NODE_MASK;
463 	p_type &= ~mte_parent_slot_mask(p_type);
464 	switch (p_type) {
465 	case MAPLE_PARENT_RANGE64: /* or MAPLE_PARENT_ARANGE64 */
466 		if (mt_is_alloc(mas->tree))
467 			return maple_arange_64;
468 		return maple_range_64;
469 	}
470 
471 	return 0;
472 }
473 
474 /*
475  * mas_set_parent() - Set the parent node and encode the slot
476  * @mas: The maple state
477  * @enode: The encoded maple node.
478  * @parent: The encoded maple node that is the parent of @enode.
479  * @slot: The slot that @enode resides in @parent.
480  *
481  * Slot number is encoded in the enode->parent bit 3-6 or 2-6, depending on the
482  * parent type.
483  */
484 static inline
485 void mas_set_parent(struct ma_state *mas, struct maple_enode *enode,
486 		    const struct maple_enode *parent, unsigned char slot)
487 {
488 	unsigned long val = (unsigned long)parent;
489 	unsigned long shift;
490 	unsigned long type;
491 	enum maple_type p_type = mte_node_type(parent);
492 
493 	MAS_BUG_ON(mas, p_type == maple_dense);
494 	MAS_BUG_ON(mas, p_type == maple_leaf_64);
495 
496 	switch (p_type) {
497 	case maple_range_64:
498 	case maple_arange_64:
499 		shift = MAPLE_PARENT_SLOT_SHIFT;
500 		type = MAPLE_PARENT_RANGE64;
501 		break;
502 	default:
503 	case maple_dense:
504 	case maple_leaf_64:
505 		shift = type = 0;
506 		break;
507 	}
508 
509 	val &= ~MAPLE_NODE_MASK; /* Clear all node metadata in parent */
510 	val |= (slot << shift) | type;
511 	mte_to_node(enode)->parent = ma_parent_ptr(val);
512 }
513 
514 /*
515  * mte_parent_slot() - get the parent slot of @enode.
516  * @enode: The encoded maple node.
517  *
518  * Return: The slot in the parent node where @enode resides.
519  */
520 static __always_inline
521 unsigned int mte_parent_slot(const struct maple_enode *enode)
522 {
523 	unsigned long val = (unsigned long)mte_to_node(enode)->parent;
524 
525 	if (unlikely(val & MA_ROOT_PARENT))
526 		return 0;
527 
528 	/*
529 	 * Okay to use MAPLE_PARENT_16B_SLOT_MASK as the last bit will be lost
530 	 * by shift if the parent shift is MAPLE_PARENT_SLOT_SHIFT
531 	 */
532 	return (val & MAPLE_PARENT_16B_SLOT_MASK) >> mte_parent_shift(val);
533 }
534 
535 /*
536  * mte_parent() - Get the parent of @node.
537  * @enode: The encoded maple node.
538  *
539  * Return: The parent maple node.
540  */
541 static __always_inline
542 struct maple_node *mte_parent(const struct maple_enode *enode)
543 {
544 	return (void *)((unsigned long)
545 			(mte_to_node(enode)->parent) & ~MAPLE_NODE_MASK);
546 }
547 
548 /*
549  * ma_dead_node() - check if the @enode is dead.
550  * @enode: The encoded maple node
551  *
552  * Return: true if dead, false otherwise.
553  */
554 static __always_inline bool ma_dead_node(const struct maple_node *node)
555 {
556 	struct maple_node *parent;
557 
558 	/* Do not reorder reads from the node prior to the parent check */
559 	smp_rmb();
560 	parent = (void *)((unsigned long) node->parent & ~MAPLE_NODE_MASK);
561 	return (parent == node);
562 }
563 
564 /*
565  * mte_dead_node() - check if the @enode is dead.
566  * @enode: The encoded maple node
567  *
568  * Return: true if dead, false otherwise.
569  */
570 static __always_inline bool mte_dead_node(const struct maple_enode *enode)
571 {
572 	struct maple_node *parent, *node;
573 
574 	node = mte_to_node(enode);
575 	/* Do not reorder reads from the node prior to the parent check */
576 	smp_rmb();
577 	parent = mte_parent(enode);
578 	return (parent == node);
579 }
580 
581 /*
582  * mas_allocated() - Get the number of nodes allocated in a maple state.
583  * @mas: The maple state
584  *
585  * The ma_state alloc member is overloaded to hold a pointer to the first
586  * allocated node or to the number of requested nodes to allocate.  If bit 0 is
587  * set, then the alloc contains the number of requested nodes.  If there is an
588  * allocated node, then the total allocated nodes is in that node.
589  *
590  * Return: The total number of nodes allocated
591  */
592 static inline unsigned long mas_allocated(const struct ma_state *mas)
593 {
594 	if (!mas->alloc || ((unsigned long)mas->alloc & 0x1))
595 		return 0;
596 
597 	return mas->alloc->total;
598 }
599 
600 /*
601  * mas_set_alloc_req() - Set the requested number of allocations.
602  * @mas: the maple state
603  * @count: the number of allocations.
604  *
605  * The requested number of allocations is either in the first allocated node,
606  * located in @mas->alloc->request_count, or directly in @mas->alloc if there is
607  * no allocated node.  Set the request either in the node or do the necessary
608  * encoding to store in @mas->alloc directly.
609  */
610 static inline void mas_set_alloc_req(struct ma_state *mas, unsigned long count)
611 {
612 	if (!mas->alloc || ((unsigned long)mas->alloc & 0x1)) {
613 		if (!count)
614 			mas->alloc = NULL;
615 		else
616 			mas->alloc = (struct maple_alloc *)(((count) << 1U) | 1U);
617 		return;
618 	}
619 
620 	mas->alloc->request_count = count;
621 }
622 
623 /*
624  * mas_alloc_req() - get the requested number of allocations.
625  * @mas: The maple state
626  *
627  * The alloc count is either stored directly in @mas, or in
628  * @mas->alloc->request_count if there is at least one node allocated.  Decode
629  * the request count if it's stored directly in @mas->alloc.
630  *
631  * Return: The allocation request count.
632  */
633 static inline unsigned int mas_alloc_req(const struct ma_state *mas)
634 {
635 	if ((unsigned long)mas->alloc & 0x1)
636 		return (unsigned long)(mas->alloc) >> 1;
637 	else if (mas->alloc)
638 		return mas->alloc->request_count;
639 	return 0;
640 }
641 
642 /*
643  * ma_pivots() - Get a pointer to the maple node pivots.
644  * @node: the maple node
645  * @type: the node type
646  *
647  * In the event of a dead node, this array may be %NULL
648  *
649  * Return: A pointer to the maple node pivots
650  */
651 static inline unsigned long *ma_pivots(struct maple_node *node,
652 					   enum maple_type type)
653 {
654 	switch (type) {
655 	case maple_arange_64:
656 		return node->ma64.pivot;
657 	case maple_range_64:
658 	case maple_leaf_64:
659 		return node->mr64.pivot;
660 	case maple_dense:
661 		return NULL;
662 	}
663 	return NULL;
664 }
665 
666 /*
667  * ma_gaps() - Get a pointer to the maple node gaps.
668  * @node: the maple node
669  * @type: the node type
670  *
671  * Return: A pointer to the maple node gaps
672  */
673 static inline unsigned long *ma_gaps(struct maple_node *node,
674 				     enum maple_type type)
675 {
676 	switch (type) {
677 	case maple_arange_64:
678 		return node->ma64.gap;
679 	case maple_range_64:
680 	case maple_leaf_64:
681 	case maple_dense:
682 		return NULL;
683 	}
684 	return NULL;
685 }
686 
687 /*
688  * mas_safe_pivot() - get the pivot at @piv or mas->max.
689  * @mas: The maple state
690  * @pivots: The pointer to the maple node pivots
691  * @piv: The pivot to fetch
692  * @type: The maple node type
693  *
694  * Return: The pivot at @piv within the limit of the @pivots array, @mas->max
695  * otherwise.
696  */
697 static __always_inline unsigned long
698 mas_safe_pivot(const struct ma_state *mas, unsigned long *pivots,
699 	       unsigned char piv, enum maple_type type)
700 {
701 	if (piv >= mt_pivots[type])
702 		return mas->max;
703 
704 	return pivots[piv];
705 }
706 
707 /*
708  * mas_safe_min() - Return the minimum for a given offset.
709  * @mas: The maple state
710  * @pivots: The pointer to the maple node pivots
711  * @offset: The offset into the pivot array
712  *
713  * Return: The minimum range value that is contained in @offset.
714  */
715 static inline unsigned long
716 mas_safe_min(struct ma_state *mas, unsigned long *pivots, unsigned char offset)
717 {
718 	if (likely(offset))
719 		return pivots[offset - 1] + 1;
720 
721 	return mas->min;
722 }
723 
724 /*
725  * mte_set_pivot() - Set a pivot to a value in an encoded maple node.
726  * @mn: The encoded maple node
727  * @piv: The pivot offset
728  * @val: The value of the pivot
729  */
730 static inline void mte_set_pivot(struct maple_enode *mn, unsigned char piv,
731 				unsigned long val)
732 {
733 	struct maple_node *node = mte_to_node(mn);
734 	enum maple_type type = mte_node_type(mn);
735 
736 	BUG_ON(piv >= mt_pivots[type]);
737 	switch (type) {
738 	case maple_range_64:
739 	case maple_leaf_64:
740 		node->mr64.pivot[piv] = val;
741 		break;
742 	case maple_arange_64:
743 		node->ma64.pivot[piv] = val;
744 		break;
745 	case maple_dense:
746 		break;
747 	}
748 
749 }
750 
751 /*
752  * ma_slots() - Get a pointer to the maple node slots.
753  * @mn: The maple node
754  * @mt: The maple node type
755  *
756  * Return: A pointer to the maple node slots
757  */
758 static inline void __rcu **ma_slots(struct maple_node *mn, enum maple_type mt)
759 {
760 	switch (mt) {
761 	case maple_arange_64:
762 		return mn->ma64.slot;
763 	case maple_range_64:
764 	case maple_leaf_64:
765 		return mn->mr64.slot;
766 	case maple_dense:
767 		return mn->slot;
768 	}
769 
770 	return NULL;
771 }
772 
773 static inline bool mt_write_locked(const struct maple_tree *mt)
774 {
775 	return mt_external_lock(mt) ? mt_write_lock_is_held(mt) :
776 		lockdep_is_held(&mt->ma_lock);
777 }
778 
779 static __always_inline bool mt_locked(const struct maple_tree *mt)
780 {
781 	return mt_external_lock(mt) ? mt_lock_is_held(mt) :
782 		lockdep_is_held(&mt->ma_lock);
783 }
784 
785 static __always_inline void *mt_slot(const struct maple_tree *mt,
786 		void __rcu **slots, unsigned char offset)
787 {
788 	return rcu_dereference_check(slots[offset], mt_locked(mt));
789 }
790 
791 static __always_inline void *mt_slot_locked(struct maple_tree *mt,
792 		void __rcu **slots, unsigned char offset)
793 {
794 	return rcu_dereference_protected(slots[offset], mt_write_locked(mt));
795 }
796 /*
797  * mas_slot_locked() - Get the slot value when holding the maple tree lock.
798  * @mas: The maple state
799  * @slots: The pointer to the slots
800  * @offset: The offset into the slots array to fetch
801  *
802  * Return: The entry stored in @slots at the @offset.
803  */
804 static __always_inline void *mas_slot_locked(struct ma_state *mas,
805 		void __rcu **slots, unsigned char offset)
806 {
807 	return mt_slot_locked(mas->tree, slots, offset);
808 }
809 
810 /*
811  * mas_slot() - Get the slot value when not holding the maple tree lock.
812  * @mas: The maple state
813  * @slots: The pointer to the slots
814  * @offset: The offset into the slots array to fetch
815  *
816  * Return: The entry stored in @slots at the @offset
817  */
818 static __always_inline void *mas_slot(struct ma_state *mas, void __rcu **slots,
819 		unsigned char offset)
820 {
821 	return mt_slot(mas->tree, slots, offset);
822 }
823 
824 /*
825  * mas_root() - Get the maple tree root.
826  * @mas: The maple state.
827  *
828  * Return: The pointer to the root of the tree
829  */
830 static __always_inline void *mas_root(struct ma_state *mas)
831 {
832 	return rcu_dereference_check(mas->tree->ma_root, mt_locked(mas->tree));
833 }
834 
835 static inline void *mt_root_locked(struct maple_tree *mt)
836 {
837 	return rcu_dereference_protected(mt->ma_root, mt_write_locked(mt));
838 }
839 
840 /*
841  * mas_root_locked() - Get the maple tree root when holding the maple tree lock.
842  * @mas: The maple state.
843  *
844  * Return: The pointer to the root of the tree
845  */
846 static inline void *mas_root_locked(struct ma_state *mas)
847 {
848 	return mt_root_locked(mas->tree);
849 }
850 
851 static inline struct maple_metadata *ma_meta(struct maple_node *mn,
852 					     enum maple_type mt)
853 {
854 	switch (mt) {
855 	case maple_arange_64:
856 		return &mn->ma64.meta;
857 	default:
858 		return &mn->mr64.meta;
859 	}
860 }
861 
862 /*
863  * ma_set_meta() - Set the metadata information of a node.
864  * @mn: The maple node
865  * @mt: The maple node type
866  * @offset: The offset of the highest sub-gap in this node.
867  * @end: The end of the data in this node.
868  */
869 static inline void ma_set_meta(struct maple_node *mn, enum maple_type mt,
870 			       unsigned char offset, unsigned char end)
871 {
872 	struct maple_metadata *meta = ma_meta(mn, mt);
873 
874 	meta->gap = offset;
875 	meta->end = end;
876 }
877 
878 /*
879  * mt_clear_meta() - clear the metadata information of a node, if it exists
880  * @mt: The maple tree
881  * @mn: The maple node
882  * @type: The maple node type
883  */
884 static inline void mt_clear_meta(struct maple_tree *mt, struct maple_node *mn,
885 				  enum maple_type type)
886 {
887 	struct maple_metadata *meta;
888 	unsigned long *pivots;
889 	void __rcu **slots;
890 	void *next;
891 
892 	switch (type) {
893 	case maple_range_64:
894 		pivots = mn->mr64.pivot;
895 		if (unlikely(pivots[MAPLE_RANGE64_SLOTS - 2])) {
896 			slots = mn->mr64.slot;
897 			next = mt_slot_locked(mt, slots,
898 					      MAPLE_RANGE64_SLOTS - 1);
899 			if (unlikely((mte_to_node(next) &&
900 				      mte_node_type(next))))
901 				return; /* no metadata, could be node */
902 		}
903 		fallthrough;
904 	case maple_arange_64:
905 		meta = ma_meta(mn, type);
906 		break;
907 	default:
908 		return;
909 	}
910 
911 	meta->gap = 0;
912 	meta->end = 0;
913 }
914 
915 /*
916  * ma_meta_end() - Get the data end of a node from the metadata
917  * @mn: The maple node
918  * @mt: The maple node type
919  */
920 static inline unsigned char ma_meta_end(struct maple_node *mn,
921 					enum maple_type mt)
922 {
923 	struct maple_metadata *meta = ma_meta(mn, mt);
924 
925 	return meta->end;
926 }
927 
928 /*
929  * ma_meta_gap() - Get the largest gap location of a node from the metadata
930  * @mn: The maple node
931  */
932 static inline unsigned char ma_meta_gap(struct maple_node *mn)
933 {
934 	return mn->ma64.meta.gap;
935 }
936 
937 /*
938  * ma_set_meta_gap() - Set the largest gap location in a nodes metadata
939  * @mn: The maple node
940  * @mt: The maple node type
941  * @offset: The location of the largest gap.
942  */
943 static inline void ma_set_meta_gap(struct maple_node *mn, enum maple_type mt,
944 				   unsigned char offset)
945 {
946 
947 	struct maple_metadata *meta = ma_meta(mn, mt);
948 
949 	meta->gap = offset;
950 }
951 
952 /*
953  * mat_add() - Add a @dead_enode to the ma_topiary of a list of dead nodes.
954  * @mat: the ma_topiary, a linked list of dead nodes.
955  * @dead_enode: the node to be marked as dead and added to the tail of the list
956  *
957  * Add the @dead_enode to the linked list in @mat.
958  */
959 static inline void mat_add(struct ma_topiary *mat,
960 			   struct maple_enode *dead_enode)
961 {
962 	mte_set_node_dead(dead_enode);
963 	mte_to_mat(dead_enode)->next = NULL;
964 	if (!mat->tail) {
965 		mat->tail = mat->head = dead_enode;
966 		return;
967 	}
968 
969 	mte_to_mat(mat->tail)->next = dead_enode;
970 	mat->tail = dead_enode;
971 }
972 
973 static void mt_free_walk(struct rcu_head *head);
974 static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt,
975 			    bool free);
976 /*
977  * mas_mat_destroy() - Free all nodes and subtrees in a dead list.
978  * @mas: the maple state
979  * @mat: the ma_topiary linked list of dead nodes to free.
980  *
981  * Destroy walk a dead list.
982  */
983 static void mas_mat_destroy(struct ma_state *mas, struct ma_topiary *mat)
984 {
985 	struct maple_enode *next;
986 	struct maple_node *node;
987 	bool in_rcu = mt_in_rcu(mas->tree);
988 
989 	while (mat->head) {
990 		next = mte_to_mat(mat->head)->next;
991 		node = mte_to_node(mat->head);
992 		mt_destroy_walk(mat->head, mas->tree, !in_rcu);
993 		if (in_rcu)
994 			call_rcu(&node->rcu, mt_free_walk);
995 		mat->head = next;
996 	}
997 }
998 /*
999  * mas_descend() - Descend into the slot stored in the ma_state.
1000  * @mas: the maple state.
1001  *
1002  * Note: Not RCU safe, only use in write side or debug code.
1003  */
1004 static inline void mas_descend(struct ma_state *mas)
1005 {
1006 	enum maple_type type;
1007 	unsigned long *pivots;
1008 	struct maple_node *node;
1009 	void __rcu **slots;
1010 
1011 	node = mas_mn(mas);
1012 	type = mte_node_type(mas->node);
1013 	pivots = ma_pivots(node, type);
1014 	slots = ma_slots(node, type);
1015 
1016 	if (mas->offset)
1017 		mas->min = pivots[mas->offset - 1] + 1;
1018 	mas->max = mas_safe_pivot(mas, pivots, mas->offset, type);
1019 	mas->node = mas_slot(mas, slots, mas->offset);
1020 }
1021 
1022 /*
1023  * mte_set_gap() - Set a maple node gap.
1024  * @mn: The encoded maple node
1025  * @gap: The offset of the gap to set
1026  * @val: The gap value
1027  */
1028 static inline void mte_set_gap(const struct maple_enode *mn,
1029 				 unsigned char gap, unsigned long val)
1030 {
1031 	switch (mte_node_type(mn)) {
1032 	default:
1033 		break;
1034 	case maple_arange_64:
1035 		mte_to_node(mn)->ma64.gap[gap] = val;
1036 		break;
1037 	}
1038 }
1039 
1040 /*
1041  * mas_ascend() - Walk up a level of the tree.
1042  * @mas: The maple state
1043  *
1044  * Sets the @mas->max and @mas->min to the correct values when walking up.  This
1045  * may cause several levels of walking up to find the correct min and max.
1046  * May find a dead node which will cause a premature return.
1047  * Return: 1 on dead node, 0 otherwise
1048  */
1049 static int mas_ascend(struct ma_state *mas)
1050 {
1051 	struct maple_enode *p_enode; /* parent enode. */
1052 	struct maple_enode *a_enode; /* ancestor enode. */
1053 	struct maple_node *a_node; /* ancestor node. */
1054 	struct maple_node *p_node; /* parent node. */
1055 	unsigned char a_slot;
1056 	enum maple_type a_type;
1057 	unsigned long min, max;
1058 	unsigned long *pivots;
1059 	bool set_max = false, set_min = false;
1060 
1061 	a_node = mas_mn(mas);
1062 	if (ma_is_root(a_node)) {
1063 		mas->offset = 0;
1064 		return 0;
1065 	}
1066 
1067 	p_node = mte_parent(mas->node);
1068 	if (unlikely(a_node == p_node))
1069 		return 1;
1070 
1071 	a_type = mas_parent_type(mas, mas->node);
1072 	mas->offset = mte_parent_slot(mas->node);
1073 	a_enode = mt_mk_node(p_node, a_type);
1074 
1075 	/* Check to make sure all parent information is still accurate */
1076 	if (p_node != mte_parent(mas->node))
1077 		return 1;
1078 
1079 	mas->node = a_enode;
1080 
1081 	if (mte_is_root(a_enode)) {
1082 		mas->max = ULONG_MAX;
1083 		mas->min = 0;
1084 		return 0;
1085 	}
1086 
1087 	min = 0;
1088 	max = ULONG_MAX;
1089 	if (!mas->offset) {
1090 		min = mas->min;
1091 		set_min = true;
1092 	}
1093 
1094 	if (mas->max == ULONG_MAX)
1095 		set_max = true;
1096 
1097 	do {
1098 		p_enode = a_enode;
1099 		a_type = mas_parent_type(mas, p_enode);
1100 		a_node = mte_parent(p_enode);
1101 		a_slot = mte_parent_slot(p_enode);
1102 		a_enode = mt_mk_node(a_node, a_type);
1103 		pivots = ma_pivots(a_node, a_type);
1104 
1105 		if (unlikely(ma_dead_node(a_node)))
1106 			return 1;
1107 
1108 		if (!set_min && a_slot) {
1109 			set_min = true;
1110 			min = pivots[a_slot - 1] + 1;
1111 		}
1112 
1113 		if (!set_max && a_slot < mt_pivots[a_type]) {
1114 			set_max = true;
1115 			max = pivots[a_slot];
1116 		}
1117 
1118 		if (unlikely(ma_dead_node(a_node)))
1119 			return 1;
1120 
1121 		if (unlikely(ma_is_root(a_node)))
1122 			break;
1123 
1124 	} while (!set_min || !set_max);
1125 
1126 	mas->max = max;
1127 	mas->min = min;
1128 	return 0;
1129 }
1130 
1131 /*
1132  * mas_pop_node() - Get a previously allocated maple node from the maple state.
1133  * @mas: The maple state
1134  *
1135  * Return: A pointer to a maple node.
1136  */
1137 static inline struct maple_node *mas_pop_node(struct ma_state *mas)
1138 {
1139 	struct maple_alloc *ret, *node = mas->alloc;
1140 	unsigned long total = mas_allocated(mas);
1141 	unsigned int req = mas_alloc_req(mas);
1142 
1143 	/* nothing or a request pending. */
1144 	if (WARN_ON(!total))
1145 		return NULL;
1146 
1147 	if (total == 1) {
1148 		/* single allocation in this ma_state */
1149 		mas->alloc = NULL;
1150 		ret = node;
1151 		goto single_node;
1152 	}
1153 
1154 	if (node->node_count == 1) {
1155 		/* Single allocation in this node. */
1156 		mas->alloc = node->slot[0];
1157 		mas->alloc->total = node->total - 1;
1158 		ret = node;
1159 		goto new_head;
1160 	}
1161 	node->total--;
1162 	ret = node->slot[--node->node_count];
1163 	node->slot[node->node_count] = NULL;
1164 
1165 single_node:
1166 new_head:
1167 	if (req) {
1168 		req++;
1169 		mas_set_alloc_req(mas, req);
1170 	}
1171 
1172 	memset(ret, 0, sizeof(*ret));
1173 	return (struct maple_node *)ret;
1174 }
1175 
1176 /*
1177  * mas_push_node() - Push a node back on the maple state allocation.
1178  * @mas: The maple state
1179  * @used: The used maple node
1180  *
1181  * Stores the maple node back into @mas->alloc for reuse.  Updates allocated and
1182  * requested node count as necessary.
1183  */
1184 static inline void mas_push_node(struct ma_state *mas, struct maple_node *used)
1185 {
1186 	struct maple_alloc *reuse = (struct maple_alloc *)used;
1187 	struct maple_alloc *head = mas->alloc;
1188 	unsigned long count;
1189 	unsigned int requested = mas_alloc_req(mas);
1190 
1191 	count = mas_allocated(mas);
1192 
1193 	reuse->request_count = 0;
1194 	reuse->node_count = 0;
1195 	if (count && (head->node_count < MAPLE_ALLOC_SLOTS)) {
1196 		head->slot[head->node_count++] = reuse;
1197 		head->total++;
1198 		goto done;
1199 	}
1200 
1201 	reuse->total = 1;
1202 	if ((head) && !((unsigned long)head & 0x1)) {
1203 		reuse->slot[0] = head;
1204 		reuse->node_count = 1;
1205 		reuse->total += head->total;
1206 	}
1207 
1208 	mas->alloc = reuse;
1209 done:
1210 	if (requested > 1)
1211 		mas_set_alloc_req(mas, requested - 1);
1212 }
1213 
1214 /*
1215  * mas_alloc_nodes() - Allocate nodes into a maple state
1216  * @mas: The maple state
1217  * @gfp: The GFP Flags
1218  */
1219 static inline void mas_alloc_nodes(struct ma_state *mas, gfp_t gfp)
1220 {
1221 	struct maple_alloc *node;
1222 	unsigned long allocated = mas_allocated(mas);
1223 	unsigned int requested = mas_alloc_req(mas);
1224 	unsigned int count;
1225 	void **slots = NULL;
1226 	unsigned int max_req = 0;
1227 
1228 	if (!requested)
1229 		return;
1230 
1231 	mas_set_alloc_req(mas, 0);
1232 	if (mas->mas_flags & MA_STATE_PREALLOC) {
1233 		if (allocated)
1234 			return;
1235 		BUG_ON(!allocated);
1236 		WARN_ON(!allocated);
1237 	}
1238 
1239 	if (!allocated || mas->alloc->node_count == MAPLE_ALLOC_SLOTS) {
1240 		node = (struct maple_alloc *)mt_alloc_one(gfp);
1241 		if (!node)
1242 			goto nomem_one;
1243 
1244 		if (allocated) {
1245 			node->slot[0] = mas->alloc;
1246 			node->node_count = 1;
1247 		} else {
1248 			node->node_count = 0;
1249 		}
1250 
1251 		mas->alloc = node;
1252 		node->total = ++allocated;
1253 		requested--;
1254 	}
1255 
1256 	node = mas->alloc;
1257 	node->request_count = 0;
1258 	while (requested) {
1259 		max_req = MAPLE_ALLOC_SLOTS - node->node_count;
1260 		slots = (void **)&node->slot[node->node_count];
1261 		max_req = min(requested, max_req);
1262 		count = mt_alloc_bulk(gfp, max_req, slots);
1263 		if (!count)
1264 			goto nomem_bulk;
1265 
1266 		if (node->node_count == 0) {
1267 			node->slot[0]->node_count = 0;
1268 			node->slot[0]->request_count = 0;
1269 		}
1270 
1271 		node->node_count += count;
1272 		allocated += count;
1273 		node = node->slot[0];
1274 		requested -= count;
1275 	}
1276 	mas->alloc->total = allocated;
1277 	return;
1278 
1279 nomem_bulk:
1280 	/* Clean up potential freed allocations on bulk failure */
1281 	memset(slots, 0, max_req * sizeof(unsigned long));
1282 nomem_one:
1283 	mas_set_alloc_req(mas, requested);
1284 	if (mas->alloc && !(((unsigned long)mas->alloc & 0x1)))
1285 		mas->alloc->total = allocated;
1286 	mas_set_err(mas, -ENOMEM);
1287 }
1288 
1289 /*
1290  * mas_free() - Free an encoded maple node
1291  * @mas: The maple state
1292  * @used: The encoded maple node to free.
1293  *
1294  * Uses rcu free if necessary, pushes @used back on the maple state allocations
1295  * otherwise.
1296  */
1297 static inline void mas_free(struct ma_state *mas, struct maple_enode *used)
1298 {
1299 	struct maple_node *tmp = mte_to_node(used);
1300 
1301 	if (mt_in_rcu(mas->tree))
1302 		ma_free_rcu(tmp);
1303 	else
1304 		mas_push_node(mas, tmp);
1305 }
1306 
1307 /*
1308  * mas_node_count_gfp() - Check if enough nodes are allocated and request more
1309  * if there is not enough nodes.
1310  * @mas: The maple state
1311  * @count: The number of nodes needed
1312  * @gfp: the gfp flags
1313  */
1314 static void mas_node_count_gfp(struct ma_state *mas, int count, gfp_t gfp)
1315 {
1316 	unsigned long allocated = mas_allocated(mas);
1317 
1318 	if (allocated < count) {
1319 		mas_set_alloc_req(mas, count - allocated);
1320 		mas_alloc_nodes(mas, gfp);
1321 	}
1322 }
1323 
1324 /*
1325  * mas_node_count() - Check if enough nodes are allocated and request more if
1326  * there is not enough nodes.
1327  * @mas: The maple state
1328  * @count: The number of nodes needed
1329  *
1330  * Note: Uses GFP_NOWAIT | __GFP_NOWARN for gfp flags.
1331  */
1332 static void mas_node_count(struct ma_state *mas, int count)
1333 {
1334 	return mas_node_count_gfp(mas, count, GFP_NOWAIT | __GFP_NOWARN);
1335 }
1336 
1337 /*
1338  * mas_start() - Sets up maple state for operations.
1339  * @mas: The maple state.
1340  *
1341  * If mas->status == mas_start, then set the min, max and depth to
1342  * defaults.
1343  *
1344  * Return:
1345  * - If mas->node is an error or not mas_start, return NULL.
1346  * - If it's an empty tree:     NULL & mas->status == ma_none
1347  * - If it's a single entry:    The entry & mas->status == ma_root
1348  * - If it's a tree:            NULL & mas->status == ma_active
1349  */
1350 static inline struct maple_enode *mas_start(struct ma_state *mas)
1351 {
1352 	if (likely(mas_is_start(mas))) {
1353 		struct maple_enode *root;
1354 
1355 		mas->min = 0;
1356 		mas->max = ULONG_MAX;
1357 
1358 retry:
1359 		mas->depth = 0;
1360 		root = mas_root(mas);
1361 		/* Tree with nodes */
1362 		if (likely(xa_is_node(root))) {
1363 			mas->depth = 1;
1364 			mas->status = ma_active;
1365 			mas->node = mte_safe_root(root);
1366 			mas->offset = 0;
1367 			if (mte_dead_node(mas->node))
1368 				goto retry;
1369 
1370 			return NULL;
1371 		}
1372 
1373 		mas->node = NULL;
1374 		/* empty tree */
1375 		if (unlikely(!root)) {
1376 			mas->status = ma_none;
1377 			mas->offset = MAPLE_NODE_SLOTS;
1378 			return NULL;
1379 		}
1380 
1381 		/* Single entry tree */
1382 		mas->status = ma_root;
1383 		mas->offset = MAPLE_NODE_SLOTS;
1384 
1385 		/* Single entry tree. */
1386 		if (mas->index > 0)
1387 			return NULL;
1388 
1389 		return root;
1390 	}
1391 
1392 	return NULL;
1393 }
1394 
1395 /*
1396  * ma_data_end() - Find the end of the data in a node.
1397  * @node: The maple node
1398  * @type: The maple node type
1399  * @pivots: The array of pivots in the node
1400  * @max: The maximum value in the node
1401  *
1402  * Uses metadata to find the end of the data when possible.
1403  * Return: The zero indexed last slot with data (may be null).
1404  */
1405 static __always_inline unsigned char ma_data_end(struct maple_node *node,
1406 		enum maple_type type, unsigned long *pivots, unsigned long max)
1407 {
1408 	unsigned char offset;
1409 
1410 	if (!pivots)
1411 		return 0;
1412 
1413 	if (type == maple_arange_64)
1414 		return ma_meta_end(node, type);
1415 
1416 	offset = mt_pivots[type] - 1;
1417 	if (likely(!pivots[offset]))
1418 		return ma_meta_end(node, type);
1419 
1420 	if (likely(pivots[offset] == max))
1421 		return offset;
1422 
1423 	return mt_pivots[type];
1424 }
1425 
1426 /*
1427  * mas_data_end() - Find the end of the data (slot).
1428  * @mas: the maple state
1429  *
1430  * This method is optimized to check the metadata of a node if the node type
1431  * supports data end metadata.
1432  *
1433  * Return: The zero indexed last slot with data (may be null).
1434  */
1435 static inline unsigned char mas_data_end(struct ma_state *mas)
1436 {
1437 	enum maple_type type;
1438 	struct maple_node *node;
1439 	unsigned char offset;
1440 	unsigned long *pivots;
1441 
1442 	type = mte_node_type(mas->node);
1443 	node = mas_mn(mas);
1444 	if (type == maple_arange_64)
1445 		return ma_meta_end(node, type);
1446 
1447 	pivots = ma_pivots(node, type);
1448 	if (unlikely(ma_dead_node(node)))
1449 		return 0;
1450 
1451 	offset = mt_pivots[type] - 1;
1452 	if (likely(!pivots[offset]))
1453 		return ma_meta_end(node, type);
1454 
1455 	if (likely(pivots[offset] == mas->max))
1456 		return offset;
1457 
1458 	return mt_pivots[type];
1459 }
1460 
1461 /*
1462  * mas_leaf_max_gap() - Returns the largest gap in a leaf node
1463  * @mas: the maple state
1464  *
1465  * Return: The maximum gap in the leaf.
1466  */
1467 static unsigned long mas_leaf_max_gap(struct ma_state *mas)
1468 {
1469 	enum maple_type mt;
1470 	unsigned long pstart, gap, max_gap;
1471 	struct maple_node *mn;
1472 	unsigned long *pivots;
1473 	void __rcu **slots;
1474 	unsigned char i;
1475 	unsigned char max_piv;
1476 
1477 	mt = mte_node_type(mas->node);
1478 	mn = mas_mn(mas);
1479 	slots = ma_slots(mn, mt);
1480 	max_gap = 0;
1481 	if (unlikely(ma_is_dense(mt))) {
1482 		gap = 0;
1483 		for (i = 0; i < mt_slots[mt]; i++) {
1484 			if (slots[i]) {
1485 				if (gap > max_gap)
1486 					max_gap = gap;
1487 				gap = 0;
1488 			} else {
1489 				gap++;
1490 			}
1491 		}
1492 		if (gap > max_gap)
1493 			max_gap = gap;
1494 		return max_gap;
1495 	}
1496 
1497 	/*
1498 	 * Check the first implied pivot optimizes the loop below and slot 1 may
1499 	 * be skipped if there is a gap in slot 0.
1500 	 */
1501 	pivots = ma_pivots(mn, mt);
1502 	if (likely(!slots[0])) {
1503 		max_gap = pivots[0] - mas->min + 1;
1504 		i = 2;
1505 	} else {
1506 		i = 1;
1507 	}
1508 
1509 	/* reduce max_piv as the special case is checked before the loop */
1510 	max_piv = ma_data_end(mn, mt, pivots, mas->max) - 1;
1511 	/*
1512 	 * Check end implied pivot which can only be a gap on the right most
1513 	 * node.
1514 	 */
1515 	if (unlikely(mas->max == ULONG_MAX) && !slots[max_piv + 1]) {
1516 		gap = ULONG_MAX - pivots[max_piv];
1517 		if (gap > max_gap)
1518 			max_gap = gap;
1519 
1520 		if (max_gap > pivots[max_piv] - mas->min)
1521 			return max_gap;
1522 	}
1523 
1524 	for (; i <= max_piv; i++) {
1525 		/* data == no gap. */
1526 		if (likely(slots[i]))
1527 			continue;
1528 
1529 		pstart = pivots[i - 1];
1530 		gap = pivots[i] - pstart;
1531 		if (gap > max_gap)
1532 			max_gap = gap;
1533 
1534 		/* There cannot be two gaps in a row. */
1535 		i++;
1536 	}
1537 	return max_gap;
1538 }
1539 
1540 /*
1541  * ma_max_gap() - Get the maximum gap in a maple node (non-leaf)
1542  * @node: The maple node
1543  * @gaps: The pointer to the gaps
1544  * @mt: The maple node type
1545  * @off: Pointer to store the offset location of the gap.
1546  *
1547  * Uses the metadata data end to scan backwards across set gaps.
1548  *
1549  * Return: The maximum gap value
1550  */
1551 static inline unsigned long
1552 ma_max_gap(struct maple_node *node, unsigned long *gaps, enum maple_type mt,
1553 	    unsigned char *off)
1554 {
1555 	unsigned char offset, i;
1556 	unsigned long max_gap = 0;
1557 
1558 	i = offset = ma_meta_end(node, mt);
1559 	do {
1560 		if (gaps[i] > max_gap) {
1561 			max_gap = gaps[i];
1562 			offset = i;
1563 		}
1564 	} while (i--);
1565 
1566 	*off = offset;
1567 	return max_gap;
1568 }
1569 
1570 /*
1571  * mas_max_gap() - find the largest gap in a non-leaf node and set the slot.
1572  * @mas: The maple state.
1573  *
1574  * Return: The gap value.
1575  */
1576 static inline unsigned long mas_max_gap(struct ma_state *mas)
1577 {
1578 	unsigned long *gaps;
1579 	unsigned char offset;
1580 	enum maple_type mt;
1581 	struct maple_node *node;
1582 
1583 	mt = mte_node_type(mas->node);
1584 	if (ma_is_leaf(mt))
1585 		return mas_leaf_max_gap(mas);
1586 
1587 	node = mas_mn(mas);
1588 	MAS_BUG_ON(mas, mt != maple_arange_64);
1589 	offset = ma_meta_gap(node);
1590 	gaps = ma_gaps(node, mt);
1591 	return gaps[offset];
1592 }
1593 
1594 /*
1595  * mas_parent_gap() - Set the parent gap and any gaps above, as needed
1596  * @mas: The maple state
1597  * @offset: The gap offset in the parent to set
1598  * @new: The new gap value.
1599  *
1600  * Set the parent gap then continue to set the gap upwards, using the metadata
1601  * of the parent to see if it is necessary to check the node above.
1602  */
1603 static inline void mas_parent_gap(struct ma_state *mas, unsigned char offset,
1604 		unsigned long new)
1605 {
1606 	unsigned long meta_gap = 0;
1607 	struct maple_node *pnode;
1608 	struct maple_enode *penode;
1609 	unsigned long *pgaps;
1610 	unsigned char meta_offset;
1611 	enum maple_type pmt;
1612 
1613 	pnode = mte_parent(mas->node);
1614 	pmt = mas_parent_type(mas, mas->node);
1615 	penode = mt_mk_node(pnode, pmt);
1616 	pgaps = ma_gaps(pnode, pmt);
1617 
1618 ascend:
1619 	MAS_BUG_ON(mas, pmt != maple_arange_64);
1620 	meta_offset = ma_meta_gap(pnode);
1621 	meta_gap = pgaps[meta_offset];
1622 
1623 	pgaps[offset] = new;
1624 
1625 	if (meta_gap == new)
1626 		return;
1627 
1628 	if (offset != meta_offset) {
1629 		if (meta_gap > new)
1630 			return;
1631 
1632 		ma_set_meta_gap(pnode, pmt, offset);
1633 	} else if (new < meta_gap) {
1634 		new = ma_max_gap(pnode, pgaps, pmt, &meta_offset);
1635 		ma_set_meta_gap(pnode, pmt, meta_offset);
1636 	}
1637 
1638 	if (ma_is_root(pnode))
1639 		return;
1640 
1641 	/* Go to the parent node. */
1642 	pnode = mte_parent(penode);
1643 	pmt = mas_parent_type(mas, penode);
1644 	pgaps = ma_gaps(pnode, pmt);
1645 	offset = mte_parent_slot(penode);
1646 	penode = mt_mk_node(pnode, pmt);
1647 	goto ascend;
1648 }
1649 
1650 /*
1651  * mas_update_gap() - Update a nodes gaps and propagate up if necessary.
1652  * @mas: the maple state.
1653  */
1654 static inline void mas_update_gap(struct ma_state *mas)
1655 {
1656 	unsigned char pslot;
1657 	unsigned long p_gap;
1658 	unsigned long max_gap;
1659 
1660 	if (!mt_is_alloc(mas->tree))
1661 		return;
1662 
1663 	if (mte_is_root(mas->node))
1664 		return;
1665 
1666 	max_gap = mas_max_gap(mas);
1667 
1668 	pslot = mte_parent_slot(mas->node);
1669 	p_gap = ma_gaps(mte_parent(mas->node),
1670 			mas_parent_type(mas, mas->node))[pslot];
1671 
1672 	if (p_gap != max_gap)
1673 		mas_parent_gap(mas, pslot, max_gap);
1674 }
1675 
1676 /*
1677  * mas_adopt_children() - Set the parent pointer of all nodes in @parent to
1678  * @parent with the slot encoded.
1679  * @mas: the maple state (for the tree)
1680  * @parent: the maple encoded node containing the children.
1681  */
1682 static inline void mas_adopt_children(struct ma_state *mas,
1683 		struct maple_enode *parent)
1684 {
1685 	enum maple_type type = mte_node_type(parent);
1686 	struct maple_node *node = mte_to_node(parent);
1687 	void __rcu **slots = ma_slots(node, type);
1688 	unsigned long *pivots = ma_pivots(node, type);
1689 	struct maple_enode *child;
1690 	unsigned char offset;
1691 
1692 	offset = ma_data_end(node, type, pivots, mas->max);
1693 	do {
1694 		child = mas_slot_locked(mas, slots, offset);
1695 		mas_set_parent(mas, child, parent, offset);
1696 	} while (offset--);
1697 }
1698 
1699 /*
1700  * mas_put_in_tree() - Put a new node in the tree, smp_wmb(), and mark the old
1701  * node as dead.
1702  * @mas: the maple state with the new node
1703  * @old_enode: The old maple encoded node to replace.
1704  */
1705 static inline void mas_put_in_tree(struct ma_state *mas,
1706 		struct maple_enode *old_enode)
1707 	__must_hold(mas->tree->ma_lock)
1708 {
1709 	unsigned char offset;
1710 	void __rcu **slots;
1711 
1712 	if (mte_is_root(mas->node)) {
1713 		mas_mn(mas)->parent = ma_parent_ptr(mas_tree_parent(mas));
1714 		rcu_assign_pointer(mas->tree->ma_root, mte_mk_root(mas->node));
1715 		mas_set_height(mas);
1716 	} else {
1717 
1718 		offset = mte_parent_slot(mas->node);
1719 		slots = ma_slots(mte_parent(mas->node),
1720 				 mas_parent_type(mas, mas->node));
1721 		rcu_assign_pointer(slots[offset], mas->node);
1722 	}
1723 
1724 	mte_set_node_dead(old_enode);
1725 }
1726 
1727 /*
1728  * mas_replace_node() - Replace a node by putting it in the tree, marking it
1729  * dead, and freeing it.
1730  * the parent encoding to locate the maple node in the tree.
1731  * @mas: the ma_state with @mas->node pointing to the new node.
1732  * @old_enode: The old maple encoded node.
1733  */
1734 static inline void mas_replace_node(struct ma_state *mas,
1735 		struct maple_enode *old_enode)
1736 	__must_hold(mas->tree->ma_lock)
1737 {
1738 	mas_put_in_tree(mas, old_enode);
1739 	mas_free(mas, old_enode);
1740 }
1741 
1742 /*
1743  * mas_find_child() - Find a child who has the parent @mas->node.
1744  * @mas: the maple state with the parent.
1745  * @child: the maple state to store the child.
1746  */
1747 static inline bool mas_find_child(struct ma_state *mas, struct ma_state *child)
1748 	__must_hold(mas->tree->ma_lock)
1749 {
1750 	enum maple_type mt;
1751 	unsigned char offset;
1752 	unsigned char end;
1753 	unsigned long *pivots;
1754 	struct maple_enode *entry;
1755 	struct maple_node *node;
1756 	void __rcu **slots;
1757 
1758 	mt = mte_node_type(mas->node);
1759 	node = mas_mn(mas);
1760 	slots = ma_slots(node, mt);
1761 	pivots = ma_pivots(node, mt);
1762 	end = ma_data_end(node, mt, pivots, mas->max);
1763 	for (offset = mas->offset; offset <= end; offset++) {
1764 		entry = mas_slot_locked(mas, slots, offset);
1765 		if (mte_parent(entry) == node) {
1766 			*child = *mas;
1767 			mas->offset = offset + 1;
1768 			child->offset = offset;
1769 			mas_descend(child);
1770 			child->offset = 0;
1771 			return true;
1772 		}
1773 	}
1774 	return false;
1775 }
1776 
1777 /*
1778  * mab_shift_right() - Shift the data in mab right. Note, does not clean out the
1779  * old data or set b_node->b_end.
1780  * @b_node: the maple_big_node
1781  * @shift: the shift count
1782  */
1783 static inline void mab_shift_right(struct maple_big_node *b_node,
1784 				 unsigned char shift)
1785 {
1786 	unsigned long size = b_node->b_end * sizeof(unsigned long);
1787 
1788 	memmove(b_node->pivot + shift, b_node->pivot, size);
1789 	memmove(b_node->slot + shift, b_node->slot, size);
1790 	if (b_node->type == maple_arange_64)
1791 		memmove(b_node->gap + shift, b_node->gap, size);
1792 }
1793 
1794 /*
1795  * mab_middle_node() - Check if a middle node is needed (unlikely)
1796  * @b_node: the maple_big_node that contains the data.
1797  * @split: the potential split location
1798  * @slot_count: the size that can be stored in a single node being considered.
1799  *
1800  * Return: true if a middle node is required.
1801  */
1802 static inline bool mab_middle_node(struct maple_big_node *b_node, int split,
1803 				   unsigned char slot_count)
1804 {
1805 	unsigned char size = b_node->b_end;
1806 
1807 	if (size >= 2 * slot_count)
1808 		return true;
1809 
1810 	if (!b_node->slot[split] && (size >= 2 * slot_count - 1))
1811 		return true;
1812 
1813 	return false;
1814 }
1815 
1816 /*
1817  * mab_no_null_split() - ensure the split doesn't fall on a NULL
1818  * @b_node: the maple_big_node with the data
1819  * @split: the suggested split location
1820  * @slot_count: the number of slots in the node being considered.
1821  *
1822  * Return: the split location.
1823  */
1824 static inline int mab_no_null_split(struct maple_big_node *b_node,
1825 				    unsigned char split, unsigned char slot_count)
1826 {
1827 	if (!b_node->slot[split]) {
1828 		/*
1829 		 * If the split is less than the max slot && the right side will
1830 		 * still be sufficient, then increment the split on NULL.
1831 		 */
1832 		if ((split < slot_count - 1) &&
1833 		    (b_node->b_end - split) > (mt_min_slots[b_node->type]))
1834 			split++;
1835 		else
1836 			split--;
1837 	}
1838 	return split;
1839 }
1840 
1841 /*
1842  * mab_calc_split() - Calculate the split location and if there needs to be two
1843  * splits.
1844  * @mas: The maple state
1845  * @bn: The maple_big_node with the data
1846  * @mid_split: The second split, if required.  0 otherwise.
1847  *
1848  * Return: The first split location.  The middle split is set in @mid_split.
1849  */
1850 static inline int mab_calc_split(struct ma_state *mas,
1851 	 struct maple_big_node *bn, unsigned char *mid_split, unsigned long min)
1852 {
1853 	unsigned char b_end = bn->b_end;
1854 	int split = b_end / 2; /* Assume equal split. */
1855 	unsigned char slot_min, slot_count = mt_slots[bn->type];
1856 
1857 	/*
1858 	 * To support gap tracking, all NULL entries are kept together and a node cannot
1859 	 * end on a NULL entry, with the exception of the left-most leaf.  The
1860 	 * limitation means that the split of a node must be checked for this condition
1861 	 * and be able to put more data in one direction or the other.
1862 	 */
1863 	if (unlikely((mas->mas_flags & MA_STATE_BULK))) {
1864 		*mid_split = 0;
1865 		split = b_end - mt_min_slots[bn->type];
1866 
1867 		if (!ma_is_leaf(bn->type))
1868 			return split;
1869 
1870 		mas->mas_flags |= MA_STATE_REBALANCE;
1871 		if (!bn->slot[split])
1872 			split--;
1873 		return split;
1874 	}
1875 
1876 	/*
1877 	 * Although extremely rare, it is possible to enter what is known as the 3-way
1878 	 * split scenario.  The 3-way split comes about by means of a store of a range
1879 	 * that overwrites the end and beginning of two full nodes.  The result is a set
1880 	 * of entries that cannot be stored in 2 nodes.  Sometimes, these two nodes can
1881 	 * also be located in different parent nodes which are also full.  This can
1882 	 * carry upwards all the way to the root in the worst case.
1883 	 */
1884 	if (unlikely(mab_middle_node(bn, split, slot_count))) {
1885 		split = b_end / 3;
1886 		*mid_split = split * 2;
1887 	} else {
1888 		slot_min = mt_min_slots[bn->type];
1889 
1890 		*mid_split = 0;
1891 		/*
1892 		 * Avoid having a range less than the slot count unless it
1893 		 * causes one node to be deficient.
1894 		 * NOTE: mt_min_slots is 1 based, b_end and split are zero.
1895 		 */
1896 		while ((split < slot_count - 1) &&
1897 		       ((bn->pivot[split] - min) < slot_count - 1) &&
1898 		       (b_end - split > slot_min))
1899 			split++;
1900 	}
1901 
1902 	/* Avoid ending a node on a NULL entry */
1903 	split = mab_no_null_split(bn, split, slot_count);
1904 
1905 	if (unlikely(*mid_split))
1906 		*mid_split = mab_no_null_split(bn, *mid_split, slot_count);
1907 
1908 	return split;
1909 }
1910 
1911 /*
1912  * mas_mab_cp() - Copy data from a maple state inclusively to a maple_big_node
1913  * and set @b_node->b_end to the next free slot.
1914  * @mas: The maple state
1915  * @mas_start: The starting slot to copy
1916  * @mas_end: The end slot to copy (inclusively)
1917  * @b_node: The maple_big_node to place the data
1918  * @mab_start: The starting location in maple_big_node to store the data.
1919  */
1920 static inline void mas_mab_cp(struct ma_state *mas, unsigned char mas_start,
1921 			unsigned char mas_end, struct maple_big_node *b_node,
1922 			unsigned char mab_start)
1923 {
1924 	enum maple_type mt;
1925 	struct maple_node *node;
1926 	void __rcu **slots;
1927 	unsigned long *pivots, *gaps;
1928 	int i = mas_start, j = mab_start;
1929 	unsigned char piv_end;
1930 
1931 	node = mas_mn(mas);
1932 	mt = mte_node_type(mas->node);
1933 	pivots = ma_pivots(node, mt);
1934 	if (!i) {
1935 		b_node->pivot[j] = pivots[i++];
1936 		if (unlikely(i > mas_end))
1937 			goto complete;
1938 		j++;
1939 	}
1940 
1941 	piv_end = min(mas_end, mt_pivots[mt]);
1942 	for (; i < piv_end; i++, j++) {
1943 		b_node->pivot[j] = pivots[i];
1944 		if (unlikely(!b_node->pivot[j]))
1945 			goto complete;
1946 
1947 		if (unlikely(mas->max == b_node->pivot[j]))
1948 			goto complete;
1949 	}
1950 
1951 	b_node->pivot[j] = mas_safe_pivot(mas, pivots, i, mt);
1952 
1953 complete:
1954 	b_node->b_end = ++j;
1955 	j -= mab_start;
1956 	slots = ma_slots(node, mt);
1957 	memcpy(b_node->slot + mab_start, slots + mas_start, sizeof(void *) * j);
1958 	if (!ma_is_leaf(mt) && mt_is_alloc(mas->tree)) {
1959 		gaps = ma_gaps(node, mt);
1960 		memcpy(b_node->gap + mab_start, gaps + mas_start,
1961 		       sizeof(unsigned long) * j);
1962 	}
1963 }
1964 
1965 /*
1966  * mas_leaf_set_meta() - Set the metadata of a leaf if possible.
1967  * @node: The maple node
1968  * @mt: The maple type
1969  * @end: The node end
1970  */
1971 static inline void mas_leaf_set_meta(struct maple_node *node,
1972 		enum maple_type mt, unsigned char end)
1973 {
1974 	if (end < mt_slots[mt] - 1)
1975 		ma_set_meta(node, mt, 0, end);
1976 }
1977 
1978 /*
1979  * mab_mas_cp() - Copy data from maple_big_node to a maple encoded node.
1980  * @b_node: the maple_big_node that has the data
1981  * @mab_start: the start location in @b_node.
1982  * @mab_end: The end location in @b_node (inclusively)
1983  * @mas: The maple state with the maple encoded node.
1984  */
1985 static inline void mab_mas_cp(struct maple_big_node *b_node,
1986 			      unsigned char mab_start, unsigned char mab_end,
1987 			      struct ma_state *mas, bool new_max)
1988 {
1989 	int i, j = 0;
1990 	enum maple_type mt = mte_node_type(mas->node);
1991 	struct maple_node *node = mte_to_node(mas->node);
1992 	void __rcu **slots = ma_slots(node, mt);
1993 	unsigned long *pivots = ma_pivots(node, mt);
1994 	unsigned long *gaps = NULL;
1995 	unsigned char end;
1996 
1997 	if (mab_end - mab_start > mt_pivots[mt])
1998 		mab_end--;
1999 
2000 	if (!pivots[mt_pivots[mt] - 1])
2001 		slots[mt_pivots[mt]] = NULL;
2002 
2003 	i = mab_start;
2004 	do {
2005 		pivots[j++] = b_node->pivot[i++];
2006 	} while (i <= mab_end && likely(b_node->pivot[i]));
2007 
2008 	memcpy(slots, b_node->slot + mab_start,
2009 	       sizeof(void *) * (i - mab_start));
2010 
2011 	if (new_max)
2012 		mas->max = b_node->pivot[i - 1];
2013 
2014 	end = j - 1;
2015 	if (likely(!ma_is_leaf(mt) && mt_is_alloc(mas->tree))) {
2016 		unsigned long max_gap = 0;
2017 		unsigned char offset = 0;
2018 
2019 		gaps = ma_gaps(node, mt);
2020 		do {
2021 			gaps[--j] = b_node->gap[--i];
2022 			if (gaps[j] > max_gap) {
2023 				offset = j;
2024 				max_gap = gaps[j];
2025 			}
2026 		} while (j);
2027 
2028 		ma_set_meta(node, mt, offset, end);
2029 	} else {
2030 		mas_leaf_set_meta(node, mt, end);
2031 	}
2032 }
2033 
2034 /*
2035  * mas_bulk_rebalance() - Rebalance the end of a tree after a bulk insert.
2036  * @mas: The maple state
2037  * @end: The maple node end
2038  * @mt: The maple node type
2039  */
2040 static inline void mas_bulk_rebalance(struct ma_state *mas, unsigned char end,
2041 				      enum maple_type mt)
2042 {
2043 	if (!(mas->mas_flags & MA_STATE_BULK))
2044 		return;
2045 
2046 	if (mte_is_root(mas->node))
2047 		return;
2048 
2049 	if (end > mt_min_slots[mt]) {
2050 		mas->mas_flags &= ~MA_STATE_REBALANCE;
2051 		return;
2052 	}
2053 }
2054 
2055 /*
2056  * mas_store_b_node() - Store an @entry into the b_node while also copying the
2057  * data from a maple encoded node.
2058  * @wr_mas: the maple write state
2059  * @b_node: the maple_big_node to fill with data
2060  * @offset_end: the offset to end copying
2061  *
2062  * Return: The actual end of the data stored in @b_node
2063  */
2064 static noinline_for_kasan void mas_store_b_node(struct ma_wr_state *wr_mas,
2065 		struct maple_big_node *b_node, unsigned char offset_end)
2066 {
2067 	unsigned char slot;
2068 	unsigned char b_end;
2069 	/* Possible underflow of piv will wrap back to 0 before use. */
2070 	unsigned long piv;
2071 	struct ma_state *mas = wr_mas->mas;
2072 
2073 	b_node->type = wr_mas->type;
2074 	b_end = 0;
2075 	slot = mas->offset;
2076 	if (slot) {
2077 		/* Copy start data up to insert. */
2078 		mas_mab_cp(mas, 0, slot - 1, b_node, 0);
2079 		b_end = b_node->b_end;
2080 		piv = b_node->pivot[b_end - 1];
2081 	} else
2082 		piv = mas->min - 1;
2083 
2084 	if (piv + 1 < mas->index) {
2085 		/* Handle range starting after old range */
2086 		b_node->slot[b_end] = wr_mas->content;
2087 		if (!wr_mas->content)
2088 			b_node->gap[b_end] = mas->index - 1 - piv;
2089 		b_node->pivot[b_end++] = mas->index - 1;
2090 	}
2091 
2092 	/* Store the new entry. */
2093 	mas->offset = b_end;
2094 	b_node->slot[b_end] = wr_mas->entry;
2095 	b_node->pivot[b_end] = mas->last;
2096 
2097 	/* Appended. */
2098 	if (mas->last >= mas->max)
2099 		goto b_end;
2100 
2101 	/* Handle new range ending before old range ends */
2102 	piv = mas_safe_pivot(mas, wr_mas->pivots, offset_end, wr_mas->type);
2103 	if (piv > mas->last) {
2104 		if (piv == ULONG_MAX)
2105 			mas_bulk_rebalance(mas, b_node->b_end, wr_mas->type);
2106 
2107 		if (offset_end != slot)
2108 			wr_mas->content = mas_slot_locked(mas, wr_mas->slots,
2109 							  offset_end);
2110 
2111 		b_node->slot[++b_end] = wr_mas->content;
2112 		if (!wr_mas->content)
2113 			b_node->gap[b_end] = piv - mas->last + 1;
2114 		b_node->pivot[b_end] = piv;
2115 	}
2116 
2117 	slot = offset_end + 1;
2118 	if (slot > mas->end)
2119 		goto b_end;
2120 
2121 	/* Copy end data to the end of the node. */
2122 	mas_mab_cp(mas, slot, mas->end + 1, b_node, ++b_end);
2123 	b_node->b_end--;
2124 	return;
2125 
2126 b_end:
2127 	b_node->b_end = b_end;
2128 }
2129 
2130 /*
2131  * mas_prev_sibling() - Find the previous node with the same parent.
2132  * @mas: the maple state
2133  *
2134  * Return: True if there is a previous sibling, false otherwise.
2135  */
2136 static inline bool mas_prev_sibling(struct ma_state *mas)
2137 {
2138 	unsigned int p_slot = mte_parent_slot(mas->node);
2139 
2140 	if (mte_is_root(mas->node))
2141 		return false;
2142 
2143 	if (!p_slot)
2144 		return false;
2145 
2146 	mas_ascend(mas);
2147 	mas->offset = p_slot - 1;
2148 	mas_descend(mas);
2149 	return true;
2150 }
2151 
2152 /*
2153  * mas_next_sibling() - Find the next node with the same parent.
2154  * @mas: the maple state
2155  *
2156  * Return: true if there is a next sibling, false otherwise.
2157  */
2158 static inline bool mas_next_sibling(struct ma_state *mas)
2159 {
2160 	MA_STATE(parent, mas->tree, mas->index, mas->last);
2161 
2162 	if (mte_is_root(mas->node))
2163 		return false;
2164 
2165 	parent = *mas;
2166 	mas_ascend(&parent);
2167 	parent.offset = mte_parent_slot(mas->node) + 1;
2168 	if (parent.offset > mas_data_end(&parent))
2169 		return false;
2170 
2171 	*mas = parent;
2172 	mas_descend(mas);
2173 	return true;
2174 }
2175 
2176 /*
2177  * mas_node_or_none() - Set the enode and state.
2178  * @mas: the maple state
2179  * @enode: The encoded maple node.
2180  *
2181  * Set the node to the enode and the status.
2182  */
2183 static inline void mas_node_or_none(struct ma_state *mas,
2184 		struct maple_enode *enode)
2185 {
2186 	if (enode) {
2187 		mas->node = enode;
2188 		mas->status = ma_active;
2189 	} else {
2190 		mas->node = NULL;
2191 		mas->status = ma_none;
2192 	}
2193 }
2194 
2195 /*
2196  * mas_wr_node_walk() - Find the correct offset for the index in the @mas.
2197  *                      If @mas->index cannot be found within the containing
2198  *                      node, we traverse to the last entry in the node.
2199  * @wr_mas: The maple write state
2200  *
2201  * Uses mas_slot_locked() and does not need to worry about dead nodes.
2202  */
2203 static inline void mas_wr_node_walk(struct ma_wr_state *wr_mas)
2204 {
2205 	struct ma_state *mas = wr_mas->mas;
2206 	unsigned char count, offset;
2207 
2208 	if (unlikely(ma_is_dense(wr_mas->type))) {
2209 		wr_mas->r_max = wr_mas->r_min = mas->index;
2210 		mas->offset = mas->index = mas->min;
2211 		return;
2212 	}
2213 
2214 	wr_mas->node = mas_mn(wr_mas->mas);
2215 	wr_mas->pivots = ma_pivots(wr_mas->node, wr_mas->type);
2216 	count = mas->end = ma_data_end(wr_mas->node, wr_mas->type,
2217 				       wr_mas->pivots, mas->max);
2218 	offset = mas->offset;
2219 
2220 	while (offset < count && mas->index > wr_mas->pivots[offset])
2221 		offset++;
2222 
2223 	wr_mas->r_max = offset < count ? wr_mas->pivots[offset] : mas->max;
2224 	wr_mas->r_min = mas_safe_min(mas, wr_mas->pivots, offset);
2225 	wr_mas->offset_end = mas->offset = offset;
2226 }
2227 
2228 /*
2229  * mast_rebalance_next() - Rebalance against the next node
2230  * @mast: The maple subtree state
2231  */
2232 static inline void mast_rebalance_next(struct maple_subtree_state *mast)
2233 {
2234 	unsigned char b_end = mast->bn->b_end;
2235 
2236 	mas_mab_cp(mast->orig_r, 0, mt_slot_count(mast->orig_r->node),
2237 		   mast->bn, b_end);
2238 	mast->orig_r->last = mast->orig_r->max;
2239 }
2240 
2241 /*
2242  * mast_rebalance_prev() - Rebalance against the previous node
2243  * @mast: The maple subtree state
2244  */
2245 static inline void mast_rebalance_prev(struct maple_subtree_state *mast)
2246 {
2247 	unsigned char end = mas_data_end(mast->orig_l) + 1;
2248 	unsigned char b_end = mast->bn->b_end;
2249 
2250 	mab_shift_right(mast->bn, end);
2251 	mas_mab_cp(mast->orig_l, 0, end - 1, mast->bn, 0);
2252 	mast->l->min = mast->orig_l->min;
2253 	mast->orig_l->index = mast->orig_l->min;
2254 	mast->bn->b_end = end + b_end;
2255 	mast->l->offset += end;
2256 }
2257 
2258 /*
2259  * mast_spanning_rebalance() - Rebalance nodes with nearest neighbour favouring
2260  * the node to the right.  Checking the nodes to the right then the left at each
2261  * level upwards until root is reached.
2262  * Data is copied into the @mast->bn.
2263  * @mast: The maple_subtree_state.
2264  */
2265 static inline
2266 bool mast_spanning_rebalance(struct maple_subtree_state *mast)
2267 {
2268 	struct ma_state r_tmp = *mast->orig_r;
2269 	struct ma_state l_tmp = *mast->orig_l;
2270 	unsigned char depth = 0;
2271 
2272 	do {
2273 		mas_ascend(mast->orig_r);
2274 		mas_ascend(mast->orig_l);
2275 		depth++;
2276 		if (mast->orig_r->offset < mas_data_end(mast->orig_r)) {
2277 			mast->orig_r->offset++;
2278 			do {
2279 				mas_descend(mast->orig_r);
2280 				mast->orig_r->offset = 0;
2281 			} while (--depth);
2282 
2283 			mast_rebalance_next(mast);
2284 			*mast->orig_l = l_tmp;
2285 			return true;
2286 		} else if (mast->orig_l->offset != 0) {
2287 			mast->orig_l->offset--;
2288 			do {
2289 				mas_descend(mast->orig_l);
2290 				mast->orig_l->offset =
2291 					mas_data_end(mast->orig_l);
2292 			} while (--depth);
2293 
2294 			mast_rebalance_prev(mast);
2295 			*mast->orig_r = r_tmp;
2296 			return true;
2297 		}
2298 	} while (!mte_is_root(mast->orig_r->node));
2299 
2300 	*mast->orig_r = r_tmp;
2301 	*mast->orig_l = l_tmp;
2302 	return false;
2303 }
2304 
2305 /*
2306  * mast_ascend() - Ascend the original left and right maple states.
2307  * @mast: the maple subtree state.
2308  *
2309  * Ascend the original left and right sides.  Set the offsets to point to the
2310  * data already in the new tree (@mast->l and @mast->r).
2311  */
2312 static inline void mast_ascend(struct maple_subtree_state *mast)
2313 {
2314 	MA_WR_STATE(wr_mas, mast->orig_r,  NULL);
2315 	mas_ascend(mast->orig_l);
2316 	mas_ascend(mast->orig_r);
2317 
2318 	mast->orig_r->offset = 0;
2319 	mast->orig_r->index = mast->r->max;
2320 	/* last should be larger than or equal to index */
2321 	if (mast->orig_r->last < mast->orig_r->index)
2322 		mast->orig_r->last = mast->orig_r->index;
2323 
2324 	wr_mas.type = mte_node_type(mast->orig_r->node);
2325 	mas_wr_node_walk(&wr_mas);
2326 	/* Set up the left side of things */
2327 	mast->orig_l->offset = 0;
2328 	mast->orig_l->index = mast->l->min;
2329 	wr_mas.mas = mast->orig_l;
2330 	wr_mas.type = mte_node_type(mast->orig_l->node);
2331 	mas_wr_node_walk(&wr_mas);
2332 
2333 	mast->bn->type = wr_mas.type;
2334 }
2335 
2336 /*
2337  * mas_new_ma_node() - Create and return a new maple node.  Helper function.
2338  * @mas: the maple state with the allocations.
2339  * @b_node: the maple_big_node with the type encoding.
2340  *
2341  * Use the node type from the maple_big_node to allocate a new node from the
2342  * ma_state.  This function exists mainly for code readability.
2343  *
2344  * Return: A new maple encoded node
2345  */
2346 static inline struct maple_enode
2347 *mas_new_ma_node(struct ma_state *mas, struct maple_big_node *b_node)
2348 {
2349 	return mt_mk_node(ma_mnode_ptr(mas_pop_node(mas)), b_node->type);
2350 }
2351 
2352 /*
2353  * mas_mab_to_node() - Set up right and middle nodes
2354  *
2355  * @mas: the maple state that contains the allocations.
2356  * @b_node: the node which contains the data.
2357  * @left: The pointer which will have the left node
2358  * @right: The pointer which may have the right node
2359  * @middle: the pointer which may have the middle node (rare)
2360  * @mid_split: the split location for the middle node
2361  *
2362  * Return: the split of left.
2363  */
2364 static inline unsigned char mas_mab_to_node(struct ma_state *mas,
2365 	struct maple_big_node *b_node, struct maple_enode **left,
2366 	struct maple_enode **right, struct maple_enode **middle,
2367 	unsigned char *mid_split, unsigned long min)
2368 {
2369 	unsigned char split = 0;
2370 	unsigned char slot_count = mt_slots[b_node->type];
2371 
2372 	*left = mas_new_ma_node(mas, b_node);
2373 	*right = NULL;
2374 	*middle = NULL;
2375 	*mid_split = 0;
2376 
2377 	if (b_node->b_end < slot_count) {
2378 		split = b_node->b_end;
2379 	} else {
2380 		split = mab_calc_split(mas, b_node, mid_split, min);
2381 		*right = mas_new_ma_node(mas, b_node);
2382 	}
2383 
2384 	if (*mid_split)
2385 		*middle = mas_new_ma_node(mas, b_node);
2386 
2387 	return split;
2388 
2389 }
2390 
2391 /*
2392  * mab_set_b_end() - Add entry to b_node at b_node->b_end and increment the end
2393  * pointer.
2394  * @b_node: the big node to add the entry
2395  * @mas: the maple state to get the pivot (mas->max)
2396  * @entry: the entry to add, if NULL nothing happens.
2397  */
2398 static inline void mab_set_b_end(struct maple_big_node *b_node,
2399 				 struct ma_state *mas,
2400 				 void *entry)
2401 {
2402 	if (!entry)
2403 		return;
2404 
2405 	b_node->slot[b_node->b_end] = entry;
2406 	if (mt_is_alloc(mas->tree))
2407 		b_node->gap[b_node->b_end] = mas_max_gap(mas);
2408 	b_node->pivot[b_node->b_end++] = mas->max;
2409 }
2410 
2411 /*
2412  * mas_set_split_parent() - combine_then_separate helper function.  Sets the parent
2413  * of @mas->node to either @left or @right, depending on @slot and @split
2414  *
2415  * @mas: the maple state with the node that needs a parent
2416  * @left: possible parent 1
2417  * @right: possible parent 2
2418  * @slot: the slot the mas->node was placed
2419  * @split: the split location between @left and @right
2420  */
2421 static inline void mas_set_split_parent(struct ma_state *mas,
2422 					struct maple_enode *left,
2423 					struct maple_enode *right,
2424 					unsigned char *slot, unsigned char split)
2425 {
2426 	if (mas_is_none(mas))
2427 		return;
2428 
2429 	if ((*slot) <= split)
2430 		mas_set_parent(mas, mas->node, left, *slot);
2431 	else if (right)
2432 		mas_set_parent(mas, mas->node, right, (*slot) - split - 1);
2433 
2434 	(*slot)++;
2435 }
2436 
2437 /*
2438  * mte_mid_split_check() - Check if the next node passes the mid-split
2439  * @l: Pointer to left encoded maple node.
2440  * @m: Pointer to middle encoded maple node.
2441  * @r: Pointer to right encoded maple node.
2442  * @slot: The offset
2443  * @split: The split location.
2444  * @mid_split: The middle split.
2445  */
2446 static inline void mte_mid_split_check(struct maple_enode **l,
2447 				       struct maple_enode **r,
2448 				       struct maple_enode *right,
2449 				       unsigned char slot,
2450 				       unsigned char *split,
2451 				       unsigned char mid_split)
2452 {
2453 	if (*r == right)
2454 		return;
2455 
2456 	if (slot < mid_split)
2457 		return;
2458 
2459 	*l = *r;
2460 	*r = right;
2461 	*split = mid_split;
2462 }
2463 
2464 /*
2465  * mast_set_split_parents() - Helper function to set three nodes parents.  Slot
2466  * is taken from @mast->l.
2467  * @mast: the maple subtree state
2468  * @left: the left node
2469  * @right: the right node
2470  * @split: the split location.
2471  */
2472 static inline void mast_set_split_parents(struct maple_subtree_state *mast,
2473 					  struct maple_enode *left,
2474 					  struct maple_enode *middle,
2475 					  struct maple_enode *right,
2476 					  unsigned char split,
2477 					  unsigned char mid_split)
2478 {
2479 	unsigned char slot;
2480 	struct maple_enode *l = left;
2481 	struct maple_enode *r = right;
2482 
2483 	if (mas_is_none(mast->l))
2484 		return;
2485 
2486 	if (middle)
2487 		r = middle;
2488 
2489 	slot = mast->l->offset;
2490 
2491 	mte_mid_split_check(&l, &r, right, slot, &split, mid_split);
2492 	mas_set_split_parent(mast->l, l, r, &slot, split);
2493 
2494 	mte_mid_split_check(&l, &r, right, slot, &split, mid_split);
2495 	mas_set_split_parent(mast->m, l, r, &slot, split);
2496 
2497 	mte_mid_split_check(&l, &r, right, slot, &split, mid_split);
2498 	mas_set_split_parent(mast->r, l, r, &slot, split);
2499 }
2500 
2501 /*
2502  * mas_topiary_node() - Dispose of a single node
2503  * @mas: The maple state for pushing nodes
2504  * @in_rcu: If the tree is in rcu mode
2505  *
2506  * The node will either be RCU freed or pushed back on the maple state.
2507  */
2508 static inline void mas_topiary_node(struct ma_state *mas,
2509 		struct ma_state *tmp_mas, bool in_rcu)
2510 {
2511 	struct maple_node *tmp;
2512 	struct maple_enode *enode;
2513 
2514 	if (mas_is_none(tmp_mas))
2515 		return;
2516 
2517 	enode = tmp_mas->node;
2518 	tmp = mte_to_node(enode);
2519 	mte_set_node_dead(enode);
2520 	if (in_rcu)
2521 		ma_free_rcu(tmp);
2522 	else
2523 		mas_push_node(mas, tmp);
2524 }
2525 
2526 /*
2527  * mas_topiary_replace() - Replace the data with new data, then repair the
2528  * parent links within the new tree.  Iterate over the dead sub-tree and collect
2529  * the dead subtrees and topiary the nodes that are no longer of use.
2530  *
2531  * The new tree will have up to three children with the correct parent.  Keep
2532  * track of the new entries as they need to be followed to find the next level
2533  * of new entries.
2534  *
2535  * The old tree will have up to three children with the old parent.  Keep track
2536  * of the old entries as they may have more nodes below replaced.  Nodes within
2537  * [index, last] are dead subtrees, others need to be freed and followed.
2538  *
2539  * @mas: The maple state pointing at the new data
2540  * @old_enode: The maple encoded node being replaced
2541  *
2542  */
2543 static inline void mas_topiary_replace(struct ma_state *mas,
2544 		struct maple_enode *old_enode)
2545 {
2546 	struct ma_state tmp[3], tmp_next[3];
2547 	MA_TOPIARY(subtrees, mas->tree);
2548 	bool in_rcu;
2549 	int i, n;
2550 
2551 	/* Place data in tree & then mark node as old */
2552 	mas_put_in_tree(mas, old_enode);
2553 
2554 	/* Update the parent pointers in the tree */
2555 	tmp[0] = *mas;
2556 	tmp[0].offset = 0;
2557 	tmp[1].status = ma_none;
2558 	tmp[2].status = ma_none;
2559 	while (!mte_is_leaf(tmp[0].node)) {
2560 		n = 0;
2561 		for (i = 0; i < 3; i++) {
2562 			if (mas_is_none(&tmp[i]))
2563 				continue;
2564 
2565 			while (n < 3) {
2566 				if (!mas_find_child(&tmp[i], &tmp_next[n]))
2567 					break;
2568 				n++;
2569 			}
2570 
2571 			mas_adopt_children(&tmp[i], tmp[i].node);
2572 		}
2573 
2574 		if (MAS_WARN_ON(mas, n == 0))
2575 			break;
2576 
2577 		while (n < 3)
2578 			tmp_next[n++].status = ma_none;
2579 
2580 		for (i = 0; i < 3; i++)
2581 			tmp[i] = tmp_next[i];
2582 	}
2583 
2584 	/* Collect the old nodes that need to be discarded */
2585 	if (mte_is_leaf(old_enode))
2586 		return mas_free(mas, old_enode);
2587 
2588 	tmp[0] = *mas;
2589 	tmp[0].offset = 0;
2590 	tmp[0].node = old_enode;
2591 	tmp[1].status = ma_none;
2592 	tmp[2].status = ma_none;
2593 	in_rcu = mt_in_rcu(mas->tree);
2594 	do {
2595 		n = 0;
2596 		for (i = 0; i < 3; i++) {
2597 			if (mas_is_none(&tmp[i]))
2598 				continue;
2599 
2600 			while (n < 3) {
2601 				if (!mas_find_child(&tmp[i], &tmp_next[n]))
2602 					break;
2603 
2604 				if ((tmp_next[n].min >= tmp_next->index) &&
2605 				    (tmp_next[n].max <= tmp_next->last)) {
2606 					mat_add(&subtrees, tmp_next[n].node);
2607 					tmp_next[n].status = ma_none;
2608 				} else {
2609 					n++;
2610 				}
2611 			}
2612 		}
2613 
2614 		if (MAS_WARN_ON(mas, n == 0))
2615 			break;
2616 
2617 		while (n < 3)
2618 			tmp_next[n++].status = ma_none;
2619 
2620 		for (i = 0; i < 3; i++) {
2621 			mas_topiary_node(mas, &tmp[i], in_rcu);
2622 			tmp[i] = tmp_next[i];
2623 		}
2624 	} while (!mte_is_leaf(tmp[0].node));
2625 
2626 	for (i = 0; i < 3; i++)
2627 		mas_topiary_node(mas, &tmp[i], in_rcu);
2628 
2629 	mas_mat_destroy(mas, &subtrees);
2630 }
2631 
2632 /*
2633  * mas_wmb_replace() - Write memory barrier and replace
2634  * @mas: The maple state
2635  * @old_enode: The old maple encoded node that is being replaced.
2636  *
2637  * Updates gap as necessary.
2638  */
2639 static inline void mas_wmb_replace(struct ma_state *mas,
2640 		struct maple_enode *old_enode)
2641 {
2642 	/* Insert the new data in the tree */
2643 	mas_topiary_replace(mas, old_enode);
2644 
2645 	if (mte_is_leaf(mas->node))
2646 		return;
2647 
2648 	mas_update_gap(mas);
2649 }
2650 
2651 /*
2652  * mast_cp_to_nodes() - Copy data out to nodes.
2653  * @mast: The maple subtree state
2654  * @left: The left encoded maple node
2655  * @middle: The middle encoded maple node
2656  * @right: The right encoded maple node
2657  * @split: The location to split between left and (middle ? middle : right)
2658  * @mid_split: The location to split between middle and right.
2659  */
2660 static inline void mast_cp_to_nodes(struct maple_subtree_state *mast,
2661 	struct maple_enode *left, struct maple_enode *middle,
2662 	struct maple_enode *right, unsigned char split, unsigned char mid_split)
2663 {
2664 	bool new_lmax = true;
2665 
2666 	mas_node_or_none(mast->l, left);
2667 	mas_node_or_none(mast->m, middle);
2668 	mas_node_or_none(mast->r, right);
2669 
2670 	mast->l->min = mast->orig_l->min;
2671 	if (split == mast->bn->b_end) {
2672 		mast->l->max = mast->orig_r->max;
2673 		new_lmax = false;
2674 	}
2675 
2676 	mab_mas_cp(mast->bn, 0, split, mast->l, new_lmax);
2677 
2678 	if (middle) {
2679 		mab_mas_cp(mast->bn, 1 + split, mid_split, mast->m, true);
2680 		mast->m->min = mast->bn->pivot[split] + 1;
2681 		split = mid_split;
2682 	}
2683 
2684 	mast->r->max = mast->orig_r->max;
2685 	if (right) {
2686 		mab_mas_cp(mast->bn, 1 + split, mast->bn->b_end, mast->r, false);
2687 		mast->r->min = mast->bn->pivot[split] + 1;
2688 	}
2689 }
2690 
2691 /*
2692  * mast_combine_cp_left - Copy in the original left side of the tree into the
2693  * combined data set in the maple subtree state big node.
2694  * @mast: The maple subtree state
2695  */
2696 static inline void mast_combine_cp_left(struct maple_subtree_state *mast)
2697 {
2698 	unsigned char l_slot = mast->orig_l->offset;
2699 
2700 	if (!l_slot)
2701 		return;
2702 
2703 	mas_mab_cp(mast->orig_l, 0, l_slot - 1, mast->bn, 0);
2704 }
2705 
2706 /*
2707  * mast_combine_cp_right: Copy in the original right side of the tree into the
2708  * combined data set in the maple subtree state big node.
2709  * @mast: The maple subtree state
2710  */
2711 static inline void mast_combine_cp_right(struct maple_subtree_state *mast)
2712 {
2713 	if (mast->bn->pivot[mast->bn->b_end - 1] >= mast->orig_r->max)
2714 		return;
2715 
2716 	mas_mab_cp(mast->orig_r, mast->orig_r->offset + 1,
2717 		   mt_slot_count(mast->orig_r->node), mast->bn,
2718 		   mast->bn->b_end);
2719 	mast->orig_r->last = mast->orig_r->max;
2720 }
2721 
2722 /*
2723  * mast_sufficient: Check if the maple subtree state has enough data in the big
2724  * node to create at least one sufficient node
2725  * @mast: the maple subtree state
2726  */
2727 static inline bool mast_sufficient(struct maple_subtree_state *mast)
2728 {
2729 	if (mast->bn->b_end > mt_min_slot_count(mast->orig_l->node))
2730 		return true;
2731 
2732 	return false;
2733 }
2734 
2735 /*
2736  * mast_overflow: Check if there is too much data in the subtree state for a
2737  * single node.
2738  * @mast: The maple subtree state
2739  */
2740 static inline bool mast_overflow(struct maple_subtree_state *mast)
2741 {
2742 	if (mast->bn->b_end >= mt_slot_count(mast->orig_l->node))
2743 		return true;
2744 
2745 	return false;
2746 }
2747 
2748 static inline void *mtree_range_walk(struct ma_state *mas)
2749 {
2750 	unsigned long *pivots;
2751 	unsigned char offset;
2752 	struct maple_node *node;
2753 	struct maple_enode *next, *last;
2754 	enum maple_type type;
2755 	void __rcu **slots;
2756 	unsigned char end;
2757 	unsigned long max, min;
2758 	unsigned long prev_max, prev_min;
2759 
2760 	next = mas->node;
2761 	min = mas->min;
2762 	max = mas->max;
2763 	do {
2764 		last = next;
2765 		node = mte_to_node(next);
2766 		type = mte_node_type(next);
2767 		pivots = ma_pivots(node, type);
2768 		end = ma_data_end(node, type, pivots, max);
2769 		prev_min = min;
2770 		prev_max = max;
2771 		if (pivots[0] >= mas->index) {
2772 			offset = 0;
2773 			max = pivots[0];
2774 			goto next;
2775 		}
2776 
2777 		offset = 1;
2778 		while (offset < end) {
2779 			if (pivots[offset] >= mas->index) {
2780 				max = pivots[offset];
2781 				break;
2782 			}
2783 			offset++;
2784 		}
2785 
2786 		min = pivots[offset - 1] + 1;
2787 next:
2788 		slots = ma_slots(node, type);
2789 		next = mt_slot(mas->tree, slots, offset);
2790 		if (unlikely(ma_dead_node(node)))
2791 			goto dead_node;
2792 	} while (!ma_is_leaf(type));
2793 
2794 	mas->end = end;
2795 	mas->offset = offset;
2796 	mas->index = min;
2797 	mas->last = max;
2798 	mas->min = prev_min;
2799 	mas->max = prev_max;
2800 	mas->node = last;
2801 	return (void *)next;
2802 
2803 dead_node:
2804 	mas_reset(mas);
2805 	return NULL;
2806 }
2807 
2808 /*
2809  * mas_spanning_rebalance() - Rebalance across two nodes which may not be peers.
2810  * @mas: The starting maple state
2811  * @mast: The maple_subtree_state, keeps track of 4 maple states.
2812  * @count: The estimated count of iterations needed.
2813  *
2814  * Follow the tree upwards from @l_mas and @r_mas for @count, or until the root
2815  * is hit.  First @b_node is split into two entries which are inserted into the
2816  * next iteration of the loop.  @b_node is returned populated with the final
2817  * iteration. @mas is used to obtain allocations.  orig_l_mas keeps track of the
2818  * nodes that will remain active by using orig_l_mas->index and orig_l_mas->last
2819  * to account of what has been copied into the new sub-tree.  The update of
2820  * orig_l_mas->last is used in mas_consume to find the slots that will need to
2821  * be either freed or destroyed.  orig_l_mas->depth keeps track of the height of
2822  * the new sub-tree in case the sub-tree becomes the full tree.
2823  */
2824 static void mas_spanning_rebalance(struct ma_state *mas,
2825 		struct maple_subtree_state *mast, unsigned char count)
2826 {
2827 	unsigned char split, mid_split;
2828 	unsigned char slot = 0;
2829 	struct maple_enode *left = NULL, *middle = NULL, *right = NULL;
2830 	struct maple_enode *old_enode;
2831 
2832 	MA_STATE(l_mas, mas->tree, mas->index, mas->index);
2833 	MA_STATE(r_mas, mas->tree, mas->index, mas->last);
2834 	MA_STATE(m_mas, mas->tree, mas->index, mas->index);
2835 
2836 	/*
2837 	 * The tree needs to be rebalanced and leaves need to be kept at the same level.
2838 	 * Rebalancing is done by use of the ``struct maple_topiary``.
2839 	 */
2840 	mast->l = &l_mas;
2841 	mast->m = &m_mas;
2842 	mast->r = &r_mas;
2843 	l_mas.status = r_mas.status = m_mas.status = ma_none;
2844 
2845 	/* Check if this is not root and has sufficient data.  */
2846 	if (((mast->orig_l->min != 0) || (mast->orig_r->max != ULONG_MAX)) &&
2847 	    unlikely(mast->bn->b_end <= mt_min_slots[mast->bn->type]))
2848 		mast_spanning_rebalance(mast);
2849 
2850 	l_mas.depth = 0;
2851 
2852 	/*
2853 	 * Each level of the tree is examined and balanced, pushing data to the left or
2854 	 * right, or rebalancing against left or right nodes is employed to avoid
2855 	 * rippling up the tree to limit the amount of churn.  Once a new sub-section of
2856 	 * the tree is created, there may be a mix of new and old nodes.  The old nodes
2857 	 * will have the incorrect parent pointers and currently be in two trees: the
2858 	 * original tree and the partially new tree.  To remedy the parent pointers in
2859 	 * the old tree, the new data is swapped into the active tree and a walk down
2860 	 * the tree is performed and the parent pointers are updated.
2861 	 * See mas_topiary_replace() for more information.
2862 	 */
2863 	while (count--) {
2864 		mast->bn->b_end--;
2865 		mast->bn->type = mte_node_type(mast->orig_l->node);
2866 		split = mas_mab_to_node(mas, mast->bn, &left, &right, &middle,
2867 					&mid_split, mast->orig_l->min);
2868 		mast_set_split_parents(mast, left, middle, right, split,
2869 				       mid_split);
2870 		mast_cp_to_nodes(mast, left, middle, right, split, mid_split);
2871 
2872 		/*
2873 		 * Copy data from next level in the tree to mast->bn from next
2874 		 * iteration
2875 		 */
2876 		memset(mast->bn, 0, sizeof(struct maple_big_node));
2877 		mast->bn->type = mte_node_type(left);
2878 		l_mas.depth++;
2879 
2880 		/* Root already stored in l->node. */
2881 		if (mas_is_root_limits(mast->l))
2882 			goto new_root;
2883 
2884 		mast_ascend(mast);
2885 		mast_combine_cp_left(mast);
2886 		l_mas.offset = mast->bn->b_end;
2887 		mab_set_b_end(mast->bn, &l_mas, left);
2888 		mab_set_b_end(mast->bn, &m_mas, middle);
2889 		mab_set_b_end(mast->bn, &r_mas, right);
2890 
2891 		/* Copy anything necessary out of the right node. */
2892 		mast_combine_cp_right(mast);
2893 		mast->orig_l->last = mast->orig_l->max;
2894 
2895 		if (mast_sufficient(mast))
2896 			continue;
2897 
2898 		if (mast_overflow(mast))
2899 			continue;
2900 
2901 		/* May be a new root stored in mast->bn */
2902 		if (mas_is_root_limits(mast->orig_l))
2903 			break;
2904 
2905 		mast_spanning_rebalance(mast);
2906 
2907 		/* rebalancing from other nodes may require another loop. */
2908 		if (!count)
2909 			count++;
2910 	}
2911 
2912 	l_mas.node = mt_mk_node(ma_mnode_ptr(mas_pop_node(mas)),
2913 				mte_node_type(mast->orig_l->node));
2914 	l_mas.depth++;
2915 	mab_mas_cp(mast->bn, 0, mt_slots[mast->bn->type] - 1, &l_mas, true);
2916 	mas_set_parent(mas, left, l_mas.node, slot);
2917 	if (middle)
2918 		mas_set_parent(mas, middle, l_mas.node, ++slot);
2919 
2920 	if (right)
2921 		mas_set_parent(mas, right, l_mas.node, ++slot);
2922 
2923 	if (mas_is_root_limits(mast->l)) {
2924 new_root:
2925 		mas_mn(mast->l)->parent = ma_parent_ptr(mas_tree_parent(mas));
2926 		while (!mte_is_root(mast->orig_l->node))
2927 			mast_ascend(mast);
2928 	} else {
2929 		mas_mn(&l_mas)->parent = mas_mn(mast->orig_l)->parent;
2930 	}
2931 
2932 	old_enode = mast->orig_l->node;
2933 	mas->depth = l_mas.depth;
2934 	mas->node = l_mas.node;
2935 	mas->min = l_mas.min;
2936 	mas->max = l_mas.max;
2937 	mas->offset = l_mas.offset;
2938 	mas_wmb_replace(mas, old_enode);
2939 	mtree_range_walk(mas);
2940 	return;
2941 }
2942 
2943 /*
2944  * mas_rebalance() - Rebalance a given node.
2945  * @mas: The maple state
2946  * @b_node: The big maple node.
2947  *
2948  * Rebalance two nodes into a single node or two new nodes that are sufficient.
2949  * Continue upwards until tree is sufficient.
2950  */
2951 static inline void mas_rebalance(struct ma_state *mas,
2952 				struct maple_big_node *b_node)
2953 {
2954 	char empty_count = mas_mt_height(mas);
2955 	struct maple_subtree_state mast;
2956 	unsigned char shift, b_end = ++b_node->b_end;
2957 
2958 	MA_STATE(l_mas, mas->tree, mas->index, mas->last);
2959 	MA_STATE(r_mas, mas->tree, mas->index, mas->last);
2960 
2961 	trace_ma_op(__func__, mas);
2962 
2963 	/*
2964 	 * Rebalancing occurs if a node is insufficient.  Data is rebalanced
2965 	 * against the node to the right if it exists, otherwise the node to the
2966 	 * left of this node is rebalanced against this node.  If rebalancing
2967 	 * causes just one node to be produced instead of two, then the parent
2968 	 * is also examined and rebalanced if it is insufficient.  Every level
2969 	 * tries to combine the data in the same way.  If one node contains the
2970 	 * entire range of the tree, then that node is used as a new root node.
2971 	 */
2972 
2973 	mast.orig_l = &l_mas;
2974 	mast.orig_r = &r_mas;
2975 	mast.bn = b_node;
2976 	mast.bn->type = mte_node_type(mas->node);
2977 
2978 	l_mas = r_mas = *mas;
2979 
2980 	if (mas_next_sibling(&r_mas)) {
2981 		mas_mab_cp(&r_mas, 0, mt_slot_count(r_mas.node), b_node, b_end);
2982 		r_mas.last = r_mas.index = r_mas.max;
2983 	} else {
2984 		mas_prev_sibling(&l_mas);
2985 		shift = mas_data_end(&l_mas) + 1;
2986 		mab_shift_right(b_node, shift);
2987 		mas->offset += shift;
2988 		mas_mab_cp(&l_mas, 0, shift - 1, b_node, 0);
2989 		b_node->b_end = shift + b_end;
2990 		l_mas.index = l_mas.last = l_mas.min;
2991 	}
2992 
2993 	return mas_spanning_rebalance(mas, &mast, empty_count);
2994 }
2995 
2996 /*
2997  * mas_destroy_rebalance() - Rebalance left-most node while destroying the maple
2998  * state.
2999  * @mas: The maple state
3000  * @end: The end of the left-most node.
3001  *
3002  * During a mass-insert event (such as forking), it may be necessary to
3003  * rebalance the left-most node when it is not sufficient.
3004  */
3005 static inline void mas_destroy_rebalance(struct ma_state *mas, unsigned char end)
3006 {
3007 	enum maple_type mt = mte_node_type(mas->node);
3008 	struct maple_node reuse, *newnode, *parent, *new_left, *left, *node;
3009 	struct maple_enode *eparent, *old_eparent;
3010 	unsigned char offset, tmp, split = mt_slots[mt] / 2;
3011 	void __rcu **l_slots, **slots;
3012 	unsigned long *l_pivs, *pivs, gap;
3013 	bool in_rcu = mt_in_rcu(mas->tree);
3014 
3015 	MA_STATE(l_mas, mas->tree, mas->index, mas->last);
3016 
3017 	l_mas = *mas;
3018 	mas_prev_sibling(&l_mas);
3019 
3020 	/* set up node. */
3021 	if (in_rcu) {
3022 		newnode = mas_pop_node(mas);
3023 	} else {
3024 		newnode = &reuse;
3025 	}
3026 
3027 	node = mas_mn(mas);
3028 	newnode->parent = node->parent;
3029 	slots = ma_slots(newnode, mt);
3030 	pivs = ma_pivots(newnode, mt);
3031 	left = mas_mn(&l_mas);
3032 	l_slots = ma_slots(left, mt);
3033 	l_pivs = ma_pivots(left, mt);
3034 	if (!l_slots[split])
3035 		split++;
3036 	tmp = mas_data_end(&l_mas) - split;
3037 
3038 	memcpy(slots, l_slots + split + 1, sizeof(void *) * tmp);
3039 	memcpy(pivs, l_pivs + split + 1, sizeof(unsigned long) * tmp);
3040 	pivs[tmp] = l_mas.max;
3041 	memcpy(slots + tmp, ma_slots(node, mt), sizeof(void *) * end);
3042 	memcpy(pivs + tmp, ma_pivots(node, mt), sizeof(unsigned long) * end);
3043 
3044 	l_mas.max = l_pivs[split];
3045 	mas->min = l_mas.max + 1;
3046 	old_eparent = mt_mk_node(mte_parent(l_mas.node),
3047 			     mas_parent_type(&l_mas, l_mas.node));
3048 	tmp += end;
3049 	if (!in_rcu) {
3050 		unsigned char max_p = mt_pivots[mt];
3051 		unsigned char max_s = mt_slots[mt];
3052 
3053 		if (tmp < max_p)
3054 			memset(pivs + tmp, 0,
3055 			       sizeof(unsigned long) * (max_p - tmp));
3056 
3057 		if (tmp < mt_slots[mt])
3058 			memset(slots + tmp, 0, sizeof(void *) * (max_s - tmp));
3059 
3060 		memcpy(node, newnode, sizeof(struct maple_node));
3061 		ma_set_meta(node, mt, 0, tmp - 1);
3062 		mte_set_pivot(old_eparent, mte_parent_slot(l_mas.node),
3063 			      l_pivs[split]);
3064 
3065 		/* Remove data from l_pivs. */
3066 		tmp = split + 1;
3067 		memset(l_pivs + tmp, 0, sizeof(unsigned long) * (max_p - tmp));
3068 		memset(l_slots + tmp, 0, sizeof(void *) * (max_s - tmp));
3069 		ma_set_meta(left, mt, 0, split);
3070 		eparent = old_eparent;
3071 
3072 		goto done;
3073 	}
3074 
3075 	/* RCU requires replacing both l_mas, mas, and parent. */
3076 	mas->node = mt_mk_node(newnode, mt);
3077 	ma_set_meta(newnode, mt, 0, tmp);
3078 
3079 	new_left = mas_pop_node(mas);
3080 	new_left->parent = left->parent;
3081 	mt = mte_node_type(l_mas.node);
3082 	slots = ma_slots(new_left, mt);
3083 	pivs = ma_pivots(new_left, mt);
3084 	memcpy(slots, l_slots, sizeof(void *) * split);
3085 	memcpy(pivs, l_pivs, sizeof(unsigned long) * split);
3086 	ma_set_meta(new_left, mt, 0, split);
3087 	l_mas.node = mt_mk_node(new_left, mt);
3088 
3089 	/* replace parent. */
3090 	offset = mte_parent_slot(mas->node);
3091 	mt = mas_parent_type(&l_mas, l_mas.node);
3092 	parent = mas_pop_node(mas);
3093 	slots = ma_slots(parent, mt);
3094 	pivs = ma_pivots(parent, mt);
3095 	memcpy(parent, mte_to_node(old_eparent), sizeof(struct maple_node));
3096 	rcu_assign_pointer(slots[offset], mas->node);
3097 	rcu_assign_pointer(slots[offset - 1], l_mas.node);
3098 	pivs[offset - 1] = l_mas.max;
3099 	eparent = mt_mk_node(parent, mt);
3100 done:
3101 	gap = mas_leaf_max_gap(mas);
3102 	mte_set_gap(eparent, mte_parent_slot(mas->node), gap);
3103 	gap = mas_leaf_max_gap(&l_mas);
3104 	mte_set_gap(eparent, mte_parent_slot(l_mas.node), gap);
3105 	mas_ascend(mas);
3106 
3107 	if (in_rcu) {
3108 		mas_replace_node(mas, old_eparent);
3109 		mas_adopt_children(mas, mas->node);
3110 	}
3111 
3112 	mas_update_gap(mas);
3113 }
3114 
3115 /*
3116  * mas_split_final_node() - Split the final node in a subtree operation.
3117  * @mast: the maple subtree state
3118  * @mas: The maple state
3119  * @height: The height of the tree in case it's a new root.
3120  */
3121 static inline void mas_split_final_node(struct maple_subtree_state *mast,
3122 					struct ma_state *mas, int height)
3123 {
3124 	struct maple_enode *ancestor;
3125 
3126 	if (mte_is_root(mas->node)) {
3127 		if (mt_is_alloc(mas->tree))
3128 			mast->bn->type = maple_arange_64;
3129 		else
3130 			mast->bn->type = maple_range_64;
3131 		mas->depth = height;
3132 	}
3133 	/*
3134 	 * Only a single node is used here, could be root.
3135 	 * The Big_node data should just fit in a single node.
3136 	 */
3137 	ancestor = mas_new_ma_node(mas, mast->bn);
3138 	mas_set_parent(mas, mast->l->node, ancestor, mast->l->offset);
3139 	mas_set_parent(mas, mast->r->node, ancestor, mast->r->offset);
3140 	mte_to_node(ancestor)->parent = mas_mn(mas)->parent;
3141 
3142 	mast->l->node = ancestor;
3143 	mab_mas_cp(mast->bn, 0, mt_slots[mast->bn->type] - 1, mast->l, true);
3144 	mas->offset = mast->bn->b_end - 1;
3145 }
3146 
3147 /*
3148  * mast_fill_bnode() - Copy data into the big node in the subtree state
3149  * @mast: The maple subtree state
3150  * @mas: the maple state
3151  * @skip: The number of entries to skip for new nodes insertion.
3152  */
3153 static inline void mast_fill_bnode(struct maple_subtree_state *mast,
3154 					 struct ma_state *mas,
3155 					 unsigned char skip)
3156 {
3157 	bool cp = true;
3158 	unsigned char split;
3159 
3160 	memset(mast->bn, 0, sizeof(struct maple_big_node));
3161 
3162 	if (mte_is_root(mas->node)) {
3163 		cp = false;
3164 	} else {
3165 		mas_ascend(mas);
3166 		mas->offset = mte_parent_slot(mas->node);
3167 	}
3168 
3169 	if (cp && mast->l->offset)
3170 		mas_mab_cp(mas, 0, mast->l->offset - 1, mast->bn, 0);
3171 
3172 	split = mast->bn->b_end;
3173 	mab_set_b_end(mast->bn, mast->l, mast->l->node);
3174 	mast->r->offset = mast->bn->b_end;
3175 	mab_set_b_end(mast->bn, mast->r, mast->r->node);
3176 	if (mast->bn->pivot[mast->bn->b_end - 1] == mas->max)
3177 		cp = false;
3178 
3179 	if (cp)
3180 		mas_mab_cp(mas, split + skip, mt_slot_count(mas->node) - 1,
3181 			   mast->bn, mast->bn->b_end);
3182 
3183 	mast->bn->b_end--;
3184 	mast->bn->type = mte_node_type(mas->node);
3185 }
3186 
3187 /*
3188  * mast_split_data() - Split the data in the subtree state big node into regular
3189  * nodes.
3190  * @mast: The maple subtree state
3191  * @mas: The maple state
3192  * @split: The location to split the big node
3193  */
3194 static inline void mast_split_data(struct maple_subtree_state *mast,
3195 	   struct ma_state *mas, unsigned char split)
3196 {
3197 	unsigned char p_slot;
3198 
3199 	mab_mas_cp(mast->bn, 0, split, mast->l, true);
3200 	mte_set_pivot(mast->r->node, 0, mast->r->max);
3201 	mab_mas_cp(mast->bn, split + 1, mast->bn->b_end, mast->r, false);
3202 	mast->l->offset = mte_parent_slot(mas->node);
3203 	mast->l->max = mast->bn->pivot[split];
3204 	mast->r->min = mast->l->max + 1;
3205 	if (mte_is_leaf(mas->node))
3206 		return;
3207 
3208 	p_slot = mast->orig_l->offset;
3209 	mas_set_split_parent(mast->orig_l, mast->l->node, mast->r->node,
3210 			     &p_slot, split);
3211 	mas_set_split_parent(mast->orig_r, mast->l->node, mast->r->node,
3212 			     &p_slot, split);
3213 }
3214 
3215 /*
3216  * mas_push_data() - Instead of splitting a node, it is beneficial to push the
3217  * data to the right or left node if there is room.
3218  * @mas: The maple state
3219  * @height: The current height of the maple state
3220  * @mast: The maple subtree state
3221  * @left: Push left or not.
3222  *
3223  * Keeping the height of the tree low means faster lookups.
3224  *
3225  * Return: True if pushed, false otherwise.
3226  */
3227 static inline bool mas_push_data(struct ma_state *mas, int height,
3228 				 struct maple_subtree_state *mast, bool left)
3229 {
3230 	unsigned char slot_total = mast->bn->b_end;
3231 	unsigned char end, space, split;
3232 
3233 	MA_STATE(tmp_mas, mas->tree, mas->index, mas->last);
3234 	tmp_mas = *mas;
3235 	tmp_mas.depth = mast->l->depth;
3236 
3237 	if (left && !mas_prev_sibling(&tmp_mas))
3238 		return false;
3239 	else if (!left && !mas_next_sibling(&tmp_mas))
3240 		return false;
3241 
3242 	end = mas_data_end(&tmp_mas);
3243 	slot_total += end;
3244 	space = 2 * mt_slot_count(mas->node) - 2;
3245 	/* -2 instead of -1 to ensure there isn't a triple split */
3246 	if (ma_is_leaf(mast->bn->type))
3247 		space--;
3248 
3249 	if (mas->max == ULONG_MAX)
3250 		space--;
3251 
3252 	if (slot_total >= space)
3253 		return false;
3254 
3255 	/* Get the data; Fill mast->bn */
3256 	mast->bn->b_end++;
3257 	if (left) {
3258 		mab_shift_right(mast->bn, end + 1);
3259 		mas_mab_cp(&tmp_mas, 0, end, mast->bn, 0);
3260 		mast->bn->b_end = slot_total + 1;
3261 	} else {
3262 		mas_mab_cp(&tmp_mas, 0, end, mast->bn, mast->bn->b_end);
3263 	}
3264 
3265 	/* Configure mast for splitting of mast->bn */
3266 	split = mt_slots[mast->bn->type] - 2;
3267 	if (left) {
3268 		/*  Switch mas to prev node  */
3269 		*mas = tmp_mas;
3270 		/* Start using mast->l for the left side. */
3271 		tmp_mas.node = mast->l->node;
3272 		*mast->l = tmp_mas;
3273 	} else {
3274 		tmp_mas.node = mast->r->node;
3275 		*mast->r = tmp_mas;
3276 		split = slot_total - split;
3277 	}
3278 	split = mab_no_null_split(mast->bn, split, mt_slots[mast->bn->type]);
3279 	/* Update parent slot for split calculation. */
3280 	if (left)
3281 		mast->orig_l->offset += end + 1;
3282 
3283 	mast_split_data(mast, mas, split);
3284 	mast_fill_bnode(mast, mas, 2);
3285 	mas_split_final_node(mast, mas, height + 1);
3286 	return true;
3287 }
3288 
3289 /*
3290  * mas_split() - Split data that is too big for one node into two.
3291  * @mas: The maple state
3292  * @b_node: The maple big node
3293  */
3294 static void mas_split(struct ma_state *mas, struct maple_big_node *b_node)
3295 {
3296 	struct maple_subtree_state mast;
3297 	int height = 0;
3298 	unsigned char mid_split, split = 0;
3299 	struct maple_enode *old;
3300 
3301 	/*
3302 	 * Splitting is handled differently from any other B-tree; the Maple
3303 	 * Tree splits upwards.  Splitting up means that the split operation
3304 	 * occurs when the walk of the tree hits the leaves and not on the way
3305 	 * down.  The reason for splitting up is that it is impossible to know
3306 	 * how much space will be needed until the leaf is (or leaves are)
3307 	 * reached.  Since overwriting data is allowed and a range could
3308 	 * overwrite more than one range or result in changing one entry into 3
3309 	 * entries, it is impossible to know if a split is required until the
3310 	 * data is examined.
3311 	 *
3312 	 * Splitting is a balancing act between keeping allocations to a minimum
3313 	 * and avoiding a 'jitter' event where a tree is expanded to make room
3314 	 * for an entry followed by a contraction when the entry is removed.  To
3315 	 * accomplish the balance, there are empty slots remaining in both left
3316 	 * and right nodes after a split.
3317 	 */
3318 	MA_STATE(l_mas, mas->tree, mas->index, mas->last);
3319 	MA_STATE(r_mas, mas->tree, mas->index, mas->last);
3320 	MA_STATE(prev_l_mas, mas->tree, mas->index, mas->last);
3321 	MA_STATE(prev_r_mas, mas->tree, mas->index, mas->last);
3322 
3323 	trace_ma_op(__func__, mas);
3324 	mas->depth = mas_mt_height(mas);
3325 
3326 	mast.l = &l_mas;
3327 	mast.r = &r_mas;
3328 	mast.orig_l = &prev_l_mas;
3329 	mast.orig_r = &prev_r_mas;
3330 	mast.bn = b_node;
3331 
3332 	while (height++ <= mas->depth) {
3333 		if (mt_slots[b_node->type] > b_node->b_end) {
3334 			mas_split_final_node(&mast, mas, height);
3335 			break;
3336 		}
3337 
3338 		l_mas = r_mas = *mas;
3339 		l_mas.node = mas_new_ma_node(mas, b_node);
3340 		r_mas.node = mas_new_ma_node(mas, b_node);
3341 		/*
3342 		 * Another way that 'jitter' is avoided is to terminate a split up early if the
3343 		 * left or right node has space to spare.  This is referred to as "pushing left"
3344 		 * or "pushing right" and is similar to the B* tree, except the nodes left or
3345 		 * right can rarely be reused due to RCU, but the ripple upwards is halted which
3346 		 * is a significant savings.
3347 		 */
3348 		/* Try to push left. */
3349 		if (mas_push_data(mas, height, &mast, true))
3350 			break;
3351 		/* Try to push right. */
3352 		if (mas_push_data(mas, height, &mast, false))
3353 			break;
3354 
3355 		split = mab_calc_split(mas, b_node, &mid_split, prev_l_mas.min);
3356 		mast_split_data(&mast, mas, split);
3357 		/*
3358 		 * Usually correct, mab_mas_cp in the above call overwrites
3359 		 * r->max.
3360 		 */
3361 		mast.r->max = mas->max;
3362 		mast_fill_bnode(&mast, mas, 1);
3363 		prev_l_mas = *mast.l;
3364 		prev_r_mas = *mast.r;
3365 	}
3366 
3367 	/* Set the original node as dead */
3368 	old = mas->node;
3369 	mas->node = l_mas.node;
3370 	mas_wmb_replace(mas, old);
3371 	mtree_range_walk(mas);
3372 	return;
3373 }
3374 
3375 /*
3376  * mas_commit_b_node() - Commit the big node into the tree.
3377  * @wr_mas: The maple write state
3378  * @b_node: The maple big node
3379  */
3380 static noinline_for_kasan void mas_commit_b_node(struct ma_wr_state *wr_mas,
3381 			    struct maple_big_node *b_node)
3382 {
3383 	enum store_type type = wr_mas->mas->store_type;
3384 
3385 	WARN_ON_ONCE(type != wr_rebalance && type != wr_split_store);
3386 
3387 	if (type == wr_rebalance)
3388 		return mas_rebalance(wr_mas->mas, b_node);
3389 
3390 	return mas_split(wr_mas->mas, b_node);
3391 }
3392 
3393 /*
3394  * mas_root_expand() - Expand a root to a node
3395  * @mas: The maple state
3396  * @entry: The entry to store into the tree
3397  */
3398 static inline int mas_root_expand(struct ma_state *mas, void *entry)
3399 {
3400 	void *contents = mas_root_locked(mas);
3401 	enum maple_type type = maple_leaf_64;
3402 	struct maple_node *node;
3403 	void __rcu **slots;
3404 	unsigned long *pivots;
3405 	int slot = 0;
3406 
3407 	node = mas_pop_node(mas);
3408 	pivots = ma_pivots(node, type);
3409 	slots = ma_slots(node, type);
3410 	node->parent = ma_parent_ptr(mas_tree_parent(mas));
3411 	mas->node = mt_mk_node(node, type);
3412 	mas->status = ma_active;
3413 
3414 	if (mas->index) {
3415 		if (contents) {
3416 			rcu_assign_pointer(slots[slot], contents);
3417 			if (likely(mas->index > 1))
3418 				slot++;
3419 		}
3420 		pivots[slot++] = mas->index - 1;
3421 	}
3422 
3423 	rcu_assign_pointer(slots[slot], entry);
3424 	mas->offset = slot;
3425 	pivots[slot] = mas->last;
3426 	if (mas->last != ULONG_MAX)
3427 		pivots[++slot] = ULONG_MAX;
3428 
3429 	mas->depth = 1;
3430 	mas_set_height(mas);
3431 	ma_set_meta(node, maple_leaf_64, 0, slot);
3432 	/* swap the new root into the tree */
3433 	rcu_assign_pointer(mas->tree->ma_root, mte_mk_root(mas->node));
3434 	return slot;
3435 }
3436 
3437 static inline void mas_store_root(struct ma_state *mas, void *entry)
3438 {
3439 	if (likely((mas->last != 0) || (mas->index != 0)))
3440 		mas_root_expand(mas, entry);
3441 	else if (((unsigned long) (entry) & 3) == 2)
3442 		mas_root_expand(mas, entry);
3443 	else {
3444 		rcu_assign_pointer(mas->tree->ma_root, entry);
3445 		mas->status = ma_start;
3446 	}
3447 }
3448 
3449 /*
3450  * mas_is_span_wr() - Check if the write needs to be treated as a write that
3451  * spans the node.
3452  * @wr_mas: The maple write state
3453  *
3454  * Spanning writes are writes that start in one node and end in another OR if
3455  * the write of a %NULL will cause the node to end with a %NULL.
3456  *
3457  * Return: True if this is a spanning write, false otherwise.
3458  */
3459 static bool mas_is_span_wr(struct ma_wr_state *wr_mas)
3460 {
3461 	unsigned long max = wr_mas->r_max;
3462 	unsigned long last = wr_mas->mas->last;
3463 	enum maple_type type = wr_mas->type;
3464 	void *entry = wr_mas->entry;
3465 
3466 	/* Contained in this pivot, fast path */
3467 	if (last < max)
3468 		return false;
3469 
3470 	if (ma_is_leaf(type)) {
3471 		max = wr_mas->mas->max;
3472 		if (last < max)
3473 			return false;
3474 	}
3475 
3476 	if (last == max) {
3477 		/*
3478 		 * The last entry of leaf node cannot be NULL unless it is the
3479 		 * rightmost node (writing ULONG_MAX), otherwise it spans slots.
3480 		 */
3481 		if (entry || last == ULONG_MAX)
3482 			return false;
3483 	}
3484 
3485 	trace_ma_write(__func__, wr_mas->mas, wr_mas->r_max, entry);
3486 	return true;
3487 }
3488 
3489 static inline void mas_wr_walk_descend(struct ma_wr_state *wr_mas)
3490 {
3491 	wr_mas->type = mte_node_type(wr_mas->mas->node);
3492 	mas_wr_node_walk(wr_mas);
3493 	wr_mas->slots = ma_slots(wr_mas->node, wr_mas->type);
3494 }
3495 
3496 static inline void mas_wr_walk_traverse(struct ma_wr_state *wr_mas)
3497 {
3498 	wr_mas->mas->max = wr_mas->r_max;
3499 	wr_mas->mas->min = wr_mas->r_min;
3500 	wr_mas->mas->node = wr_mas->content;
3501 	wr_mas->mas->offset = 0;
3502 	wr_mas->mas->depth++;
3503 }
3504 /*
3505  * mas_wr_walk() - Walk the tree for a write.
3506  * @wr_mas: The maple write state
3507  *
3508  * Uses mas_slot_locked() and does not need to worry about dead nodes.
3509  *
3510  * Return: True if it's contained in a node, false on spanning write.
3511  */
3512 static bool mas_wr_walk(struct ma_wr_state *wr_mas)
3513 {
3514 	struct ma_state *mas = wr_mas->mas;
3515 
3516 	while (true) {
3517 		mas_wr_walk_descend(wr_mas);
3518 		if (unlikely(mas_is_span_wr(wr_mas)))
3519 			return false;
3520 
3521 		wr_mas->content = mas_slot_locked(mas, wr_mas->slots,
3522 						  mas->offset);
3523 		if (ma_is_leaf(wr_mas->type))
3524 			return true;
3525 
3526 		mas_wr_walk_traverse(wr_mas);
3527 	}
3528 
3529 	return true;
3530 }
3531 
3532 static void mas_wr_walk_index(struct ma_wr_state *wr_mas)
3533 {
3534 	struct ma_state *mas = wr_mas->mas;
3535 
3536 	while (true) {
3537 		mas_wr_walk_descend(wr_mas);
3538 		wr_mas->content = mas_slot_locked(mas, wr_mas->slots,
3539 						  mas->offset);
3540 		if (ma_is_leaf(wr_mas->type))
3541 			return;
3542 		mas_wr_walk_traverse(wr_mas);
3543 	}
3544 }
3545 /*
3546  * mas_extend_spanning_null() - Extend a store of a %NULL to include surrounding %NULLs.
3547  * @l_wr_mas: The left maple write state
3548  * @r_wr_mas: The right maple write state
3549  */
3550 static inline void mas_extend_spanning_null(struct ma_wr_state *l_wr_mas,
3551 					    struct ma_wr_state *r_wr_mas)
3552 {
3553 	struct ma_state *r_mas = r_wr_mas->mas;
3554 	struct ma_state *l_mas = l_wr_mas->mas;
3555 	unsigned char l_slot;
3556 
3557 	l_slot = l_mas->offset;
3558 	if (!l_wr_mas->content)
3559 		l_mas->index = l_wr_mas->r_min;
3560 
3561 	if ((l_mas->index == l_wr_mas->r_min) &&
3562 		 (l_slot &&
3563 		  !mas_slot_locked(l_mas, l_wr_mas->slots, l_slot - 1))) {
3564 		if (l_slot > 1)
3565 			l_mas->index = l_wr_mas->pivots[l_slot - 2] + 1;
3566 		else
3567 			l_mas->index = l_mas->min;
3568 
3569 		l_mas->offset = l_slot - 1;
3570 	}
3571 
3572 	if (!r_wr_mas->content) {
3573 		if (r_mas->last < r_wr_mas->r_max)
3574 			r_mas->last = r_wr_mas->r_max;
3575 		r_mas->offset++;
3576 	} else if ((r_mas->last == r_wr_mas->r_max) &&
3577 	    (r_mas->last < r_mas->max) &&
3578 	    !mas_slot_locked(r_mas, r_wr_mas->slots, r_mas->offset + 1)) {
3579 		r_mas->last = mas_safe_pivot(r_mas, r_wr_mas->pivots,
3580 					     r_wr_mas->type, r_mas->offset + 1);
3581 		r_mas->offset++;
3582 	}
3583 }
3584 
3585 static inline void *mas_state_walk(struct ma_state *mas)
3586 {
3587 	void *entry;
3588 
3589 	entry = mas_start(mas);
3590 	if (mas_is_none(mas))
3591 		return NULL;
3592 
3593 	if (mas_is_ptr(mas))
3594 		return entry;
3595 
3596 	return mtree_range_walk(mas);
3597 }
3598 
3599 /*
3600  * mtree_lookup_walk() - Internal quick lookup that does not keep maple state up
3601  * to date.
3602  *
3603  * @mas: The maple state.
3604  *
3605  * Note: Leaves mas in undesirable state.
3606  * Return: The entry for @mas->index or %NULL on dead node.
3607  */
3608 static inline void *mtree_lookup_walk(struct ma_state *mas)
3609 {
3610 	unsigned long *pivots;
3611 	unsigned char offset;
3612 	struct maple_node *node;
3613 	struct maple_enode *next;
3614 	enum maple_type type;
3615 	void __rcu **slots;
3616 	unsigned char end;
3617 
3618 	next = mas->node;
3619 	do {
3620 		node = mte_to_node(next);
3621 		type = mte_node_type(next);
3622 		pivots = ma_pivots(node, type);
3623 		end = mt_pivots[type];
3624 		offset = 0;
3625 		do {
3626 			if (pivots[offset] >= mas->index)
3627 				break;
3628 		} while (++offset < end);
3629 
3630 		slots = ma_slots(node, type);
3631 		next = mt_slot(mas->tree, slots, offset);
3632 		if (unlikely(ma_dead_node(node)))
3633 			goto dead_node;
3634 	} while (!ma_is_leaf(type));
3635 
3636 	return (void *)next;
3637 
3638 dead_node:
3639 	mas_reset(mas);
3640 	return NULL;
3641 }
3642 
3643 static void mte_destroy_walk(struct maple_enode *, struct maple_tree *);
3644 /*
3645  * mas_new_root() - Create a new root node that only contains the entry passed
3646  * in.
3647  * @mas: The maple state
3648  * @entry: The entry to store.
3649  *
3650  * Only valid when the index == 0 and the last == ULONG_MAX
3651  */
3652 static inline void mas_new_root(struct ma_state *mas, void *entry)
3653 {
3654 	struct maple_enode *root = mas_root_locked(mas);
3655 	enum maple_type type = maple_leaf_64;
3656 	struct maple_node *node;
3657 	void __rcu **slots;
3658 	unsigned long *pivots;
3659 
3660 	if (!entry && !mas->index && mas->last == ULONG_MAX) {
3661 		mas->depth = 0;
3662 		mas_set_height(mas);
3663 		rcu_assign_pointer(mas->tree->ma_root, entry);
3664 		mas->status = ma_start;
3665 		goto done;
3666 	}
3667 
3668 	node = mas_pop_node(mas);
3669 	pivots = ma_pivots(node, type);
3670 	slots = ma_slots(node, type);
3671 	node->parent = ma_parent_ptr(mas_tree_parent(mas));
3672 	mas->node = mt_mk_node(node, type);
3673 	mas->status = ma_active;
3674 	rcu_assign_pointer(slots[0], entry);
3675 	pivots[0] = mas->last;
3676 	mas->depth = 1;
3677 	mas_set_height(mas);
3678 	rcu_assign_pointer(mas->tree->ma_root, mte_mk_root(mas->node));
3679 
3680 done:
3681 	if (xa_is_node(root))
3682 		mte_destroy_walk(root, mas->tree);
3683 
3684 	return;
3685 }
3686 /*
3687  * mas_wr_spanning_store() - Create a subtree with the store operation completed
3688  * and new nodes where necessary, then place the sub-tree in the actual tree.
3689  * Note that mas is expected to point to the node which caused the store to
3690  * span.
3691  * @wr_mas: The maple write state
3692  */
3693 static noinline void mas_wr_spanning_store(struct ma_wr_state *wr_mas)
3694 {
3695 	struct maple_subtree_state mast;
3696 	struct maple_big_node b_node;
3697 	struct ma_state *mas;
3698 	unsigned char height;
3699 
3700 	/* Left and Right side of spanning store */
3701 	MA_STATE(l_mas, NULL, 0, 0);
3702 	MA_STATE(r_mas, NULL, 0, 0);
3703 	MA_WR_STATE(r_wr_mas, &r_mas, wr_mas->entry);
3704 	MA_WR_STATE(l_wr_mas, &l_mas, wr_mas->entry);
3705 
3706 	/*
3707 	 * A store operation that spans multiple nodes is called a spanning
3708 	 * store and is handled early in the store call stack by the function
3709 	 * mas_is_span_wr().  When a spanning store is identified, the maple
3710 	 * state is duplicated.  The first maple state walks the left tree path
3711 	 * to ``index``, the duplicate walks the right tree path to ``last``.
3712 	 * The data in the two nodes are combined into a single node, two nodes,
3713 	 * or possibly three nodes (see the 3-way split above).  A ``NULL``
3714 	 * written to the last entry of a node is considered a spanning store as
3715 	 * a rebalance is required for the operation to complete and an overflow
3716 	 * of data may happen.
3717 	 */
3718 	mas = wr_mas->mas;
3719 	trace_ma_op(__func__, mas);
3720 
3721 	if (unlikely(!mas->index && mas->last == ULONG_MAX))
3722 		return mas_new_root(mas, wr_mas->entry);
3723 	/*
3724 	 * Node rebalancing may occur due to this store, so there may be three new
3725 	 * entries per level plus a new root.
3726 	 */
3727 	height = mas_mt_height(mas);
3728 
3729 	/*
3730 	 * Set up right side.  Need to get to the next offset after the spanning
3731 	 * store to ensure it's not NULL and to combine both the next node and
3732 	 * the node with the start together.
3733 	 */
3734 	r_mas = *mas;
3735 	/* Avoid overflow, walk to next slot in the tree. */
3736 	if (r_mas.last + 1)
3737 		r_mas.last++;
3738 
3739 	r_mas.index = r_mas.last;
3740 	mas_wr_walk_index(&r_wr_mas);
3741 	r_mas.last = r_mas.index = mas->last;
3742 
3743 	/* Set up left side. */
3744 	l_mas = *mas;
3745 	mas_wr_walk_index(&l_wr_mas);
3746 
3747 	if (!wr_mas->entry) {
3748 		mas_extend_spanning_null(&l_wr_mas, &r_wr_mas);
3749 		mas->offset = l_mas.offset;
3750 		mas->index = l_mas.index;
3751 		mas->last = l_mas.last = r_mas.last;
3752 	}
3753 
3754 	/* expanding NULLs may make this cover the entire range */
3755 	if (!l_mas.index && r_mas.last == ULONG_MAX) {
3756 		mas_set_range(mas, 0, ULONG_MAX);
3757 		return mas_new_root(mas, wr_mas->entry);
3758 	}
3759 
3760 	memset(&b_node, 0, sizeof(struct maple_big_node));
3761 	/* Copy l_mas and store the value in b_node. */
3762 	mas_store_b_node(&l_wr_mas, &b_node, l_mas.end);
3763 	/* Copy r_mas into b_node if there is anything to copy. */
3764 	if (r_mas.max > r_mas.last)
3765 		mas_mab_cp(&r_mas, r_mas.offset, r_mas.end,
3766 			   &b_node, b_node.b_end + 1);
3767 	else
3768 		b_node.b_end++;
3769 
3770 	/* Stop spanning searches by searching for just index. */
3771 	l_mas.index = l_mas.last = mas->index;
3772 
3773 	mast.bn = &b_node;
3774 	mast.orig_l = &l_mas;
3775 	mast.orig_r = &r_mas;
3776 	/* Combine l_mas and r_mas and split them up evenly again. */
3777 	return mas_spanning_rebalance(mas, &mast, height + 1);
3778 }
3779 
3780 /*
3781  * mas_wr_node_store() - Attempt to store the value in a node
3782  * @wr_mas: The maple write state
3783  *
3784  * Attempts to reuse the node, but may allocate.
3785  */
3786 static inline void mas_wr_node_store(struct ma_wr_state *wr_mas,
3787 				     unsigned char new_end)
3788 {
3789 	struct ma_state *mas = wr_mas->mas;
3790 	void __rcu **dst_slots;
3791 	unsigned long *dst_pivots;
3792 	unsigned char dst_offset, offset_end = wr_mas->offset_end;
3793 	struct maple_node reuse, *newnode;
3794 	unsigned char copy_size, node_pivots = mt_pivots[wr_mas->type];
3795 	bool in_rcu = mt_in_rcu(mas->tree);
3796 
3797 	if (mas->last == wr_mas->end_piv)
3798 		offset_end++; /* don't copy this offset */
3799 	else if (unlikely(wr_mas->r_max == ULONG_MAX))
3800 		mas_bulk_rebalance(mas, mas->end, wr_mas->type);
3801 
3802 	/* set up node. */
3803 	if (in_rcu) {
3804 		newnode = mas_pop_node(mas);
3805 	} else {
3806 		memset(&reuse, 0, sizeof(struct maple_node));
3807 		newnode = &reuse;
3808 	}
3809 
3810 	newnode->parent = mas_mn(mas)->parent;
3811 	dst_pivots = ma_pivots(newnode, wr_mas->type);
3812 	dst_slots = ma_slots(newnode, wr_mas->type);
3813 	/* Copy from start to insert point */
3814 	memcpy(dst_pivots, wr_mas->pivots, sizeof(unsigned long) * mas->offset);
3815 	memcpy(dst_slots, wr_mas->slots, sizeof(void *) * mas->offset);
3816 
3817 	/* Handle insert of new range starting after old range */
3818 	if (wr_mas->r_min < mas->index) {
3819 		rcu_assign_pointer(dst_slots[mas->offset], wr_mas->content);
3820 		dst_pivots[mas->offset++] = mas->index - 1;
3821 	}
3822 
3823 	/* Store the new entry and range end. */
3824 	if (mas->offset < node_pivots)
3825 		dst_pivots[mas->offset] = mas->last;
3826 	rcu_assign_pointer(dst_slots[mas->offset], wr_mas->entry);
3827 
3828 	/*
3829 	 * this range wrote to the end of the node or it overwrote the rest of
3830 	 * the data
3831 	 */
3832 	if (offset_end > mas->end)
3833 		goto done;
3834 
3835 	dst_offset = mas->offset + 1;
3836 	/* Copy to the end of node if necessary. */
3837 	copy_size = mas->end - offset_end + 1;
3838 	memcpy(dst_slots + dst_offset, wr_mas->slots + offset_end,
3839 	       sizeof(void *) * copy_size);
3840 	memcpy(dst_pivots + dst_offset, wr_mas->pivots + offset_end,
3841 	       sizeof(unsigned long) * (copy_size - 1));
3842 
3843 	if (new_end < node_pivots)
3844 		dst_pivots[new_end] = mas->max;
3845 
3846 done:
3847 	mas_leaf_set_meta(newnode, maple_leaf_64, new_end);
3848 	if (in_rcu) {
3849 		struct maple_enode *old_enode = mas->node;
3850 
3851 		mas->node = mt_mk_node(newnode, wr_mas->type);
3852 		mas_replace_node(mas, old_enode);
3853 	} else {
3854 		memcpy(wr_mas->node, newnode, sizeof(struct maple_node));
3855 	}
3856 	trace_ma_write(__func__, mas, 0, wr_mas->entry);
3857 	mas_update_gap(mas);
3858 	mas->end = new_end;
3859 	return;
3860 }
3861 
3862 /*
3863  * mas_wr_slot_store: Attempt to store a value in a slot.
3864  * @wr_mas: the maple write state
3865  */
3866 static inline void mas_wr_slot_store(struct ma_wr_state *wr_mas)
3867 {
3868 	struct ma_state *mas = wr_mas->mas;
3869 	unsigned char offset = mas->offset;
3870 	void __rcu **slots = wr_mas->slots;
3871 	bool gap = false;
3872 
3873 	gap |= !mt_slot_locked(mas->tree, slots, offset);
3874 	gap |= !mt_slot_locked(mas->tree, slots, offset + 1);
3875 
3876 	if (wr_mas->offset_end - offset == 1) {
3877 		if (mas->index == wr_mas->r_min) {
3878 			/* Overwriting the range and a part of the next one */
3879 			rcu_assign_pointer(slots[offset], wr_mas->entry);
3880 			wr_mas->pivots[offset] = mas->last;
3881 		} else {
3882 			/* Overwriting a part of the range and the next one */
3883 			rcu_assign_pointer(slots[offset + 1], wr_mas->entry);
3884 			wr_mas->pivots[offset] = mas->index - 1;
3885 			mas->offset++; /* Keep mas accurate. */
3886 		}
3887 	} else if (!mt_in_rcu(mas->tree)) {
3888 		/*
3889 		 * Expand the range, only partially overwriting the previous and
3890 		 * next ranges
3891 		 */
3892 		gap |= !mt_slot_locked(mas->tree, slots, offset + 2);
3893 		rcu_assign_pointer(slots[offset + 1], wr_mas->entry);
3894 		wr_mas->pivots[offset] = mas->index - 1;
3895 		wr_mas->pivots[offset + 1] = mas->last;
3896 		mas->offset++; /* Keep mas accurate. */
3897 	} else {
3898 		return;
3899 	}
3900 
3901 	trace_ma_write(__func__, mas, 0, wr_mas->entry);
3902 	/*
3903 	 * Only update gap when the new entry is empty or there is an empty
3904 	 * entry in the original two ranges.
3905 	 */
3906 	if (!wr_mas->entry || gap)
3907 		mas_update_gap(mas);
3908 
3909 	return;
3910 }
3911 
3912 static inline void mas_wr_extend_null(struct ma_wr_state *wr_mas)
3913 {
3914 	struct ma_state *mas = wr_mas->mas;
3915 
3916 	if (!wr_mas->slots[wr_mas->offset_end]) {
3917 		/* If this one is null, the next and prev are not */
3918 		mas->last = wr_mas->end_piv;
3919 	} else {
3920 		/* Check next slot(s) if we are overwriting the end */
3921 		if ((mas->last == wr_mas->end_piv) &&
3922 		    (mas->end != wr_mas->offset_end) &&
3923 		    !wr_mas->slots[wr_mas->offset_end + 1]) {
3924 			wr_mas->offset_end++;
3925 			if (wr_mas->offset_end == mas->end)
3926 				mas->last = mas->max;
3927 			else
3928 				mas->last = wr_mas->pivots[wr_mas->offset_end];
3929 			wr_mas->end_piv = mas->last;
3930 		}
3931 	}
3932 
3933 	if (!wr_mas->content) {
3934 		/* If this one is null, the next and prev are not */
3935 		mas->index = wr_mas->r_min;
3936 	} else {
3937 		/* Check prev slot if we are overwriting the start */
3938 		if (mas->index == wr_mas->r_min && mas->offset &&
3939 		    !wr_mas->slots[mas->offset - 1]) {
3940 			mas->offset--;
3941 			wr_mas->r_min = mas->index =
3942 				mas_safe_min(mas, wr_mas->pivots, mas->offset);
3943 			wr_mas->r_max = wr_mas->pivots[mas->offset];
3944 		}
3945 	}
3946 }
3947 
3948 static inline void mas_wr_end_piv(struct ma_wr_state *wr_mas)
3949 {
3950 	while ((wr_mas->offset_end < wr_mas->mas->end) &&
3951 	       (wr_mas->mas->last > wr_mas->pivots[wr_mas->offset_end]))
3952 		wr_mas->offset_end++;
3953 
3954 	if (wr_mas->offset_end < wr_mas->mas->end)
3955 		wr_mas->end_piv = wr_mas->pivots[wr_mas->offset_end];
3956 	else
3957 		wr_mas->end_piv = wr_mas->mas->max;
3958 }
3959 
3960 static inline unsigned char mas_wr_new_end(struct ma_wr_state *wr_mas)
3961 {
3962 	struct ma_state *mas = wr_mas->mas;
3963 	unsigned char new_end = mas->end + 2;
3964 
3965 	new_end -= wr_mas->offset_end - mas->offset;
3966 	if (wr_mas->r_min == mas->index)
3967 		new_end--;
3968 
3969 	if (wr_mas->end_piv == mas->last)
3970 		new_end--;
3971 
3972 	return new_end;
3973 }
3974 
3975 /*
3976  * mas_wr_append: Attempt to append
3977  * @wr_mas: the maple write state
3978  * @new_end: The end of the node after the modification
3979  *
3980  * This is currently unsafe in rcu mode since the end of the node may be cached
3981  * by readers while the node contents may be updated which could result in
3982  * inaccurate information.
3983  */
3984 static inline void mas_wr_append(struct ma_wr_state *wr_mas,
3985 		unsigned char new_end)
3986 {
3987 	struct ma_state *mas = wr_mas->mas;
3988 	void __rcu **slots;
3989 	unsigned char end = mas->end;
3990 
3991 	if (new_end < mt_pivots[wr_mas->type]) {
3992 		wr_mas->pivots[new_end] = wr_mas->pivots[end];
3993 		ma_set_meta(wr_mas->node, wr_mas->type, 0, new_end);
3994 	}
3995 
3996 	slots = wr_mas->slots;
3997 	if (new_end == end + 1) {
3998 		if (mas->last == wr_mas->r_max) {
3999 			/* Append to end of range */
4000 			rcu_assign_pointer(slots[new_end], wr_mas->entry);
4001 			wr_mas->pivots[end] = mas->index - 1;
4002 			mas->offset = new_end;
4003 		} else {
4004 			/* Append to start of range */
4005 			rcu_assign_pointer(slots[new_end], wr_mas->content);
4006 			wr_mas->pivots[end] = mas->last;
4007 			rcu_assign_pointer(slots[end], wr_mas->entry);
4008 		}
4009 	} else {
4010 		/* Append to the range without touching any boundaries. */
4011 		rcu_assign_pointer(slots[new_end], wr_mas->content);
4012 		wr_mas->pivots[end + 1] = mas->last;
4013 		rcu_assign_pointer(slots[end + 1], wr_mas->entry);
4014 		wr_mas->pivots[end] = mas->index - 1;
4015 		mas->offset = end + 1;
4016 	}
4017 
4018 	if (!wr_mas->content || !wr_mas->entry)
4019 		mas_update_gap(mas);
4020 
4021 	mas->end = new_end;
4022 	trace_ma_write(__func__, mas, new_end, wr_mas->entry);
4023 	return;
4024 }
4025 
4026 /*
4027  * mas_wr_bnode() - Slow path for a modification.
4028  * @wr_mas: The write maple state
4029  *
4030  * This is where split, rebalance end up.
4031  */
4032 static void mas_wr_bnode(struct ma_wr_state *wr_mas)
4033 {
4034 	struct maple_big_node b_node;
4035 
4036 	trace_ma_write(__func__, wr_mas->mas, 0, wr_mas->entry);
4037 	memset(&b_node, 0, sizeof(struct maple_big_node));
4038 	mas_store_b_node(wr_mas, &b_node, wr_mas->offset_end);
4039 	mas_commit_b_node(wr_mas, &b_node);
4040 }
4041 
4042 /*
4043  * mas_wr_store_entry() - Internal call to store a value
4044  * @wr_mas: The maple write state
4045  */
4046 static inline void mas_wr_store_entry(struct ma_wr_state *wr_mas)
4047 {
4048 	struct ma_state *mas = wr_mas->mas;
4049 	unsigned char new_end = mas_wr_new_end(wr_mas);
4050 
4051 	switch (mas->store_type) {
4052 	case wr_invalid:
4053 		MT_BUG_ON(mas->tree, 1);
4054 		return;
4055 	case wr_new_root:
4056 		mas_new_root(mas, wr_mas->entry);
4057 		break;
4058 	case wr_store_root:
4059 		mas_store_root(mas, wr_mas->entry);
4060 		break;
4061 	case wr_exact_fit:
4062 		rcu_assign_pointer(wr_mas->slots[mas->offset], wr_mas->entry);
4063 		if (!!wr_mas->entry ^ !!wr_mas->content)
4064 			mas_update_gap(mas);
4065 		break;
4066 	case wr_append:
4067 		mas_wr_append(wr_mas, new_end);
4068 		break;
4069 	case wr_slot_store:
4070 		mas_wr_slot_store(wr_mas);
4071 		break;
4072 	case wr_node_store:
4073 		mas_wr_node_store(wr_mas, new_end);
4074 		break;
4075 	case wr_spanning_store:
4076 		mas_wr_spanning_store(wr_mas);
4077 		break;
4078 	case wr_split_store:
4079 	case wr_rebalance:
4080 		mas_wr_bnode(wr_mas);
4081 		break;
4082 	}
4083 
4084 	return;
4085 }
4086 
4087 static inline void mas_wr_prealloc_setup(struct ma_wr_state *wr_mas)
4088 {
4089 	struct ma_state *mas = wr_mas->mas;
4090 
4091 	if (!mas_is_active(mas)) {
4092 		if (mas_is_start(mas))
4093 			goto set_content;
4094 
4095 		if (unlikely(mas_is_paused(mas)))
4096 			goto reset;
4097 
4098 		if (unlikely(mas_is_none(mas)))
4099 			goto reset;
4100 
4101 		if (unlikely(mas_is_overflow(mas)))
4102 			goto reset;
4103 
4104 		if (unlikely(mas_is_underflow(mas)))
4105 			goto reset;
4106 	}
4107 
4108 	/*
4109 	 * A less strict version of mas_is_span_wr() where we allow spanning
4110 	 * writes within this node.  This is to stop partial walks in
4111 	 * mas_prealloc() from being reset.
4112 	 */
4113 	if (mas->last > mas->max)
4114 		goto reset;
4115 
4116 	if (wr_mas->entry)
4117 		goto set_content;
4118 
4119 	if (mte_is_leaf(mas->node) && mas->last == mas->max)
4120 		goto reset;
4121 
4122 	goto set_content;
4123 
4124 reset:
4125 	mas_reset(mas);
4126 set_content:
4127 	wr_mas->content = mas_start(mas);
4128 }
4129 
4130 /**
4131  * mas_prealloc_calc() - Calculate number of nodes needed for a
4132  * given store oepration
4133  * @mas: The maple state
4134  * @entry: The entry to store into the tree
4135  *
4136  * Return: Number of nodes required for preallocation.
4137  */
4138 static inline int mas_prealloc_calc(struct ma_state *mas, void *entry)
4139 {
4140 	int ret = mas_mt_height(mas) * 3 + 1;
4141 
4142 	switch (mas->store_type) {
4143 	case wr_invalid:
4144 		WARN_ON_ONCE(1);
4145 		break;
4146 	case wr_new_root:
4147 		ret = 1;
4148 		break;
4149 	case wr_store_root:
4150 		if (likely((mas->last != 0) || (mas->index != 0)))
4151 			ret = 1;
4152 		else if (((unsigned long) (entry) & 3) == 2)
4153 			ret = 1;
4154 		else
4155 			ret = 0;
4156 		break;
4157 	case wr_spanning_store:
4158 		ret =  mas_mt_height(mas) * 3 + 1;
4159 		break;
4160 	case wr_split_store:
4161 		ret =  mas_mt_height(mas) * 2 + 1;
4162 		break;
4163 	case wr_rebalance:
4164 		ret =  mas_mt_height(mas) * 2 - 1;
4165 		break;
4166 	case wr_node_store:
4167 		ret = mt_in_rcu(mas->tree) ? 1 : 0;
4168 		break;
4169 	case wr_append:
4170 	case wr_exact_fit:
4171 	case wr_slot_store:
4172 		ret = 0;
4173 	}
4174 
4175 	return ret;
4176 }
4177 
4178 /*
4179  * mas_wr_store_type() - Set the store type for a given
4180  * store operation.
4181  * @wr_mas: The maple write state
4182  */
4183 static inline void mas_wr_store_type(struct ma_wr_state *wr_mas)
4184 {
4185 	struct ma_state *mas = wr_mas->mas;
4186 	unsigned char new_end;
4187 
4188 	if (unlikely(mas_is_none(mas) || mas_is_ptr(mas))) {
4189 		mas->store_type = wr_store_root;
4190 		return;
4191 	}
4192 
4193 	if (unlikely(!mas_wr_walk(wr_mas))) {
4194 		mas->store_type = wr_spanning_store;
4195 		return;
4196 	}
4197 
4198 	/* At this point, we are at the leaf node that needs to be altered. */
4199 	mas_wr_end_piv(wr_mas);
4200 	if (!wr_mas->entry)
4201 		mas_wr_extend_null(wr_mas);
4202 
4203 	new_end = mas_wr_new_end(wr_mas);
4204 	if ((wr_mas->r_min == mas->index) && (wr_mas->r_max == mas->last)) {
4205 		mas->store_type = wr_exact_fit;
4206 		return;
4207 	}
4208 
4209 	if (unlikely(!mas->index && mas->last == ULONG_MAX)) {
4210 		mas->store_type = wr_new_root;
4211 		return;
4212 	}
4213 
4214 	/* Potential spanning rebalance collapsing a node */
4215 	if (new_end < mt_min_slots[wr_mas->type]) {
4216 		if (!mte_is_root(mas->node) && !(mas->mas_flags & MA_STATE_BULK)) {
4217 			mas->store_type = wr_rebalance;
4218 			return;
4219 		}
4220 		mas->store_type = wr_node_store;
4221 		return;
4222 	}
4223 
4224 	if (new_end >= mt_slots[wr_mas->type]) {
4225 		mas->store_type = wr_split_store;
4226 		return;
4227 	}
4228 
4229 	if (!mt_in_rcu(mas->tree) && (mas->offset == mas->end)) {
4230 		mas->store_type = wr_append;
4231 		return;
4232 	}
4233 
4234 	if ((new_end == mas->end) && (!mt_in_rcu(mas->tree) ||
4235 		(wr_mas->offset_end - mas->offset == 1))) {
4236 		mas->store_type = wr_slot_store;
4237 		return;
4238 	}
4239 
4240 	if (mte_is_root(mas->node) || (new_end >= mt_min_slots[wr_mas->type]) ||
4241 		(mas->mas_flags & MA_STATE_BULK)) {
4242 		mas->store_type = wr_node_store;
4243 		return;
4244 	}
4245 
4246 	mas->store_type = wr_invalid;
4247 	MAS_WARN_ON(mas, 1);
4248 }
4249 
4250 /**
4251  * mas_wr_preallocate() - Preallocate enough nodes for a store operation
4252  * @wr_mas: The maple write state
4253  * @entry: The entry that will be stored
4254  *
4255  */
4256 static inline void mas_wr_preallocate(struct ma_wr_state *wr_mas, void *entry)
4257 {
4258 	struct ma_state *mas = wr_mas->mas;
4259 	int request;
4260 
4261 	mas_wr_prealloc_setup(wr_mas);
4262 	mas_wr_store_type(wr_mas);
4263 	request = mas_prealloc_calc(mas, entry);
4264 	if (!request)
4265 		return;
4266 
4267 	mas_node_count(mas, request);
4268 }
4269 
4270 /**
4271  * mas_insert() - Internal call to insert a value
4272  * @mas: The maple state
4273  * @entry: The entry to store
4274  *
4275  * Return: %NULL or the contents that already exists at the requested index
4276  * otherwise.  The maple state needs to be checked for error conditions.
4277  */
4278 static inline void *mas_insert(struct ma_state *mas, void *entry)
4279 {
4280 	MA_WR_STATE(wr_mas, mas, entry);
4281 
4282 	/*
4283 	 * Inserting a new range inserts either 0, 1, or 2 pivots within the
4284 	 * tree.  If the insert fits exactly into an existing gap with a value
4285 	 * of NULL, then the slot only needs to be written with the new value.
4286 	 * If the range being inserted is adjacent to another range, then only a
4287 	 * single pivot needs to be inserted (as well as writing the entry).  If
4288 	 * the new range is within a gap but does not touch any other ranges,
4289 	 * then two pivots need to be inserted: the start - 1, and the end.  As
4290 	 * usual, the entry must be written.  Most operations require a new node
4291 	 * to be allocated and replace an existing node to ensure RCU safety,
4292 	 * when in RCU mode.  The exception to requiring a newly allocated node
4293 	 * is when inserting at the end of a node (appending).  When done
4294 	 * carefully, appending can reuse the node in place.
4295 	 */
4296 	wr_mas.content = mas_start(mas);
4297 	if (wr_mas.content)
4298 		goto exists;
4299 
4300 	mas_wr_preallocate(&wr_mas, entry);
4301 	if (mas_is_err(mas))
4302 		return NULL;
4303 
4304 	/* spanning writes always overwrite something */
4305 	if (mas->store_type == wr_spanning_store)
4306 		goto exists;
4307 
4308 	/* At this point, we are at the leaf node that needs to be altered. */
4309 	if (mas->store_type != wr_new_root && mas->store_type != wr_store_root) {
4310 		wr_mas.offset_end = mas->offset;
4311 		wr_mas.end_piv = wr_mas.r_max;
4312 
4313 		if (wr_mas.content || (mas->last > wr_mas.r_max))
4314 			goto exists;
4315 	}
4316 
4317 	mas_wr_store_entry(&wr_mas);
4318 	return wr_mas.content;
4319 
4320 exists:
4321 	mas_set_err(mas, -EEXIST);
4322 	return wr_mas.content;
4323 
4324 }
4325 
4326 /**
4327  * mas_alloc_cyclic() - Internal call to find somewhere to store an entry
4328  * @mas: The maple state.
4329  * @startp: Pointer to ID.
4330  * @range_lo: Lower bound of range to search.
4331  * @range_hi: Upper bound of range to search.
4332  * @entry: The entry to store.
4333  * @next: Pointer to next ID to allocate.
4334  * @gfp: The GFP_FLAGS to use for allocations.
4335  *
4336  * Return: 0 if the allocation succeeded without wrapping, 1 if the
4337  * allocation succeeded after wrapping, or -EBUSY if there are no
4338  * free entries.
4339  */
4340 int mas_alloc_cyclic(struct ma_state *mas, unsigned long *startp,
4341 		void *entry, unsigned long range_lo, unsigned long range_hi,
4342 		unsigned long *next, gfp_t gfp)
4343 {
4344 	unsigned long min = range_lo;
4345 	int ret = 0;
4346 
4347 	range_lo = max(min, *next);
4348 	ret = mas_empty_area(mas, range_lo, range_hi, 1);
4349 	if ((mas->tree->ma_flags & MT_FLAGS_ALLOC_WRAPPED) && ret == 0) {
4350 		mas->tree->ma_flags &= ~MT_FLAGS_ALLOC_WRAPPED;
4351 		ret = 1;
4352 	}
4353 	if (ret < 0 && range_lo > min) {
4354 		ret = mas_empty_area(mas, min, range_hi, 1);
4355 		if (ret == 0)
4356 			ret = 1;
4357 	}
4358 	if (ret < 0)
4359 		return ret;
4360 
4361 	do {
4362 		mas_insert(mas, entry);
4363 	} while (mas_nomem(mas, gfp));
4364 	if (mas_is_err(mas))
4365 		return xa_err(mas->node);
4366 
4367 	*startp = mas->index;
4368 	*next = *startp + 1;
4369 	if (*next == 0)
4370 		mas->tree->ma_flags |= MT_FLAGS_ALLOC_WRAPPED;
4371 
4372 	mas_destroy(mas);
4373 	return ret;
4374 }
4375 EXPORT_SYMBOL(mas_alloc_cyclic);
4376 
4377 static __always_inline void mas_rewalk(struct ma_state *mas, unsigned long index)
4378 {
4379 retry:
4380 	mas_set(mas, index);
4381 	mas_state_walk(mas);
4382 	if (mas_is_start(mas))
4383 		goto retry;
4384 }
4385 
4386 static __always_inline bool mas_rewalk_if_dead(struct ma_state *mas,
4387 		struct maple_node *node, const unsigned long index)
4388 {
4389 	if (unlikely(ma_dead_node(node))) {
4390 		mas_rewalk(mas, index);
4391 		return true;
4392 	}
4393 	return false;
4394 }
4395 
4396 /*
4397  * mas_prev_node() - Find the prev non-null entry at the same level in the
4398  * tree.  The prev value will be mas->node[mas->offset] or the status will be
4399  * ma_none.
4400  * @mas: The maple state
4401  * @min: The lower limit to search
4402  *
4403  * The prev node value will be mas->node[mas->offset] or the status will be
4404  * ma_none.
4405  * Return: 1 if the node is dead, 0 otherwise.
4406  */
4407 static int mas_prev_node(struct ma_state *mas, unsigned long min)
4408 {
4409 	enum maple_type mt;
4410 	int offset, level;
4411 	void __rcu **slots;
4412 	struct maple_node *node;
4413 	unsigned long *pivots;
4414 	unsigned long max;
4415 
4416 	node = mas_mn(mas);
4417 	if (!mas->min)
4418 		goto no_entry;
4419 
4420 	max = mas->min - 1;
4421 	if (max < min)
4422 		goto no_entry;
4423 
4424 	level = 0;
4425 	do {
4426 		if (ma_is_root(node))
4427 			goto no_entry;
4428 
4429 		/* Walk up. */
4430 		if (unlikely(mas_ascend(mas)))
4431 			return 1;
4432 		offset = mas->offset;
4433 		level++;
4434 		node = mas_mn(mas);
4435 	} while (!offset);
4436 
4437 	offset--;
4438 	mt = mte_node_type(mas->node);
4439 	while (level > 1) {
4440 		level--;
4441 		slots = ma_slots(node, mt);
4442 		mas->node = mas_slot(mas, slots, offset);
4443 		if (unlikely(ma_dead_node(node)))
4444 			return 1;
4445 
4446 		mt = mte_node_type(mas->node);
4447 		node = mas_mn(mas);
4448 		pivots = ma_pivots(node, mt);
4449 		offset = ma_data_end(node, mt, pivots, max);
4450 		if (unlikely(ma_dead_node(node)))
4451 			return 1;
4452 	}
4453 
4454 	slots = ma_slots(node, mt);
4455 	mas->node = mas_slot(mas, slots, offset);
4456 	pivots = ma_pivots(node, mt);
4457 	if (unlikely(ma_dead_node(node)))
4458 		return 1;
4459 
4460 	if (likely(offset))
4461 		mas->min = pivots[offset - 1] + 1;
4462 	mas->max = max;
4463 	mas->offset = mas_data_end(mas);
4464 	if (unlikely(mte_dead_node(mas->node)))
4465 		return 1;
4466 
4467 	mas->end = mas->offset;
4468 	return 0;
4469 
4470 no_entry:
4471 	if (unlikely(ma_dead_node(node)))
4472 		return 1;
4473 
4474 	mas->status = ma_underflow;
4475 	return 0;
4476 }
4477 
4478 /*
4479  * mas_prev_slot() - Get the entry in the previous slot
4480  *
4481  * @mas: The maple state
4482  * @min: The minimum starting range
4483  * @empty: Can be empty
4484  *
4485  * Return: The entry in the previous slot which is possibly NULL
4486  */
4487 static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty)
4488 {
4489 	void *entry;
4490 	void __rcu **slots;
4491 	unsigned long pivot;
4492 	enum maple_type type;
4493 	unsigned long *pivots;
4494 	struct maple_node *node;
4495 	unsigned long save_point = mas->index;
4496 
4497 retry:
4498 	node = mas_mn(mas);
4499 	type = mte_node_type(mas->node);
4500 	pivots = ma_pivots(node, type);
4501 	if (unlikely(mas_rewalk_if_dead(mas, node, save_point)))
4502 		goto retry;
4503 
4504 	if (mas->min <= min) {
4505 		pivot = mas_safe_min(mas, pivots, mas->offset);
4506 
4507 		if (unlikely(mas_rewalk_if_dead(mas, node, save_point)))
4508 			goto retry;
4509 
4510 		if (pivot <= min)
4511 			goto underflow;
4512 	}
4513 
4514 again:
4515 	if (likely(mas->offset)) {
4516 		mas->offset--;
4517 		mas->last = mas->index - 1;
4518 		mas->index = mas_safe_min(mas, pivots, mas->offset);
4519 	} else  {
4520 		if (mas->index <= min)
4521 			goto underflow;
4522 
4523 		if (mas_prev_node(mas, min)) {
4524 			mas_rewalk(mas, save_point);
4525 			goto retry;
4526 		}
4527 
4528 		if (WARN_ON_ONCE(mas_is_underflow(mas)))
4529 			return NULL;
4530 
4531 		mas->last = mas->max;
4532 		node = mas_mn(mas);
4533 		type = mte_node_type(mas->node);
4534 		pivots = ma_pivots(node, type);
4535 		mas->index = pivots[mas->offset - 1] + 1;
4536 	}
4537 
4538 	slots = ma_slots(node, type);
4539 	entry = mas_slot(mas, slots, mas->offset);
4540 	if (unlikely(mas_rewalk_if_dead(mas, node, save_point)))
4541 		goto retry;
4542 
4543 
4544 	if (likely(entry))
4545 		return entry;
4546 
4547 	if (!empty) {
4548 		if (mas->index <= min) {
4549 			mas->status = ma_underflow;
4550 			return NULL;
4551 		}
4552 
4553 		goto again;
4554 	}
4555 
4556 	return entry;
4557 
4558 underflow:
4559 	mas->status = ma_underflow;
4560 	return NULL;
4561 }
4562 
4563 /*
4564  * mas_next_node() - Get the next node at the same level in the tree.
4565  * @mas: The maple state
4566  * @node: The maple node
4567  * @max: The maximum pivot value to check.
4568  *
4569  * The next value will be mas->node[mas->offset] or the status will have
4570  * overflowed.
4571  * Return: 1 on dead node, 0 otherwise.
4572  */
4573 static int mas_next_node(struct ma_state *mas, struct maple_node *node,
4574 		unsigned long max)
4575 {
4576 	unsigned long min;
4577 	unsigned long *pivots;
4578 	struct maple_enode *enode;
4579 	struct maple_node *tmp;
4580 	int level = 0;
4581 	unsigned char node_end;
4582 	enum maple_type mt;
4583 	void __rcu **slots;
4584 
4585 	if (mas->max >= max)
4586 		goto overflow;
4587 
4588 	min = mas->max + 1;
4589 	level = 0;
4590 	do {
4591 		if (ma_is_root(node))
4592 			goto overflow;
4593 
4594 		/* Walk up. */
4595 		if (unlikely(mas_ascend(mas)))
4596 			return 1;
4597 
4598 		level++;
4599 		node = mas_mn(mas);
4600 		mt = mte_node_type(mas->node);
4601 		pivots = ma_pivots(node, mt);
4602 		node_end = ma_data_end(node, mt, pivots, mas->max);
4603 		if (unlikely(ma_dead_node(node)))
4604 			return 1;
4605 
4606 	} while (unlikely(mas->offset == node_end));
4607 
4608 	slots = ma_slots(node, mt);
4609 	mas->offset++;
4610 	enode = mas_slot(mas, slots, mas->offset);
4611 	if (unlikely(ma_dead_node(node)))
4612 		return 1;
4613 
4614 	if (level > 1)
4615 		mas->offset = 0;
4616 
4617 	while (unlikely(level > 1)) {
4618 		level--;
4619 		mas->node = enode;
4620 		node = mas_mn(mas);
4621 		mt = mte_node_type(mas->node);
4622 		slots = ma_slots(node, mt);
4623 		enode = mas_slot(mas, slots, 0);
4624 		if (unlikely(ma_dead_node(node)))
4625 			return 1;
4626 	}
4627 
4628 	if (!mas->offset)
4629 		pivots = ma_pivots(node, mt);
4630 
4631 	mas->max = mas_safe_pivot(mas, pivots, mas->offset, mt);
4632 	tmp = mte_to_node(enode);
4633 	mt = mte_node_type(enode);
4634 	pivots = ma_pivots(tmp, mt);
4635 	mas->end = ma_data_end(tmp, mt, pivots, mas->max);
4636 	if (unlikely(ma_dead_node(node)))
4637 		return 1;
4638 
4639 	mas->node = enode;
4640 	mas->min = min;
4641 	return 0;
4642 
4643 overflow:
4644 	if (unlikely(ma_dead_node(node)))
4645 		return 1;
4646 
4647 	mas->status = ma_overflow;
4648 	return 0;
4649 }
4650 
4651 /*
4652  * mas_next_slot() - Get the entry in the next slot
4653  *
4654  * @mas: The maple state
4655  * @max: The maximum starting range
4656  * @empty: Can be empty
4657  *
4658  * Return: The entry in the next slot which is possibly NULL
4659  */
4660 static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty)
4661 {
4662 	void __rcu **slots;
4663 	unsigned long *pivots;
4664 	unsigned long pivot;
4665 	enum maple_type type;
4666 	struct maple_node *node;
4667 	unsigned long save_point = mas->last;
4668 	void *entry;
4669 
4670 retry:
4671 	node = mas_mn(mas);
4672 	type = mte_node_type(mas->node);
4673 	pivots = ma_pivots(node, type);
4674 	if (unlikely(mas_rewalk_if_dead(mas, node, save_point)))
4675 		goto retry;
4676 
4677 	if (mas->max >= max) {
4678 		if (likely(mas->offset < mas->end))
4679 			pivot = pivots[mas->offset];
4680 		else
4681 			pivot = mas->max;
4682 
4683 		if (unlikely(mas_rewalk_if_dead(mas, node, save_point)))
4684 			goto retry;
4685 
4686 		if (pivot >= max) { /* Was at the limit, next will extend beyond */
4687 			mas->status = ma_overflow;
4688 			return NULL;
4689 		}
4690 	}
4691 
4692 	if (likely(mas->offset < mas->end)) {
4693 		mas->index = pivots[mas->offset] + 1;
4694 again:
4695 		mas->offset++;
4696 		if (likely(mas->offset < mas->end))
4697 			mas->last = pivots[mas->offset];
4698 		else
4699 			mas->last = mas->max;
4700 	} else  {
4701 		if (mas->last >= max) {
4702 			mas->status = ma_overflow;
4703 			return NULL;
4704 		}
4705 
4706 		if (mas_next_node(mas, node, max)) {
4707 			mas_rewalk(mas, save_point);
4708 			goto retry;
4709 		}
4710 
4711 		if (WARN_ON_ONCE(mas_is_overflow(mas)))
4712 			return NULL;
4713 
4714 		mas->offset = 0;
4715 		mas->index = mas->min;
4716 		node = mas_mn(mas);
4717 		type = mte_node_type(mas->node);
4718 		pivots = ma_pivots(node, type);
4719 		mas->last = pivots[0];
4720 	}
4721 
4722 	slots = ma_slots(node, type);
4723 	entry = mt_slot(mas->tree, slots, mas->offset);
4724 	if (unlikely(mas_rewalk_if_dead(mas, node, save_point)))
4725 		goto retry;
4726 
4727 	if (entry)
4728 		return entry;
4729 
4730 
4731 	if (!empty) {
4732 		if (mas->last >= max) {
4733 			mas->status = ma_overflow;
4734 			return NULL;
4735 		}
4736 
4737 		mas->index = mas->last + 1;
4738 		goto again;
4739 	}
4740 
4741 	return entry;
4742 }
4743 
4744 /*
4745  * mas_next_entry() - Internal function to get the next entry.
4746  * @mas: The maple state
4747  * @limit: The maximum range start.
4748  *
4749  * Set the @mas->node to the next entry and the range_start to
4750  * the beginning value for the entry.  Does not check beyond @limit.
4751  * Sets @mas->index and @mas->last to the range, Does not update @mas->index and
4752  * @mas->last on overflow.
4753  * Restarts on dead nodes.
4754  *
4755  * Return: the next entry or %NULL.
4756  */
4757 static inline void *mas_next_entry(struct ma_state *mas, unsigned long limit)
4758 {
4759 	if (mas->last >= limit) {
4760 		mas->status = ma_overflow;
4761 		return NULL;
4762 	}
4763 
4764 	return mas_next_slot(mas, limit, false);
4765 }
4766 
4767 /*
4768  * mas_rev_awalk() - Internal function.  Reverse allocation walk.  Find the
4769  * highest gap address of a given size in a given node and descend.
4770  * @mas: The maple state
4771  * @size: The needed size.
4772  *
4773  * Return: True if found in a leaf, false otherwise.
4774  *
4775  */
4776 static bool mas_rev_awalk(struct ma_state *mas, unsigned long size,
4777 		unsigned long *gap_min, unsigned long *gap_max)
4778 {
4779 	enum maple_type type = mte_node_type(mas->node);
4780 	struct maple_node *node = mas_mn(mas);
4781 	unsigned long *pivots, *gaps;
4782 	void __rcu **slots;
4783 	unsigned long gap = 0;
4784 	unsigned long max, min;
4785 	unsigned char offset;
4786 
4787 	if (unlikely(mas_is_err(mas)))
4788 		return true;
4789 
4790 	if (ma_is_dense(type)) {
4791 		/* dense nodes. */
4792 		mas->offset = (unsigned char)(mas->index - mas->min);
4793 		return true;
4794 	}
4795 
4796 	pivots = ma_pivots(node, type);
4797 	slots = ma_slots(node, type);
4798 	gaps = ma_gaps(node, type);
4799 	offset = mas->offset;
4800 	min = mas_safe_min(mas, pivots, offset);
4801 	/* Skip out of bounds. */
4802 	while (mas->last < min)
4803 		min = mas_safe_min(mas, pivots, --offset);
4804 
4805 	max = mas_safe_pivot(mas, pivots, offset, type);
4806 	while (mas->index <= max) {
4807 		gap = 0;
4808 		if (gaps)
4809 			gap = gaps[offset];
4810 		else if (!mas_slot(mas, slots, offset))
4811 			gap = max - min + 1;
4812 
4813 		if (gap) {
4814 			if ((size <= gap) && (size <= mas->last - min + 1))
4815 				break;
4816 
4817 			if (!gaps) {
4818 				/* Skip the next slot, it cannot be a gap. */
4819 				if (offset < 2)
4820 					goto ascend;
4821 
4822 				offset -= 2;
4823 				max = pivots[offset];
4824 				min = mas_safe_min(mas, pivots, offset);
4825 				continue;
4826 			}
4827 		}
4828 
4829 		if (!offset)
4830 			goto ascend;
4831 
4832 		offset--;
4833 		max = min - 1;
4834 		min = mas_safe_min(mas, pivots, offset);
4835 	}
4836 
4837 	if (unlikely((mas->index > max) || (size - 1 > max - mas->index)))
4838 		goto no_space;
4839 
4840 	if (unlikely(ma_is_leaf(type))) {
4841 		mas->offset = offset;
4842 		*gap_min = min;
4843 		*gap_max = min + gap - 1;
4844 		return true;
4845 	}
4846 
4847 	/* descend, only happens under lock. */
4848 	mas->node = mas_slot(mas, slots, offset);
4849 	mas->min = min;
4850 	mas->max = max;
4851 	mas->offset = mas_data_end(mas);
4852 	return false;
4853 
4854 ascend:
4855 	if (!mte_is_root(mas->node))
4856 		return false;
4857 
4858 no_space:
4859 	mas_set_err(mas, -EBUSY);
4860 	return false;
4861 }
4862 
4863 static inline bool mas_anode_descend(struct ma_state *mas, unsigned long size)
4864 {
4865 	enum maple_type type = mte_node_type(mas->node);
4866 	unsigned long pivot, min, gap = 0;
4867 	unsigned char offset, data_end;
4868 	unsigned long *gaps, *pivots;
4869 	void __rcu **slots;
4870 	struct maple_node *node;
4871 	bool found = false;
4872 
4873 	if (ma_is_dense(type)) {
4874 		mas->offset = (unsigned char)(mas->index - mas->min);
4875 		return true;
4876 	}
4877 
4878 	node = mas_mn(mas);
4879 	pivots = ma_pivots(node, type);
4880 	slots = ma_slots(node, type);
4881 	gaps = ma_gaps(node, type);
4882 	offset = mas->offset;
4883 	min = mas_safe_min(mas, pivots, offset);
4884 	data_end = ma_data_end(node, type, pivots, mas->max);
4885 	for (; offset <= data_end; offset++) {
4886 		pivot = mas_safe_pivot(mas, pivots, offset, type);
4887 
4888 		/* Not within lower bounds */
4889 		if (mas->index > pivot)
4890 			goto next_slot;
4891 
4892 		if (gaps)
4893 			gap = gaps[offset];
4894 		else if (!mas_slot(mas, slots, offset))
4895 			gap = min(pivot, mas->last) - max(mas->index, min) + 1;
4896 		else
4897 			goto next_slot;
4898 
4899 		if (gap >= size) {
4900 			if (ma_is_leaf(type)) {
4901 				found = true;
4902 				goto done;
4903 			}
4904 			if (mas->index <= pivot) {
4905 				mas->node = mas_slot(mas, slots, offset);
4906 				mas->min = min;
4907 				mas->max = pivot;
4908 				offset = 0;
4909 				break;
4910 			}
4911 		}
4912 next_slot:
4913 		min = pivot + 1;
4914 		if (mas->last <= pivot) {
4915 			mas_set_err(mas, -EBUSY);
4916 			return true;
4917 		}
4918 	}
4919 
4920 	if (mte_is_root(mas->node))
4921 		found = true;
4922 done:
4923 	mas->offset = offset;
4924 	return found;
4925 }
4926 
4927 /**
4928  * mas_walk() - Search for @mas->index in the tree.
4929  * @mas: The maple state.
4930  *
4931  * mas->index and mas->last will be set to the range if there is a value.  If
4932  * mas->status is ma_none, reset to ma_start
4933  *
4934  * Return: the entry at the location or %NULL.
4935  */
4936 void *mas_walk(struct ma_state *mas)
4937 {
4938 	void *entry;
4939 
4940 	if (!mas_is_active(mas) || !mas_is_start(mas))
4941 		mas->status = ma_start;
4942 retry:
4943 	entry = mas_state_walk(mas);
4944 	if (mas_is_start(mas)) {
4945 		goto retry;
4946 	} else if (mas_is_none(mas)) {
4947 		mas->index = 0;
4948 		mas->last = ULONG_MAX;
4949 	} else if (mas_is_ptr(mas)) {
4950 		if (!mas->index) {
4951 			mas->last = 0;
4952 			return entry;
4953 		}
4954 
4955 		mas->index = 1;
4956 		mas->last = ULONG_MAX;
4957 		mas->status = ma_none;
4958 		return NULL;
4959 	}
4960 
4961 	return entry;
4962 }
4963 EXPORT_SYMBOL_GPL(mas_walk);
4964 
4965 static inline bool mas_rewind_node(struct ma_state *mas)
4966 {
4967 	unsigned char slot;
4968 
4969 	do {
4970 		if (mte_is_root(mas->node)) {
4971 			slot = mas->offset;
4972 			if (!slot)
4973 				return false;
4974 		} else {
4975 			mas_ascend(mas);
4976 			slot = mas->offset;
4977 		}
4978 	} while (!slot);
4979 
4980 	mas->offset = --slot;
4981 	return true;
4982 }
4983 
4984 /*
4985  * mas_skip_node() - Internal function.  Skip over a node.
4986  * @mas: The maple state.
4987  *
4988  * Return: true if there is another node, false otherwise.
4989  */
4990 static inline bool mas_skip_node(struct ma_state *mas)
4991 {
4992 	if (mas_is_err(mas))
4993 		return false;
4994 
4995 	do {
4996 		if (mte_is_root(mas->node)) {
4997 			if (mas->offset >= mas_data_end(mas)) {
4998 				mas_set_err(mas, -EBUSY);
4999 				return false;
5000 			}
5001 		} else {
5002 			mas_ascend(mas);
5003 		}
5004 	} while (mas->offset >= mas_data_end(mas));
5005 
5006 	mas->offset++;
5007 	return true;
5008 }
5009 
5010 /*
5011  * mas_awalk() - Allocation walk.  Search from low address to high, for a gap of
5012  * @size
5013  * @mas: The maple state
5014  * @size: The size of the gap required
5015  *
5016  * Search between @mas->index and @mas->last for a gap of @size.
5017  */
5018 static inline void mas_awalk(struct ma_state *mas, unsigned long size)
5019 {
5020 	struct maple_enode *last = NULL;
5021 
5022 	/*
5023 	 * There are 4 options:
5024 	 * go to child (descend)
5025 	 * go back to parent (ascend)
5026 	 * no gap found. (return, slot == MAPLE_NODE_SLOTS)
5027 	 * found the gap. (return, slot != MAPLE_NODE_SLOTS)
5028 	 */
5029 	while (!mas_is_err(mas) && !mas_anode_descend(mas, size)) {
5030 		if (last == mas->node)
5031 			mas_skip_node(mas);
5032 		else
5033 			last = mas->node;
5034 	}
5035 }
5036 
5037 /*
5038  * mas_sparse_area() - Internal function.  Return upper or lower limit when
5039  * searching for a gap in an empty tree.
5040  * @mas: The maple state
5041  * @min: the minimum range
5042  * @max: The maximum range
5043  * @size: The size of the gap
5044  * @fwd: Searching forward or back
5045  */
5046 static inline int mas_sparse_area(struct ma_state *mas, unsigned long min,
5047 				unsigned long max, unsigned long size, bool fwd)
5048 {
5049 	if (!unlikely(mas_is_none(mas)) && min == 0) {
5050 		min++;
5051 		/*
5052 		 * At this time, min is increased, we need to recheck whether
5053 		 * the size is satisfied.
5054 		 */
5055 		if (min > max || max - min + 1 < size)
5056 			return -EBUSY;
5057 	}
5058 	/* mas_is_ptr */
5059 
5060 	if (fwd) {
5061 		mas->index = min;
5062 		mas->last = min + size - 1;
5063 	} else {
5064 		mas->last = max;
5065 		mas->index = max - size + 1;
5066 	}
5067 	return 0;
5068 }
5069 
5070 /*
5071  * mas_empty_area() - Get the lowest address within the range that is
5072  * sufficient for the size requested.
5073  * @mas: The maple state
5074  * @min: The lowest value of the range
5075  * @max: The highest value of the range
5076  * @size: The size needed
5077  */
5078 int mas_empty_area(struct ma_state *mas, unsigned long min,
5079 		unsigned long max, unsigned long size)
5080 {
5081 	unsigned char offset;
5082 	unsigned long *pivots;
5083 	enum maple_type mt;
5084 	struct maple_node *node;
5085 
5086 	if (min > max)
5087 		return -EINVAL;
5088 
5089 	if (size == 0 || max - min < size - 1)
5090 		return -EINVAL;
5091 
5092 	if (mas_is_start(mas))
5093 		mas_start(mas);
5094 	else if (mas->offset >= 2)
5095 		mas->offset -= 2;
5096 	else if (!mas_skip_node(mas))
5097 		return -EBUSY;
5098 
5099 	/* Empty set */
5100 	if (mas_is_none(mas) || mas_is_ptr(mas))
5101 		return mas_sparse_area(mas, min, max, size, true);
5102 
5103 	/* The start of the window can only be within these values */
5104 	mas->index = min;
5105 	mas->last = max;
5106 	mas_awalk(mas, size);
5107 
5108 	if (unlikely(mas_is_err(mas)))
5109 		return xa_err(mas->node);
5110 
5111 	offset = mas->offset;
5112 	if (unlikely(offset == MAPLE_NODE_SLOTS))
5113 		return -EBUSY;
5114 
5115 	node = mas_mn(mas);
5116 	mt = mte_node_type(mas->node);
5117 	pivots = ma_pivots(node, mt);
5118 	min = mas_safe_min(mas, pivots, offset);
5119 	if (mas->index < min)
5120 		mas->index = min;
5121 	mas->last = mas->index + size - 1;
5122 	mas->end = ma_data_end(node, mt, pivots, mas->max);
5123 	return 0;
5124 }
5125 EXPORT_SYMBOL_GPL(mas_empty_area);
5126 
5127 /*
5128  * mas_empty_area_rev() - Get the highest address within the range that is
5129  * sufficient for the size requested.
5130  * @mas: The maple state
5131  * @min: The lowest value of the range
5132  * @max: The highest value of the range
5133  * @size: The size needed
5134  */
5135 int mas_empty_area_rev(struct ma_state *mas, unsigned long min,
5136 		unsigned long max, unsigned long size)
5137 {
5138 	struct maple_enode *last = mas->node;
5139 
5140 	if (min > max)
5141 		return -EINVAL;
5142 
5143 	if (size == 0 || max - min < size - 1)
5144 		return -EINVAL;
5145 
5146 	if (mas_is_start(mas))
5147 		mas_start(mas);
5148 	else if ((mas->offset < 2) && (!mas_rewind_node(mas)))
5149 		return -EBUSY;
5150 
5151 	if (unlikely(mas_is_none(mas) || mas_is_ptr(mas)))
5152 		return mas_sparse_area(mas, min, max, size, false);
5153 	else if (mas->offset >= 2)
5154 		mas->offset -= 2;
5155 	else
5156 		mas->offset = mas_data_end(mas);
5157 
5158 
5159 	/* The start of the window can only be within these values. */
5160 	mas->index = min;
5161 	mas->last = max;
5162 
5163 	while (!mas_rev_awalk(mas, size, &min, &max)) {
5164 		if (last == mas->node) {
5165 			if (!mas_rewind_node(mas))
5166 				return -EBUSY;
5167 		} else {
5168 			last = mas->node;
5169 		}
5170 	}
5171 
5172 	if (mas_is_err(mas))
5173 		return xa_err(mas->node);
5174 
5175 	if (unlikely(mas->offset == MAPLE_NODE_SLOTS))
5176 		return -EBUSY;
5177 
5178 	/* Trim the upper limit to the max. */
5179 	if (max < mas->last)
5180 		mas->last = max;
5181 
5182 	mas->index = mas->last - size + 1;
5183 	mas->end = mas_data_end(mas);
5184 	return 0;
5185 }
5186 EXPORT_SYMBOL_GPL(mas_empty_area_rev);
5187 
5188 /*
5189  * mte_dead_leaves() - Mark all leaves of a node as dead.
5190  * @enode: the encoded node
5191  * @mt: the maple tree
5192  * @slots: Pointer to the slot array
5193  *
5194  * Must hold the write lock.
5195  *
5196  * Return: The number of leaves marked as dead.
5197  */
5198 static inline
5199 unsigned char mte_dead_leaves(struct maple_enode *enode, struct maple_tree *mt,
5200 			      void __rcu **slots)
5201 {
5202 	struct maple_node *node;
5203 	enum maple_type type;
5204 	void *entry;
5205 	int offset;
5206 
5207 	for (offset = 0; offset < mt_slot_count(enode); offset++) {
5208 		entry = mt_slot(mt, slots, offset);
5209 		type = mte_node_type(entry);
5210 		node = mte_to_node(entry);
5211 		/* Use both node and type to catch LE & BE metadata */
5212 		if (!node || !type)
5213 			break;
5214 
5215 		mte_set_node_dead(entry);
5216 		node->type = type;
5217 		rcu_assign_pointer(slots[offset], node);
5218 	}
5219 
5220 	return offset;
5221 }
5222 
5223 /**
5224  * mte_dead_walk() - Walk down a dead tree to just before the leaves
5225  * @enode: The maple encoded node
5226  * @offset: The starting offset
5227  *
5228  * Note: This can only be used from the RCU callback context.
5229  */
5230 static void __rcu **mte_dead_walk(struct maple_enode **enode, unsigned char offset)
5231 {
5232 	struct maple_node *node, *next;
5233 	void __rcu **slots = NULL;
5234 
5235 	next = mte_to_node(*enode);
5236 	do {
5237 		*enode = ma_enode_ptr(next);
5238 		node = mte_to_node(*enode);
5239 		slots = ma_slots(node, node->type);
5240 		next = rcu_dereference_protected(slots[offset],
5241 					lock_is_held(&rcu_callback_map));
5242 		offset = 0;
5243 	} while (!ma_is_leaf(next->type));
5244 
5245 	return slots;
5246 }
5247 
5248 /**
5249  * mt_free_walk() - Walk & free a tree in the RCU callback context
5250  * @head: The RCU head that's within the node.
5251  *
5252  * Note: This can only be used from the RCU callback context.
5253  */
5254 static void mt_free_walk(struct rcu_head *head)
5255 {
5256 	void __rcu **slots;
5257 	struct maple_node *node, *start;
5258 	struct maple_enode *enode;
5259 	unsigned char offset;
5260 	enum maple_type type;
5261 
5262 	node = container_of(head, struct maple_node, rcu);
5263 
5264 	if (ma_is_leaf(node->type))
5265 		goto free_leaf;
5266 
5267 	start = node;
5268 	enode = mt_mk_node(node, node->type);
5269 	slots = mte_dead_walk(&enode, 0);
5270 	node = mte_to_node(enode);
5271 	do {
5272 		mt_free_bulk(node->slot_len, slots);
5273 		offset = node->parent_slot + 1;
5274 		enode = node->piv_parent;
5275 		if (mte_to_node(enode) == node)
5276 			goto free_leaf;
5277 
5278 		type = mte_node_type(enode);
5279 		slots = ma_slots(mte_to_node(enode), type);
5280 		if ((offset < mt_slots[type]) &&
5281 		    rcu_dereference_protected(slots[offset],
5282 					      lock_is_held(&rcu_callback_map)))
5283 			slots = mte_dead_walk(&enode, offset);
5284 		node = mte_to_node(enode);
5285 	} while ((node != start) || (node->slot_len < offset));
5286 
5287 	slots = ma_slots(node, node->type);
5288 	mt_free_bulk(node->slot_len, slots);
5289 
5290 free_leaf:
5291 	mt_free_rcu(&node->rcu);
5292 }
5293 
5294 static inline void __rcu **mte_destroy_descend(struct maple_enode **enode,
5295 	struct maple_tree *mt, struct maple_enode *prev, unsigned char offset)
5296 {
5297 	struct maple_node *node;
5298 	struct maple_enode *next = *enode;
5299 	void __rcu **slots = NULL;
5300 	enum maple_type type;
5301 	unsigned char next_offset = 0;
5302 
5303 	do {
5304 		*enode = next;
5305 		node = mte_to_node(*enode);
5306 		type = mte_node_type(*enode);
5307 		slots = ma_slots(node, type);
5308 		next = mt_slot_locked(mt, slots, next_offset);
5309 		if ((mte_dead_node(next)))
5310 			next = mt_slot_locked(mt, slots, ++next_offset);
5311 
5312 		mte_set_node_dead(*enode);
5313 		node->type = type;
5314 		node->piv_parent = prev;
5315 		node->parent_slot = offset;
5316 		offset = next_offset;
5317 		next_offset = 0;
5318 		prev = *enode;
5319 	} while (!mte_is_leaf(next));
5320 
5321 	return slots;
5322 }
5323 
5324 static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt,
5325 			    bool free)
5326 {
5327 	void __rcu **slots;
5328 	struct maple_node *node = mte_to_node(enode);
5329 	struct maple_enode *start;
5330 
5331 	if (mte_is_leaf(enode)) {
5332 		node->type = mte_node_type(enode);
5333 		goto free_leaf;
5334 	}
5335 
5336 	start = enode;
5337 	slots = mte_destroy_descend(&enode, mt, start, 0);
5338 	node = mte_to_node(enode); // Updated in the above call.
5339 	do {
5340 		enum maple_type type;
5341 		unsigned char offset;
5342 		struct maple_enode *parent, *tmp;
5343 
5344 		node->slot_len = mte_dead_leaves(enode, mt, slots);
5345 		if (free)
5346 			mt_free_bulk(node->slot_len, slots);
5347 		offset = node->parent_slot + 1;
5348 		enode = node->piv_parent;
5349 		if (mte_to_node(enode) == node)
5350 			goto free_leaf;
5351 
5352 		type = mte_node_type(enode);
5353 		slots = ma_slots(mte_to_node(enode), type);
5354 		if (offset >= mt_slots[type])
5355 			goto next;
5356 
5357 		tmp = mt_slot_locked(mt, slots, offset);
5358 		if (mte_node_type(tmp) && mte_to_node(tmp)) {
5359 			parent = enode;
5360 			enode = tmp;
5361 			slots = mte_destroy_descend(&enode, mt, parent, offset);
5362 		}
5363 next:
5364 		node = mte_to_node(enode);
5365 	} while (start != enode);
5366 
5367 	node = mte_to_node(enode);
5368 	node->slot_len = mte_dead_leaves(enode, mt, slots);
5369 	if (free)
5370 		mt_free_bulk(node->slot_len, slots);
5371 
5372 free_leaf:
5373 	if (free)
5374 		mt_free_rcu(&node->rcu);
5375 	else
5376 		mt_clear_meta(mt, node, node->type);
5377 }
5378 
5379 /*
5380  * mte_destroy_walk() - Free a tree or sub-tree.
5381  * @enode: the encoded maple node (maple_enode) to start
5382  * @mt: the tree to free - needed for node types.
5383  *
5384  * Must hold the write lock.
5385  */
5386 static inline void mte_destroy_walk(struct maple_enode *enode,
5387 				    struct maple_tree *mt)
5388 {
5389 	struct maple_node *node = mte_to_node(enode);
5390 
5391 	if (mt_in_rcu(mt)) {
5392 		mt_destroy_walk(enode, mt, false);
5393 		call_rcu(&node->rcu, mt_free_walk);
5394 	} else {
5395 		mt_destroy_walk(enode, mt, true);
5396 	}
5397 }
5398 /* Interface */
5399 
5400 /**
5401  * mas_store() - Store an @entry.
5402  * @mas: The maple state.
5403  * @entry: The entry to store.
5404  *
5405  * The @mas->index and @mas->last is used to set the range for the @entry.
5406  *
5407  * Return: the first entry between mas->index and mas->last or %NULL.
5408  */
5409 void *mas_store(struct ma_state *mas, void *entry)
5410 {
5411 	int request;
5412 	MA_WR_STATE(wr_mas, mas, entry);
5413 
5414 	trace_ma_write(__func__, mas, 0, entry);
5415 #ifdef CONFIG_DEBUG_MAPLE_TREE
5416 	if (MAS_WARN_ON(mas, mas->index > mas->last))
5417 		pr_err("Error %lX > %lX %p\n", mas->index, mas->last, entry);
5418 
5419 	if (mas->index > mas->last) {
5420 		mas_set_err(mas, -EINVAL);
5421 		return NULL;
5422 	}
5423 
5424 #endif
5425 
5426 	/*
5427 	 * Storing is the same operation as insert with the added caveat that it
5428 	 * can overwrite entries.  Although this seems simple enough, one may
5429 	 * want to examine what happens if a single store operation was to
5430 	 * overwrite multiple entries within a self-balancing B-Tree.
5431 	 */
5432 	mas_wr_prealloc_setup(&wr_mas);
5433 	mas_wr_store_type(&wr_mas);
5434 	if (mas->mas_flags & MA_STATE_PREALLOC) {
5435 		mas_wr_store_entry(&wr_mas);
5436 		MAS_WR_BUG_ON(&wr_mas, mas_is_err(mas));
5437 		return wr_mas.content;
5438 	}
5439 
5440 	request = mas_prealloc_calc(mas, entry);
5441 	if (!request)
5442 		goto store;
5443 
5444 	mas_node_count(mas, request);
5445 	if (mas_is_err(mas))
5446 		return NULL;
5447 
5448 store:
5449 	mas_wr_store_entry(&wr_mas);
5450 	mas_destroy(mas);
5451 	return wr_mas.content;
5452 }
5453 EXPORT_SYMBOL_GPL(mas_store);
5454 
5455 /**
5456  * mas_store_gfp() - Store a value into the tree.
5457  * @mas: The maple state
5458  * @entry: The entry to store
5459  * @gfp: The GFP_FLAGS to use for allocations if necessary.
5460  *
5461  * Return: 0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
5462  * be allocated.
5463  */
5464 int mas_store_gfp(struct ma_state *mas, void *entry, gfp_t gfp)
5465 {
5466 	unsigned long index = mas->index;
5467 	unsigned long last = mas->last;
5468 	MA_WR_STATE(wr_mas, mas, entry);
5469 	int ret = 0;
5470 
5471 retry:
5472 	mas_wr_preallocate(&wr_mas, entry);
5473 	if (unlikely(mas_nomem(mas, gfp))) {
5474 		if (!entry)
5475 			__mas_set_range(mas, index, last);
5476 		goto retry;
5477 	}
5478 
5479 	if (mas_is_err(mas)) {
5480 		ret = xa_err(mas->node);
5481 		goto out;
5482 	}
5483 
5484 	mas_wr_store_entry(&wr_mas);
5485 out:
5486 	mas_destroy(mas);
5487 	return ret;
5488 }
5489 EXPORT_SYMBOL_GPL(mas_store_gfp);
5490 
5491 /**
5492  * mas_store_prealloc() - Store a value into the tree using memory
5493  * preallocated in the maple state.
5494  * @mas: The maple state
5495  * @entry: The entry to store.
5496  */
5497 void mas_store_prealloc(struct ma_state *mas, void *entry)
5498 {
5499 	MA_WR_STATE(wr_mas, mas, entry);
5500 
5501 	if (mas->store_type == wr_store_root) {
5502 		mas_wr_prealloc_setup(&wr_mas);
5503 		goto store;
5504 	}
5505 
5506 	mas_wr_walk_descend(&wr_mas);
5507 	if (mas->store_type != wr_spanning_store) {
5508 		/* set wr_mas->content to current slot */
5509 		wr_mas.content = mas_slot_locked(mas, wr_mas.slots, mas->offset);
5510 		mas_wr_end_piv(&wr_mas);
5511 	}
5512 
5513 store:
5514 	trace_ma_write(__func__, mas, 0, entry);
5515 	mas_wr_store_entry(&wr_mas);
5516 	MAS_WR_BUG_ON(&wr_mas, mas_is_err(mas));
5517 	mas_destroy(mas);
5518 }
5519 EXPORT_SYMBOL_GPL(mas_store_prealloc);
5520 
5521 /**
5522  * mas_preallocate() - Preallocate enough nodes for a store operation
5523  * @mas: The maple state
5524  * @entry: The entry that will be stored
5525  * @gfp: The GFP_FLAGS to use for allocations.
5526  *
5527  * Return: 0 on success, -ENOMEM if memory could not be allocated.
5528  */
5529 int mas_preallocate(struct ma_state *mas, void *entry, gfp_t gfp)
5530 {
5531 	MA_WR_STATE(wr_mas, mas, entry);
5532 	int ret = 0;
5533 	int request;
5534 
5535 	mas_wr_prealloc_setup(&wr_mas);
5536 	mas_wr_store_type(&wr_mas);
5537 	request = mas_prealloc_calc(mas, entry);
5538 	if (!request)
5539 		return ret;
5540 
5541 	mas_node_count_gfp(mas, request, gfp);
5542 	if (mas_is_err(mas)) {
5543 		mas_set_alloc_req(mas, 0);
5544 		ret = xa_err(mas->node);
5545 		mas_destroy(mas);
5546 		mas_reset(mas);
5547 		return ret;
5548 	}
5549 
5550 	mas->mas_flags |= MA_STATE_PREALLOC;
5551 	return ret;
5552 }
5553 EXPORT_SYMBOL_GPL(mas_preallocate);
5554 
5555 /*
5556  * mas_destroy() - destroy a maple state.
5557  * @mas: The maple state
5558  *
5559  * Upon completion, check the left-most node and rebalance against the node to
5560  * the right if necessary.  Frees any allocated nodes associated with this maple
5561  * state.
5562  */
5563 void mas_destroy(struct ma_state *mas)
5564 {
5565 	struct maple_alloc *node;
5566 	unsigned long total;
5567 
5568 	/*
5569 	 * When using mas_for_each() to insert an expected number of elements,
5570 	 * it is possible that the number inserted is less than the expected
5571 	 * number.  To fix an invalid final node, a check is performed here to
5572 	 * rebalance the previous node with the final node.
5573 	 */
5574 	if (mas->mas_flags & MA_STATE_REBALANCE) {
5575 		unsigned char end;
5576 		if (mas_is_err(mas))
5577 			mas_reset(mas);
5578 		mas_start(mas);
5579 		mtree_range_walk(mas);
5580 		end = mas->end + 1;
5581 		if (end < mt_min_slot_count(mas->node) - 1)
5582 			mas_destroy_rebalance(mas, end);
5583 
5584 		mas->mas_flags &= ~MA_STATE_REBALANCE;
5585 	}
5586 	mas->mas_flags &= ~(MA_STATE_BULK|MA_STATE_PREALLOC);
5587 
5588 	total = mas_allocated(mas);
5589 	while (total) {
5590 		node = mas->alloc;
5591 		mas->alloc = node->slot[0];
5592 		if (node->node_count > 1) {
5593 			size_t count = node->node_count - 1;
5594 
5595 			mt_free_bulk(count, (void __rcu **)&node->slot[1]);
5596 			total -= count;
5597 		}
5598 		mt_free_one(ma_mnode_ptr(node));
5599 		total--;
5600 	}
5601 
5602 	mas->alloc = NULL;
5603 }
5604 EXPORT_SYMBOL_GPL(mas_destroy);
5605 
5606 /*
5607  * mas_expected_entries() - Set the expected number of entries that will be inserted.
5608  * @mas: The maple state
5609  * @nr_entries: The number of expected entries.
5610  *
5611  * This will attempt to pre-allocate enough nodes to store the expected number
5612  * of entries.  The allocations will occur using the bulk allocator interface
5613  * for speed.  Please call mas_destroy() on the @mas after inserting the entries
5614  * to ensure any unused nodes are freed.
5615  *
5616  * Return: 0 on success, -ENOMEM if memory could not be allocated.
5617  */
5618 int mas_expected_entries(struct ma_state *mas, unsigned long nr_entries)
5619 {
5620 	int nonleaf_cap = MAPLE_ARANGE64_SLOTS - 2;
5621 	struct maple_enode *enode = mas->node;
5622 	int nr_nodes;
5623 	int ret;
5624 
5625 	/*
5626 	 * Sometimes it is necessary to duplicate a tree to a new tree, such as
5627 	 * forking a process and duplicating the VMAs from one tree to a new
5628 	 * tree.  When such a situation arises, it is known that the new tree is
5629 	 * not going to be used until the entire tree is populated.  For
5630 	 * performance reasons, it is best to use a bulk load with RCU disabled.
5631 	 * This allows for optimistic splitting that favours the left and reuse
5632 	 * of nodes during the operation.
5633 	 */
5634 
5635 	/* Optimize splitting for bulk insert in-order */
5636 	mas->mas_flags |= MA_STATE_BULK;
5637 
5638 	/*
5639 	 * Avoid overflow, assume a gap between each entry and a trailing null.
5640 	 * If this is wrong, it just means allocation can happen during
5641 	 * insertion of entries.
5642 	 */
5643 	nr_nodes = max(nr_entries, nr_entries * 2 + 1);
5644 	if (!mt_is_alloc(mas->tree))
5645 		nonleaf_cap = MAPLE_RANGE64_SLOTS - 2;
5646 
5647 	/* Leaves; reduce slots to keep space for expansion */
5648 	nr_nodes = DIV_ROUND_UP(nr_nodes, MAPLE_RANGE64_SLOTS - 2);
5649 	/* Internal nodes */
5650 	nr_nodes += DIV_ROUND_UP(nr_nodes, nonleaf_cap);
5651 	/* Add working room for split (2 nodes) + new parents */
5652 	mas_node_count_gfp(mas, nr_nodes + 3, GFP_KERNEL);
5653 
5654 	/* Detect if allocations run out */
5655 	mas->mas_flags |= MA_STATE_PREALLOC;
5656 
5657 	if (!mas_is_err(mas))
5658 		return 0;
5659 
5660 	ret = xa_err(mas->node);
5661 	mas->node = enode;
5662 	mas_destroy(mas);
5663 	return ret;
5664 
5665 }
5666 EXPORT_SYMBOL_GPL(mas_expected_entries);
5667 
5668 static bool mas_next_setup(struct ma_state *mas, unsigned long max,
5669 		void **entry)
5670 {
5671 	bool was_none = mas_is_none(mas);
5672 
5673 	if (unlikely(mas->last >= max)) {
5674 		mas->status = ma_overflow;
5675 		return true;
5676 	}
5677 
5678 	switch (mas->status) {
5679 	case ma_active:
5680 		return false;
5681 	case ma_none:
5682 		fallthrough;
5683 	case ma_pause:
5684 		mas->status = ma_start;
5685 		fallthrough;
5686 	case ma_start:
5687 		mas_walk(mas); /* Retries on dead nodes handled by mas_walk */
5688 		break;
5689 	case ma_overflow:
5690 		/* Overflowed before, but the max changed */
5691 		mas->status = ma_active;
5692 		break;
5693 	case ma_underflow:
5694 		/* The user expects the mas to be one before where it is */
5695 		mas->status = ma_active;
5696 		*entry = mas_walk(mas);
5697 		if (*entry)
5698 			return true;
5699 		break;
5700 	case ma_root:
5701 		break;
5702 	case ma_error:
5703 		return true;
5704 	}
5705 
5706 	if (likely(mas_is_active(mas))) /* Fast path */
5707 		return false;
5708 
5709 	if (mas_is_ptr(mas)) {
5710 		*entry = NULL;
5711 		if (was_none && mas->index == 0) {
5712 			mas->index = mas->last = 0;
5713 			return true;
5714 		}
5715 		mas->index = 1;
5716 		mas->last = ULONG_MAX;
5717 		mas->status = ma_none;
5718 		return true;
5719 	}
5720 
5721 	if (mas_is_none(mas))
5722 		return true;
5723 
5724 	return false;
5725 }
5726 
5727 /**
5728  * mas_next() - Get the next entry.
5729  * @mas: The maple state
5730  * @max: The maximum index to check.
5731  *
5732  * Returns the next entry after @mas->index.
5733  * Must hold rcu_read_lock or the write lock.
5734  * Can return the zero entry.
5735  *
5736  * Return: The next entry or %NULL
5737  */
5738 void *mas_next(struct ma_state *mas, unsigned long max)
5739 {
5740 	void *entry = NULL;
5741 
5742 	if (mas_next_setup(mas, max, &entry))
5743 		return entry;
5744 
5745 	/* Retries on dead nodes handled by mas_next_slot */
5746 	return mas_next_slot(mas, max, false);
5747 }
5748 EXPORT_SYMBOL_GPL(mas_next);
5749 
5750 /**
5751  * mas_next_range() - Advance the maple state to the next range
5752  * @mas: The maple state
5753  * @max: The maximum index to check.
5754  *
5755  * Sets @mas->index and @mas->last to the range.
5756  * Must hold rcu_read_lock or the write lock.
5757  * Can return the zero entry.
5758  *
5759  * Return: The next entry or %NULL
5760  */
5761 void *mas_next_range(struct ma_state *mas, unsigned long max)
5762 {
5763 	void *entry = NULL;
5764 
5765 	if (mas_next_setup(mas, max, &entry))
5766 		return entry;
5767 
5768 	/* Retries on dead nodes handled by mas_next_slot */
5769 	return mas_next_slot(mas, max, true);
5770 }
5771 EXPORT_SYMBOL_GPL(mas_next_range);
5772 
5773 /**
5774  * mt_next() - get the next value in the maple tree
5775  * @mt: The maple tree
5776  * @index: The start index
5777  * @max: The maximum index to check
5778  *
5779  * Takes RCU read lock internally to protect the search, which does not
5780  * protect the returned pointer after dropping RCU read lock.
5781  * See also: Documentation/core-api/maple_tree.rst
5782  *
5783  * Return: The entry higher than @index or %NULL if nothing is found.
5784  */
5785 void *mt_next(struct maple_tree *mt, unsigned long index, unsigned long max)
5786 {
5787 	void *entry = NULL;
5788 	MA_STATE(mas, mt, index, index);
5789 
5790 	rcu_read_lock();
5791 	entry = mas_next(&mas, max);
5792 	rcu_read_unlock();
5793 	return entry;
5794 }
5795 EXPORT_SYMBOL_GPL(mt_next);
5796 
5797 static bool mas_prev_setup(struct ma_state *mas, unsigned long min, void **entry)
5798 {
5799 	if (unlikely(mas->index <= min)) {
5800 		mas->status = ma_underflow;
5801 		return true;
5802 	}
5803 
5804 	switch (mas->status) {
5805 	case ma_active:
5806 		return false;
5807 	case ma_start:
5808 		break;
5809 	case ma_none:
5810 		fallthrough;
5811 	case ma_pause:
5812 		mas->status = ma_start;
5813 		break;
5814 	case ma_underflow:
5815 		/* underflowed before but the min changed */
5816 		mas->status = ma_active;
5817 		break;
5818 	case ma_overflow:
5819 		/* User expects mas to be one after where it is */
5820 		mas->status = ma_active;
5821 		*entry = mas_walk(mas);
5822 		if (*entry)
5823 			return true;
5824 		break;
5825 	case ma_root:
5826 		break;
5827 	case ma_error:
5828 		return true;
5829 	}
5830 
5831 	if (mas_is_start(mas))
5832 		mas_walk(mas);
5833 
5834 	if (unlikely(mas_is_ptr(mas))) {
5835 		if (!mas->index) {
5836 			mas->status = ma_none;
5837 			return true;
5838 		}
5839 		mas->index = mas->last = 0;
5840 		*entry = mas_root(mas);
5841 		return true;
5842 	}
5843 
5844 	if (mas_is_none(mas)) {
5845 		if (mas->index) {
5846 			/* Walked to out-of-range pointer? */
5847 			mas->index = mas->last = 0;
5848 			mas->status = ma_root;
5849 			*entry = mas_root(mas);
5850 			return true;
5851 		}
5852 		return true;
5853 	}
5854 
5855 	return false;
5856 }
5857 
5858 /**
5859  * mas_prev() - Get the previous entry
5860  * @mas: The maple state
5861  * @min: The minimum value to check.
5862  *
5863  * Must hold rcu_read_lock or the write lock.
5864  * Will reset mas to ma_start if the status is ma_none.  Will stop on not
5865  * searchable nodes.
5866  *
5867  * Return: the previous value or %NULL.
5868  */
5869 void *mas_prev(struct ma_state *mas, unsigned long min)
5870 {
5871 	void *entry = NULL;
5872 
5873 	if (mas_prev_setup(mas, min, &entry))
5874 		return entry;
5875 
5876 	return mas_prev_slot(mas, min, false);
5877 }
5878 EXPORT_SYMBOL_GPL(mas_prev);
5879 
5880 /**
5881  * mas_prev_range() - Advance to the previous range
5882  * @mas: The maple state
5883  * @min: The minimum value to check.
5884  *
5885  * Sets @mas->index and @mas->last to the range.
5886  * Must hold rcu_read_lock or the write lock.
5887  * Will reset mas to ma_start if the node is ma_none.  Will stop on not
5888  * searchable nodes.
5889  *
5890  * Return: the previous value or %NULL.
5891  */
5892 void *mas_prev_range(struct ma_state *mas, unsigned long min)
5893 {
5894 	void *entry = NULL;
5895 
5896 	if (mas_prev_setup(mas, min, &entry))
5897 		return entry;
5898 
5899 	return mas_prev_slot(mas, min, true);
5900 }
5901 EXPORT_SYMBOL_GPL(mas_prev_range);
5902 
5903 /**
5904  * mt_prev() - get the previous value in the maple tree
5905  * @mt: The maple tree
5906  * @index: The start index
5907  * @min: The minimum index to check
5908  *
5909  * Takes RCU read lock internally to protect the search, which does not
5910  * protect the returned pointer after dropping RCU read lock.
5911  * See also: Documentation/core-api/maple_tree.rst
5912  *
5913  * Return: The entry before @index or %NULL if nothing is found.
5914  */
5915 void *mt_prev(struct maple_tree *mt, unsigned long index, unsigned long min)
5916 {
5917 	void *entry = NULL;
5918 	MA_STATE(mas, mt, index, index);
5919 
5920 	rcu_read_lock();
5921 	entry = mas_prev(&mas, min);
5922 	rcu_read_unlock();
5923 	return entry;
5924 }
5925 EXPORT_SYMBOL_GPL(mt_prev);
5926 
5927 /**
5928  * mas_pause() - Pause a mas_find/mas_for_each to drop the lock.
5929  * @mas: The maple state to pause
5930  *
5931  * Some users need to pause a walk and drop the lock they're holding in
5932  * order to yield to a higher priority thread or carry out an operation
5933  * on an entry.  Those users should call this function before they drop
5934  * the lock.  It resets the @mas to be suitable for the next iteration
5935  * of the loop after the user has reacquired the lock.  If most entries
5936  * found during a walk require you to call mas_pause(), the mt_for_each()
5937  * iterator may be more appropriate.
5938  *
5939  */
5940 void mas_pause(struct ma_state *mas)
5941 {
5942 	mas->status = ma_pause;
5943 	mas->node = NULL;
5944 }
5945 EXPORT_SYMBOL_GPL(mas_pause);
5946 
5947 /**
5948  * mas_find_setup() - Internal function to set up mas_find*().
5949  * @mas: The maple state
5950  * @max: The maximum index
5951  * @entry: Pointer to the entry
5952  *
5953  * Returns: True if entry is the answer, false otherwise.
5954  */
5955 static __always_inline bool mas_find_setup(struct ma_state *mas, unsigned long max, void **entry)
5956 {
5957 	switch (mas->status) {
5958 	case ma_active:
5959 		if (mas->last < max)
5960 			return false;
5961 		return true;
5962 	case ma_start:
5963 		break;
5964 	case ma_pause:
5965 		if (unlikely(mas->last >= max))
5966 			return true;
5967 
5968 		mas->index = ++mas->last;
5969 		mas->status = ma_start;
5970 		break;
5971 	case ma_none:
5972 		if (unlikely(mas->last >= max))
5973 			return true;
5974 
5975 		mas->index = mas->last;
5976 		mas->status = ma_start;
5977 		break;
5978 	case ma_underflow:
5979 		/* mas is pointing at entry before unable to go lower */
5980 		if (unlikely(mas->index >= max)) {
5981 			mas->status = ma_overflow;
5982 			return true;
5983 		}
5984 
5985 		mas->status = ma_active;
5986 		*entry = mas_walk(mas);
5987 		if (*entry)
5988 			return true;
5989 		break;
5990 	case ma_overflow:
5991 		if (unlikely(mas->last >= max))
5992 			return true;
5993 
5994 		mas->status = ma_active;
5995 		*entry = mas_walk(mas);
5996 		if (*entry)
5997 			return true;
5998 		break;
5999 	case ma_root:
6000 		break;
6001 	case ma_error:
6002 		return true;
6003 	}
6004 
6005 	if (mas_is_start(mas)) {
6006 		/* First run or continue */
6007 		if (mas->index > max)
6008 			return true;
6009 
6010 		*entry = mas_walk(mas);
6011 		if (*entry)
6012 			return true;
6013 
6014 	}
6015 
6016 	if (unlikely(mas_is_ptr(mas)))
6017 		goto ptr_out_of_range;
6018 
6019 	if (unlikely(mas_is_none(mas)))
6020 		return true;
6021 
6022 	if (mas->index == max)
6023 		return true;
6024 
6025 	return false;
6026 
6027 ptr_out_of_range:
6028 	mas->status = ma_none;
6029 	mas->index = 1;
6030 	mas->last = ULONG_MAX;
6031 	return true;
6032 }
6033 
6034 /**
6035  * mas_find() - On the first call, find the entry at or after mas->index up to
6036  * %max.  Otherwise, find the entry after mas->index.
6037  * @mas: The maple state
6038  * @max: The maximum value to check.
6039  *
6040  * Must hold rcu_read_lock or the write lock.
6041  * If an entry exists, last and index are updated accordingly.
6042  * May set @mas->status to ma_overflow.
6043  *
6044  * Return: The entry or %NULL.
6045  */
6046 void *mas_find(struct ma_state *mas, unsigned long max)
6047 {
6048 	void *entry = NULL;
6049 
6050 	if (mas_find_setup(mas, max, &entry))
6051 		return entry;
6052 
6053 	/* Retries on dead nodes handled by mas_next_slot */
6054 	entry = mas_next_slot(mas, max, false);
6055 	/* Ignore overflow */
6056 	mas->status = ma_active;
6057 	return entry;
6058 }
6059 EXPORT_SYMBOL_GPL(mas_find);
6060 
6061 /**
6062  * mas_find_range() - On the first call, find the entry at or after
6063  * mas->index up to %max.  Otherwise, advance to the next slot mas->index.
6064  * @mas: The maple state
6065  * @max: The maximum value to check.
6066  *
6067  * Must hold rcu_read_lock or the write lock.
6068  * If an entry exists, last and index are updated accordingly.
6069  * May set @mas->status to ma_overflow.
6070  *
6071  * Return: The entry or %NULL.
6072  */
6073 void *mas_find_range(struct ma_state *mas, unsigned long max)
6074 {
6075 	void *entry = NULL;
6076 
6077 	if (mas_find_setup(mas, max, &entry))
6078 		return entry;
6079 
6080 	/* Retries on dead nodes handled by mas_next_slot */
6081 	return mas_next_slot(mas, max, true);
6082 }
6083 EXPORT_SYMBOL_GPL(mas_find_range);
6084 
6085 /**
6086  * mas_find_rev_setup() - Internal function to set up mas_find_*_rev()
6087  * @mas: The maple state
6088  * @min: The minimum index
6089  * @entry: Pointer to the entry
6090  *
6091  * Returns: True if entry is the answer, false otherwise.
6092  */
6093 static bool mas_find_rev_setup(struct ma_state *mas, unsigned long min,
6094 		void **entry)
6095 {
6096 
6097 	switch (mas->status) {
6098 	case ma_active:
6099 		goto active;
6100 	case ma_start:
6101 		break;
6102 	case ma_pause:
6103 		if (unlikely(mas->index <= min)) {
6104 			mas->status = ma_underflow;
6105 			return true;
6106 		}
6107 		mas->last = --mas->index;
6108 		mas->status = ma_start;
6109 		break;
6110 	case ma_none:
6111 		if (mas->index <= min)
6112 			goto none;
6113 
6114 		mas->last = mas->index;
6115 		mas->status = ma_start;
6116 		break;
6117 	case ma_overflow: /* user expects the mas to be one after where it is */
6118 		if (unlikely(mas->index <= min)) {
6119 			mas->status = ma_underflow;
6120 			return true;
6121 		}
6122 
6123 		mas->status = ma_active;
6124 		break;
6125 	case ma_underflow: /* user expects the mas to be one before where it is */
6126 		if (unlikely(mas->index <= min))
6127 			return true;
6128 
6129 		mas->status = ma_active;
6130 		break;
6131 	case ma_root:
6132 		break;
6133 	case ma_error:
6134 		return true;
6135 	}
6136 
6137 	if (mas_is_start(mas)) {
6138 		/* First run or continue */
6139 		if (mas->index < min)
6140 			return true;
6141 
6142 		*entry = mas_walk(mas);
6143 		if (*entry)
6144 			return true;
6145 	}
6146 
6147 	if (unlikely(mas_is_ptr(mas)))
6148 		goto none;
6149 
6150 	if (unlikely(mas_is_none(mas))) {
6151 		/*
6152 		 * Walked to the location, and there was nothing so the previous
6153 		 * location is 0.
6154 		 */
6155 		mas->last = mas->index = 0;
6156 		mas->status = ma_root;
6157 		*entry = mas_root(mas);
6158 		return true;
6159 	}
6160 
6161 active:
6162 	if (mas->index < min)
6163 		return true;
6164 
6165 	return false;
6166 
6167 none:
6168 	mas->status = ma_none;
6169 	return true;
6170 }
6171 
6172 /**
6173  * mas_find_rev: On the first call, find the first non-null entry at or below
6174  * mas->index down to %min.  Otherwise find the first non-null entry below
6175  * mas->index down to %min.
6176  * @mas: The maple state
6177  * @min: The minimum value to check.
6178  *
6179  * Must hold rcu_read_lock or the write lock.
6180  * If an entry exists, last and index are updated accordingly.
6181  * May set @mas->status to ma_underflow.
6182  *
6183  * Return: The entry or %NULL.
6184  */
6185 void *mas_find_rev(struct ma_state *mas, unsigned long min)
6186 {
6187 	void *entry = NULL;
6188 
6189 	if (mas_find_rev_setup(mas, min, &entry))
6190 		return entry;
6191 
6192 	/* Retries on dead nodes handled by mas_prev_slot */
6193 	return mas_prev_slot(mas, min, false);
6194 
6195 }
6196 EXPORT_SYMBOL_GPL(mas_find_rev);
6197 
6198 /**
6199  * mas_find_range_rev: On the first call, find the first non-null entry at or
6200  * below mas->index down to %min.  Otherwise advance to the previous slot after
6201  * mas->index down to %min.
6202  * @mas: The maple state
6203  * @min: The minimum value to check.
6204  *
6205  * Must hold rcu_read_lock or the write lock.
6206  * If an entry exists, last and index are updated accordingly.
6207  * May set @mas->status to ma_underflow.
6208  *
6209  * Return: The entry or %NULL.
6210  */
6211 void *mas_find_range_rev(struct ma_state *mas, unsigned long min)
6212 {
6213 	void *entry = NULL;
6214 
6215 	if (mas_find_rev_setup(mas, min, &entry))
6216 		return entry;
6217 
6218 	/* Retries on dead nodes handled by mas_prev_slot */
6219 	return mas_prev_slot(mas, min, true);
6220 }
6221 EXPORT_SYMBOL_GPL(mas_find_range_rev);
6222 
6223 /**
6224  * mas_erase() - Find the range in which index resides and erase the entire
6225  * range.
6226  * @mas: The maple state
6227  *
6228  * Must hold the write lock.
6229  * Searches for @mas->index, sets @mas->index and @mas->last to the range and
6230  * erases that range.
6231  *
6232  * Return: the entry that was erased or %NULL, @mas->index and @mas->last are updated.
6233  */
6234 void *mas_erase(struct ma_state *mas)
6235 {
6236 	void *entry;
6237 	unsigned long index = mas->index;
6238 	MA_WR_STATE(wr_mas, mas, NULL);
6239 
6240 	if (!mas_is_active(mas) || !mas_is_start(mas))
6241 		mas->status = ma_start;
6242 
6243 write_retry:
6244 	entry = mas_state_walk(mas);
6245 	if (!entry)
6246 		return NULL;
6247 
6248 	/* Must reset to ensure spanning writes of last slot are detected */
6249 	mas_reset(mas);
6250 	mas_wr_preallocate(&wr_mas, NULL);
6251 	if (mas_nomem(mas, GFP_KERNEL)) {
6252 		/* in case the range of entry changed when unlocked */
6253 		mas->index = mas->last = index;
6254 		goto write_retry;
6255 	}
6256 
6257 	if (mas_is_err(mas))
6258 		goto out;
6259 
6260 	mas_wr_store_entry(&wr_mas);
6261 out:
6262 	mas_destroy(mas);
6263 	return entry;
6264 }
6265 EXPORT_SYMBOL_GPL(mas_erase);
6266 
6267 /**
6268  * mas_nomem() - Check if there was an error allocating and do the allocation
6269  * if necessary If there are allocations, then free them.
6270  * @mas: The maple state
6271  * @gfp: The GFP_FLAGS to use for allocations
6272  * Return: true on allocation, false otherwise.
6273  */
6274 bool mas_nomem(struct ma_state *mas, gfp_t gfp)
6275 	__must_hold(mas->tree->ma_lock)
6276 {
6277 	if (likely(mas->node != MA_ERROR(-ENOMEM)))
6278 		return false;
6279 
6280 	if (gfpflags_allow_blocking(gfp) && !mt_external_lock(mas->tree)) {
6281 		mtree_unlock(mas->tree);
6282 		mas_alloc_nodes(mas, gfp);
6283 		mtree_lock(mas->tree);
6284 	} else {
6285 		mas_alloc_nodes(mas, gfp);
6286 	}
6287 
6288 	if (!mas_allocated(mas))
6289 		return false;
6290 
6291 	mas->status = ma_start;
6292 	return true;
6293 }
6294 
6295 void __init maple_tree_init(void)
6296 {
6297 	maple_node_cache = kmem_cache_create("maple_node",
6298 			sizeof(struct maple_node), sizeof(struct maple_node),
6299 			SLAB_PANIC, NULL);
6300 }
6301 
6302 /**
6303  * mtree_load() - Load a value stored in a maple tree
6304  * @mt: The maple tree
6305  * @index: The index to load
6306  *
6307  * Return: the entry or %NULL
6308  */
6309 void *mtree_load(struct maple_tree *mt, unsigned long index)
6310 {
6311 	MA_STATE(mas, mt, index, index);
6312 	void *entry;
6313 
6314 	trace_ma_read(__func__, &mas);
6315 	rcu_read_lock();
6316 retry:
6317 	entry = mas_start(&mas);
6318 	if (unlikely(mas_is_none(&mas)))
6319 		goto unlock;
6320 
6321 	if (unlikely(mas_is_ptr(&mas))) {
6322 		if (index)
6323 			entry = NULL;
6324 
6325 		goto unlock;
6326 	}
6327 
6328 	entry = mtree_lookup_walk(&mas);
6329 	if (!entry && unlikely(mas_is_start(&mas)))
6330 		goto retry;
6331 unlock:
6332 	rcu_read_unlock();
6333 	if (xa_is_zero(entry))
6334 		return NULL;
6335 
6336 	return entry;
6337 }
6338 EXPORT_SYMBOL(mtree_load);
6339 
6340 /**
6341  * mtree_store_range() - Store an entry at a given range.
6342  * @mt: The maple tree
6343  * @index: The start of the range
6344  * @last: The end of the range
6345  * @entry: The entry to store
6346  * @gfp: The GFP_FLAGS to use for allocations
6347  *
6348  * Return: 0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
6349  * be allocated.
6350  */
6351 int mtree_store_range(struct maple_tree *mt, unsigned long index,
6352 		unsigned long last, void *entry, gfp_t gfp)
6353 {
6354 	MA_STATE(mas, mt, index, last);
6355 	int ret = 0;
6356 
6357 	trace_ma_write(__func__, &mas, 0, entry);
6358 	if (WARN_ON_ONCE(xa_is_advanced(entry)))
6359 		return -EINVAL;
6360 
6361 	if (index > last)
6362 		return -EINVAL;
6363 
6364 	mtree_lock(mt);
6365 	ret = mas_store_gfp(&mas, entry, gfp);
6366 	mtree_unlock(mt);
6367 
6368 	return ret;
6369 }
6370 EXPORT_SYMBOL(mtree_store_range);
6371 
6372 /**
6373  * mtree_store() - Store an entry at a given index.
6374  * @mt: The maple tree
6375  * @index: The index to store the value
6376  * @entry: The entry to store
6377  * @gfp: The GFP_FLAGS to use for allocations
6378  *
6379  * Return: 0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
6380  * be allocated.
6381  */
6382 int mtree_store(struct maple_tree *mt, unsigned long index, void *entry,
6383 		 gfp_t gfp)
6384 {
6385 	return mtree_store_range(mt, index, index, entry, gfp);
6386 }
6387 EXPORT_SYMBOL(mtree_store);
6388 
6389 /**
6390  * mtree_insert_range() - Insert an entry at a given range if there is no value.
6391  * @mt: The maple tree
6392  * @first: The start of the range
6393  * @last: The end of the range
6394  * @entry: The entry to store
6395  * @gfp: The GFP_FLAGS to use for allocations.
6396  *
6397  * Return: 0 on success, -EEXISTS if the range is occupied, -EINVAL on invalid
6398  * request, -ENOMEM if memory could not be allocated.
6399  */
6400 int mtree_insert_range(struct maple_tree *mt, unsigned long first,
6401 		unsigned long last, void *entry, gfp_t gfp)
6402 {
6403 	MA_STATE(ms, mt, first, last);
6404 	int ret = 0;
6405 
6406 	if (WARN_ON_ONCE(xa_is_advanced(entry)))
6407 		return -EINVAL;
6408 
6409 	if (first > last)
6410 		return -EINVAL;
6411 
6412 	mtree_lock(mt);
6413 retry:
6414 	mas_insert(&ms, entry);
6415 	if (mas_nomem(&ms, gfp))
6416 		goto retry;
6417 
6418 	mtree_unlock(mt);
6419 	if (mas_is_err(&ms))
6420 		ret = xa_err(ms.node);
6421 
6422 	mas_destroy(&ms);
6423 	return ret;
6424 }
6425 EXPORT_SYMBOL(mtree_insert_range);
6426 
6427 /**
6428  * mtree_insert() - Insert an entry at a given index if there is no value.
6429  * @mt: The maple tree
6430  * @index : The index to store the value
6431  * @entry: The entry to store
6432  * @gfp: The GFP_FLAGS to use for allocations.
6433  *
6434  * Return: 0 on success, -EEXISTS if the range is occupied, -EINVAL on invalid
6435  * request, -ENOMEM if memory could not be allocated.
6436  */
6437 int mtree_insert(struct maple_tree *mt, unsigned long index, void *entry,
6438 		 gfp_t gfp)
6439 {
6440 	return mtree_insert_range(mt, index, index, entry, gfp);
6441 }
6442 EXPORT_SYMBOL(mtree_insert);
6443 
6444 int mtree_alloc_range(struct maple_tree *mt, unsigned long *startp,
6445 		void *entry, unsigned long size, unsigned long min,
6446 		unsigned long max, gfp_t gfp)
6447 {
6448 	int ret = 0;
6449 
6450 	MA_STATE(mas, mt, 0, 0);
6451 	if (!mt_is_alloc(mt))
6452 		return -EINVAL;
6453 
6454 	if (WARN_ON_ONCE(mt_is_reserved(entry)))
6455 		return -EINVAL;
6456 
6457 	mtree_lock(mt);
6458 retry:
6459 	ret = mas_empty_area(&mas, min, max, size);
6460 	if (ret)
6461 		goto unlock;
6462 
6463 	mas_insert(&mas, entry);
6464 	/*
6465 	 * mas_nomem() may release the lock, causing the allocated area
6466 	 * to be unavailable, so try to allocate a free area again.
6467 	 */
6468 	if (mas_nomem(&mas, gfp))
6469 		goto retry;
6470 
6471 	if (mas_is_err(&mas))
6472 		ret = xa_err(mas.node);
6473 	else
6474 		*startp = mas.index;
6475 
6476 unlock:
6477 	mtree_unlock(mt);
6478 	mas_destroy(&mas);
6479 	return ret;
6480 }
6481 EXPORT_SYMBOL(mtree_alloc_range);
6482 
6483 /**
6484  * mtree_alloc_cyclic() - Find somewhere to store this entry in the tree.
6485  * @mt: The maple tree.
6486  * @startp: Pointer to ID.
6487  * @range_lo: Lower bound of range to search.
6488  * @range_hi: Upper bound of range to search.
6489  * @entry: The entry to store.
6490  * @next: Pointer to next ID to allocate.
6491  * @gfp: The GFP_FLAGS to use for allocations.
6492  *
6493  * Finds an empty entry in @mt after @next, stores the new index into
6494  * the @id pointer, stores the entry at that index, then updates @next.
6495  *
6496  * @mt must be initialized with the MT_FLAGS_ALLOC_RANGE flag.
6497  *
6498  * Context: Any context.  Takes and releases the mt.lock.  May sleep if
6499  * the @gfp flags permit.
6500  *
6501  * Return: 0 if the allocation succeeded without wrapping, 1 if the
6502  * allocation succeeded after wrapping, -ENOMEM if memory could not be
6503  * allocated, -EINVAL if @mt cannot be used, or -EBUSY if there are no
6504  * free entries.
6505  */
6506 int mtree_alloc_cyclic(struct maple_tree *mt, unsigned long *startp,
6507 		void *entry, unsigned long range_lo, unsigned long range_hi,
6508 		unsigned long *next, gfp_t gfp)
6509 {
6510 	int ret;
6511 
6512 	MA_STATE(mas, mt, 0, 0);
6513 
6514 	if (!mt_is_alloc(mt))
6515 		return -EINVAL;
6516 	if (WARN_ON_ONCE(mt_is_reserved(entry)))
6517 		return -EINVAL;
6518 	mtree_lock(mt);
6519 	ret = mas_alloc_cyclic(&mas, startp, entry, range_lo, range_hi,
6520 			       next, gfp);
6521 	mtree_unlock(mt);
6522 	return ret;
6523 }
6524 EXPORT_SYMBOL(mtree_alloc_cyclic);
6525 
6526 int mtree_alloc_rrange(struct maple_tree *mt, unsigned long *startp,
6527 		void *entry, unsigned long size, unsigned long min,
6528 		unsigned long max, gfp_t gfp)
6529 {
6530 	int ret = 0;
6531 
6532 	MA_STATE(mas, mt, 0, 0);
6533 	if (!mt_is_alloc(mt))
6534 		return -EINVAL;
6535 
6536 	if (WARN_ON_ONCE(mt_is_reserved(entry)))
6537 		return -EINVAL;
6538 
6539 	mtree_lock(mt);
6540 retry:
6541 	ret = mas_empty_area_rev(&mas, min, max, size);
6542 	if (ret)
6543 		goto unlock;
6544 
6545 	mas_insert(&mas, entry);
6546 	/*
6547 	 * mas_nomem() may release the lock, causing the allocated area
6548 	 * to be unavailable, so try to allocate a free area again.
6549 	 */
6550 	if (mas_nomem(&mas, gfp))
6551 		goto retry;
6552 
6553 	if (mas_is_err(&mas))
6554 		ret = xa_err(mas.node);
6555 	else
6556 		*startp = mas.index;
6557 
6558 unlock:
6559 	mtree_unlock(mt);
6560 	mas_destroy(&mas);
6561 	return ret;
6562 }
6563 EXPORT_SYMBOL(mtree_alloc_rrange);
6564 
6565 /**
6566  * mtree_erase() - Find an index and erase the entire range.
6567  * @mt: The maple tree
6568  * @index: The index to erase
6569  *
6570  * Erasing is the same as a walk to an entry then a store of a NULL to that
6571  * ENTIRE range.  In fact, it is implemented as such using the advanced API.
6572  *
6573  * Return: The entry stored at the @index or %NULL
6574  */
6575 void *mtree_erase(struct maple_tree *mt, unsigned long index)
6576 {
6577 	void *entry = NULL;
6578 
6579 	MA_STATE(mas, mt, index, index);
6580 	trace_ma_op(__func__, &mas);
6581 
6582 	mtree_lock(mt);
6583 	entry = mas_erase(&mas);
6584 	mtree_unlock(mt);
6585 
6586 	return entry;
6587 }
6588 EXPORT_SYMBOL(mtree_erase);
6589 
6590 /*
6591  * mas_dup_free() - Free an incomplete duplication of a tree.
6592  * @mas: The maple state of a incomplete tree.
6593  *
6594  * The parameter @mas->node passed in indicates that the allocation failed on
6595  * this node. This function frees all nodes starting from @mas->node in the
6596  * reverse order of mas_dup_build(). There is no need to hold the source tree
6597  * lock at this time.
6598  */
6599 static void mas_dup_free(struct ma_state *mas)
6600 {
6601 	struct maple_node *node;
6602 	enum maple_type type;
6603 	void __rcu **slots;
6604 	unsigned char count, i;
6605 
6606 	/* Maybe the first node allocation failed. */
6607 	if (mas_is_none(mas))
6608 		return;
6609 
6610 	while (!mte_is_root(mas->node)) {
6611 		mas_ascend(mas);
6612 		if (mas->offset) {
6613 			mas->offset--;
6614 			do {
6615 				mas_descend(mas);
6616 				mas->offset = mas_data_end(mas);
6617 			} while (!mte_is_leaf(mas->node));
6618 
6619 			mas_ascend(mas);
6620 		}
6621 
6622 		node = mte_to_node(mas->node);
6623 		type = mte_node_type(mas->node);
6624 		slots = ma_slots(node, type);
6625 		count = mas_data_end(mas) + 1;
6626 		for (i = 0; i < count; i++)
6627 			((unsigned long *)slots)[i] &= ~MAPLE_NODE_MASK;
6628 		mt_free_bulk(count, slots);
6629 	}
6630 
6631 	node = mte_to_node(mas->node);
6632 	mt_free_one(node);
6633 }
6634 
6635 /*
6636  * mas_copy_node() - Copy a maple node and replace the parent.
6637  * @mas: The maple state of source tree.
6638  * @new_mas: The maple state of new tree.
6639  * @parent: The parent of the new node.
6640  *
6641  * Copy @mas->node to @new_mas->node, set @parent to be the parent of
6642  * @new_mas->node. If memory allocation fails, @mas is set to -ENOMEM.
6643  */
6644 static inline void mas_copy_node(struct ma_state *mas, struct ma_state *new_mas,
6645 		struct maple_pnode *parent)
6646 {
6647 	struct maple_node *node = mte_to_node(mas->node);
6648 	struct maple_node *new_node = mte_to_node(new_mas->node);
6649 	unsigned long val;
6650 
6651 	/* Copy the node completely. */
6652 	memcpy(new_node, node, sizeof(struct maple_node));
6653 	/* Update the parent node pointer. */
6654 	val = (unsigned long)node->parent & MAPLE_NODE_MASK;
6655 	new_node->parent = ma_parent_ptr(val | (unsigned long)parent);
6656 }
6657 
6658 /*
6659  * mas_dup_alloc() - Allocate child nodes for a maple node.
6660  * @mas: The maple state of source tree.
6661  * @new_mas: The maple state of new tree.
6662  * @gfp: The GFP_FLAGS to use for allocations.
6663  *
6664  * This function allocates child nodes for @new_mas->node during the duplication
6665  * process. If memory allocation fails, @mas is set to -ENOMEM.
6666  */
6667 static inline void mas_dup_alloc(struct ma_state *mas, struct ma_state *new_mas,
6668 		gfp_t gfp)
6669 {
6670 	struct maple_node *node = mte_to_node(mas->node);
6671 	struct maple_node *new_node = mte_to_node(new_mas->node);
6672 	enum maple_type type;
6673 	unsigned char request, count, i;
6674 	void __rcu **slots;
6675 	void __rcu **new_slots;
6676 	unsigned long val;
6677 
6678 	/* Allocate memory for child nodes. */
6679 	type = mte_node_type(mas->node);
6680 	new_slots = ma_slots(new_node, type);
6681 	request = mas_data_end(mas) + 1;
6682 	count = mt_alloc_bulk(gfp, request, (void **)new_slots);
6683 	if (unlikely(count < request)) {
6684 		memset(new_slots, 0, request * sizeof(void *));
6685 		mas_set_err(mas, -ENOMEM);
6686 		return;
6687 	}
6688 
6689 	/* Restore node type information in slots. */
6690 	slots = ma_slots(node, type);
6691 	for (i = 0; i < count; i++) {
6692 		val = (unsigned long)mt_slot_locked(mas->tree, slots, i);
6693 		val &= MAPLE_NODE_MASK;
6694 		((unsigned long *)new_slots)[i] |= val;
6695 	}
6696 }
6697 
6698 /*
6699  * mas_dup_build() - Build a new maple tree from a source tree
6700  * @mas: The maple state of source tree, need to be in MAS_START state.
6701  * @new_mas: The maple state of new tree, need to be in MAS_START state.
6702  * @gfp: The GFP_FLAGS to use for allocations.
6703  *
6704  * This function builds a new tree in DFS preorder. If the memory allocation
6705  * fails, the error code -ENOMEM will be set in @mas, and @new_mas points to the
6706  * last node. mas_dup_free() will free the incomplete duplication of a tree.
6707  *
6708  * Note that the attributes of the two trees need to be exactly the same, and the
6709  * new tree needs to be empty, otherwise -EINVAL will be set in @mas.
6710  */
6711 static inline void mas_dup_build(struct ma_state *mas, struct ma_state *new_mas,
6712 		gfp_t gfp)
6713 {
6714 	struct maple_node *node;
6715 	struct maple_pnode *parent = NULL;
6716 	struct maple_enode *root;
6717 	enum maple_type type;
6718 
6719 	if (unlikely(mt_attr(mas->tree) != mt_attr(new_mas->tree)) ||
6720 	    unlikely(!mtree_empty(new_mas->tree))) {
6721 		mas_set_err(mas, -EINVAL);
6722 		return;
6723 	}
6724 
6725 	root = mas_start(mas);
6726 	if (mas_is_ptr(mas) || mas_is_none(mas))
6727 		goto set_new_tree;
6728 
6729 	node = mt_alloc_one(gfp);
6730 	if (!node) {
6731 		new_mas->status = ma_none;
6732 		mas_set_err(mas, -ENOMEM);
6733 		return;
6734 	}
6735 
6736 	type = mte_node_type(mas->node);
6737 	root = mt_mk_node(node, type);
6738 	new_mas->node = root;
6739 	new_mas->min = 0;
6740 	new_mas->max = ULONG_MAX;
6741 	root = mte_mk_root(root);
6742 	while (1) {
6743 		mas_copy_node(mas, new_mas, parent);
6744 		if (!mte_is_leaf(mas->node)) {
6745 			/* Only allocate child nodes for non-leaf nodes. */
6746 			mas_dup_alloc(mas, new_mas, gfp);
6747 			if (unlikely(mas_is_err(mas)))
6748 				return;
6749 		} else {
6750 			/*
6751 			 * This is the last leaf node and duplication is
6752 			 * completed.
6753 			 */
6754 			if (mas->max == ULONG_MAX)
6755 				goto done;
6756 
6757 			/* This is not the last leaf node and needs to go up. */
6758 			do {
6759 				mas_ascend(mas);
6760 				mas_ascend(new_mas);
6761 			} while (mas->offset == mas_data_end(mas));
6762 
6763 			/* Move to the next subtree. */
6764 			mas->offset++;
6765 			new_mas->offset++;
6766 		}
6767 
6768 		mas_descend(mas);
6769 		parent = ma_parent_ptr(mte_to_node(new_mas->node));
6770 		mas_descend(new_mas);
6771 		mas->offset = 0;
6772 		new_mas->offset = 0;
6773 	}
6774 done:
6775 	/* Specially handle the parent of the root node. */
6776 	mte_to_node(root)->parent = ma_parent_ptr(mas_tree_parent(new_mas));
6777 set_new_tree:
6778 	/* Make them the same height */
6779 	new_mas->tree->ma_flags = mas->tree->ma_flags;
6780 	rcu_assign_pointer(new_mas->tree->ma_root, root);
6781 }
6782 
6783 /**
6784  * __mt_dup(): Duplicate an entire maple tree
6785  * @mt: The source maple tree
6786  * @new: The new maple tree
6787  * @gfp: The GFP_FLAGS to use for allocations
6788  *
6789  * This function duplicates a maple tree in Depth-First Search (DFS) pre-order
6790  * traversal. It uses memcpy() to copy nodes in the source tree and allocate
6791  * new child nodes in non-leaf nodes. The new node is exactly the same as the
6792  * source node except for all the addresses stored in it. It will be faster than
6793  * traversing all elements in the source tree and inserting them one by one into
6794  * the new tree.
6795  * The user needs to ensure that the attributes of the source tree and the new
6796  * tree are the same, and the new tree needs to be an empty tree, otherwise
6797  * -EINVAL will be returned.
6798  * Note that the user needs to manually lock the source tree and the new tree.
6799  *
6800  * Return: 0 on success, -ENOMEM if memory could not be allocated, -EINVAL If
6801  * the attributes of the two trees are different or the new tree is not an empty
6802  * tree.
6803  */
6804 int __mt_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp)
6805 {
6806 	int ret = 0;
6807 	MA_STATE(mas, mt, 0, 0);
6808 	MA_STATE(new_mas, new, 0, 0);
6809 
6810 	mas_dup_build(&mas, &new_mas, gfp);
6811 	if (unlikely(mas_is_err(&mas))) {
6812 		ret = xa_err(mas.node);
6813 		if (ret == -ENOMEM)
6814 			mas_dup_free(&new_mas);
6815 	}
6816 
6817 	return ret;
6818 }
6819 EXPORT_SYMBOL(__mt_dup);
6820 
6821 /**
6822  * mtree_dup(): Duplicate an entire maple tree
6823  * @mt: The source maple tree
6824  * @new: The new maple tree
6825  * @gfp: The GFP_FLAGS to use for allocations
6826  *
6827  * This function duplicates a maple tree in Depth-First Search (DFS) pre-order
6828  * traversal. It uses memcpy() to copy nodes in the source tree and allocate
6829  * new child nodes in non-leaf nodes. The new node is exactly the same as the
6830  * source node except for all the addresses stored in it. It will be faster than
6831  * traversing all elements in the source tree and inserting them one by one into
6832  * the new tree.
6833  * The user needs to ensure that the attributes of the source tree and the new
6834  * tree are the same, and the new tree needs to be an empty tree, otherwise
6835  * -EINVAL will be returned.
6836  *
6837  * Return: 0 on success, -ENOMEM if memory could not be allocated, -EINVAL If
6838  * the attributes of the two trees are different or the new tree is not an empty
6839  * tree.
6840  */
6841 int mtree_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp)
6842 {
6843 	int ret = 0;
6844 	MA_STATE(mas, mt, 0, 0);
6845 	MA_STATE(new_mas, new, 0, 0);
6846 
6847 	mas_lock(&new_mas);
6848 	mas_lock_nested(&mas, SINGLE_DEPTH_NESTING);
6849 	mas_dup_build(&mas, &new_mas, gfp);
6850 	mas_unlock(&mas);
6851 	if (unlikely(mas_is_err(&mas))) {
6852 		ret = xa_err(mas.node);
6853 		if (ret == -ENOMEM)
6854 			mas_dup_free(&new_mas);
6855 	}
6856 
6857 	mas_unlock(&new_mas);
6858 	return ret;
6859 }
6860 EXPORT_SYMBOL(mtree_dup);
6861 
6862 /**
6863  * __mt_destroy() - Walk and free all nodes of a locked maple tree.
6864  * @mt: The maple tree
6865  *
6866  * Note: Does not handle locking.
6867  */
6868 void __mt_destroy(struct maple_tree *mt)
6869 {
6870 	void *root = mt_root_locked(mt);
6871 
6872 	rcu_assign_pointer(mt->ma_root, NULL);
6873 	if (xa_is_node(root))
6874 		mte_destroy_walk(root, mt);
6875 
6876 	mt->ma_flags = mt_attr(mt);
6877 }
6878 EXPORT_SYMBOL_GPL(__mt_destroy);
6879 
6880 /**
6881  * mtree_destroy() - Destroy a maple tree
6882  * @mt: The maple tree
6883  *
6884  * Frees all resources used by the tree.  Handles locking.
6885  */
6886 void mtree_destroy(struct maple_tree *mt)
6887 {
6888 	mtree_lock(mt);
6889 	__mt_destroy(mt);
6890 	mtree_unlock(mt);
6891 }
6892 EXPORT_SYMBOL(mtree_destroy);
6893 
6894 /**
6895  * mt_find() - Search from the start up until an entry is found.
6896  * @mt: The maple tree
6897  * @index: Pointer which contains the start location of the search
6898  * @max: The maximum value of the search range
6899  *
6900  * Takes RCU read lock internally to protect the search, which does not
6901  * protect the returned pointer after dropping RCU read lock.
6902  * See also: Documentation/core-api/maple_tree.rst
6903  *
6904  * In case that an entry is found @index is updated to point to the next
6905  * possible entry independent whether the found entry is occupying a
6906  * single index or a range if indices.
6907  *
6908  * Return: The entry at or after the @index or %NULL
6909  */
6910 void *mt_find(struct maple_tree *mt, unsigned long *index, unsigned long max)
6911 {
6912 	MA_STATE(mas, mt, *index, *index);
6913 	void *entry;
6914 #ifdef CONFIG_DEBUG_MAPLE_TREE
6915 	unsigned long copy = *index;
6916 #endif
6917 
6918 	trace_ma_read(__func__, &mas);
6919 
6920 	if ((*index) > max)
6921 		return NULL;
6922 
6923 	rcu_read_lock();
6924 retry:
6925 	entry = mas_state_walk(&mas);
6926 	if (mas_is_start(&mas))
6927 		goto retry;
6928 
6929 	if (unlikely(xa_is_zero(entry)))
6930 		entry = NULL;
6931 
6932 	if (entry)
6933 		goto unlock;
6934 
6935 	while (mas_is_active(&mas) && (mas.last < max)) {
6936 		entry = mas_next_entry(&mas, max);
6937 		if (likely(entry && !xa_is_zero(entry)))
6938 			break;
6939 	}
6940 
6941 	if (unlikely(xa_is_zero(entry)))
6942 		entry = NULL;
6943 unlock:
6944 	rcu_read_unlock();
6945 	if (likely(entry)) {
6946 		*index = mas.last + 1;
6947 #ifdef CONFIG_DEBUG_MAPLE_TREE
6948 		if (MT_WARN_ON(mt, (*index) && ((*index) <= copy)))
6949 			pr_err("index not increased! %lx <= %lx\n",
6950 			       *index, copy);
6951 #endif
6952 	}
6953 
6954 	return entry;
6955 }
6956 EXPORT_SYMBOL(mt_find);
6957 
6958 /**
6959  * mt_find_after() - Search from the start up until an entry is found.
6960  * @mt: The maple tree
6961  * @index: Pointer which contains the start location of the search
6962  * @max: The maximum value to check
6963  *
6964  * Same as mt_find() except that it checks @index for 0 before
6965  * searching. If @index == 0, the search is aborted. This covers a wrap
6966  * around of @index to 0 in an iterator loop.
6967  *
6968  * Return: The entry at or after the @index or %NULL
6969  */
6970 void *mt_find_after(struct maple_tree *mt, unsigned long *index,
6971 		    unsigned long max)
6972 {
6973 	if (!(*index))
6974 		return NULL;
6975 
6976 	return mt_find(mt, index, max);
6977 }
6978 EXPORT_SYMBOL(mt_find_after);
6979 
6980 #ifdef CONFIG_DEBUG_MAPLE_TREE
6981 atomic_t maple_tree_tests_run;
6982 EXPORT_SYMBOL_GPL(maple_tree_tests_run);
6983 atomic_t maple_tree_tests_passed;
6984 EXPORT_SYMBOL_GPL(maple_tree_tests_passed);
6985 
6986 #ifndef __KERNEL__
6987 extern void kmem_cache_set_non_kernel(struct kmem_cache *, unsigned int);
6988 void mt_set_non_kernel(unsigned int val)
6989 {
6990 	kmem_cache_set_non_kernel(maple_node_cache, val);
6991 }
6992 
6993 extern void kmem_cache_set_callback(struct kmem_cache *cachep,
6994 		void (*callback)(void *));
6995 void mt_set_callback(void (*callback)(void *))
6996 {
6997 	kmem_cache_set_callback(maple_node_cache, callback);
6998 }
6999 
7000 extern void kmem_cache_set_private(struct kmem_cache *cachep, void *private);
7001 void mt_set_private(void *private)
7002 {
7003 	kmem_cache_set_private(maple_node_cache, private);
7004 }
7005 
7006 extern unsigned long kmem_cache_get_alloc(struct kmem_cache *);
7007 unsigned long mt_get_alloc_size(void)
7008 {
7009 	return kmem_cache_get_alloc(maple_node_cache);
7010 }
7011 
7012 extern void kmem_cache_zero_nr_tallocated(struct kmem_cache *);
7013 void mt_zero_nr_tallocated(void)
7014 {
7015 	kmem_cache_zero_nr_tallocated(maple_node_cache);
7016 }
7017 
7018 extern unsigned int kmem_cache_nr_tallocated(struct kmem_cache *);
7019 unsigned int mt_nr_tallocated(void)
7020 {
7021 	return kmem_cache_nr_tallocated(maple_node_cache);
7022 }
7023 
7024 extern unsigned int kmem_cache_nr_allocated(struct kmem_cache *);
7025 unsigned int mt_nr_allocated(void)
7026 {
7027 	return kmem_cache_nr_allocated(maple_node_cache);
7028 }
7029 
7030 void mt_cache_shrink(void)
7031 {
7032 }
7033 #else
7034 /*
7035  * mt_cache_shrink() - For testing, don't use this.
7036  *
7037  * Certain testcases can trigger an OOM when combined with other memory
7038  * debugging configuration options.  This function is used to reduce the
7039  * possibility of an out of memory even due to kmem_cache objects remaining
7040  * around for longer than usual.
7041  */
7042 void mt_cache_shrink(void)
7043 {
7044 	kmem_cache_shrink(maple_node_cache);
7045 
7046 }
7047 EXPORT_SYMBOL_GPL(mt_cache_shrink);
7048 
7049 #endif /* not defined __KERNEL__ */
7050 /*
7051  * mas_get_slot() - Get the entry in the maple state node stored at @offset.
7052  * @mas: The maple state
7053  * @offset: The offset into the slot array to fetch.
7054  *
7055  * Return: The entry stored at @offset.
7056  */
7057 static inline struct maple_enode *mas_get_slot(struct ma_state *mas,
7058 		unsigned char offset)
7059 {
7060 	return mas_slot(mas, ma_slots(mas_mn(mas), mte_node_type(mas->node)),
7061 			offset);
7062 }
7063 
7064 /* Depth first search, post-order */
7065 static void mas_dfs_postorder(struct ma_state *mas, unsigned long max)
7066 {
7067 
7068 	struct maple_enode *p, *mn = mas->node;
7069 	unsigned long p_min, p_max;
7070 
7071 	mas_next_node(mas, mas_mn(mas), max);
7072 	if (!mas_is_overflow(mas))
7073 		return;
7074 
7075 	if (mte_is_root(mn))
7076 		return;
7077 
7078 	mas->node = mn;
7079 	mas_ascend(mas);
7080 	do {
7081 		p = mas->node;
7082 		p_min = mas->min;
7083 		p_max = mas->max;
7084 		mas_prev_node(mas, 0);
7085 	} while (!mas_is_underflow(mas));
7086 
7087 	mas->node = p;
7088 	mas->max = p_max;
7089 	mas->min = p_min;
7090 }
7091 
7092 /* Tree validations */
7093 static void mt_dump_node(const struct maple_tree *mt, void *entry,
7094 		unsigned long min, unsigned long max, unsigned int depth,
7095 		enum mt_dump_format format);
7096 static void mt_dump_range(unsigned long min, unsigned long max,
7097 			  unsigned int depth, enum mt_dump_format format)
7098 {
7099 	static const char spaces[] = "                                ";
7100 
7101 	switch(format) {
7102 	case mt_dump_hex:
7103 		if (min == max)
7104 			pr_info("%.*s%lx: ", depth * 2, spaces, min);
7105 		else
7106 			pr_info("%.*s%lx-%lx: ", depth * 2, spaces, min, max);
7107 		break;
7108 	case mt_dump_dec:
7109 		if (min == max)
7110 			pr_info("%.*s%lu: ", depth * 2, spaces, min);
7111 		else
7112 			pr_info("%.*s%lu-%lu: ", depth * 2, spaces, min, max);
7113 	}
7114 }
7115 
7116 static void mt_dump_entry(void *entry, unsigned long min, unsigned long max,
7117 			  unsigned int depth, enum mt_dump_format format)
7118 {
7119 	mt_dump_range(min, max, depth, format);
7120 
7121 	if (xa_is_value(entry))
7122 		pr_cont("value %ld (0x%lx) [%p]\n", xa_to_value(entry),
7123 				xa_to_value(entry), entry);
7124 	else if (xa_is_zero(entry))
7125 		pr_cont("zero (%ld)\n", xa_to_internal(entry));
7126 	else if (mt_is_reserved(entry))
7127 		pr_cont("UNKNOWN ENTRY (%p)\n", entry);
7128 	else
7129 		pr_cont("%p\n", entry);
7130 }
7131 
7132 static void mt_dump_range64(const struct maple_tree *mt, void *entry,
7133 		unsigned long min, unsigned long max, unsigned int depth,
7134 		enum mt_dump_format format)
7135 {
7136 	struct maple_range_64 *node = &mte_to_node(entry)->mr64;
7137 	bool leaf = mte_is_leaf(entry);
7138 	unsigned long first = min;
7139 	int i;
7140 
7141 	pr_cont(" contents: ");
7142 	for (i = 0; i < MAPLE_RANGE64_SLOTS - 1; i++) {
7143 		switch(format) {
7144 		case mt_dump_hex:
7145 			pr_cont("%p %lX ", node->slot[i], node->pivot[i]);
7146 			break;
7147 		case mt_dump_dec:
7148 			pr_cont("%p %lu ", node->slot[i], node->pivot[i]);
7149 		}
7150 	}
7151 	pr_cont("%p\n", node->slot[i]);
7152 	for (i = 0; i < MAPLE_RANGE64_SLOTS; i++) {
7153 		unsigned long last = max;
7154 
7155 		if (i < (MAPLE_RANGE64_SLOTS - 1))
7156 			last = node->pivot[i];
7157 		else if (!node->slot[i] && max != mt_node_max(entry))
7158 			break;
7159 		if (last == 0 && i > 0)
7160 			break;
7161 		if (leaf)
7162 			mt_dump_entry(mt_slot(mt, node->slot, i),
7163 					first, last, depth + 1, format);
7164 		else if (node->slot[i])
7165 			mt_dump_node(mt, mt_slot(mt, node->slot, i),
7166 					first, last, depth + 1, format);
7167 
7168 		if (last == max)
7169 			break;
7170 		if (last > max) {
7171 			switch(format) {
7172 			case mt_dump_hex:
7173 				pr_err("node %p last (%lx) > max (%lx) at pivot %d!\n",
7174 					node, last, max, i);
7175 				break;
7176 			case mt_dump_dec:
7177 				pr_err("node %p last (%lu) > max (%lu) at pivot %d!\n",
7178 					node, last, max, i);
7179 			}
7180 		}
7181 		first = last + 1;
7182 	}
7183 }
7184 
7185 static void mt_dump_arange64(const struct maple_tree *mt, void *entry,
7186 	unsigned long min, unsigned long max, unsigned int depth,
7187 	enum mt_dump_format format)
7188 {
7189 	struct maple_arange_64 *node = &mte_to_node(entry)->ma64;
7190 	unsigned long first = min;
7191 	int i;
7192 
7193 	pr_cont(" contents: ");
7194 	for (i = 0; i < MAPLE_ARANGE64_SLOTS; i++) {
7195 		switch (format) {
7196 		case mt_dump_hex:
7197 			pr_cont("%lx ", node->gap[i]);
7198 			break;
7199 		case mt_dump_dec:
7200 			pr_cont("%lu ", node->gap[i]);
7201 		}
7202 	}
7203 	pr_cont("| %02X %02X| ", node->meta.end, node->meta.gap);
7204 	for (i = 0; i < MAPLE_ARANGE64_SLOTS - 1; i++) {
7205 		switch (format) {
7206 		case mt_dump_hex:
7207 			pr_cont("%p %lX ", node->slot[i], node->pivot[i]);
7208 			break;
7209 		case mt_dump_dec:
7210 			pr_cont("%p %lu ", node->slot[i], node->pivot[i]);
7211 		}
7212 	}
7213 	pr_cont("%p\n", node->slot[i]);
7214 	for (i = 0; i < MAPLE_ARANGE64_SLOTS; i++) {
7215 		unsigned long last = max;
7216 
7217 		if (i < (MAPLE_ARANGE64_SLOTS - 1))
7218 			last = node->pivot[i];
7219 		else if (!node->slot[i])
7220 			break;
7221 		if (last == 0 && i > 0)
7222 			break;
7223 		if (node->slot[i])
7224 			mt_dump_node(mt, mt_slot(mt, node->slot, i),
7225 					first, last, depth + 1, format);
7226 
7227 		if (last == max)
7228 			break;
7229 		if (last > max) {
7230 			switch(format) {
7231 			case mt_dump_hex:
7232 				pr_err("node %p last (%lx) > max (%lx) at pivot %d!\n",
7233 					node, last, max, i);
7234 				break;
7235 			case mt_dump_dec:
7236 				pr_err("node %p last (%lu) > max (%lu) at pivot %d!\n",
7237 					node, last, max, i);
7238 			}
7239 		}
7240 		first = last + 1;
7241 	}
7242 }
7243 
7244 static void mt_dump_node(const struct maple_tree *mt, void *entry,
7245 		unsigned long min, unsigned long max, unsigned int depth,
7246 		enum mt_dump_format format)
7247 {
7248 	struct maple_node *node = mte_to_node(entry);
7249 	unsigned int type = mte_node_type(entry);
7250 	unsigned int i;
7251 
7252 	mt_dump_range(min, max, depth, format);
7253 
7254 	pr_cont("node %p depth %d type %d parent %p", node, depth, type,
7255 			node ? node->parent : NULL);
7256 	switch (type) {
7257 	case maple_dense:
7258 		pr_cont("\n");
7259 		for (i = 0; i < MAPLE_NODE_SLOTS; i++) {
7260 			if (min + i > max)
7261 				pr_cont("OUT OF RANGE: ");
7262 			mt_dump_entry(mt_slot(mt, node->slot, i),
7263 					min + i, min + i, depth, format);
7264 		}
7265 		break;
7266 	case maple_leaf_64:
7267 	case maple_range_64:
7268 		mt_dump_range64(mt, entry, min, max, depth, format);
7269 		break;
7270 	case maple_arange_64:
7271 		mt_dump_arange64(mt, entry, min, max, depth, format);
7272 		break;
7273 
7274 	default:
7275 		pr_cont(" UNKNOWN TYPE\n");
7276 	}
7277 }
7278 
7279 void mt_dump(const struct maple_tree *mt, enum mt_dump_format format)
7280 {
7281 	void *entry = rcu_dereference_check(mt->ma_root, mt_locked(mt));
7282 
7283 	pr_info("maple_tree(%p) flags %X, height %u root %p\n",
7284 		 mt, mt->ma_flags, mt_height(mt), entry);
7285 	if (!xa_is_node(entry))
7286 		mt_dump_entry(entry, 0, 0, 0, format);
7287 	else if (entry)
7288 		mt_dump_node(mt, entry, 0, mt_node_max(entry), 0, format);
7289 }
7290 EXPORT_SYMBOL_GPL(mt_dump);
7291 
7292 /*
7293  * Calculate the maximum gap in a node and check if that's what is reported in
7294  * the parent (unless root).
7295  */
7296 static void mas_validate_gaps(struct ma_state *mas)
7297 {
7298 	struct maple_enode *mte = mas->node;
7299 	struct maple_node *p_mn, *node = mte_to_node(mte);
7300 	enum maple_type mt = mte_node_type(mas->node);
7301 	unsigned long gap = 0, max_gap = 0;
7302 	unsigned long p_end, p_start = mas->min;
7303 	unsigned char p_slot, offset;
7304 	unsigned long *gaps = NULL;
7305 	unsigned long *pivots = ma_pivots(node, mt);
7306 	unsigned int i;
7307 
7308 	if (ma_is_dense(mt)) {
7309 		for (i = 0; i < mt_slot_count(mte); i++) {
7310 			if (mas_get_slot(mas, i)) {
7311 				if (gap > max_gap)
7312 					max_gap = gap;
7313 				gap = 0;
7314 				continue;
7315 			}
7316 			gap++;
7317 		}
7318 		goto counted;
7319 	}
7320 
7321 	gaps = ma_gaps(node, mt);
7322 	for (i = 0; i < mt_slot_count(mte); i++) {
7323 		p_end = mas_safe_pivot(mas, pivots, i, mt);
7324 
7325 		if (!gaps) {
7326 			if (!mas_get_slot(mas, i))
7327 				gap = p_end - p_start + 1;
7328 		} else {
7329 			void *entry = mas_get_slot(mas, i);
7330 
7331 			gap = gaps[i];
7332 			MT_BUG_ON(mas->tree, !entry);
7333 
7334 			if (gap > p_end - p_start + 1) {
7335 				pr_err("%p[%u] %lu >= %lu - %lu + 1 (%lu)\n",
7336 				       mas_mn(mas), i, gap, p_end, p_start,
7337 				       p_end - p_start + 1);
7338 				MT_BUG_ON(mas->tree, gap > p_end - p_start + 1);
7339 			}
7340 		}
7341 
7342 		if (gap > max_gap)
7343 			max_gap = gap;
7344 
7345 		p_start = p_end + 1;
7346 		if (p_end >= mas->max)
7347 			break;
7348 	}
7349 
7350 counted:
7351 	if (mt == maple_arange_64) {
7352 		MT_BUG_ON(mas->tree, !gaps);
7353 		offset = ma_meta_gap(node);
7354 		if (offset > i) {
7355 			pr_err("gap offset %p[%u] is invalid\n", node, offset);
7356 			MT_BUG_ON(mas->tree, 1);
7357 		}
7358 
7359 		if (gaps[offset] != max_gap) {
7360 			pr_err("gap %p[%u] is not the largest gap %lu\n",
7361 			       node, offset, max_gap);
7362 			MT_BUG_ON(mas->tree, 1);
7363 		}
7364 
7365 		for (i++ ; i < mt_slot_count(mte); i++) {
7366 			if (gaps[i] != 0) {
7367 				pr_err("gap %p[%u] beyond node limit != 0\n",
7368 				       node, i);
7369 				MT_BUG_ON(mas->tree, 1);
7370 			}
7371 		}
7372 	}
7373 
7374 	if (mte_is_root(mte))
7375 		return;
7376 
7377 	p_slot = mte_parent_slot(mas->node);
7378 	p_mn = mte_parent(mte);
7379 	MT_BUG_ON(mas->tree, max_gap > mas->max);
7380 	if (ma_gaps(p_mn, mas_parent_type(mas, mte))[p_slot] != max_gap) {
7381 		pr_err("gap %p[%u] != %lu\n", p_mn, p_slot, max_gap);
7382 		mt_dump(mas->tree, mt_dump_hex);
7383 		MT_BUG_ON(mas->tree, 1);
7384 	}
7385 }
7386 
7387 static void mas_validate_parent_slot(struct ma_state *mas)
7388 {
7389 	struct maple_node *parent;
7390 	struct maple_enode *node;
7391 	enum maple_type p_type;
7392 	unsigned char p_slot;
7393 	void __rcu **slots;
7394 	int i;
7395 
7396 	if (mte_is_root(mas->node))
7397 		return;
7398 
7399 	p_slot = mte_parent_slot(mas->node);
7400 	p_type = mas_parent_type(mas, mas->node);
7401 	parent = mte_parent(mas->node);
7402 	slots = ma_slots(parent, p_type);
7403 	MT_BUG_ON(mas->tree, mas_mn(mas) == parent);
7404 
7405 	/* Check prev/next parent slot for duplicate node entry */
7406 
7407 	for (i = 0; i < mt_slots[p_type]; i++) {
7408 		node = mas_slot(mas, slots, i);
7409 		if (i == p_slot) {
7410 			if (node != mas->node)
7411 				pr_err("parent %p[%u] does not have %p\n",
7412 					parent, i, mas_mn(mas));
7413 			MT_BUG_ON(mas->tree, node != mas->node);
7414 		} else if (node == mas->node) {
7415 			pr_err("Invalid child %p at parent %p[%u] p_slot %u\n",
7416 			       mas_mn(mas), parent, i, p_slot);
7417 			MT_BUG_ON(mas->tree, node == mas->node);
7418 		}
7419 	}
7420 }
7421 
7422 static void mas_validate_child_slot(struct ma_state *mas)
7423 {
7424 	enum maple_type type = mte_node_type(mas->node);
7425 	void __rcu **slots = ma_slots(mte_to_node(mas->node), type);
7426 	unsigned long *pivots = ma_pivots(mte_to_node(mas->node), type);
7427 	struct maple_enode *child;
7428 	unsigned char i;
7429 
7430 	if (mte_is_leaf(mas->node))
7431 		return;
7432 
7433 	for (i = 0; i < mt_slots[type]; i++) {
7434 		child = mas_slot(mas, slots, i);
7435 
7436 		if (!child) {
7437 			pr_err("Non-leaf node lacks child at %p[%u]\n",
7438 			       mas_mn(mas), i);
7439 			MT_BUG_ON(mas->tree, 1);
7440 		}
7441 
7442 		if (mte_parent_slot(child) != i) {
7443 			pr_err("Slot error at %p[%u]: child %p has pslot %u\n",
7444 			       mas_mn(mas), i, mte_to_node(child),
7445 			       mte_parent_slot(child));
7446 			MT_BUG_ON(mas->tree, 1);
7447 		}
7448 
7449 		if (mte_parent(child) != mte_to_node(mas->node)) {
7450 			pr_err("child %p has parent %p not %p\n",
7451 			       mte_to_node(child), mte_parent(child),
7452 			       mte_to_node(mas->node));
7453 			MT_BUG_ON(mas->tree, 1);
7454 		}
7455 
7456 		if (i < mt_pivots[type] && pivots[i] == mas->max)
7457 			break;
7458 	}
7459 }
7460 
7461 /*
7462  * Validate all pivots are within mas->min and mas->max, check metadata ends
7463  * where the maximum ends and ensure there is no slots or pivots set outside of
7464  * the end of the data.
7465  */
7466 static void mas_validate_limits(struct ma_state *mas)
7467 {
7468 	int i;
7469 	unsigned long prev_piv = 0;
7470 	enum maple_type type = mte_node_type(mas->node);
7471 	void __rcu **slots = ma_slots(mte_to_node(mas->node), type);
7472 	unsigned long *pivots = ma_pivots(mas_mn(mas), type);
7473 
7474 	for (i = 0; i < mt_slots[type]; i++) {
7475 		unsigned long piv;
7476 
7477 		piv = mas_safe_pivot(mas, pivots, i, type);
7478 
7479 		if (!piv && (i != 0)) {
7480 			pr_err("Missing node limit pivot at %p[%u]",
7481 			       mas_mn(mas), i);
7482 			MAS_WARN_ON(mas, 1);
7483 		}
7484 
7485 		if (prev_piv > piv) {
7486 			pr_err("%p[%u] piv %lu < prev_piv %lu\n",
7487 				mas_mn(mas), i, piv, prev_piv);
7488 			MAS_WARN_ON(mas, piv < prev_piv);
7489 		}
7490 
7491 		if (piv < mas->min) {
7492 			pr_err("%p[%u] %lu < %lu\n", mas_mn(mas), i,
7493 				piv, mas->min);
7494 			MAS_WARN_ON(mas, piv < mas->min);
7495 		}
7496 		if (piv > mas->max) {
7497 			pr_err("%p[%u] %lu > %lu\n", mas_mn(mas), i,
7498 				piv, mas->max);
7499 			MAS_WARN_ON(mas, piv > mas->max);
7500 		}
7501 		prev_piv = piv;
7502 		if (piv == mas->max)
7503 			break;
7504 	}
7505 
7506 	if (mas_data_end(mas) != i) {
7507 		pr_err("node%p: data_end %u != the last slot offset %u\n",
7508 		       mas_mn(mas), mas_data_end(mas), i);
7509 		MT_BUG_ON(mas->tree, 1);
7510 	}
7511 
7512 	for (i += 1; i < mt_slots[type]; i++) {
7513 		void *entry = mas_slot(mas, slots, i);
7514 
7515 		if (entry && (i != mt_slots[type] - 1)) {
7516 			pr_err("%p[%u] should not have entry %p\n", mas_mn(mas),
7517 			       i, entry);
7518 			MT_BUG_ON(mas->tree, entry != NULL);
7519 		}
7520 
7521 		if (i < mt_pivots[type]) {
7522 			unsigned long piv = pivots[i];
7523 
7524 			if (!piv)
7525 				continue;
7526 
7527 			pr_err("%p[%u] should not have piv %lu\n",
7528 			       mas_mn(mas), i, piv);
7529 			MAS_WARN_ON(mas, i < mt_pivots[type] - 1);
7530 		}
7531 	}
7532 }
7533 
7534 static void mt_validate_nulls(struct maple_tree *mt)
7535 {
7536 	void *entry, *last = (void *)1;
7537 	unsigned char offset = 0;
7538 	void __rcu **slots;
7539 	MA_STATE(mas, mt, 0, 0);
7540 
7541 	mas_start(&mas);
7542 	if (mas_is_none(&mas) || (mas_is_ptr(&mas)))
7543 		return;
7544 
7545 	while (!mte_is_leaf(mas.node))
7546 		mas_descend(&mas);
7547 
7548 	slots = ma_slots(mte_to_node(mas.node), mte_node_type(mas.node));
7549 	do {
7550 		entry = mas_slot(&mas, slots, offset);
7551 		if (!last && !entry) {
7552 			pr_err("Sequential nulls end at %p[%u]\n",
7553 				mas_mn(&mas), offset);
7554 		}
7555 		MT_BUG_ON(mt, !last && !entry);
7556 		last = entry;
7557 		if (offset == mas_data_end(&mas)) {
7558 			mas_next_node(&mas, mas_mn(&mas), ULONG_MAX);
7559 			if (mas_is_overflow(&mas))
7560 				return;
7561 			offset = 0;
7562 			slots = ma_slots(mte_to_node(mas.node),
7563 					 mte_node_type(mas.node));
7564 		} else {
7565 			offset++;
7566 		}
7567 
7568 	} while (!mas_is_overflow(&mas));
7569 }
7570 
7571 /*
7572  * validate a maple tree by checking:
7573  * 1. The limits (pivots are within mas->min to mas->max)
7574  * 2. The gap is correctly set in the parents
7575  */
7576 void mt_validate(struct maple_tree *mt)
7577 	__must_hold(mas->tree->ma_lock)
7578 {
7579 	unsigned char end;
7580 
7581 	MA_STATE(mas, mt, 0, 0);
7582 	mas_start(&mas);
7583 	if (!mas_is_active(&mas))
7584 		return;
7585 
7586 	while (!mte_is_leaf(mas.node))
7587 		mas_descend(&mas);
7588 
7589 	while (!mas_is_overflow(&mas)) {
7590 		MAS_WARN_ON(&mas, mte_dead_node(mas.node));
7591 		end = mas_data_end(&mas);
7592 		if (MAS_WARN_ON(&mas, (end < mt_min_slot_count(mas.node)) &&
7593 				(mas.max != ULONG_MAX))) {
7594 			pr_err("Invalid size %u of %p\n", end, mas_mn(&mas));
7595 		}
7596 
7597 		mas_validate_parent_slot(&mas);
7598 		mas_validate_limits(&mas);
7599 		mas_validate_child_slot(&mas);
7600 		if (mt_is_alloc(mt))
7601 			mas_validate_gaps(&mas);
7602 		mas_dfs_postorder(&mas, ULONG_MAX);
7603 	}
7604 	mt_validate_nulls(mt);
7605 }
7606 EXPORT_SYMBOL_GPL(mt_validate);
7607 
7608 void mas_dump(const struct ma_state *mas)
7609 {
7610 	pr_err("MAS: tree=%p enode=%p ", mas->tree, mas->node);
7611 	switch (mas->status) {
7612 	case ma_active:
7613 		pr_err("(ma_active)");
7614 		break;
7615 	case ma_none:
7616 		pr_err("(ma_none)");
7617 		break;
7618 	case ma_root:
7619 		pr_err("(ma_root)");
7620 		break;
7621 	case ma_start:
7622 		pr_err("(ma_start) ");
7623 		break;
7624 	case ma_pause:
7625 		pr_err("(ma_pause) ");
7626 		break;
7627 	case ma_overflow:
7628 		pr_err("(ma_overflow) ");
7629 		break;
7630 	case ma_underflow:
7631 		pr_err("(ma_underflow) ");
7632 		break;
7633 	case ma_error:
7634 		pr_err("(ma_error) ");
7635 		break;
7636 	}
7637 
7638 	pr_err("Store Type: ");
7639 	switch (mas->store_type) {
7640 	case wr_invalid:
7641 		pr_err("invalid store type\n");
7642 		break;
7643 	case wr_new_root:
7644 		pr_err("new_root\n");
7645 		break;
7646 	case wr_store_root:
7647 		pr_err("store_root\n");
7648 		break;
7649 	case wr_exact_fit:
7650 		pr_err("exact_fit\n");
7651 		break;
7652 	case wr_split_store:
7653 		pr_err("split_store\n");
7654 		break;
7655 	case wr_slot_store:
7656 		pr_err("slot_store\n");
7657 		break;
7658 	case wr_append:
7659 		pr_err("append\n");
7660 		break;
7661 	case wr_node_store:
7662 		pr_err("node_store\n");
7663 		break;
7664 	case wr_spanning_store:
7665 		pr_err("spanning_store\n");
7666 		break;
7667 	case wr_rebalance:
7668 		pr_err("rebalance\n");
7669 		break;
7670 	}
7671 
7672 	pr_err("[%u/%u] index=%lx last=%lx\n", mas->offset, mas->end,
7673 	       mas->index, mas->last);
7674 	pr_err("     min=%lx max=%lx alloc=%p, depth=%u, flags=%x\n",
7675 	       mas->min, mas->max, mas->alloc, mas->depth, mas->mas_flags);
7676 	if (mas->index > mas->last)
7677 		pr_err("Check index & last\n");
7678 }
7679 EXPORT_SYMBOL_GPL(mas_dump);
7680 
7681 void mas_wr_dump(const struct ma_wr_state *wr_mas)
7682 {
7683 	pr_err("WR_MAS: node=%p r_min=%lx r_max=%lx\n",
7684 	       wr_mas->node, wr_mas->r_min, wr_mas->r_max);
7685 	pr_err("        type=%u off_end=%u, node_end=%u, end_piv=%lx\n",
7686 	       wr_mas->type, wr_mas->offset_end, wr_mas->mas->end,
7687 	       wr_mas->end_piv);
7688 }
7689 EXPORT_SYMBOL_GPL(mas_wr_dump);
7690 
7691 #endif /* CONFIG_DEBUG_MAPLE_TREE */
7692