xref: /linux/lib/maple_tree.c (revision e8a71f284ba7eeddd9475bb0b65200e95428b497)
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 /*
3895  * mas_next_no_node() - Finish a next walk that restarted into a tree without
3896  * nodes.
3897  * @mas: The inactive maple state (ma_none or ma_root)
3898  *
3899  * The arrival here is either because there is a root value or nothing.  Either
3900  * way, the next entry is nothing.  So set the limits and overwrite the status.
3901  *
3902  * Return: NULL
3903  */
3904 static inline void *mas_next_no_node(struct ma_state *mas)
3905 {
3906 	if (mas_is_ptr(mas))
3907 		mas->index = 1;
3908 	else
3909 		mas->index = 0;
3910 
3911 	mas->last = ULONG_MAX;
3912 	mas->status = ma_none;
3913 	return NULL;
3914 }
3915 
3916 /*
3917  * mas_prev_no_node() - Finish a prev walk that restarted into a tree without
3918  * nodes.
3919  * @mas: The inactive maple state (ma_none or ma_root)
3920  * @index: The start of the range the walk left
3921  * @min: The lowest index to return
3922  *
3923  * The arrival here is either because there is a root value or nothing.  With
3924  * nothing, leave the limits mas_walk() sets for an empty tree.  A root value
3925  * sits at 0: stop on it as mas_prev_setup() does, unless the walk was at 0.
3926  *
3927  * Return: The root entry if @index and @min allow it, NULL otherwise.  A node
3928  * if the root changed again since the walk; the caller restarts.
3929  */
3930 static inline void *mas_prev_no_node(struct ma_state *mas, unsigned long index,
3931 		unsigned long min)
3932 {
3933 	void *entry;
3934 
3935 	mas->index = 0;
3936 	if (mas_is_none(mas)) {
3937 		mas->last = ULONG_MAX;
3938 		return NULL;
3939 	}
3940 
3941 	mas->last = 0;
3942 	if (!index || min)
3943 		return NULL;
3944 
3945 	entry = mas_root(mas);
3946 	if (!entry) {
3947 		mas->status = ma_none;
3948 		mas->last = ULONG_MAX;
3949 	}
3950 
3951 	return entry;
3952 }
3953 
3954 /*
3955  * mas_prev_node() - Find the prev non-null entry at the same level in the
3956  * tree.  The prev value will be mas->node[mas->offset] or the status will be
3957  * ma_none.
3958  * @mas: The maple state
3959  * @min: The lower limit to search
3960  *
3961  * The prev node value will be mas->node[mas->offset] or the status will be
3962  * ma_none.
3963  * Return: 1 if the node is dead, 0 otherwise.
3964  */
3965 static int mas_prev_node(struct ma_state *mas, unsigned long min)
3966 {
3967 	enum maple_type mt;
3968 	int offset, level;
3969 	void __rcu **slots;
3970 	struct maple_node *node;
3971 	unsigned long *pivots;
3972 	unsigned long max;
3973 
3974 	node = mas_mn(mas);
3975 	if (!mas->min)
3976 		goto no_entry;
3977 
3978 	max = mas->min - 1;
3979 	if (max < min)
3980 		goto no_entry;
3981 
3982 	level = 0;
3983 	do {
3984 		if (ma_is_root(node))
3985 			goto no_entry;
3986 
3987 		/* Walk up. */
3988 		if (unlikely(mas_ascend(mas)))
3989 			return 1;
3990 		offset = mas->offset;
3991 		level++;
3992 		node = mas_mn(mas);
3993 	} while (!offset);
3994 
3995 	offset--;
3996 	mt = mte_node_type(mas->node);
3997 	while (level > 1) {
3998 		level--;
3999 		slots = ma_slots(node, mt);
4000 		mas->node = mas_slot(mas, slots, offset);
4001 		if (unlikely(ma_dead_node(node)))
4002 			return 1;
4003 
4004 		mt = mte_node_type(mas->node);
4005 		node = mas_mn(mas);
4006 		pivots = ma_pivots(node, mt);
4007 		offset = ma_data_end(node, mt, pivots, max);
4008 		if (unlikely(ma_dead_node(node)))
4009 			return 1;
4010 	}
4011 
4012 	slots = ma_slots(node, mt);
4013 	mas->node = mas_slot(mas, slots, offset);
4014 	pivots = ma_pivots(node, mt);
4015 	if (unlikely(ma_dead_node(node)))
4016 		return 1;
4017 
4018 	if (likely(offset))
4019 		mas->min = pivots[offset - 1] + 1;
4020 	mas->max = max;
4021 	mas->offset = mas_data_end(mas);
4022 	if (unlikely(mte_dead_node(mas->node)))
4023 		return 1;
4024 
4025 	mas->end = mas->offset;
4026 	return 0;
4027 
4028 no_entry:
4029 	if (unlikely(ma_dead_node(node)))
4030 		return 1;
4031 
4032 	mas->status = ma_underflow;
4033 	return 0;
4034 }
4035 
4036 /*
4037  * mas_prev_slot() - Get the entry in the previous slot
4038  *
4039  * @mas: The maple state
4040  * @min: The minimum starting range
4041  * @empty: Can be empty
4042  *
4043  * Return: The entry in the previous slot which is possibly NULL
4044  */
4045 static void *mas_prev_slot(struct ma_state *mas, unsigned long min, bool empty)
4046 {
4047 	void *entry;
4048 	void __rcu **slots;
4049 	unsigned long pivot;
4050 	enum maple_type type;
4051 	unsigned long *pivots;
4052 	struct maple_node *node;
4053 	unsigned long save_point = mas->index;
4054 
4055 retry:
4056 	node = mas_mn(mas);
4057 	type = mte_node_type(mas->node);
4058 	pivots = ma_pivots(node, type);
4059 	if (unlikely(ma_dead_node(node)))
4060 		goto dead;
4061 
4062 	if (mas->min <= min) {
4063 		pivot = mas_safe_min(mas, pivots, mas->offset);
4064 
4065 		if (unlikely(ma_dead_node(node)))
4066 			goto dead;
4067 
4068 		if (pivot <= min)
4069 			goto underflow;
4070 	}
4071 
4072 again:
4073 	if (likely(mas->offset)) {
4074 		mas->offset--;
4075 		mas->last = mas->index - 1;
4076 		mas->index = mas_safe_min(mas, pivots, mas->offset);
4077 	} else  {
4078 		if (mas->index <= min)
4079 			goto underflow;
4080 
4081 		if (mas_prev_node(mas, min))
4082 			goto dead;
4083 
4084 		if (WARN_ON_ONCE(mas_is_underflow(mas)))
4085 			return NULL;
4086 
4087 		mas->last = mas->max;
4088 		node = mas_mn(mas);
4089 		type = mte_node_type(mas->node);
4090 		pivots = ma_pivots(node, type);
4091 		mas->index = pivots[mas->offset - 1] + 1;
4092 	}
4093 
4094 	slots = ma_slots(node, type);
4095 	entry = mas_slot(mas, slots, mas->offset);
4096 	if (unlikely(ma_dead_node(node)))
4097 		goto dead;
4098 
4099 	if (likely(entry))
4100 		return entry;
4101 
4102 	if (!empty) {
4103 		if (mas->index <= min)
4104 			goto underflow;
4105 
4106 		goto again;
4107 	}
4108 
4109 	return entry;
4110 
4111 underflow:
4112 	mas->status = ma_underflow;
4113 	return NULL;
4114 
4115 dead:
4116 	mas_rewalk(mas, save_point);
4117 	if (likely(mas_is_active(mas)))
4118 		goto retry;
4119 
4120 	entry = mas_prev_no_node(mas, save_point, min);
4121 	if (unlikely(xa_is_node(entry))) /* The root changed again */
4122 		goto dead;
4123 
4124 	return entry;
4125 }
4126 
4127 /*
4128  * mas_next_node() - Get the next node at the same level in the tree.
4129  * @mas: The maple state
4130  * @node: The maple node
4131  * @max: The maximum pivot value to check.
4132  *
4133  * The next value will be mas->node[mas->offset] or the status will have
4134  * overflowed.
4135  * Return: 1 on dead node, 0 otherwise.
4136  */
4137 static int mas_next_node(struct ma_state *mas, struct maple_node *node,
4138 		unsigned long max)
4139 {
4140 	unsigned long min;
4141 	unsigned long *pivots;
4142 	struct maple_enode *enode;
4143 	struct maple_node *tmp;
4144 	int level = 0;
4145 	unsigned char node_end;
4146 	enum maple_type mt;
4147 	void __rcu **slots;
4148 
4149 	if (mas->max >= max)
4150 		goto overflow;
4151 
4152 	min = mas->max + 1;
4153 	level = 0;
4154 	do {
4155 		if (ma_is_root(node))
4156 			goto overflow;
4157 
4158 		/* Walk up. */
4159 		if (unlikely(mas_ascend(mas)))
4160 			return 1;
4161 
4162 		level++;
4163 		node = mas_mn(mas);
4164 		mt = mte_node_type(mas->node);
4165 		pivots = ma_pivots(node, mt);
4166 		node_end = ma_data_end(node, mt, pivots, mas->max);
4167 		if (unlikely(ma_dead_node(node)))
4168 			return 1;
4169 
4170 	} while (unlikely(mas->offset == node_end));
4171 
4172 	slots = ma_slots(node, mt);
4173 	mas->offset++;
4174 	enode = mas_slot(mas, slots, mas->offset);
4175 	if (unlikely(ma_dead_node(node)))
4176 		return 1;
4177 
4178 	if (level > 1)
4179 		mas->offset = 0;
4180 
4181 	while (unlikely(level > 1)) {
4182 		level--;
4183 		mas->node = enode;
4184 		node = mas_mn(mas);
4185 		mt = mte_node_type(mas->node);
4186 		slots = ma_slots(node, mt);
4187 		enode = mas_slot(mas, slots, 0);
4188 		if (unlikely(ma_dead_node(node)))
4189 			return 1;
4190 	}
4191 
4192 	if (!mas->offset)
4193 		pivots = ma_pivots(node, mt);
4194 
4195 	mas->max = mas_safe_pivot(mas, pivots, mas->offset, mt);
4196 	tmp = mte_to_node(enode);
4197 	mt = mte_node_type(enode);
4198 	pivots = ma_pivots(tmp, mt);
4199 	mas->end = ma_data_end(tmp, mt, pivots, mas->max);
4200 	if (unlikely(ma_dead_node(node)))
4201 		return 1;
4202 
4203 	mas->node = enode;
4204 	mas->min = min;
4205 	return 0;
4206 
4207 overflow:
4208 	if (unlikely(ma_dead_node(node)))
4209 		return 1;
4210 
4211 	mas->status = ma_overflow;
4212 	return 0;
4213 }
4214 
4215 /*
4216  * mas_next_slot() - Get the entry in the next slot
4217  *
4218  * @mas: The maple state
4219  * @max: The maximum starting range
4220  * @empty: Can be empty
4221  *
4222  * Return: The entry in the next slot which is possibly NULL
4223  */
4224 static void *mas_next_slot(struct ma_state *mas, unsigned long max, bool empty)
4225 {
4226 	void __rcu **slots;
4227 	unsigned long *pivots;
4228 	unsigned long pivot;
4229 	enum maple_type type;
4230 	struct maple_node *node;
4231 	unsigned long save_point = mas->last;
4232 	void *entry;
4233 
4234 retry:
4235 	node = mas_mn(mas);
4236 	type = mte_node_type(mas->node);
4237 	pivots = ma_pivots(node, type);
4238 	if (unlikely(ma_dead_node(node)))
4239 		goto dead;
4240 
4241 	if (mas->max >= max) {
4242 		if (likely(mas->offset < mas->end))
4243 			pivot = pivots[mas->offset];
4244 		else
4245 			pivot = mas->max;
4246 
4247 		if (unlikely(ma_dead_node(node)))
4248 			goto dead;
4249 
4250 		if (pivot >= max) { /* Was at the limit, next will extend beyond */
4251 			mas->status = ma_overflow;
4252 			return NULL;
4253 		}
4254 	}
4255 
4256 	if (likely(mas->offset < mas->end)) {
4257 		mas->index = pivots[mas->offset] + 1;
4258 again:
4259 		mas->offset++;
4260 		if (likely(mas->offset < mas->end))
4261 			mas->last = pivots[mas->offset];
4262 		else
4263 			mas->last = mas->max;
4264 	} else  {
4265 		if (mas->last >= max) {
4266 			mas->status = ma_overflow;
4267 			return NULL;
4268 		}
4269 
4270 		if (mas_next_node(mas, node, max))
4271 			goto dead;
4272 
4273 		if (WARN_ON_ONCE(mas_is_overflow(mas)))
4274 			return NULL;
4275 
4276 		mas->offset = 0;
4277 		mas->index = mas->min;
4278 		node = mas_mn(mas);
4279 		type = mte_node_type(mas->node);
4280 		pivots = ma_pivots(node, type);
4281 		mas->last = pivots[0];
4282 	}
4283 
4284 	slots = ma_slots(node, type);
4285 	entry = mt_slot(mas->tree, slots, mas->offset);
4286 	if (unlikely(ma_dead_node(node)))
4287 		goto dead;
4288 
4289 	if (entry)
4290 		return entry;
4291 
4292 
4293 	if (!empty) {
4294 		if (mas->last >= max) {
4295 			mas->status = ma_overflow;
4296 			return NULL;
4297 		}
4298 
4299 		mas->index = mas->last + 1;
4300 		goto again;
4301 	}
4302 
4303 	return entry;
4304 
4305 dead:
4306 	mas_rewalk(mas, save_point);
4307 	if (likely(mas_is_active(mas)))
4308 		goto retry;
4309 
4310 	return mas_next_no_node(mas);
4311 }
4312 
4313 /*
4314  * mas_rev_awalk() - Internal function.  Reverse allocation walk.  Find the
4315  * highest gap address of a given size in a given node and descend.
4316  * @mas: The maple state
4317  * @size: The needed size.
4318  *
4319  * Return: True if found in a leaf, false otherwise.
4320  *
4321  */
4322 static bool mas_rev_awalk(struct ma_state *mas, unsigned long size,
4323 		unsigned long *gap_min, unsigned long *gap_max)
4324 {
4325 	enum maple_type type = mte_node_type(mas->node);
4326 	struct maple_node *node = mas_mn(mas);
4327 	unsigned long *pivots, *gaps;
4328 	void __rcu **slots;
4329 	unsigned long gap = 0;
4330 	unsigned long max, min;
4331 	unsigned char offset;
4332 
4333 	if (unlikely(mas_is_err(mas)))
4334 		return true;
4335 
4336 	if (ma_is_dense(type)) {
4337 		/* dense nodes. */
4338 		mas->offset = (unsigned char)(mas->index - mas->min);
4339 		return true;
4340 	}
4341 
4342 	pivots = ma_pivots(node, type);
4343 	slots = ma_slots(node, type);
4344 	gaps = ma_gaps(node, type);
4345 	offset = mas->offset;
4346 	min = mas_safe_min(mas, pivots, offset);
4347 	/* Skip out of bounds. */
4348 	while (mas->last < min)
4349 		min = mas_safe_min(mas, pivots, --offset);
4350 
4351 	max = mas_safe_pivot(mas, pivots, offset, type);
4352 	while (mas->index <= max) {
4353 		gap = 0;
4354 		if (gaps)
4355 			gap = gaps[offset];
4356 		else if (!mas_slot(mas, slots, offset))
4357 			gap = max - min + 1;
4358 
4359 		if (gap) {
4360 			if ((size <= gap) && (size <= mas->last - min + 1))
4361 				break;
4362 
4363 			if (!gaps) {
4364 				/* Skip the next slot, it cannot be a gap. */
4365 				if (offset < 2)
4366 					goto ascend;
4367 
4368 				offset -= 2;
4369 				max = pivots[offset];
4370 				min = mas_safe_min(mas, pivots, offset);
4371 				continue;
4372 			}
4373 		}
4374 
4375 		if (!offset)
4376 			goto ascend;
4377 
4378 		offset--;
4379 		max = min - 1;
4380 		min = mas_safe_min(mas, pivots, offset);
4381 	}
4382 
4383 	if (unlikely((mas->index > max) || (size - 1 > max - mas->index)))
4384 		goto no_space;
4385 
4386 	if (unlikely(ma_is_leaf(type))) {
4387 		mas->offset = offset;
4388 		*gap_min = min;
4389 		*gap_max = min + gap - 1;
4390 		return true;
4391 	}
4392 
4393 	/* descend, only happens under lock. */
4394 	mas->node = mas_slot(mas, slots, offset);
4395 	mas->min = min;
4396 	mas->max = max;
4397 	mas->offset = mas_data_end(mas);
4398 	return false;
4399 
4400 ascend:
4401 	if (!mte_is_root(mas->node))
4402 		return false;
4403 
4404 no_space:
4405 	mas_set_err(mas, -EBUSY);
4406 	return false;
4407 }
4408 
4409 static inline bool mas_anode_descend(struct ma_state *mas, unsigned long size)
4410 {
4411 	enum maple_type type = mte_node_type(mas->node);
4412 	unsigned long pivot, min, gap = 0;
4413 	unsigned char offset, data_end;
4414 	unsigned long *gaps, *pivots;
4415 	void __rcu **slots;
4416 	struct maple_node *node;
4417 	bool found = false;
4418 
4419 	if (ma_is_dense(type)) {
4420 		mas->offset = (unsigned char)(mas->index - mas->min);
4421 		return true;
4422 	}
4423 
4424 	node = mas_mn(mas);
4425 	pivots = ma_pivots(node, type);
4426 	slots = ma_slots(node, type);
4427 	gaps = ma_gaps(node, type);
4428 	offset = mas->offset;
4429 	min = mas_safe_min(mas, pivots, offset);
4430 	data_end = ma_data_end(node, type, pivots, mas->max);
4431 	for (; offset <= data_end; offset++) {
4432 		pivot = mas_safe_pivot(mas, pivots, offset, type);
4433 
4434 		/* Not within lower bounds */
4435 		if (mas->index > pivot)
4436 			goto next_slot;
4437 
4438 		if (gaps)
4439 			gap = gaps[offset];
4440 		else if (!mas_slot(mas, slots, offset))
4441 			gap = min(pivot, mas->last) - max(mas->index, min) + 1;
4442 		else
4443 			goto next_slot;
4444 
4445 		if (gap >= size) {
4446 			if (ma_is_leaf(type)) {
4447 				found = true;
4448 				break;
4449 			}
4450 
4451 			mas->node = mas_slot(mas, slots, offset);
4452 			mas->min = min;
4453 			mas->max = pivot;
4454 			offset = 0;
4455 			break;
4456 		}
4457 next_slot:
4458 		min = pivot + 1;
4459 		if (mas->last <= pivot) {
4460 			mas_set_err(mas, -EBUSY);
4461 			return true;
4462 		}
4463 	}
4464 
4465 	mas->offset = offset;
4466 	return found;
4467 }
4468 
4469 /**
4470  * mas_walk() - Search for @mas->index in the tree.
4471  * @mas: The maple state.
4472  *
4473  * mas->index and mas->last will be set to the range if there is a value.  If
4474  * mas->status is ma_none, reset to ma_start
4475  *
4476  * Return: the entry at the location or %NULL.
4477  */
4478 void *mas_walk(struct ma_state *mas)
4479 {
4480 	void *entry;
4481 
4482 	mas_may_init_lock_check(mas);
4483 	mas_make_walkable(mas);
4484 retry:
4485 	entry = mas_state_walk(mas);
4486 	if (mas_is_start(mas)) {
4487 		goto retry;
4488 	} else if (mas_is_none(mas)) {
4489 		mas->index = 0;
4490 		mas->last = ULONG_MAX;
4491 	} else if (mas_is_ptr(mas)) {
4492 		if (!mas->index) {
4493 			mas->last = 0;
4494 			return entry;
4495 		}
4496 
4497 		mas->index = 1;
4498 		mas->last = ULONG_MAX;
4499 		mas->status = ma_none;
4500 		return NULL;
4501 	}
4502 
4503 	return entry;
4504 }
4505 EXPORT_SYMBOL_GPL(mas_walk);
4506 
4507 static inline bool mas_rewind_node(struct ma_state *mas)
4508 {
4509 	unsigned char slot;
4510 
4511 	do {
4512 		if (mte_is_root(mas->node)) {
4513 			slot = mas->offset;
4514 			if (!slot)
4515 				return false;
4516 		} else {
4517 			mas_ascend(mas);
4518 			slot = mas->offset;
4519 		}
4520 	} while (!slot);
4521 
4522 	mas->offset = --slot;
4523 	return true;
4524 }
4525 
4526 /*
4527  * mas_skip_node() - Internal function.  Skip over a node.
4528  * @mas: The maple state.
4529  *
4530  * Return: true if there is another node, false otherwise.
4531  */
4532 static inline bool mas_skip_node(struct ma_state *mas)
4533 {
4534 	if (mas_is_err(mas))
4535 		return false;
4536 
4537 	do {
4538 		if (mte_is_root(mas->node)) {
4539 			if (mas->offset >= mas_data_end(mas)) {
4540 				mas_set_err(mas, -EBUSY);
4541 				return false;
4542 			}
4543 		} else {
4544 			mas_ascend(mas);
4545 		}
4546 	} while (mas->offset >= mas_data_end(mas));
4547 
4548 	mas->offset++;
4549 	return true;
4550 }
4551 
4552 /*
4553  * mas_awalk() - Allocation walk.  Search from low address to high, for a gap of
4554  * @size
4555  * @mas: The maple state
4556  * @size: The size of the gap required
4557  *
4558  * Search between @mas->index and @mas->last for a gap of @size.
4559  */
4560 static inline void mas_awalk(struct ma_state *mas, unsigned long size)
4561 {
4562 	struct maple_enode *last = NULL;
4563 
4564 	/*
4565 	 * There are 4 options:
4566 	 * go to child (descend)
4567 	 * go back to parent (ascend)
4568 	 * no gap found. (return, error == -EBUSY)
4569 	 * found the gap. (return)
4570 	 */
4571 	while (!mas_is_err(mas) && !mas_anode_descend(mas, size)) {
4572 		if (last == mas->node)
4573 			mas_skip_node(mas);
4574 		else
4575 			last = mas->node;
4576 	}
4577 }
4578 
4579 /*
4580  * mas_sparse_area() - Internal function.  Return upper or lower limit when
4581  * searching for a gap in an empty tree.
4582  * @mas: The maple state
4583  * @min: the minimum range
4584  * @max: The maximum range
4585  * @size: The size of the gap
4586  * @fwd: Searching forward or back
4587  */
4588 static inline int mas_sparse_area(struct ma_state *mas, unsigned long min,
4589 				unsigned long max, unsigned long size, bool fwd)
4590 {
4591 	if (!unlikely(mas_is_none(mas)) && min == 0) {
4592 		min++;
4593 		/*
4594 		 * At this time, min is increased, we need to recheck whether
4595 		 * the size is satisfied.
4596 		 */
4597 		if (min > max || max - min + 1 < size)
4598 			return -EBUSY;
4599 	}
4600 	/* mas_is_ptr */
4601 
4602 	if (fwd) {
4603 		mas->index = min;
4604 		mas->last = min + size - 1;
4605 	} else {
4606 		mas->last = max;
4607 		mas->index = max - size + 1;
4608 	}
4609 	return 0;
4610 }
4611 
4612 /*
4613  * mas_empty_area() - Get the lowest address within the range that is
4614  * sufficient for the size requested.
4615  * @mas: The maple state
4616  * @min: The lowest value of the range
4617  * @max: The highest value of the range
4618  * @size: The size needed
4619  */
4620 int mas_empty_area(struct ma_state *mas, unsigned long min,
4621 		unsigned long max, unsigned long size)
4622 {
4623 	unsigned char offset;
4624 	unsigned long *pivots;
4625 	enum maple_type mt;
4626 	struct maple_node *node;
4627 
4628 	if (min > max)
4629 		return -EINVAL;
4630 
4631 	if (size == 0 || max - min < size - 1)
4632 		return -EINVAL;
4633 
4634 	if (mas_is_start(mas))
4635 		mas_start(mas);
4636 	else if (mas->offset >= 2)
4637 		mas->offset -= 2;
4638 	else if (!mas_skip_node(mas))
4639 		return -EBUSY;
4640 
4641 	/* Empty set */
4642 	if (mas_is_none(mas) || mas_is_ptr(mas))
4643 		return mas_sparse_area(mas, min, max, size, true);
4644 
4645 	/* The start of the window can only be within these values */
4646 	mas->index = min;
4647 	mas->last = max;
4648 	mas_awalk(mas, size);
4649 
4650 	if (unlikely(mas_is_err(mas)))
4651 		return xa_err(mas->node);
4652 
4653 	offset = mas->offset;
4654 	node = mas_mn(mas);
4655 	mt = mte_node_type(mas->node);
4656 	pivots = ma_pivots(node, mt);
4657 	min = mas_safe_min(mas, pivots, offset);
4658 	if (mas->index < min)
4659 		mas->index = min;
4660 	mas->last = mas->index + size - 1;
4661 	mas->end = ma_data_end(node, mt, pivots, mas->max);
4662 	return 0;
4663 }
4664 EXPORT_SYMBOL_GPL(mas_empty_area);
4665 
4666 /*
4667  * mas_empty_area_rev() - Get the highest address within the range that is
4668  * sufficient for the size requested.
4669  * @mas: The maple state
4670  * @min: The lowest value of the range
4671  * @max: The highest value of the range
4672  * @size: The size needed
4673  */
4674 int mas_empty_area_rev(struct ma_state *mas, unsigned long min,
4675 		unsigned long max, unsigned long size)
4676 {
4677 	struct maple_enode *last = mas->node;
4678 
4679 	if (min > max)
4680 		return -EINVAL;
4681 
4682 	if (size == 0 || max - min < size - 1)
4683 		return -EINVAL;
4684 
4685 	if (mas_is_start(mas))
4686 		mas_start(mas);
4687 	else if ((mas->offset < 2) && (!mas_rewind_node(mas)))
4688 		return -EBUSY;
4689 
4690 	if (unlikely(mas_is_none(mas) || mas_is_ptr(mas)))
4691 		return mas_sparse_area(mas, min, max, size, false);
4692 	else if (mas->offset >= 2)
4693 		mas->offset -= 2;
4694 	else
4695 		mas->offset = mas_data_end(mas);
4696 
4697 
4698 	/* The start of the window can only be within these values. */
4699 	mas->index = min;
4700 	mas->last = max;
4701 
4702 	while (!mas_rev_awalk(mas, size, &min, &max)) {
4703 		if (last == mas->node) {
4704 			if (!mas_rewind_node(mas))
4705 				return -EBUSY;
4706 		} else {
4707 			last = mas->node;
4708 		}
4709 	}
4710 
4711 	if (mas_is_err(mas))
4712 		return xa_err(mas->node);
4713 
4714 	if (unlikely(mas->offset == MAPLE_NODE_SLOTS))
4715 		return -EBUSY;
4716 
4717 	/* Trim the upper limit to the max. */
4718 	if (max < mas->last)
4719 		mas->last = max;
4720 
4721 	mas->index = mas->last - size + 1;
4722 	mas->end = mas_data_end(mas);
4723 	return 0;
4724 }
4725 EXPORT_SYMBOL_GPL(mas_empty_area_rev);
4726 
4727 /*
4728  * mte_dead_leaves() - Mark all leaves of a node as dead.
4729  * @enode: the encoded node
4730  * @mt: the maple tree
4731  * @slots: Pointer to the slot array
4732  *
4733  * Must hold the write lock.
4734  *
4735  * Return: The number of leaves marked as dead.
4736  */
4737 static inline
4738 unsigned char mte_dead_leaves(struct maple_enode *enode, struct maple_tree *mt,
4739 			      void __rcu **slots)
4740 {
4741 	struct maple_node *node;
4742 	enum maple_type type;
4743 	void *entry;
4744 	int offset;
4745 
4746 	for (offset = 0; offset < mt_slot_count(enode); offset++) {
4747 		entry = mt_slot(mt, slots, offset);
4748 		type = mte_node_type(entry);
4749 		node = mte_to_node(entry);
4750 		/* Use both node and type to catch LE & BE metadata */
4751 		if (!node || !type)
4752 			break;
4753 
4754 		mte_set_node_dead(entry);
4755 		node->type = type;
4756 		rcu_assign_pointer(slots[offset], node);
4757 	}
4758 
4759 	return offset;
4760 }
4761 
4762 /**
4763  * mte_dead_walk() - Walk down a dead tree to just before the leaves
4764  * @enode: The maple encoded node
4765  * @offset: The starting offset
4766  *
4767  * Note: This can only be used from the RCU callback context.
4768  */
4769 static void __rcu **mte_dead_walk(struct maple_enode **enode, unsigned char offset)
4770 {
4771 	struct maple_node *node, *next;
4772 	void __rcu **slots = NULL;
4773 
4774 	next = mte_to_node(*enode);
4775 	do {
4776 		*enode = ma_enode_ptr(next);
4777 		node = mte_to_node(*enode);
4778 		slots = ma_slots(node, node->type);
4779 		next = rcu_dereference_protected(slots[offset],
4780 					lock_is_held(&rcu_callback_map));
4781 		offset = 0;
4782 	} while (!ma_is_leaf(next->type));
4783 
4784 	return slots;
4785 }
4786 
4787 /**
4788  * mt_free_walk() - Walk & free a tree in the RCU callback context
4789  * @head: The RCU head that's within the node.
4790  *
4791  * Note: This can only be used from the RCU callback context.
4792  */
4793 static void mt_free_walk(struct rcu_head *head)
4794 {
4795 	void __rcu **slots;
4796 	struct maple_node *node, *start;
4797 	struct maple_enode *enode;
4798 	unsigned char offset;
4799 	enum maple_type type;
4800 
4801 	node = container_of(head, struct maple_node, rcu);
4802 
4803 	if (ma_is_leaf(node->type))
4804 		goto free_leaf;
4805 
4806 	start = node;
4807 	enode = mt_mk_node(node, node->type);
4808 	slots = mte_dead_walk(&enode, 0);
4809 	node = mte_to_node(enode);
4810 	do {
4811 		mt_free_bulk(node->slot_len, slots);
4812 		offset = node->parent_slot + 1;
4813 		enode = node->piv_parent;
4814 		if (mte_to_node(enode) == node)
4815 			goto free_leaf;
4816 
4817 		type = mte_node_type(enode);
4818 		slots = ma_slots(mte_to_node(enode), type);
4819 		if (offset < mte_to_node(enode)->slot_len)
4820 			slots = mte_dead_walk(&enode, offset);
4821 		node = mte_to_node(enode);
4822 	} while ((node != start) || (node->slot_len < offset));
4823 
4824 	slots = ma_slots(node, node->type);
4825 	mt_free_bulk(node->slot_len, slots);
4826 
4827 free_leaf:
4828 	kfree(node);
4829 }
4830 
4831 static inline void __rcu **mte_destroy_descend(struct maple_enode **enode,
4832 	struct maple_tree *mt, struct maple_enode *prev, unsigned char offset)
4833 {
4834 	struct maple_node *node;
4835 	struct maple_enode *next = *enode;
4836 	void __rcu **slots = NULL;
4837 	enum maple_type type;
4838 	unsigned char next_offset = 0;
4839 
4840 	do {
4841 		*enode = next;
4842 		node = mte_to_node(*enode);
4843 		type = mte_node_type(*enode);
4844 		slots = ma_slots(node, type);
4845 		next = mt_slot_locked(mt, slots, next_offset);
4846 		if ((mte_dead_node(next)))
4847 			next = mt_slot_locked(mt, slots, ++next_offset);
4848 
4849 		mte_set_node_dead(*enode);
4850 		node->type = type;
4851 		node->piv_parent = prev;
4852 		node->parent_slot = offset;
4853 		offset = next_offset;
4854 		next_offset = 0;
4855 		prev = *enode;
4856 	} while (!mte_is_leaf(next));
4857 
4858 	return slots;
4859 }
4860 
4861 static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt,
4862 			    bool free)
4863 {
4864 	void __rcu **slots;
4865 	struct maple_node *node = mte_to_node(enode);
4866 	struct maple_enode *start;
4867 
4868 	if (mte_is_leaf(enode)) {
4869 		mte_set_node_dead(enode);
4870 		node->type = mte_node_type(enode);
4871 		goto free_leaf;
4872 	}
4873 
4874 	start = enode;
4875 	slots = mte_destroy_descend(&enode, mt, start, 0);
4876 	node = mte_to_node(enode); // Updated in the above call.
4877 	do {
4878 		enum maple_type type;
4879 		unsigned char offset;
4880 		struct maple_enode *parent, *tmp;
4881 
4882 		node->slot_len = mte_dead_leaves(enode, mt, slots);
4883 		if (free)
4884 			mt_free_bulk(node->slot_len, slots);
4885 		offset = node->parent_slot + 1;
4886 		enode = node->piv_parent;
4887 		if (mte_to_node(enode) == node)
4888 			goto free_leaf;
4889 
4890 		type = mte_node_type(enode);
4891 		slots = ma_slots(mte_to_node(enode), type);
4892 		if (offset >= mt_slots[type])
4893 			goto next;
4894 
4895 		tmp = mt_slot_locked(mt, slots, offset);
4896 		if (mte_node_type(tmp) && mte_to_node(tmp)) {
4897 			parent = enode;
4898 			enode = tmp;
4899 			slots = mte_destroy_descend(&enode, mt, parent, offset);
4900 		}
4901 next:
4902 		node = mte_to_node(enode);
4903 	} while (start != enode);
4904 
4905 	node = mte_to_node(enode);
4906 	node->slot_len = mte_dead_leaves(enode, mt, slots);
4907 	if (free)
4908 		mt_free_bulk(node->slot_len, slots);
4909 
4910 free_leaf:
4911 	if (free)
4912 		kfree(node);
4913 }
4914 
4915 /*
4916  * mte_destroy_walk() - Free a tree or sub-tree.
4917  * @enode: the encoded maple node (maple_enode) to start
4918  * @mt: the tree to free - needed for node types.
4919  *
4920  * Must hold the write lock.
4921  */
4922 static inline void mte_destroy_walk(struct maple_enode *enode,
4923 				    struct maple_tree *mt)
4924 {
4925 	struct maple_node *node = mte_to_node(enode);
4926 
4927 	if (mt_in_rcu(mt)) {
4928 		mt_destroy_walk(enode, mt, false);
4929 		call_rcu(&node->rcu, mt_free_walk);
4930 	} else {
4931 		mt_destroy_walk(enode, mt, true);
4932 	}
4933 }
4934 /* Interface */
4935 
4936 /**
4937  * mas_store() - Store an @entry.
4938  * @mas: The maple state.
4939  * @entry: The entry to store.
4940  *
4941  * The @mas->index and @mas->last is used to set the range for the @entry.
4942  *
4943  * Return: the first entry between mas->index and mas->last or %NULL.
4944  */
4945 void *mas_store(struct ma_state *mas, void *entry)
4946 {
4947 	MA_WR_STATE(wr_mas, mas, entry);
4948 
4949 	mas_may_init_lock_check(mas);
4950 	trace_ma_write(TP_FCT, mas, 0, entry);
4951 #ifdef CONFIG_DEBUG_MAPLE_TREE
4952 	if (MAS_WARN_ON(mas, mas->index > mas->last))
4953 		pr_err("Error %lX > %lX " PTR_FMT "\n", mas->index, mas->last,
4954 		       entry);
4955 
4956 	if (mas->index > mas->last) {
4957 		mas_set_err(mas, -EINVAL);
4958 		return NULL;
4959 	}
4960 
4961 #endif
4962 
4963 	/*
4964 	 * Storing is the same operation as insert with the added caveat that it
4965 	 * can overwrite entries.  Although this seems simple enough, one may
4966 	 * want to examine what happens if a single store operation was to
4967 	 * overwrite multiple entries within a self-balancing B-Tree.
4968 	 */
4969 	mas_wr_prealloc_setup(&wr_mas);
4970 	mas->store_type = mas_wr_store_type(&wr_mas);
4971 	if (mas->mas_flags & MA_STATE_PREALLOC) {
4972 		mas_wr_store_entry(&wr_mas);
4973 		MAS_WR_BUG_ON(&wr_mas, mas_is_err(mas));
4974 		return wr_mas.content;
4975 	}
4976 
4977 	mas_prealloc_calc(&wr_mas, entry);
4978 	if (!mas->node_request)
4979 		goto store;
4980 
4981 	mas_alloc_nodes(mas, GFP_NOWAIT);
4982 	if (mas_is_err(mas))
4983 		return NULL;
4984 
4985 store:
4986 	mas_wr_store_entry(&wr_mas);
4987 	mas_destroy(mas);
4988 	return wr_mas.content;
4989 }
4990 EXPORT_SYMBOL_GPL(mas_store);
4991 
4992 /**
4993  * mas_store_gfp() - Store a value into the tree.
4994  * @mas: The maple state
4995  * @entry: The entry to store
4996  * @gfp: The GFP_FLAGS to use for allocations if necessary.
4997  *
4998  * Return: 0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
4999  * be allocated.
5000  */
5001 int mas_store_gfp(struct ma_state *mas, void *entry, gfp_t gfp)
5002 {
5003 	unsigned long index = mas->index;
5004 	unsigned long last = mas->last;
5005 	MA_WR_STATE(wr_mas, mas, entry);
5006 	int ret = 0;
5007 
5008 	mas_may_init_lock_check(mas);
5009 retry:
5010 	mas_wr_preallocate(&wr_mas, entry);
5011 	if (unlikely(mas_nomem(mas, gfp))) {
5012 		if (!entry)
5013 			__mas_set_range(mas, index, last);
5014 		goto retry;
5015 	}
5016 
5017 	if (mas_is_err(mas)) {
5018 		ret = xa_err(mas->node);
5019 		goto out;
5020 	}
5021 
5022 	mas_wr_store_entry(&wr_mas);
5023 out:
5024 	mas_destroy(mas);
5025 	return ret;
5026 }
5027 EXPORT_SYMBOL_GPL(mas_store_gfp);
5028 
5029 /**
5030  * mas_store_prealloc() - Store a value into the tree using memory
5031  * preallocated in the maple state.
5032  * @mas: The maple state
5033  * @entry: The entry to store.
5034  */
5035 void mas_store_prealloc(struct ma_state *mas, void *entry)
5036 {
5037 	MA_WR_STATE(wr_mas, mas, entry);
5038 
5039 	mas_lock_check(mas);
5040 	if (mas->store_type == wr_store_root) {
5041 		mas_wr_prealloc_setup(&wr_mas);
5042 		goto store;
5043 	}
5044 
5045 	mas_wr_walk_descend(&wr_mas);
5046 	if (mas->store_type != wr_spanning_store) {
5047 		/* set wr_mas->content to current slot */
5048 		wr_mas.content = mas_slot_locked(mas, wr_mas.slots, mas->offset);
5049 		mas_wr_end_piv(&wr_mas);
5050 	}
5051 
5052 store:
5053 	trace_ma_write(TP_FCT, mas, 0, entry);
5054 	mas_wr_store_entry(&wr_mas);
5055 	MAS_WR_BUG_ON(&wr_mas, mas_is_err(mas));
5056 	mas_destroy(mas);
5057 }
5058 EXPORT_SYMBOL_GPL(mas_store_prealloc);
5059 
5060 /**
5061  * mas_preallocate() - Preallocate enough nodes for a store operation
5062  * @mas: The maple state
5063  * @entry: The entry that will be stored
5064  * @gfp: The GFP_FLAGS to use for allocations.
5065  *
5066  * Return: 0 on success, -ENOMEM if memory could not be allocated.
5067  */
5068 int mas_preallocate(struct ma_state *mas, void *entry, gfp_t gfp)
5069 {
5070 	MA_WR_STATE(wr_mas, mas, entry);
5071 
5072 	mas_may_init_lock_check(mas);
5073 	mas_wr_prealloc_setup(&wr_mas);
5074 	mas->store_type = mas_wr_store_type(&wr_mas);
5075 	mas_prealloc_calc(&wr_mas, entry);
5076 	if (!mas->node_request)
5077 		goto set_flag;
5078 
5079 	mas->mas_flags &= ~MA_STATE_PREALLOC;
5080 	mas_alloc_nodes(mas, gfp);
5081 	if (mas_is_err(mas)) {
5082 		int ret = xa_err(mas->node);
5083 
5084 		mas->node_request = 0;
5085 		mas_destroy(mas);
5086 		mas_reset(mas);
5087 		return ret;
5088 	}
5089 
5090 set_flag:
5091 	mas->mas_flags |= MA_STATE_PREALLOC;
5092 	return 0;
5093 }
5094 EXPORT_SYMBOL_GPL(mas_preallocate);
5095 
5096 /*
5097  * mas_destroy() - destroy a maple state.
5098  * @mas: The maple state
5099  *
5100  * Upon completion, check the left-most node and rebalance against the node to
5101  * the right if necessary.  Frees any allocated nodes associated with this maple
5102  * state.
5103  */
5104 void mas_destroy(struct ma_state *mas)
5105 {
5106 	mas->mas_flags &= ~MA_STATE_PREALLOC;
5107 	mas_empty_nodes(mas);
5108 }
5109 EXPORT_SYMBOL_GPL(mas_destroy);
5110 
5111 static void mas_may_activate(struct ma_state *mas)
5112 {
5113 	if (!mas->node) {
5114 		mas->status = ma_start;
5115 	} else if (mas->index > mas->max || mas->index < mas->min) {
5116 		mas->status = ma_start;
5117 	} else {
5118 		mas->status = ma_active;
5119 		mas_lock_check(mas);
5120 	}
5121 }
5122 
5123 static bool mas_next_setup(struct ma_state *mas, unsigned long max,
5124 		void **entry)
5125 {
5126 	bool was_none = mas_is_none(mas);
5127 
5128 	if (unlikely(mas->last >= max)) {
5129 		mas->status = ma_overflow;
5130 		return true;
5131 	}
5132 
5133 	switch (mas->status) {
5134 	case ma_active:
5135 		return false;
5136 	case ma_none:
5137 		fallthrough;
5138 	case ma_pause:
5139 		mas->status = ma_start;
5140 		fallthrough;
5141 	case ma_start:
5142 		mas_walk(mas); /* Retries on dead nodes handled by mas_walk */
5143 		break;
5144 	case ma_overflow:
5145 		/* Overflowed before, but the max changed */
5146 		mas_may_activate(mas);
5147 		break;
5148 	case ma_underflow:
5149 		/* The user expects the mas to be one before where it is */
5150 		mas_may_activate(mas);
5151 		*entry = mas_walk(mas);
5152 		if (*entry)
5153 			return true;
5154 		break;
5155 	case ma_root:
5156 		break;
5157 	case ma_error:
5158 		return true;
5159 	}
5160 
5161 	if (likely(mas_is_active(mas))) /* Fast path */
5162 		return false;
5163 
5164 	if (mas_is_ptr(mas)) {
5165 		*entry = NULL;
5166 		if (was_none && mas->index == 0) {
5167 			mas->index = mas->last = 0;
5168 			return true;
5169 		}
5170 		mas->index = 1;
5171 		mas->last = ULONG_MAX;
5172 		mas->status = ma_none;
5173 		return true;
5174 	}
5175 
5176 	if (mas_is_none(mas))
5177 		return true;
5178 
5179 	return false;
5180 }
5181 
5182 /**
5183  * mas_next() - Get the next entry.
5184  * @mas: The maple state
5185  * @max: The maximum index to check.
5186  *
5187  * Returns the next entry after @mas->index.
5188  * Must hold rcu_read_lock or the write lock.
5189  * Can return the zero entry.
5190  *
5191  * Return: The next entry or %NULL
5192  */
5193 void *mas_next(struct ma_state *mas, unsigned long max)
5194 {
5195 	void *entry = NULL;
5196 
5197 	mas_may_init_lock_check(mas);
5198 	if (mas_next_setup(mas, max, &entry))
5199 		return entry;
5200 
5201 	/* Retries on dead nodes handled by mas_next_slot */
5202 	return mas_next_slot(mas, max, false);
5203 }
5204 EXPORT_SYMBOL_GPL(mas_next);
5205 
5206 /**
5207  * mas_next_range() - Advance the maple state to the next range
5208  * @mas: The maple state
5209  * @max: The maximum index to check.
5210  *
5211  * Sets @mas->index and @mas->last to the range.
5212  * Must hold rcu_read_lock or the write lock.
5213  * Can return the zero entry.
5214  *
5215  * Return: The next entry or %NULL
5216  */
5217 void *mas_next_range(struct ma_state *mas, unsigned long max)
5218 {
5219 	void *entry = NULL;
5220 
5221 	mas_may_init_lock_check(mas);
5222 	if (mas_next_setup(mas, max, &entry))
5223 		return entry;
5224 
5225 	/* Retries on dead nodes handled by mas_next_slot */
5226 	return mas_next_slot(mas, max, true);
5227 }
5228 EXPORT_SYMBOL_GPL(mas_next_range);
5229 
5230 /**
5231  * mt_next() - get the next value in the maple tree
5232  * @mt: The maple tree
5233  * @index: The start index
5234  * @max: The maximum index to check
5235  *
5236  * Takes RCU read lock internally to protect the search, which does not
5237  * protect the returned pointer after dropping RCU read lock.
5238  * See also: Documentation/core-api/maple_tree.rst
5239  *
5240  * Return: The entry higher than @index or %NULL if nothing is found.
5241  */
5242 void *mt_next(struct maple_tree *mt, unsigned long index, unsigned long max)
5243 {
5244 	void *entry = NULL;
5245 	MA_STATE(mas, mt, index, index);
5246 
5247 	rcu_read_lock();
5248 	entry = mas_next(&mas, max);
5249 	rcu_read_unlock();
5250 	return entry;
5251 }
5252 EXPORT_SYMBOL_GPL(mt_next);
5253 
5254 static bool mas_prev_setup(struct ma_state *mas, unsigned long min, void **entry)
5255 {
5256 	if (unlikely(mas->index <= min)) {
5257 		mas->status = ma_underflow;
5258 		return true;
5259 	}
5260 
5261 	switch (mas->status) {
5262 	case ma_active:
5263 		return false;
5264 	case ma_start:
5265 		break;
5266 	case ma_none:
5267 		fallthrough;
5268 	case ma_pause:
5269 		mas->status = ma_start;
5270 		break;
5271 	case ma_underflow:
5272 		/* underflowed before but the min changed */
5273 		mas_may_activate(mas);
5274 		break;
5275 	case ma_overflow:
5276 		/* User expects mas to be one after where it is */
5277 		mas_may_activate(mas);
5278 		*entry = mas_walk(mas);
5279 		if (*entry)
5280 			return true;
5281 		break;
5282 	case ma_root:
5283 		break;
5284 	case ma_error:
5285 		return true;
5286 	}
5287 
5288 	if (mas_is_start(mas))
5289 		mas_walk(mas);
5290 
5291 	if (unlikely(mas_is_ptr(mas))) {
5292 		if (!mas->index) {
5293 			mas->status = ma_none;
5294 			return true;
5295 		}
5296 		mas->index = mas->last = 0;
5297 		*entry = mas_root(mas);
5298 		return true;
5299 	}
5300 
5301 	if (mas_is_none(mas)) {
5302 		if (mas->index) {
5303 			/* Walked to out-of-range pointer? */
5304 			mas->index = mas->last = 0;
5305 			mas->status = ma_root;
5306 			*entry = mas_root(mas);
5307 			return true;
5308 		}
5309 		return true;
5310 	}
5311 
5312 	return false;
5313 }
5314 
5315 /**
5316  * mas_prev() - Get the previous entry
5317  * @mas: The maple state
5318  * @min: The minimum value to check.
5319  *
5320  * Must hold rcu_read_lock or the write lock.
5321  * Will reset mas to ma_start if the status is ma_none.  Will stop on not
5322  * searchable nodes.
5323  *
5324  * Return: the previous value or %NULL.
5325  */
5326 void *mas_prev(struct ma_state *mas, unsigned long min)
5327 {
5328 	void *entry = NULL;
5329 
5330 	mas_may_init_lock_check(mas);
5331 	if (mas_prev_setup(mas, min, &entry))
5332 		return entry;
5333 
5334 	return mas_prev_slot(mas, min, false);
5335 }
5336 EXPORT_SYMBOL_GPL(mas_prev);
5337 
5338 /**
5339  * mas_prev_range() - Advance to the previous range
5340  * @mas: The maple state
5341  * @min: The minimum value to check.
5342  *
5343  * Sets @mas->index and @mas->last to the range.
5344  * Must hold rcu_read_lock or the write lock.
5345  * Will reset mas to ma_start if the node is ma_none.  Will stop on not
5346  * searchable nodes.
5347  *
5348  * Return: the previous value or %NULL.
5349  */
5350 void *mas_prev_range(struct ma_state *mas, unsigned long min)
5351 {
5352 	void *entry = NULL;
5353 
5354 	mas_may_init_lock_check(mas);
5355 	if (mas_prev_setup(mas, min, &entry))
5356 		return entry;
5357 
5358 	return mas_prev_slot(mas, min, true);
5359 }
5360 EXPORT_SYMBOL_GPL(mas_prev_range);
5361 
5362 /**
5363  * mt_prev() - get the previous value in the maple tree
5364  * @mt: The maple tree
5365  * @index: The start index
5366  * @min: The minimum index to check
5367  *
5368  * Takes RCU read lock internally to protect the search, which does not
5369  * protect the returned pointer after dropping RCU read lock.
5370  * See also: Documentation/core-api/maple_tree.rst
5371  *
5372  * Return: The entry before @index or %NULL if nothing is found.
5373  */
5374 void *mt_prev(struct maple_tree *mt, unsigned long index, unsigned long min)
5375 {
5376 	void *entry = NULL;
5377 	MA_STATE(mas, mt, index, index);
5378 
5379 	rcu_read_lock();
5380 	entry = mas_prev(&mas, min);
5381 	rcu_read_unlock();
5382 	return entry;
5383 }
5384 EXPORT_SYMBOL_GPL(mt_prev);
5385 
5386 /**
5387  * mas_pause() - Pause a mas_find/mas_for_each to drop the lock.
5388  * @mas: The maple state to pause
5389  *
5390  * Some users need to pause a walk and drop the lock they're holding in
5391  * order to yield to a higher priority thread or carry out an operation
5392  * on an entry.  Those users should call this function before they drop
5393  * the lock.  It resets the @mas to be suitable for the next iteration
5394  * of the loop after the user has reacquired the lock.  If most entries
5395  * found during a walk require you to call mas_pause(), the mt_for_each()
5396  * iterator may be more appropriate.
5397  *
5398  */
5399 void mas_pause(struct ma_state *mas)
5400 {
5401 	mas_lock_check(mas);
5402 	mas->status = ma_pause;
5403 	mas->node = NULL;
5404 }
5405 EXPORT_SYMBOL_GPL(mas_pause);
5406 
5407 /**
5408  * mas_find_setup() - Internal function to set up mas_find*().
5409  * @mas: The maple state
5410  * @max: The maximum index
5411  * @entry: Pointer to the entry
5412  *
5413  * Returns: True if entry is the answer, false otherwise.
5414  */
5415 static __always_inline bool mas_find_setup(struct ma_state *mas, unsigned long max, void **entry)
5416 {
5417 	switch (mas->status) {
5418 	case ma_active:
5419 		if (mas->last < max)
5420 			return false;
5421 		return true;
5422 	case ma_start:
5423 		break;
5424 	case ma_pause:
5425 		if (unlikely(mas->last >= max))
5426 			return true;
5427 
5428 		mas->index = ++mas->last;
5429 		mas->status = ma_start;
5430 		break;
5431 	case ma_none:
5432 		if (unlikely(mas->last >= max))
5433 			return true;
5434 
5435 		mas->index = mas->last;
5436 		mas->status = ma_start;
5437 		break;
5438 	case ma_underflow:
5439 		/* mas is pointing at entry before unable to go lower */
5440 		if (unlikely(mas->index >= max)) {
5441 			mas->status = ma_overflow;
5442 			return true;
5443 		}
5444 
5445 		mas_may_activate(mas);
5446 		*entry = mas_walk(mas);
5447 		if (*entry)
5448 			return true;
5449 		break;
5450 	case ma_overflow:
5451 		if (unlikely(mas->last >= max))
5452 			return true;
5453 
5454 		mas_may_activate(mas);
5455 		*entry = mas_walk(mas);
5456 		if (*entry)
5457 			return true;
5458 		break;
5459 	case ma_root:
5460 		break;
5461 	case ma_error:
5462 		return true;
5463 	}
5464 
5465 	if (mas_is_start(mas)) {
5466 		/* First run or continue */
5467 		if (mas->index > max)
5468 			return true;
5469 
5470 		*entry = mas_walk(mas);
5471 		if (*entry)
5472 			return true;
5473 
5474 	}
5475 
5476 	if (unlikely(mas_is_ptr(mas)))
5477 		goto ptr_out_of_range;
5478 
5479 	if (unlikely(mas_is_none(mas)))
5480 		return true;
5481 
5482 	if (mas->index == max)
5483 		return true;
5484 
5485 	return false;
5486 
5487 ptr_out_of_range:
5488 	mas->status = ma_none;
5489 	mas->index = 1;
5490 	mas->last = ULONG_MAX;
5491 	return true;
5492 }
5493 
5494 /**
5495  * mas_find() - On the first call, find the entry at or after mas->index up to
5496  * %max.  Otherwise, find the entry after mas->index.
5497  * @mas: The maple state
5498  * @max: The maximum value to check.
5499  *
5500  * Must hold rcu_read_lock or the write lock.
5501  * If an entry exists, last and index are updated accordingly.
5502  * May set @mas->status to ma_overflow.
5503  *
5504  * Return: The entry or %NULL.
5505  */
5506 void *mas_find(struct ma_state *mas, unsigned long max)
5507 {
5508 	void *entry = NULL;
5509 
5510 	mas_may_init_lock_check(mas);
5511 	if (mas_find_setup(mas, max, &entry))
5512 		return entry;
5513 
5514 	/* Retries on dead nodes handled by mas_next_slot */
5515 	entry = mas_next_slot(mas, max, false);
5516 	/* Ignore overflow */
5517 	if (mas_is_overflow(mas))
5518 		mas->status = ma_active;
5519 
5520 	return entry;
5521 }
5522 EXPORT_SYMBOL_GPL(mas_find);
5523 
5524 /**
5525  * mas_find_range() - On the first call, find the entry at or after
5526  * mas->index up to %max.  Otherwise, advance to the next slot mas->index.
5527  * @mas: The maple state
5528  * @max: The maximum value to check.
5529  *
5530  * Must hold rcu_read_lock or the write lock.
5531  * If an entry exists, last and index are updated accordingly.
5532  * May set @mas->status to ma_overflow.
5533  *
5534  * Return: The entry or %NULL.
5535  */
5536 void *mas_find_range(struct ma_state *mas, unsigned long max)
5537 {
5538 	void *entry = NULL;
5539 
5540 	mas_may_init_lock_check(mas);
5541 	if (mas_find_setup(mas, max, &entry))
5542 		return entry;
5543 
5544 	/* Retries on dead nodes handled by mas_next_slot */
5545 	return mas_next_slot(mas, max, true);
5546 }
5547 EXPORT_SYMBOL_GPL(mas_find_range);
5548 
5549 /**
5550  * mas_find_rev_setup() - Internal function to set up mas_find_*_rev()
5551  * @mas: The maple state
5552  * @min: The minimum index
5553  * @entry: Pointer to the entry
5554  *
5555  * Returns: True if entry is the answer, false otherwise.
5556  */
5557 static bool mas_find_rev_setup(struct ma_state *mas, unsigned long min,
5558 		void **entry)
5559 {
5560 	switch (mas->status) {
5561 	case ma_active:
5562 		goto active;
5563 	case ma_start:
5564 		break;
5565 	case ma_pause:
5566 		if (unlikely(mas->index <= min)) {
5567 			mas->status = ma_underflow;
5568 			return true;
5569 		}
5570 		mas->last = --mas->index;
5571 		mas->status = ma_start;
5572 		break;
5573 	case ma_none:
5574 		if (mas->index <= min)
5575 			goto none;
5576 
5577 		mas->last = mas->index;
5578 		mas->status = ma_start;
5579 		break;
5580 	case ma_overflow: /* user expects the mas to be one after where it is */
5581 		if (unlikely(mas->index <= min)) {
5582 			mas->status = ma_underflow;
5583 			return true;
5584 		}
5585 
5586 		mas->status = ma_active;
5587 		break;
5588 	case ma_underflow: /* user expects the mas to be one before where it is */
5589 		if (unlikely(mas->index <= min))
5590 			return true;
5591 
5592 		mas->status = ma_active;
5593 		break;
5594 	case ma_root:
5595 		break;
5596 	case ma_error:
5597 		return true;
5598 	}
5599 
5600 	if (mas_is_start(mas)) {
5601 		/* First run or continue */
5602 		if (mas->index < min)
5603 			return true;
5604 
5605 		*entry = mas_walk(mas);
5606 		if (*entry)
5607 			return true;
5608 	}
5609 
5610 	if (unlikely(mas_is_ptr(mas)))
5611 		goto none;
5612 
5613 	if (unlikely(mas_is_none(mas))) {
5614 		/*
5615 		 * Walked to the location, and there was nothing so the previous
5616 		 * location is 0.
5617 		 */
5618 		mas->last = mas->index = 0;
5619 		mas->status = ma_root;
5620 		*entry = mas_root(mas);
5621 		return true;
5622 	}
5623 
5624 active:
5625 	if (mas->index < min)
5626 		return true;
5627 
5628 	return false;
5629 
5630 none:
5631 	mas->status = ma_none;
5632 	return true;
5633 }
5634 
5635 /**
5636  * mas_find_rev: On the first call, find the first non-null entry at or below
5637  * mas->index down to %min.  Otherwise find the first non-null entry below
5638  * mas->index down to %min.
5639  * @mas: The maple state
5640  * @min: The minimum value to check.
5641  *
5642  * Must hold rcu_read_lock or the write lock.
5643  * If an entry exists, last and index are updated accordingly.
5644  * May set @mas->status to ma_underflow.
5645  *
5646  * Return: The entry or %NULL.
5647  */
5648 void *mas_find_rev(struct ma_state *mas, unsigned long min)
5649 {
5650 	void *entry = NULL;
5651 
5652 	mas_may_init_lock_check(mas);
5653 	if (mas_find_rev_setup(mas, min, &entry))
5654 		return entry;
5655 
5656 	/* Retries on dead nodes handled by mas_prev_slot */
5657 	return mas_prev_slot(mas, min, false);
5658 
5659 }
5660 EXPORT_SYMBOL_GPL(mas_find_rev);
5661 
5662 /**
5663  * mas_find_range_rev: On the first call, find the first non-null entry at or
5664  * below mas->index down to %min.  Otherwise advance to the previous slot after
5665  * mas->index down to %min.
5666  * @mas: The maple state
5667  * @min: The minimum value to check.
5668  *
5669  * Must hold rcu_read_lock or the write lock.
5670  * If an entry exists, last and index are updated accordingly.
5671  * May set @mas->status to ma_underflow.
5672  *
5673  * Return: The entry or %NULL.
5674  */
5675 void *mas_find_range_rev(struct ma_state *mas, unsigned long min)
5676 {
5677 	void *entry = NULL;
5678 
5679 	mas_may_init_lock_check(mas);
5680 	if (mas_find_rev_setup(mas, min, &entry))
5681 		return entry;
5682 
5683 	/* Retries on dead nodes handled by mas_prev_slot */
5684 	return mas_prev_slot(mas, min, true);
5685 }
5686 EXPORT_SYMBOL_GPL(mas_find_range_rev);
5687 
5688 /**
5689  * mas_erase() - Find the range in which index resides and erase the entire
5690  * range.
5691  * @mas: The maple state
5692  *
5693  * Must hold the write lock.
5694  * Searches for @mas->index, sets @mas->index and @mas->last to the range and
5695  * erases that range.
5696  *
5697  * Note that erase requires allocations and will use GFP_KERNEL | __GFP_NOFAIL
5698  * to do so if necessary.  If the allocation fails, the internal lock will be
5699  * dropped to retry.  An externally locked tree must be protected by a lock that
5700  * allows blocking for this API.
5701  *
5702  * Return: the entry that was erased or %NULL, @mas->index and @mas->last are updated.
5703  */
5704 void *mas_erase(struct ma_state *mas)
5705 {
5706 	void *entry;
5707 	unsigned long index = mas->index;
5708 	MA_WR_STATE(wr_mas, mas, NULL);
5709 
5710 	/*
5711 	 * In low memory situations, the allocation is retried with the gfp flag
5712 	 * GFP_KERNEL | __GFP_NOFAIL.  The internal spinlock is dropped in
5713 	 * mas_nomem_nofail(), however the external lock is not dropped.
5714 	 */
5715 	if (mt_external_lock(mas->tree))
5716 		might_alloc(GFP_KERNEL);
5717 
5718 	mas_make_walkable(mas);
5719 write_retry:
5720 	entry = mas_state_walk(mas);
5721 	if (!entry)
5722 		goto out;
5723 
5724 	/* Must reset to ensure spanning writes of last slot are detected */
5725 	mas_reset(mas);
5726 	mas_wr_preallocate(&wr_mas, NULL);
5727 	if (mas_nomem_nofail(mas, index, index))
5728 		goto write_retry;
5729 
5730 	mas_wr_store_entry(&wr_mas);
5731 out:
5732 	mas_destroy(mas);
5733 	return entry;
5734 }
5735 EXPORT_SYMBOL_GPL(mas_erase);
5736 
5737 /**
5738  * mas_nomem() - Check if there was an error allocating and do the allocation
5739  * if necessary.
5740  *
5741  * @mas: The maple state
5742  * @gfp: The GFP_FLAGS to use for allocations
5743  * Return: False on no memory.  True otherwise (partial success as well)
5744  */
5745 bool mas_nomem(struct ma_state *mas, gfp_t gfp)
5746 	__must_hold(mas->tree->ma_lock)
5747 {
5748 	if (likely(mas->node != MA_ERROR(-ENOMEM)))
5749 		return false;
5750 
5751 	/* Allocations can fail, don't do this. */
5752 	WARN_ON_ONCE(!gfpflags_allow_blocking(gfp) &&
5753 		     mt_external_lock(mas->tree));
5754 
5755 	if (gfpflags_allow_blocking(gfp) && !mt_external_lock(mas->tree)) {
5756 		mtree_unlock(mas->tree);
5757 		mas_alloc_nodes(mas, gfp);
5758 		mtree_lock(mas->tree);
5759 	} else {
5760 		mas_alloc_nodes(mas, gfp);
5761 	}
5762 
5763 	/*
5764 	 * Return false on zero forward progress.  Partial allocations are kept
5765 	 * so the retry path will attempt to get the rest.  The failure should
5766 	 * not happen as we try our best to reclaim.  The user would need an
5767 	 * external lock with a non-blocking gfp in a low memory situation.
5768 	 */
5769 	if (!mas->sheaf && !mas->alloc)
5770 		return false;
5771 
5772 	mas_reset(mas);
5773 	return true;
5774 }
5775 
5776 /**
5777  * mas_nomem_nofail() - Retry allocations with __GFP_NOFAIL, if the maple state
5778  * has stored the -ENOMEM error.
5779  * @mas: The maple state
5780  * @index: The start of the range for the @mas reset
5781  * @last: The end of the range for the @mas reset
5782  *
5783  * Return: false if @mas isn't in an -ENOMEM state.  True if the allocation
5784  * happens, the state is reset.  The internal lock will be dropped and external
5785  * locks must allow blocking.
5786  */
5787 bool mas_nomem_nofail(struct ma_state *mas, unsigned long index,
5788 		unsigned long last)
5789 	__must_hold(mas->tree->ma_lock)
5790 {
5791 	gfp_t gfp;
5792 
5793 	if (likely(mas->node != MA_ERROR(-ENOMEM)))
5794 		return false;
5795 
5796 	gfp = GFP_KERNEL | __GFP_NOFAIL;
5797 	if (!mt_external_lock(mas->tree)) {
5798 		mtree_unlock(mas->tree);
5799 		mas_alloc_nodes(mas, gfp);
5800 		mtree_lock(mas->tree);
5801 	} else {
5802 		mas_alloc_nodes(mas, gfp);
5803 	}
5804 
5805 	mas_set_range(mas, index, last);
5806 	return true;
5807 }
5808 
5809 void __init maple_tree_init(void)
5810 {
5811 	struct kmem_cache_args args = {
5812 		.align  = sizeof(struct maple_node),
5813 		.sheaf_capacity = 32,
5814 	};
5815 
5816 	maple_node_cache = kmem_cache_create("maple_node",
5817 			sizeof(struct maple_node), &args,
5818 			SLAB_PANIC);
5819 }
5820 
5821 /**
5822  * mtree_load() - Load a value stored in a maple tree
5823  * @mt: The maple tree
5824  * @index: The index to load
5825  *
5826  * Return: the entry or %NULL
5827  */
5828 void *mtree_load(struct maple_tree *mt, unsigned long index)
5829 {
5830 	MA_STATE(mas, mt, index, index);
5831 	void *entry;
5832 
5833 	trace_ma_read(TP_FCT, &mas);
5834 	rcu_read_lock();
5835 retry:
5836 	entry = mas_start(&mas);
5837 	if (unlikely(mas_is_none(&mas)))
5838 		goto unlock;
5839 
5840 	if (unlikely(mas_is_ptr(&mas))) {
5841 		if (index)
5842 			entry = NULL;
5843 
5844 		goto unlock;
5845 	}
5846 
5847 	entry = mtree_lookup_walk(&mas);
5848 	if (!entry && unlikely(mas_is_start(&mas)))
5849 		goto retry;
5850 unlock:
5851 	rcu_read_unlock();
5852 	if (xa_is_zero(entry))
5853 		return NULL;
5854 
5855 	return entry;
5856 }
5857 EXPORT_SYMBOL(mtree_load);
5858 
5859 /**
5860  * mtree_store_range() - Store an entry at a given range.
5861  * @mt: The maple tree
5862  * @index: The start of the range
5863  * @last: The end of the range
5864  * @entry: The entry to store
5865  * @gfp: The GFP_FLAGS to use for allocations
5866  *
5867  * Return: 0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
5868  * be allocated.
5869  */
5870 int mtree_store_range(struct maple_tree *mt, unsigned long index,
5871 		unsigned long last, void *entry, gfp_t gfp)
5872 {
5873 	MA_STATE(mas, mt, index, last);
5874 	int ret = 0;
5875 
5876 	trace_ma_write(TP_FCT, &mas, 0, entry);
5877 	if (WARN_ON_ONCE(xa_is_advanced(entry)))
5878 		return -EINVAL;
5879 
5880 	if (index > last)
5881 		return -EINVAL;
5882 
5883 	mtree_lock(mt);
5884 	ret = mas_store_gfp(&mas, entry, gfp);
5885 	mtree_unlock(mt);
5886 
5887 	return ret;
5888 }
5889 EXPORT_SYMBOL(mtree_store_range);
5890 
5891 /**
5892  * mtree_store() - Store an entry at a given index.
5893  * @mt: The maple tree
5894  * @index: The index to store the value
5895  * @entry: The entry to store
5896  * @gfp: The GFP_FLAGS to use for allocations
5897  *
5898  * Return: 0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
5899  * be allocated.
5900  */
5901 int mtree_store(struct maple_tree *mt, unsigned long index, void *entry,
5902 		 gfp_t gfp)
5903 {
5904 	return mtree_store_range(mt, index, index, entry, gfp);
5905 }
5906 EXPORT_SYMBOL(mtree_store);
5907 
5908 /**
5909  * mtree_insert_range() - Insert an entry from [first, last] at a given range
5910  *                        if there is no value.
5911  * @mt: The maple tree
5912  * @first: The start of the range
5913  * @last: The end of the range (inclusive)
5914  * @entry: The entry to store
5915  * @gfp: The GFP_FLAGS to use for allocations.
5916  *
5917  * Note that @last is inclusive. That is, @last = @first + length - 1;
5918  *
5919  * Return: 0 on success, -EEXISTS if the range is occupied, -EINVAL on invalid
5920  * request, -ENOMEM if memory could not be allocated.
5921  */
5922 int mtree_insert_range(struct maple_tree *mt, unsigned long first,
5923 		unsigned long last, void *entry, gfp_t gfp)
5924 {
5925 	MA_STATE(ms, mt, first, last);
5926 	int ret = 0;
5927 
5928 	if (WARN_ON_ONCE(xa_is_advanced(entry)))
5929 		return -EINVAL;
5930 
5931 	if (first > last)
5932 		return -EINVAL;
5933 
5934 	mtree_lock(mt);
5935 retry:
5936 	mas_insert(&ms, entry);
5937 	if (mas_nomem(&ms, gfp))
5938 		goto retry;
5939 
5940 	mtree_unlock(mt);
5941 	if (mas_is_err(&ms))
5942 		ret = xa_err(ms.node);
5943 
5944 	mas_destroy(&ms);
5945 	return ret;
5946 }
5947 EXPORT_SYMBOL(mtree_insert_range);
5948 
5949 /**
5950  * mtree_insert() - Insert an entry at a given index if there is no value.
5951  * @mt: The maple tree
5952  * @index : The index to store the value
5953  * @entry: The entry to store
5954  * @gfp: The GFP_FLAGS to use for allocations.
5955  *
5956  * Return: 0 on success, -EEXISTS if the range is occupied, -EINVAL on invalid
5957  * request, -ENOMEM if memory could not be allocated.
5958  */
5959 int mtree_insert(struct maple_tree *mt, unsigned long index, void *entry,
5960 		 gfp_t gfp)
5961 {
5962 	return mtree_insert_range(mt, index, index, entry, gfp);
5963 }
5964 EXPORT_SYMBOL(mtree_insert);
5965 
5966 int mtree_alloc_range(struct maple_tree *mt, unsigned long *startp,
5967 		void *entry, unsigned long size, unsigned long min,
5968 		unsigned long max, gfp_t gfp)
5969 {
5970 	int ret = 0;
5971 
5972 	MA_STATE(mas, mt, 0, 0);
5973 	if (!mt_is_alloc(mt))
5974 		return -EINVAL;
5975 
5976 	if (WARN_ON_ONCE(mt_is_reserved(entry)))
5977 		return -EINVAL;
5978 
5979 	mtree_lock(mt);
5980 retry:
5981 	ret = mas_empty_area(&mas, min, max, size);
5982 	if (ret)
5983 		goto unlock;
5984 
5985 	mas_insert(&mas, entry);
5986 	/*
5987 	 * mas_nomem() may release the lock, causing the allocated area
5988 	 * to be unavailable, so try to allocate a free area again.
5989 	 */
5990 	if (mas_nomem(&mas, gfp))
5991 		goto retry;
5992 
5993 	if (mas_is_err(&mas))
5994 		ret = xa_err(mas.node);
5995 	else
5996 		*startp = mas.index;
5997 
5998 unlock:
5999 	mtree_unlock(mt);
6000 	mas_destroy(&mas);
6001 	return ret;
6002 }
6003 EXPORT_SYMBOL(mtree_alloc_range);
6004 
6005 /**
6006  * mtree_alloc_cyclic() - Find somewhere to store this entry in the tree.
6007  * @mt: The maple tree.
6008  * @startp: Pointer to ID.
6009  * @range_lo: Lower bound of range to search.
6010  * @range_hi: Upper bound of range to search.
6011  * @entry: The entry to store.
6012  * @next: Pointer to next ID to allocate.
6013  * @gfp: The GFP_FLAGS to use for allocations.
6014  *
6015  * Finds an empty entry in @mt after @next, stores the new index into
6016  * the @id pointer, stores the entry at that index, then updates @next.
6017  *
6018  * @mt must be initialized with the MT_FLAGS_ALLOC_RANGE flag.
6019  *
6020  * Context: Any context.  Takes and releases the mt.lock.  May sleep if
6021  * the @gfp flags permit.
6022  *
6023  * Return: 0 if the allocation succeeded without wrapping, 1 if the
6024  * allocation succeeded after wrapping, -ENOMEM if memory could not be
6025  * allocated, -EINVAL if @mt cannot be used, or -EBUSY if there are no
6026  * free entries.
6027  */
6028 int mtree_alloc_cyclic(struct maple_tree *mt, unsigned long *startp,
6029 		void *entry, unsigned long range_lo, unsigned long range_hi,
6030 		unsigned long *next, gfp_t gfp)
6031 {
6032 	int ret;
6033 
6034 	MA_STATE(mas, mt, 0, 0);
6035 
6036 	if (!mt_is_alloc(mt))
6037 		return -EINVAL;
6038 	if (WARN_ON_ONCE(mt_is_reserved(entry)))
6039 		return -EINVAL;
6040 	mtree_lock(mt);
6041 	ret = mas_alloc_cyclic(&mas, startp, entry, range_lo, range_hi,
6042 			       next, gfp);
6043 	mtree_unlock(mt);
6044 	return ret;
6045 }
6046 EXPORT_SYMBOL(mtree_alloc_cyclic);
6047 
6048 int mtree_alloc_rrange(struct maple_tree *mt, unsigned long *startp,
6049 		void *entry, unsigned long size, unsigned long min,
6050 		unsigned long max, gfp_t gfp)
6051 {
6052 	int ret = 0;
6053 
6054 	MA_STATE(mas, mt, 0, 0);
6055 	if (!mt_is_alloc(mt))
6056 		return -EINVAL;
6057 
6058 	if (WARN_ON_ONCE(mt_is_reserved(entry)))
6059 		return -EINVAL;
6060 
6061 	mtree_lock(mt);
6062 retry:
6063 	ret = mas_empty_area_rev(&mas, min, max, size);
6064 	if (ret)
6065 		goto unlock;
6066 
6067 	mas_insert(&mas, entry);
6068 	/*
6069 	 * mas_nomem() may release the lock, causing the allocated area
6070 	 * to be unavailable, so try to allocate a free area again.
6071 	 */
6072 	if (mas_nomem(&mas, gfp))
6073 		goto retry;
6074 
6075 	if (mas_is_err(&mas))
6076 		ret = xa_err(mas.node);
6077 	else
6078 		*startp = mas.index;
6079 
6080 unlock:
6081 	mtree_unlock(mt);
6082 	mas_destroy(&mas);
6083 	return ret;
6084 }
6085 EXPORT_SYMBOL(mtree_alloc_rrange);
6086 
6087 /**
6088  * mtree_erase() - Find an index and erase the entire range.
6089  * @mt: The maple tree
6090  * @index: The index to erase
6091  *
6092  * Erasing is the same as a walk to an entry then a store of a NULL to that
6093  * ENTIRE range.  In fact, it is implemented as such using the advanced API.
6094  *
6095  * Note that erase requires allocations and will use GFP_KERNEL | __GFP_NOFAIL
6096  * to do so if necessary.  If the allocation fails, the internal lock will be
6097  * dropped to retry.
6098  *
6099  * Return: The entry stored at the @index or %NULL
6100  */
6101 void *mtree_erase(struct maple_tree *mt, unsigned long index)
6102 {
6103 	void *entry = NULL;
6104 
6105 	MA_STATE(mas, mt, index, index);
6106 	trace_ma_op(TP_FCT, &mas);
6107 
6108 	might_alloc(GFP_KERNEL);
6109 	mtree_lock(mt);
6110 	entry = mas_erase(&mas);
6111 	mtree_unlock(mt);
6112 
6113 	return entry;
6114 }
6115 EXPORT_SYMBOL(mtree_erase);
6116 
6117 /*
6118  * mas_dup_free() - Free an incomplete duplication of a tree.
6119  * @mas: The maple state of a incomplete tree.
6120  *
6121  * The parameter @mas->node passed in indicates that the allocation failed on
6122  * this node. This function frees all nodes starting from @mas->node in the
6123  * reverse order of mas_dup_build(). There is no need to hold the source tree
6124  * lock at this time.
6125  */
6126 static void mas_dup_free(struct ma_state *mas)
6127 {
6128 	struct maple_node *node;
6129 	enum maple_type type;
6130 	void __rcu **slots;
6131 	unsigned char count, i;
6132 
6133 	/* Maybe the first node allocation failed. */
6134 	if (mas_is_none(mas))
6135 		return;
6136 
6137 	while (!mte_is_root(mas->node)) {
6138 		mas_ascend(mas);
6139 		if (mas->offset) {
6140 			mas->offset--;
6141 			do {
6142 				mas_descend(mas);
6143 				mas->offset = mas_data_end(mas);
6144 			} while (!mte_is_leaf(mas->node));
6145 
6146 			mas_ascend(mas);
6147 		}
6148 
6149 		node = mte_to_node(mas->node);
6150 		type = mte_node_type(mas->node);
6151 		slots = ma_slots(node, type);
6152 		count = mas_data_end(mas) + 1;
6153 		for (i = 0; i < count; i++)
6154 			((unsigned long *)slots)[i] &= ~MAPLE_NODE_MASK;
6155 		mt_free_bulk(count, slots);
6156 	}
6157 
6158 	node = mte_to_node(mas->node);
6159 	kfree(node);
6160 }
6161 
6162 /*
6163  * mas_copy_node() - Copy a maple node and replace the parent.
6164  * @mas: The maple state of source tree.
6165  * @new_mas: The maple state of new tree.
6166  * @parent: The parent of the new node.
6167  *
6168  * Copy @mas->node to @new_mas->node, set @parent to be the parent of
6169  * @new_mas->node. If memory allocation fails, @mas is set to -ENOMEM.
6170  */
6171 static inline void mas_copy_node(struct ma_state *mas, struct ma_state *new_mas,
6172 		struct maple_pnode *parent)
6173 {
6174 	struct maple_node *node = mte_to_node(mas->node);
6175 	struct maple_node *new_node = mte_to_node(new_mas->node);
6176 	unsigned long val;
6177 
6178 	/* Copy the node completely. */
6179 	memcpy(new_node, node, sizeof(struct maple_node));
6180 	/* Update the parent node pointer. */
6181 	val = (unsigned long)node->parent & MAPLE_NODE_MASK;
6182 	new_node->parent = ma_parent_ptr(val | (unsigned long)parent);
6183 }
6184 
6185 /*
6186  * mas_dup_alloc() - Allocate child nodes for a maple node.
6187  * @mas: The maple state of source tree.
6188  * @new_mas: The maple state of new tree.
6189  * @gfp: The GFP_FLAGS to use for allocations.
6190  *
6191  * This function allocates child nodes for @new_mas->node during the duplication
6192  * process. If memory allocation fails, @mas is set to -ENOMEM.
6193  */
6194 static inline void mas_dup_alloc(struct ma_state *mas, struct ma_state *new_mas,
6195 		gfp_t gfp)
6196 {
6197 	struct maple_node *node = mte_to_node(mas->node);
6198 	struct maple_node *new_node = mte_to_node(new_mas->node);
6199 	enum maple_type type;
6200 	unsigned char count, i;
6201 	void __rcu **slots;
6202 	void __rcu **new_slots;
6203 	unsigned long val;
6204 
6205 	/* Allocate memory for child nodes. */
6206 	type = mte_node_type(mas->node);
6207 	new_slots = ma_slots(new_node, type);
6208 	count = mas->node_request = mas_data_end(mas) + 1;
6209 	mas_alloc_nodes(mas, gfp);
6210 	if (unlikely(mas_is_err(mas)))
6211 		return;
6212 
6213 	slots = ma_slots(node, type);
6214 	for (i = 0; i < count; i++) {
6215 		val = (unsigned long)mt_slot_locked(mas->tree, slots, i);
6216 		val &= MAPLE_NODE_MASK;
6217 		/*
6218 		 * Warning, see rcu_assign_pointer() documentation.  Since this
6219 		 * is a duplication of a tree, there are no readers walking the
6220 		 * tree until after the rcu_assign_pointer() call in
6221 		 * mas_dup_build().
6222 		 */
6223 		RCU_INIT_POINTER(new_slots[i],
6224 				 ma_mnode_ptr((unsigned long)mas_pop_node(mas) |
6225 					      val));
6226 	}
6227 }
6228 
6229 /*
6230  * mas_dup_build() - Build a new maple tree from a source tree
6231  * @mas: The maple state of source tree, need to be in MAS_START state.
6232  * @new_mas: The maple state of new tree, need to be in MAS_START state.
6233  * @gfp: The GFP_FLAGS to use for allocations.
6234  *
6235  * This function builds a new tree in DFS preorder. If the memory allocation
6236  * fails, the error code -ENOMEM will be set in @mas, and @new_mas points to the
6237  * last node. mas_dup_free() will free the incomplete duplication of a tree.
6238  *
6239  * Note that the attributes of the two trees need to be exactly the same, and the
6240  * new tree needs to be empty, otherwise -EINVAL will be set in @mas.
6241  */
6242 static inline void mas_dup_build(struct ma_state *mas, struct ma_state *new_mas,
6243 		gfp_t gfp)
6244 {
6245 	struct maple_node *node;
6246 	struct maple_pnode *parent = NULL;
6247 	struct maple_enode *root;
6248 	enum maple_type type;
6249 
6250 	if (unlikely(mt_attr(mas->tree) != mt_attr(new_mas->tree)) ||
6251 	    unlikely(!mtree_empty(new_mas->tree))) {
6252 		mas_set_err(mas, -EINVAL);
6253 		return;
6254 	}
6255 
6256 	root = mas_start(mas);
6257 	if (mas_is_ptr(mas) || mas_is_none(mas))
6258 		goto set_new_tree;
6259 
6260 	node = mt_alloc_one(gfp);
6261 	if (!node) {
6262 		new_mas->status = ma_none;
6263 		mas_set_err(mas, -ENOMEM);
6264 		return;
6265 	}
6266 
6267 	type = mte_node_type(mas->node);
6268 	root = mt_mk_node(node, type);
6269 	new_mas->node = root;
6270 	new_mas->min = 0;
6271 	new_mas->max = ULONG_MAX;
6272 	root = mte_mk_root(root);
6273 	while (1) {
6274 		mas_copy_node(mas, new_mas, parent);
6275 		if (!mte_is_leaf(mas->node)) {
6276 			/* Only allocate child nodes for non-leaf nodes. */
6277 			mas_dup_alloc(mas, new_mas, gfp);
6278 			if (unlikely(mas_is_err(mas)))
6279 				goto empty_mas;
6280 		} else {
6281 			/*
6282 			 * This is the last leaf node and duplication is
6283 			 * completed.
6284 			 */
6285 			if (mas->max == ULONG_MAX)
6286 				goto done;
6287 
6288 			/* This is not the last leaf node and needs to go up. */
6289 			do {
6290 				mas_ascend(mas);
6291 				mas_ascend(new_mas);
6292 			} while (mas->offset == mas_data_end(mas));
6293 
6294 			/* Move to the next subtree. */
6295 			mas->offset++;
6296 			new_mas->offset++;
6297 		}
6298 
6299 		mas_descend(mas);
6300 		parent = ma_parent_ptr(mte_to_node(new_mas->node));
6301 		mas_descend(new_mas);
6302 		mas->offset = 0;
6303 		new_mas->offset = 0;
6304 	}
6305 done:
6306 	/* Specially handle the parent of the root node. */
6307 	mte_to_node(root)->parent = ma_parent_ptr(mas_tree_parent(new_mas));
6308 set_new_tree:
6309 	/* Make them the same height */
6310 	new_mas->tree->ma_flags = mas->tree->ma_flags;
6311 	rcu_assign_pointer(new_mas->tree->ma_root, root);
6312 empty_mas:
6313 	mas_empty_nodes(mas);
6314 }
6315 
6316 /**
6317  * __mt_dup(): Duplicate an entire maple tree
6318  * @mt: The source maple tree
6319  * @new: The new maple tree
6320  * @gfp: The GFP_FLAGS to use for allocations
6321  *
6322  * This function duplicates a maple tree in Depth-First Search (DFS) pre-order
6323  * traversal. It uses memcpy() to copy nodes in the source tree and allocate
6324  * new child nodes in non-leaf nodes. The new node is exactly the same as the
6325  * source node except for all the addresses stored in it. It will be faster than
6326  * traversing all elements in the source tree and inserting them one by one into
6327  * the new tree.
6328  * The user needs to ensure that the attributes of the source tree and the new
6329  * tree are the same, and the new tree needs to be an empty tree, otherwise
6330  * -EINVAL will be returned.
6331  * Note that the user needs to manually lock the source tree and the new tree.
6332  *
6333  * Return: 0 on success, -ENOMEM if memory could not be allocated, -EINVAL If
6334  * the attributes of the two trees are different or the new tree is not an empty
6335  * tree.
6336  */
6337 int __mt_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp)
6338 {
6339 	int ret = 0;
6340 	MA_STATE(mas, mt, 0, 0);
6341 	MA_STATE(new_mas, new, 0, 0);
6342 
6343 	mas_dup_build(&mas, &new_mas, gfp);
6344 	if (unlikely(mas_is_err(&mas))) {
6345 		ret = xa_err(mas.node);
6346 		if (ret == -ENOMEM)
6347 			mas_dup_free(&new_mas);
6348 	}
6349 
6350 	return ret;
6351 }
6352 EXPORT_SYMBOL(__mt_dup);
6353 
6354 /**
6355  * mtree_dup(): Duplicate an entire maple tree
6356  * @mt: The source maple tree
6357  * @new: The new maple tree
6358  * @gfp: The GFP_FLAGS to use for allocations
6359  *
6360  * This function duplicates a maple tree in Depth-First Search (DFS) pre-order
6361  * traversal. It uses memcpy() to copy nodes in the source tree and allocate
6362  * new child nodes in non-leaf nodes. The new node is exactly the same as the
6363  * source node except for all the addresses stored in it. It will be faster than
6364  * traversing all elements in the source tree and inserting them one by one into
6365  * the new tree.
6366  * The user needs to ensure that the attributes of the source tree and the new
6367  * tree are the same, and the new tree needs to be an empty tree, otherwise
6368  * -EINVAL will be returned.
6369  *
6370  * Return: 0 on success, -ENOMEM if memory could not be allocated, -EINVAL If
6371  * the attributes of the two trees are different or the new tree is not an empty
6372  * tree.
6373  */
6374 int mtree_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp)
6375 {
6376 	int ret = 0;
6377 	MA_STATE(mas, mt, 0, 0);
6378 	MA_STATE(new_mas, new, 0, 0);
6379 
6380 	mas_lock(&new_mas);
6381 	mas_lock_nested(&mas, SINGLE_DEPTH_NESTING);
6382 	mas_dup_build(&mas, &new_mas, gfp);
6383 	mas_unlock(&mas);
6384 	if (unlikely(mas_is_err(&mas))) {
6385 		ret = xa_err(mas.node);
6386 		if (ret == -ENOMEM)
6387 			mas_dup_free(&new_mas);
6388 	}
6389 
6390 	mas_unlock(&new_mas);
6391 	return ret;
6392 }
6393 EXPORT_SYMBOL(mtree_dup);
6394 
6395 /**
6396  * __mt_destroy() - Walk and free all nodes of a locked maple tree.
6397  * @mt: The maple tree
6398  *
6399  * Note: Does not handle locking.
6400  */
6401 void __mt_destroy(struct maple_tree *mt)
6402 {
6403 	void *root = mt_root_locked(mt);
6404 
6405 	rcu_assign_pointer(mt->ma_root, NULL);
6406 	if (xa_is_node(root))
6407 		mte_destroy_walk(root, mt);
6408 
6409 	mt->ma_flags = mt_attr(mt);
6410 }
6411 EXPORT_SYMBOL_GPL(__mt_destroy);
6412 
6413 /**
6414  * mtree_destroy() - Destroy a maple tree
6415  * @mt: The maple tree
6416  *
6417  * Frees all resources used by the tree.  Handles locking.
6418  */
6419 void mtree_destroy(struct maple_tree *mt)
6420 {
6421 	mtree_lock(mt);
6422 	__mt_destroy(mt);
6423 	mtree_unlock(mt);
6424 }
6425 EXPORT_SYMBOL(mtree_destroy);
6426 
6427 /**
6428  * mt_find() - Search from the start up until an entry is found.
6429  * @mt: The maple tree
6430  * @index: Pointer which contains the start location of the search
6431  * @max: The maximum value of the search range
6432  *
6433  * Takes RCU read lock internally to protect the search, which does not
6434  * protect the returned pointer after dropping RCU read lock.
6435  * See also: Documentation/core-api/maple_tree.rst
6436  *
6437  * In case that an entry is found @index is updated to point to the next
6438  * possible entry independent whether the found entry is occupying a
6439  * single index or a range if indices.
6440  *
6441  * Return: The entry at or after the @index or %NULL
6442  */
6443 void *mt_find(struct maple_tree *mt, unsigned long *index, unsigned long max)
6444 {
6445 	MA_STATE(mas, mt, *index, *index);
6446 	void *entry;
6447 #ifdef CONFIG_DEBUG_MAPLE_TREE
6448 	unsigned long copy = *index;
6449 #endif
6450 
6451 	trace_ma_read(TP_FCT, &mas);
6452 
6453 	if ((*index) > max)
6454 		return NULL;
6455 
6456 	rcu_read_lock();
6457 retry:
6458 	entry = mas_state_walk(&mas);
6459 	if (mas_is_start(&mas))
6460 		goto retry;
6461 
6462 	if (unlikely(xa_is_zero(entry)))
6463 		entry = NULL;
6464 
6465 	if (entry)
6466 		goto unlock;
6467 
6468 	while (mas_is_active(&mas) && (mas.last < max)) {
6469 		entry = mas_next_slot(&mas, max, false);
6470 		if (likely(entry && !xa_is_zero(entry)))
6471 			break;
6472 	}
6473 
6474 	if (unlikely(xa_is_zero(entry)))
6475 		entry = NULL;
6476 unlock:
6477 	rcu_read_unlock();
6478 	if (likely(entry)) {
6479 		*index = mas.last + 1;
6480 #ifdef CONFIG_DEBUG_MAPLE_TREE
6481 		if (MT_WARN_ON(mt, (*index) && ((*index) <= copy)))
6482 			pr_err("index not increased! %lx <= %lx\n",
6483 			       *index, copy);
6484 #endif
6485 	}
6486 
6487 	return entry;
6488 }
6489 EXPORT_SYMBOL(mt_find);
6490 
6491 /**
6492  * mt_find_after() - Search from the start up until an entry is found.
6493  * @mt: The maple tree
6494  * @index: Pointer which contains the start location of the search
6495  * @max: The maximum value to check
6496  *
6497  * Same as mt_find() except that it checks @index for 0 before
6498  * searching. If @index == 0, the search is aborted. This covers a wrap
6499  * around of @index to 0 in an iterator loop.
6500  *
6501  * Return: The entry at or after the @index or %NULL
6502  */
6503 void *mt_find_after(struct maple_tree *mt, unsigned long *index,
6504 		    unsigned long max)
6505 {
6506 	if (!(*index))
6507 		return NULL;
6508 
6509 	return mt_find(mt, index, max);
6510 }
6511 EXPORT_SYMBOL(mt_find_after);
6512 
6513 #ifdef CONFIG_DEBUG_MAPLE_TREE
6514 atomic_t maple_tree_tests_run;
6515 EXPORT_SYMBOL_GPL(maple_tree_tests_run);
6516 atomic_t maple_tree_tests_passed;
6517 EXPORT_SYMBOL_GPL(maple_tree_tests_passed);
6518 
6519 #ifndef __KERNEL__
6520 extern void kmem_cache_set_non_kernel(struct kmem_cache *, unsigned int);
6521 void mt_set_non_kernel(unsigned int val)
6522 {
6523 	kmem_cache_set_non_kernel(maple_node_cache, val);
6524 }
6525 
6526 extern void kmem_cache_set_callback(struct kmem_cache *cachep,
6527 		void (*callback)(void *));
6528 void mt_set_callback(void (*callback)(void *))
6529 {
6530 	kmem_cache_set_callback(maple_node_cache, callback);
6531 }
6532 
6533 extern void kmem_cache_set_private(struct kmem_cache *cachep, void *private);
6534 void mt_set_private(void *private)
6535 {
6536 	kmem_cache_set_private(maple_node_cache, private);
6537 }
6538 
6539 extern unsigned long kmem_cache_get_alloc(struct kmem_cache *);
6540 unsigned long mt_get_alloc_size(void)
6541 {
6542 	return kmem_cache_get_alloc(maple_node_cache);
6543 }
6544 
6545 extern void kmem_cache_zero_nr_tallocated(struct kmem_cache *);
6546 void mt_zero_nr_tallocated(void)
6547 {
6548 	kmem_cache_zero_nr_tallocated(maple_node_cache);
6549 }
6550 
6551 extern unsigned int kmem_cache_nr_tallocated(struct kmem_cache *);
6552 unsigned int mt_nr_tallocated(void)
6553 {
6554 	return kmem_cache_nr_tallocated(maple_node_cache);
6555 }
6556 
6557 extern unsigned int kmem_cache_nr_allocated(struct kmem_cache *);
6558 unsigned int mt_nr_allocated(void)
6559 {
6560 	return kmem_cache_nr_allocated(maple_node_cache);
6561 }
6562 
6563 void mt_cache_shrink(void)
6564 {
6565 }
6566 #else
6567 /*
6568  * mt_cache_shrink() - For testing, don't use this.
6569  *
6570  * Certain testcases can trigger an OOM when combined with other memory
6571  * debugging configuration options.  This function is used to reduce the
6572  * possibility of an out of memory even due to kmem_cache objects remaining
6573  * around for longer than usual.
6574  */
6575 void mt_cache_shrink(void)
6576 {
6577 	kmem_cache_shrink(maple_node_cache);
6578 
6579 }
6580 EXPORT_SYMBOL_GPL(mt_cache_shrink);
6581 
6582 #endif /* not defined __KERNEL__ */
6583 /*
6584  * mas_get_slot() - Get the entry in the maple state node stored at @offset.
6585  * @mas: The maple state
6586  * @offset: The offset into the slot array to fetch.
6587  *
6588  * Return: The entry stored at @offset.
6589  */
6590 static inline struct maple_enode *mas_get_slot(struct ma_state *mas,
6591 		unsigned char offset)
6592 {
6593 	return mas_slot(mas, ma_slots(mas_mn(mas), mte_node_type(mas->node)),
6594 			offset);
6595 }
6596 
6597 /* Depth first search, post-order */
6598 static void mas_dfs_postorder(struct ma_state *mas, unsigned long max)
6599 {
6600 
6601 	struct maple_enode *p, *mn = mas->node;
6602 	unsigned long p_min, p_max;
6603 
6604 	mas_next_node(mas, mas_mn(mas), max);
6605 	if (!mas_is_overflow(mas))
6606 		return;
6607 
6608 	if (mte_is_root(mn))
6609 		return;
6610 
6611 	mas->node = mn;
6612 	mas_ascend(mas);
6613 	do {
6614 		p = mas->node;
6615 		p_min = mas->min;
6616 		p_max = mas->max;
6617 		mas_prev_node(mas, 0);
6618 	} while (!mas_is_underflow(mas));
6619 
6620 	mas->node = p;
6621 	mas->max = p_max;
6622 	mas->min = p_min;
6623 }
6624 
6625 /* Tree validations */
6626 static void mt_dump_node(const struct maple_tree *mt, void *entry,
6627 		unsigned long min, unsigned long max, unsigned int depth,
6628 		enum mt_dump_format format);
6629 static void mt_dump_range(unsigned long min, unsigned long max,
6630 			  unsigned int depth, enum mt_dump_format format)
6631 {
6632 	static const char spaces[] = "                                ";
6633 
6634 	switch (format) {
6635 	case mt_dump_hex:
6636 		if (min == max)
6637 			pr_info("%.*s%lx: ", depth * 2, spaces, min);
6638 		else
6639 			pr_info("%.*s%lx-%lx: ", depth * 2, spaces, min, max);
6640 		break;
6641 	case mt_dump_dec:
6642 		if (min == max)
6643 			pr_info("%.*s%lu: ", depth * 2, spaces, min);
6644 		else
6645 			pr_info("%.*s%lu-%lu: ", depth * 2, spaces, min, max);
6646 	}
6647 }
6648 
6649 static void mt_dump_entry(void *entry, unsigned long min, unsigned long max,
6650 			  unsigned int depth, enum mt_dump_format format)
6651 {
6652 	mt_dump_range(min, max, depth, format);
6653 
6654 	if (xa_is_value(entry))
6655 		pr_cont("value %ld (0x%lx) [" PTR_FMT "]\n", xa_to_value(entry),
6656 			xa_to_value(entry), entry);
6657 	else if (xa_is_zero(entry))
6658 		pr_cont("zero (%ld)\n", xa_to_internal(entry));
6659 	else if (mt_is_reserved(entry))
6660 		pr_cont("UNKNOWN ENTRY (" PTR_FMT ")\n", entry);
6661 	else
6662 		pr_cont(PTR_FMT "\n", entry);
6663 }
6664 
6665 static void mt_dump_range64(const struct maple_tree *mt, void *entry,
6666 		unsigned long min, unsigned long max, unsigned int depth,
6667 		enum mt_dump_format format)
6668 {
6669 	struct maple_range_64 *node = &mte_to_node(entry)->mr64;
6670 	bool leaf = mte_is_leaf(entry);
6671 	unsigned long first = min;
6672 	int i;
6673 
6674 	pr_cont(" contents: ");
6675 	for (i = 0; i < MAPLE_RANGE64_SLOTS - 1; i++) {
6676 		switch (format) {
6677 		case mt_dump_hex:
6678 			pr_cont(PTR_FMT " %lX ", node->slot[i], node->pivot[i]);
6679 			break;
6680 		case mt_dump_dec:
6681 			pr_cont(PTR_FMT " %lu ", node->slot[i], node->pivot[i]);
6682 		}
6683 	}
6684 	pr_cont(PTR_FMT "\n", node->slot[i]);
6685 	for (i = 0; i < MAPLE_RANGE64_SLOTS; i++) {
6686 		unsigned long last = max;
6687 
6688 		if (i < (MAPLE_RANGE64_SLOTS - 1))
6689 			last = node->pivot[i];
6690 		else if (!node->slot[i] && max != mt_node_max(entry))
6691 			break;
6692 		if (last == 0 && i > 0)
6693 			break;
6694 		if (leaf)
6695 			mt_dump_entry(mt_slot(mt, node->slot, i),
6696 					first, last, depth + 1, format);
6697 		else if (node->slot[i])
6698 			mt_dump_node(mt, mt_slot(mt, node->slot, i),
6699 					first, last, depth + 1, format);
6700 
6701 		if (last == max)
6702 			break;
6703 		if (last > max) {
6704 			switch (format) {
6705 			case mt_dump_hex:
6706 				pr_err("node " PTR_FMT " last (%lx) > max (%lx) at pivot %d!\n",
6707 					node, last, max, i);
6708 				break;
6709 			case mt_dump_dec:
6710 				pr_err("node " PTR_FMT " last (%lu) > max (%lu) at pivot %d!\n",
6711 					node, last, max, i);
6712 			}
6713 		}
6714 		first = last + 1;
6715 	}
6716 }
6717 
6718 static void mt_dump_arange64(const struct maple_tree *mt, void *entry,
6719 	unsigned long min, unsigned long max, unsigned int depth,
6720 	enum mt_dump_format format)
6721 {
6722 	struct maple_arange_64 *node = &mte_to_node(entry)->ma64;
6723 	unsigned long first = min;
6724 	int i;
6725 
6726 	pr_cont(" contents: ");
6727 	for (i = 0; i < MAPLE_ARANGE64_SLOTS; i++) {
6728 		switch (format) {
6729 		case mt_dump_hex:
6730 			pr_cont("%lx ", node->gap[i]);
6731 			break;
6732 		case mt_dump_dec:
6733 			pr_cont("%lu ", node->gap[i]);
6734 		}
6735 	}
6736 	pr_cont("| %02X %02X| ", node->meta.end, node->meta.gap);
6737 	for (i = 0; i < MAPLE_ARANGE64_SLOTS - 1; i++) {
6738 		switch (format) {
6739 		case mt_dump_hex:
6740 			pr_cont(PTR_FMT " %lX ", node->slot[i], node->pivot[i]);
6741 			break;
6742 		case mt_dump_dec:
6743 			pr_cont(PTR_FMT " %lu ", node->slot[i], node->pivot[i]);
6744 		}
6745 	}
6746 	pr_cont(PTR_FMT "\n", node->slot[i]);
6747 	for (i = 0; i < MAPLE_ARANGE64_SLOTS; i++) {
6748 		unsigned long last = max;
6749 
6750 		if (i < (MAPLE_ARANGE64_SLOTS - 1))
6751 			last = node->pivot[i];
6752 		else if (!node->slot[i])
6753 			break;
6754 		if (last == 0 && i > 0)
6755 			break;
6756 		if (node->slot[i])
6757 			mt_dump_node(mt, mt_slot(mt, node->slot, i),
6758 					first, last, depth + 1, format);
6759 
6760 		if (last == max)
6761 			break;
6762 		if (last > max) {
6763 			switch (format) {
6764 			case mt_dump_hex:
6765 				pr_err("node " PTR_FMT " last (%lx) > max (%lx) at pivot %d!\n",
6766 					node, last, max, i);
6767 				break;
6768 			case mt_dump_dec:
6769 				pr_err("node " PTR_FMT " last (%lu) > max (%lu) at pivot %d!\n",
6770 					node, last, max, i);
6771 			}
6772 		}
6773 		first = last + 1;
6774 	}
6775 }
6776 
6777 static void mt_dump_node(const struct maple_tree *mt, void *entry,
6778 		unsigned long min, unsigned long max, unsigned int depth,
6779 		enum mt_dump_format format)
6780 {
6781 	struct maple_node *node = mte_to_node(entry);
6782 	unsigned int type = mte_node_type(entry);
6783 	unsigned int i;
6784 
6785 	mt_dump_range(min, max, depth, format);
6786 
6787 	pr_cont("node " PTR_FMT " depth %d type %d parent " PTR_FMT, node,
6788 		depth, type, node ? node->parent : NULL);
6789 	switch (type) {
6790 	case maple_dense:
6791 		pr_cont("\n");
6792 		for (i = 0; i < MAPLE_NODE_SLOTS; i++) {
6793 			if (min + i > max)
6794 				pr_cont("OUT OF RANGE: ");
6795 			mt_dump_entry(mt_slot(mt, node->slot, i),
6796 					min + i, min + i, depth, format);
6797 		}
6798 		break;
6799 	case maple_leaf_64:
6800 	case maple_range_64:
6801 		mt_dump_range64(mt, entry, min, max, depth, format);
6802 		break;
6803 	case maple_arange_64:
6804 		mt_dump_arange64(mt, entry, min, max, depth, format);
6805 		break;
6806 
6807 	default:
6808 		pr_cont(" UNKNOWN TYPE\n");
6809 	}
6810 }
6811 
6812 void mt_dump(const struct maple_tree *mt, enum mt_dump_format format)
6813 {
6814 	void *entry = rcu_dereference_check(mt->ma_root, mt_locked(mt));
6815 
6816 	pr_info("maple_tree(" PTR_FMT ") flags %X, height %u root " PTR_FMT "\n",
6817 		 mt, mt->ma_flags, mt_height(mt), entry);
6818 	if (xa_is_node(entry))
6819 		mt_dump_node(mt, entry, 0, mt_node_max(entry), 0, format);
6820 	else if (entry)
6821 		mt_dump_entry(entry, 0, 0, 0, format);
6822 	else
6823 		pr_info("(empty)\n");
6824 }
6825 EXPORT_SYMBOL_GPL(mt_dump);
6826 
6827 /*
6828  * Calculate the maximum gap in a node and check if that's what is reported in
6829  * the parent (unless root).
6830  */
6831 static void mas_validate_gaps(struct ma_state *mas)
6832 {
6833 	struct maple_enode *mte = mas->node;
6834 	struct maple_node *p_mn, *node = mte_to_node(mte);
6835 	enum maple_type mt = mte_node_type(mas->node);
6836 	unsigned long gap = 0, max_gap = 0;
6837 	unsigned long p_end, p_start = mas->min;
6838 	unsigned char p_slot, offset;
6839 	unsigned long *gaps = NULL;
6840 	unsigned long *pivots = ma_pivots(node, mt);
6841 	unsigned int i;
6842 
6843 	if (ma_is_dense(mt)) {
6844 		for (i = 0; i < mt_slot_count(mte); i++) {
6845 			if (mas_get_slot(mas, i)) {
6846 				if (gap > max_gap)
6847 					max_gap = gap;
6848 				gap = 0;
6849 				continue;
6850 			}
6851 			gap++;
6852 		}
6853 		goto counted;
6854 	}
6855 
6856 	gaps = ma_gaps(node, mt);
6857 	for (i = 0; i < mt_slot_count(mte); i++) {
6858 		p_end = mas_safe_pivot(mas, pivots, i, mt);
6859 
6860 		if (!gaps) {
6861 			if (!mas_get_slot(mas, i))
6862 				gap = p_end - p_start + 1;
6863 		} else {
6864 			void *entry = mas_get_slot(mas, i);
6865 
6866 			gap = gaps[i];
6867 			MT_BUG_ON(mas->tree, !entry);
6868 
6869 			if (gap > p_end - p_start + 1) {
6870 				pr_err(PTR_FMT "[%u] %lu >= %lu - %lu + 1 (%lu)\n",
6871 				       mas_mn(mas), i, gap, p_end, p_start,
6872 				       p_end - p_start + 1);
6873 				MT_BUG_ON(mas->tree, gap > p_end - p_start + 1);
6874 			}
6875 		}
6876 
6877 		if (gap > max_gap)
6878 			max_gap = gap;
6879 
6880 		p_start = p_end + 1;
6881 		if (p_end >= mas->max)
6882 			break;
6883 	}
6884 
6885 counted:
6886 	if (mt == maple_arange_64) {
6887 		MT_BUG_ON(mas->tree, !gaps);
6888 		offset = ma_meta_gap(node);
6889 		if (offset > i) {
6890 			pr_err("gap offset " PTR_FMT "[%u] is invalid\n", node, offset);
6891 			MT_BUG_ON(mas->tree, 1);
6892 		}
6893 
6894 		if (gaps[offset] != max_gap) {
6895 			pr_err("gap " PTR_FMT "[%u] is not the largest gap %lu\n",
6896 			       node, offset, max_gap);
6897 			MT_BUG_ON(mas->tree, 1);
6898 		}
6899 
6900 		for (i++ ; i < mt_slot_count(mte); i++) {
6901 			if (gaps[i] != 0) {
6902 				pr_err("gap " PTR_FMT "[%u] beyond node limit != 0\n",
6903 				       node, i);
6904 				MT_BUG_ON(mas->tree, 1);
6905 			}
6906 		}
6907 	}
6908 
6909 	if (mte_is_root(mte))
6910 		return;
6911 
6912 	p_slot = mte_parent_slot(mas->node);
6913 	p_mn = mte_parent(mte);
6914 	MT_BUG_ON(mas->tree, max_gap > mas->max);
6915 	if (ma_gaps(p_mn, mas_parent_type(mas, mte))[p_slot] != max_gap) {
6916 		pr_err("gap " PTR_FMT "[%u] != %lu\n", p_mn, p_slot, max_gap);
6917 		mt_dump(mas->tree, mt_dump_hex);
6918 		MT_BUG_ON(mas->tree, 1);
6919 	}
6920 }
6921 
6922 static void mas_validate_parent_slot(struct ma_state *mas)
6923 {
6924 	struct maple_node *parent;
6925 	struct maple_enode *node;
6926 	enum maple_type p_type;
6927 	unsigned char p_slot;
6928 	void __rcu **slots;
6929 	int i;
6930 
6931 	if (mte_is_root(mas->node))
6932 		return;
6933 
6934 	p_slot = mte_parent_slot(mas->node);
6935 	p_type = mas_parent_type(mas, mas->node);
6936 	parent = mte_parent(mas->node);
6937 	slots = ma_slots(parent, p_type);
6938 	MT_BUG_ON(mas->tree, mas_mn(mas) == parent);
6939 
6940 	/* Check prev/next parent slot for duplicate node entry */
6941 
6942 	for (i = 0; i < mt_slots[p_type]; i++) {
6943 		node = mas_slot(mas, slots, i);
6944 		if (i == p_slot) {
6945 			if (node != mas->node)
6946 				pr_err("parent " PTR_FMT "[%u] does not have " PTR_FMT "\n",
6947 					parent, i, mas_mn(mas));
6948 			MT_BUG_ON(mas->tree, node != mas->node);
6949 		} else if (node == mas->node) {
6950 			pr_err("Invalid child " PTR_FMT " at parent " PTR_FMT "[%u] p_slot %u\n",
6951 			       mas_mn(mas), parent, i, p_slot);
6952 			MT_BUG_ON(mas->tree, node == mas->node);
6953 		}
6954 	}
6955 }
6956 
6957 static void mas_validate_child_slot(struct ma_state *mas)
6958 {
6959 	enum maple_type type = mte_node_type(mas->node);
6960 	void __rcu **slots = ma_slots(mte_to_node(mas->node), type);
6961 	unsigned long *pivots = ma_pivots(mte_to_node(mas->node), type);
6962 	struct maple_enode *child;
6963 	unsigned char i;
6964 
6965 	if (mte_is_leaf(mas->node))
6966 		return;
6967 
6968 	for (i = 0; i < mt_slots[type]; i++) {
6969 		child = mas_slot(mas, slots, i);
6970 
6971 		if (!child) {
6972 			pr_err("Non-leaf node lacks child at " PTR_FMT "[%u]\n",
6973 			       mas_mn(mas), i);
6974 			MT_BUG_ON(mas->tree, 1);
6975 		}
6976 
6977 		if (mte_parent_slot(child) != i) {
6978 			pr_err("Slot error at " PTR_FMT "[%u]: child " PTR_FMT " has pslot %u\n",
6979 			       mas_mn(mas), i, mte_to_node(child),
6980 			       mte_parent_slot(child));
6981 			MT_BUG_ON(mas->tree, 1);
6982 		}
6983 
6984 		if (mte_parent(child) != mte_to_node(mas->node)) {
6985 			pr_err("child " PTR_FMT " has parent " PTR_FMT " not " PTR_FMT "\n",
6986 			       mte_to_node(child), mte_parent(child),
6987 			       mte_to_node(mas->node));
6988 			MT_BUG_ON(mas->tree, 1);
6989 		}
6990 
6991 		if (i < mt_pivots[type] && pivots[i] == mas->max)
6992 			break;
6993 	}
6994 }
6995 
6996 /*
6997  * Validate all pivots are within mas->min and mas->max, check metadata ends
6998  * where the maximum ends and ensure there is no slots or pivots set outside of
6999  * the end of the data.
7000  */
7001 static void mas_validate_limits(struct ma_state *mas)
7002 {
7003 	int i;
7004 	unsigned long prev_piv = 0;
7005 	enum maple_type type = mte_node_type(mas->node);
7006 	void __rcu **slots = ma_slots(mte_to_node(mas->node), type);
7007 	unsigned long *pivots = ma_pivots(mas_mn(mas), type);
7008 
7009 	for (i = 0; i < mt_slots[type]; i++) {
7010 		unsigned long piv;
7011 
7012 		piv = mas_safe_pivot(mas, pivots, i, type);
7013 
7014 		if (!piv && (i != 0)) {
7015 			pr_err("Missing node limit pivot at " PTR_FMT "[%u]",
7016 			       mas_mn(mas), i);
7017 			MAS_WARN_ON(mas, 1);
7018 		}
7019 
7020 		if (prev_piv > piv) {
7021 			pr_err(PTR_FMT "[%u] piv %lu < prev_piv %lu\n",
7022 				mas_mn(mas), i, piv, prev_piv);
7023 			MAS_WARN_ON(mas, piv < prev_piv);
7024 		}
7025 
7026 		if (piv < mas->min) {
7027 			pr_err(PTR_FMT "[%u] %lu < %lu\n", mas_mn(mas), i,
7028 				piv, mas->min);
7029 			MAS_WARN_ON(mas, piv < mas->min);
7030 		}
7031 		if (piv > mas->max) {
7032 			pr_err(PTR_FMT "[%u] %lu > %lu\n", mas_mn(mas), i,
7033 				piv, mas->max);
7034 			MAS_WARN_ON(mas, piv > mas->max);
7035 		}
7036 		prev_piv = piv;
7037 		if (piv == mas->max)
7038 			break;
7039 	}
7040 
7041 	if (mas_data_end(mas) != i) {
7042 		pr_err("node" PTR_FMT ": data_end %u != the last slot offset %u\n",
7043 		       mas_mn(mas), mas_data_end(mas), i);
7044 		MT_BUG_ON(mas->tree, 1);
7045 	}
7046 
7047 	for (i += 1; i < mt_slots[type]; i++) {
7048 		void *entry = mas_slot(mas, slots, i);
7049 
7050 		if (entry && (i != mt_slots[type] - 1)) {
7051 			pr_err(PTR_FMT "[%u] should not have entry " PTR_FMT "\n",
7052 			       mas_mn(mas), i, entry);
7053 			MT_BUG_ON(mas->tree, entry != NULL);
7054 		}
7055 
7056 		if (i < mt_pivots[type]) {
7057 			unsigned long piv = pivots[i];
7058 
7059 			if (!piv)
7060 				continue;
7061 
7062 			pr_err(PTR_FMT "[%u] should not have piv %lu\n",
7063 			       mas_mn(mas), i, piv);
7064 			MAS_WARN_ON(mas, i < mt_pivots[type] - 1);
7065 		}
7066 	}
7067 }
7068 
7069 static void mt_validate_nulls(struct maple_tree *mt)
7070 {
7071 	void *entry, *last = (void *)1;
7072 	unsigned char offset = 0;
7073 	void __rcu **slots;
7074 	MA_STATE(mas, mt, 0, 0);
7075 
7076 	mas_start(&mas);
7077 	if (mas_is_none(&mas) || (mas_is_ptr(&mas)))
7078 		return;
7079 
7080 	while (!mte_is_leaf(mas.node))
7081 		mas_descend(&mas);
7082 
7083 	slots = ma_slots(mte_to_node(mas.node), mte_node_type(mas.node));
7084 	do {
7085 		entry = mas_slot(&mas, slots, offset);
7086 		if (!last && !entry) {
7087 			pr_err("Sequential nulls end at " PTR_FMT "[%u]\n",
7088 				mas_mn(&mas), offset);
7089 		}
7090 		MT_BUG_ON(mt, !last && !entry);
7091 		last = entry;
7092 		if (offset == mas_data_end(&mas)) {
7093 			mas_next_node(&mas, mas_mn(&mas), ULONG_MAX);
7094 			if (mas_is_overflow(&mas))
7095 				return;
7096 			offset = 0;
7097 			slots = ma_slots(mte_to_node(mas.node),
7098 					 mte_node_type(mas.node));
7099 		} else {
7100 			offset++;
7101 		}
7102 
7103 	} while (!mas_is_overflow(&mas));
7104 }
7105 
7106 /*
7107  * validate a maple tree by checking:
7108  * 1. The limits (pivots are within mas->min to mas->max)
7109  * 2. The gap is correctly set in the parents
7110  */
7111 void mt_validate(struct maple_tree *mt)
7112 	__must_hold(mas->tree->ma_lock)
7113 {
7114 	unsigned char end;
7115 
7116 	MA_STATE(mas, mt, 0, 0);
7117 	mas_start(&mas);
7118 	if (!mas_is_active(&mas))
7119 		return;
7120 
7121 	while (!mte_is_leaf(mas.node))
7122 		mas_descend(&mas);
7123 
7124 	while (!mas_is_overflow(&mas)) {
7125 		MAS_WARN_ON(&mas, mte_dead_node(mas.node));
7126 		end = mas_data_end(&mas);
7127 		if (MAS_WARN_ON(&mas, (end < mt_min_slot_count(mas.node)) &&
7128 				(!mte_is_root(mas.node)))) {
7129 			pr_err("Invalid size %u of " PTR_FMT "\n",
7130 			       end, mas_mn(&mas));
7131 		}
7132 
7133 		mas_validate_parent_slot(&mas);
7134 		mas_validate_limits(&mas);
7135 		mas_validate_child_slot(&mas);
7136 		if (mt_is_alloc(mt))
7137 			mas_validate_gaps(&mas);
7138 		mas_dfs_postorder(&mas, ULONG_MAX);
7139 	}
7140 	mt_validate_nulls(mt);
7141 }
7142 EXPORT_SYMBOL_GPL(mt_validate);
7143 
7144 void mas_dump(const struct ma_state *mas)
7145 {
7146 	pr_err("MAS: tree=" PTR_FMT " enode=" PTR_FMT " ",
7147 	       mas->tree, mas->node);
7148 	switch (mas->status) {
7149 	case ma_active:
7150 		pr_err("(ma_active)");
7151 		break;
7152 	case ma_none:
7153 		pr_err("(ma_none)");
7154 		break;
7155 	case ma_root:
7156 		pr_err("(ma_root)");
7157 		break;
7158 	case ma_start:
7159 		pr_err("(ma_start) ");
7160 		break;
7161 	case ma_pause:
7162 		pr_err("(ma_pause) ");
7163 		break;
7164 	case ma_overflow:
7165 		pr_err("(ma_overflow) ");
7166 		break;
7167 	case ma_underflow:
7168 		pr_err("(ma_underflow) ");
7169 		break;
7170 	case ma_error:
7171 		pr_err("(ma_error) ");
7172 		break;
7173 	}
7174 
7175 	pr_err("Store Type: ");
7176 	switch (mas->store_type) {
7177 	case wr_invalid:
7178 		pr_err("invalid store type\n");
7179 		break;
7180 	case wr_new_root:
7181 		pr_err("new_root\n");
7182 		break;
7183 	case wr_store_root:
7184 		pr_err("store_root\n");
7185 		break;
7186 	case wr_exact_fit:
7187 		pr_err("exact_fit\n");
7188 		break;
7189 	case wr_split_store:
7190 		pr_err("split_store\n");
7191 		break;
7192 	case wr_slot_store:
7193 		pr_err("slot_store\n");
7194 		break;
7195 	case wr_append:
7196 		pr_err("append\n");
7197 		break;
7198 	case wr_node_store:
7199 		pr_err("node_store\n");
7200 		break;
7201 	case wr_spanning_store:
7202 		pr_err("spanning_store\n");
7203 		break;
7204 	case wr_rebalance:
7205 		pr_err("rebalance\n");
7206 		break;
7207 	}
7208 
7209 	pr_err("[%u/%u] index=%lx last=%lx\n", mas->offset, mas->end,
7210 	       mas->index, mas->last);
7211 	pr_err("     min=%lx max=%lx sheaf=" PTR_FMT ", request %lu depth=%u, flags=%x\n",
7212 	       mas->min, mas->max, mas->sheaf, mas->node_request, mas->depth,
7213 	       mas->mas_flags);
7214 	if (mas->index > mas->last)
7215 		pr_err("Check index & last\n");
7216 }
7217 EXPORT_SYMBOL_GPL(mas_dump);
7218 
7219 void mas_wr_dump(const struct ma_wr_state *wr_mas)
7220 {
7221 	pr_err("WR_MAS: node=" PTR_FMT " r_min=%lx r_max=%lx\n",
7222 	       wr_mas->node, wr_mas->r_min, wr_mas->r_max);
7223 	pr_err("        type=%u off_end=%u, node_end=%u, end_piv=%lx\n",
7224 	       wr_mas->type, wr_mas->offset_end, wr_mas->mas->end,
7225 	       wr_mas->end_piv);
7226 }
7227 EXPORT_SYMBOL_GPL(mas_wr_dump);
7228 
7229 #endif /* CONFIG_DEBUG_MAPLE_TREE */
7230