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