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