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