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