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