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