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