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