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