xref: /freebsd/sys/contrib/openzfs/module/zfs/btree.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright (c) 2019 by Delphix. All rights reserved.
14  */
15 
16 #include	<sys/btree.h>
17 #include	<sys/bitops.h>
18 #include	<sys/zfs_context.h>
19 
20 #ifndef _KERNEL
21 #define	panic(...) PANIC(__VA_ARGS__)
22 #endif
23 
24 kmem_cache_t *zfs_btree_leaf_cache = NULL;
25 
26 /*
27  * Control the extent of the verification that occurs when zfs_btree_verify is
28  * called. Primarily used for debugging when extending the btree logic and
29  * functionality. As the intensity is increased, new verification steps are
30  * added. These steps are cumulative; intensity = 3 includes the intensity = 1
31  * and intensity = 2 steps as well.
32  *
33  * Intensity 1: Verify that the tree's height is consistent throughout.
34  * Intensity 2: Verify that a core node's children's parent pointers point
35  * to the core node.
36  * Intensity 3: Verify that the total number of elements in the tree matches the
37  * sum of the number of elements in each node. Also verifies that each node's
38  * count obeys the invariants (less than or equal to maximum value, greater than
39  * or equal to half the maximum minus one).
40  * Intensity 4: Verify that each element compares less than the element
41  * immediately after it and greater than the one immediately before it using the
42  * comparator function. For core nodes, also checks that each element is greater
43  * than the last element in the first of the two nodes it separates, and less
44  * than the first element in the second of the two nodes.
45  * Intensity 5: Verifies, if ZFS_DEBUG is defined, that all unused memory inside
46  * of each node is poisoned appropriately. Note that poisoning always occurs if
47  * ZFS_DEBUG is set, so it is safe to set the intensity to 5 during normal
48  * operation.
49  *
50  * Intensity 4 and 5 are particularly expensive to perform; the previous levels
51  * are a few memory operations per node, while these levels require multiple
52  * operations per element. In addition, when creating large btrees, these
53  * operations are called at every step, resulting in extremely slow operation
54  * (while the asymptotic complexity of the other steps is the same, the
55  * importance of the constant factors cannot be denied).
56  */
57 uint_t zfs_btree_verify_intensity = 0;
58 
59 /*
60  * Convenience functions to silence warnings from memcpy/memmove's
61  * return values and change argument order to src, dest.
62  */
63 static void
bcpy(const void * src,void * dest,size_t size)64 bcpy(const void *src, void *dest, size_t size)
65 {
66 	(void) memcpy(dest, src, size);
67 }
68 
69 static void
bmov(const void * src,void * dest,size_t size)70 bmov(const void *src, void *dest, size_t size)
71 {
72 	(void) memmove(dest, src, size);
73 }
74 
75 static boolean_t
zfs_btree_is_core(struct zfs_btree_hdr * hdr)76 zfs_btree_is_core(struct zfs_btree_hdr *hdr)
77 {
78 	return (hdr->bth_first == -1);
79 }
80 
81 #ifdef _ILP32
82 #define	BTREE_POISON 0xabadb10c
83 #else
84 #define	BTREE_POISON 0xabadb10cdeadbeef
85 #endif
86 
87 static void
zfs_btree_poison_node(zfs_btree_t * tree,zfs_btree_hdr_t * hdr)88 zfs_btree_poison_node(zfs_btree_t *tree, zfs_btree_hdr_t *hdr)
89 {
90 #ifdef ZFS_DEBUG
91 	size_t size = tree->bt_elem_size;
92 	if (zfs_btree_is_core(hdr)) {
93 		zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
94 		for (uint32_t i = hdr->bth_count + 1; i <= BTREE_CORE_ELEMS;
95 		    i++) {
96 			node->btc_children[i] =
97 			    (zfs_btree_hdr_t *)BTREE_POISON;
98 		}
99 		(void) memset(node->btc_elems + hdr->bth_count * size, 0x0f,
100 		    (BTREE_CORE_ELEMS - hdr->bth_count) * size);
101 	} else {
102 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)hdr;
103 		(void) memset(leaf->btl_elems, 0x0f, hdr->bth_first * size);
104 		(void) memset(leaf->btl_elems +
105 		    (hdr->bth_first + hdr->bth_count) * size, 0x0f,
106 		    tree->bt_leaf_size - offsetof(zfs_btree_leaf_t, btl_elems) -
107 		    (hdr->bth_first + hdr->bth_count) * size);
108 	}
109 #else
110 	(void) tree; (void) hdr;
111 #endif
112 }
113 
114 static inline void
zfs_btree_poison_node_at(zfs_btree_t * tree,zfs_btree_hdr_t * hdr,uint32_t idx,uint32_t count)115 zfs_btree_poison_node_at(zfs_btree_t *tree, zfs_btree_hdr_t *hdr,
116     uint32_t idx, uint32_t count)
117 {
118 #ifdef ZFS_DEBUG
119 	size_t size = tree->bt_elem_size;
120 	if (zfs_btree_is_core(hdr)) {
121 		ASSERT3U(idx, >=, hdr->bth_count);
122 		ASSERT3U(idx, <=, BTREE_CORE_ELEMS);
123 		ASSERT3U(idx + count, <=, BTREE_CORE_ELEMS);
124 		zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
125 		for (uint32_t i = 1; i <= count; i++) {
126 			node->btc_children[idx + i] =
127 			    (zfs_btree_hdr_t *)BTREE_POISON;
128 		}
129 		(void) memset(node->btc_elems + idx * size, 0x0f, count * size);
130 	} else {
131 		ASSERT3U(idx, <=, tree->bt_leaf_cap);
132 		ASSERT3U(idx + count, <=, tree->bt_leaf_cap);
133 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)hdr;
134 		(void) memset(leaf->btl_elems +
135 		    (hdr->bth_first + idx) * size, 0x0f, count * size);
136 	}
137 #else
138 	(void) tree; (void) hdr; (void) idx; (void) count;
139 #endif
140 }
141 
142 static inline void
zfs_btree_verify_poison_at(zfs_btree_t * tree,zfs_btree_hdr_t * hdr,uint32_t idx)143 zfs_btree_verify_poison_at(zfs_btree_t *tree, zfs_btree_hdr_t *hdr,
144     uint32_t idx)
145 {
146 #ifdef ZFS_DEBUG
147 	size_t size = tree->bt_elem_size;
148 	if (zfs_btree_is_core(hdr)) {
149 		ASSERT3U(idx, <, BTREE_CORE_ELEMS);
150 		zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
151 		zfs_btree_hdr_t *cval = (zfs_btree_hdr_t *)BTREE_POISON;
152 		VERIFY3P(node->btc_children[idx + 1], ==, cval);
153 		for (size_t i = 0; i < size; i++)
154 			VERIFY3U(node->btc_elems[idx * size + i], ==, 0x0f);
155 	} else  {
156 		ASSERT3U(idx, <, tree->bt_leaf_cap);
157 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)hdr;
158 		if (idx >= tree->bt_leaf_cap - hdr->bth_first)
159 			return;
160 		for (size_t i = 0; i < size; i++) {
161 			VERIFY3U(leaf->btl_elems[(hdr->bth_first + idx)
162 			    * size + i], ==, 0x0f);
163 		}
164 	}
165 #else
166 	(void) tree; (void) hdr; (void) idx;
167 #endif
168 }
169 
170 void
zfs_btree_init(void)171 zfs_btree_init(void)
172 {
173 	zfs_btree_leaf_cache = kmem_cache_create("zfs_btree_leaf_cache",
174 	    BTREE_LEAF_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);
175 }
176 
177 void
zfs_btree_fini(void)178 zfs_btree_fini(void)
179 {
180 	kmem_cache_destroy(zfs_btree_leaf_cache);
181 }
182 
183 static void *
zfs_btree_leaf_alloc(zfs_btree_t * tree)184 zfs_btree_leaf_alloc(zfs_btree_t *tree)
185 {
186 	if (tree->bt_leaf_size == BTREE_LEAF_SIZE)
187 		return (kmem_cache_alloc(zfs_btree_leaf_cache, KM_SLEEP));
188 	else
189 		return (kmem_alloc(tree->bt_leaf_size, KM_SLEEP));
190 }
191 
192 static void
zfs_btree_leaf_free(zfs_btree_t * tree,void * ptr)193 zfs_btree_leaf_free(zfs_btree_t *tree, void *ptr)
194 {
195 	if (tree->bt_leaf_size == BTREE_LEAF_SIZE)
196 		return (kmem_cache_free(zfs_btree_leaf_cache, ptr));
197 	else
198 		return (kmem_free(ptr, tree->bt_leaf_size));
199 }
200 
201 void
zfs_btree_create(zfs_btree_t * tree,int (* compar)(const void *,const void *),bt_find_in_buf_f bt_find_in_buf,size_t size)202 zfs_btree_create(zfs_btree_t *tree, int (*compar) (const void *, const void *),
203     bt_find_in_buf_f bt_find_in_buf, size_t size)
204 {
205 	/* Verify zfs_btree_init() was called before zfs_btree_create() */
206 	ASSERT(zfs_btree_leaf_cache != NULL);
207 
208 	zfs_btree_create_custom(tree, compar, bt_find_in_buf, size,
209 	    BTREE_LEAF_SIZE);
210 }
211 
212 static void *
213 zfs_btree_find_in_buf(zfs_btree_t *tree, uint8_t *buf, uint32_t nelems,
214     const void *value, zfs_btree_index_t *where);
215 
216 void
zfs_btree_create_custom(zfs_btree_t * tree,int (* compar)(const void *,const void *),bt_find_in_buf_f bt_find_in_buf,size_t size,size_t lsize)217 zfs_btree_create_custom(zfs_btree_t *tree,
218     int (*compar) (const void *, const void *),
219     bt_find_in_buf_f bt_find_in_buf,
220     size_t size, size_t lsize)
221 {
222 	size_t esize = lsize - offsetof(zfs_btree_leaf_t, btl_elems);
223 
224 	ASSERT3U(size, <=, esize / 2);
225 	memset(tree, 0, sizeof (*tree));
226 	tree->bt_compar = compar;
227 	tree->bt_find_in_buf = (bt_find_in_buf == NULL) ?
228 	    zfs_btree_find_in_buf : bt_find_in_buf;
229 	tree->bt_elem_size = size;
230 	tree->bt_leaf_size = lsize;
231 	tree->bt_leaf_cap = P2ALIGN_TYPED(esize / size, 2, size_t);
232 	tree->bt_height = -1;
233 	tree->bt_bulk = NULL;
234 }
235 
236 /*
237  * Find value in the array of elements provided. Uses a simple binary search.
238  */
239 static void *
zfs_btree_find_in_buf(zfs_btree_t * tree,uint8_t * buf,uint32_t nelems,const void * value,zfs_btree_index_t * where)240 zfs_btree_find_in_buf(zfs_btree_t *tree, uint8_t *buf, uint32_t nelems,
241     const void *value, zfs_btree_index_t *where)
242 {
243 	uint32_t max = nelems;
244 	uint32_t min = 0;
245 	while (max > min) {
246 		uint32_t idx = (min + max) / 2;
247 		uint8_t *cur = buf + idx * tree->bt_elem_size;
248 		int comp = tree->bt_compar(cur, value);
249 		if (comp < 0) {
250 			min = idx + 1;
251 		} else if (comp > 0) {
252 			max = idx;
253 		} else {
254 			where->bti_offset = idx;
255 			where->bti_before = B_FALSE;
256 			return (cur);
257 		}
258 	}
259 
260 	where->bti_offset = max;
261 	where->bti_before = B_TRUE;
262 	return (NULL);
263 }
264 
265 /*
266  * Find the given value in the tree. where may be passed as null to use as a
267  * membership test or if the btree is being used as a map.
268  */
269 void *
zfs_btree_find(zfs_btree_t * tree,const void * value,zfs_btree_index_t * where)270 zfs_btree_find(zfs_btree_t *tree, const void *value, zfs_btree_index_t *where)
271 {
272 	if (tree->bt_height == -1) {
273 		if (where != NULL) {
274 			where->bti_node = NULL;
275 			where->bti_offset = 0;
276 		}
277 		ASSERT0(tree->bt_num_elems);
278 		return (NULL);
279 	}
280 
281 	/*
282 	 * If we're in bulk-insert mode, we check the last spot in the tree
283 	 * and the last leaf in the tree before doing the normal search,
284 	 * because for most workloads the vast majority of finds in
285 	 * bulk-insert mode are to insert new elements.
286 	 */
287 	zfs_btree_index_t idx;
288 	size_t size = tree->bt_elem_size;
289 	if (tree->bt_bulk != NULL) {
290 		zfs_btree_leaf_t *last_leaf = tree->bt_bulk;
291 		int comp = tree->bt_compar(last_leaf->btl_elems +
292 		    (last_leaf->btl_hdr.bth_first +
293 		    last_leaf->btl_hdr.bth_count - 1) * size, value);
294 		if (comp < 0) {
295 			/*
296 			 * If what they're looking for is after the last
297 			 * element, it's not in the tree.
298 			 */
299 			if (where != NULL) {
300 				where->bti_node = (zfs_btree_hdr_t *)last_leaf;
301 				where->bti_offset =
302 				    last_leaf->btl_hdr.bth_count;
303 				where->bti_before = B_TRUE;
304 			}
305 			return (NULL);
306 		} else if (comp == 0) {
307 			if (where != NULL) {
308 				where->bti_node = (zfs_btree_hdr_t *)last_leaf;
309 				where->bti_offset =
310 				    last_leaf->btl_hdr.bth_count - 1;
311 				where->bti_before = B_FALSE;
312 			}
313 			return (last_leaf->btl_elems +
314 			    (last_leaf->btl_hdr.bth_first +
315 			    last_leaf->btl_hdr.bth_count - 1) * size);
316 		}
317 		if (tree->bt_compar(last_leaf->btl_elems +
318 		    last_leaf->btl_hdr.bth_first * size, value) <= 0) {
319 			/*
320 			 * If what they're looking for is after the first
321 			 * element in the last leaf, it's in the last leaf or
322 			 * it's not in the tree.
323 			 */
324 			void *d = tree->bt_find_in_buf(tree,
325 			    last_leaf->btl_elems +
326 			    last_leaf->btl_hdr.bth_first * size,
327 			    last_leaf->btl_hdr.bth_count, value, &idx);
328 
329 			if (where != NULL) {
330 				idx.bti_node = (zfs_btree_hdr_t *)last_leaf;
331 				*where = idx;
332 			}
333 			return (d);
334 		}
335 	}
336 
337 	zfs_btree_core_t *node = NULL;
338 	uint32_t child = 0;
339 	uint32_t depth = 0;
340 
341 	/*
342 	 * Iterate down the tree, finding which child the value should be in
343 	 * by comparing with the separators.
344 	 */
345 	for (node = (zfs_btree_core_t *)tree->bt_root; depth < tree->bt_height;
346 	    node = (zfs_btree_core_t *)node->btc_children[child], depth++) {
347 		ASSERT3P(node, !=, NULL);
348 		void *d = tree->bt_find_in_buf(tree, node->btc_elems,
349 		    node->btc_hdr.bth_count, value, &idx);
350 		EQUIV(d != NULL, !idx.bti_before);
351 		if (d != NULL) {
352 			if (where != NULL) {
353 				idx.bti_node = (zfs_btree_hdr_t *)node;
354 				*where = idx;
355 			}
356 			return (d);
357 		}
358 		ASSERT(idx.bti_before);
359 		child = idx.bti_offset;
360 	}
361 
362 	/*
363 	 * The value is in this leaf, or it would be if it were in the
364 	 * tree. Find its proper location and return it.
365 	 */
366 	zfs_btree_leaf_t *leaf = (depth == 0 ?
367 	    (zfs_btree_leaf_t *)tree->bt_root : (zfs_btree_leaf_t *)node);
368 	void *d = tree->bt_find_in_buf(tree, leaf->btl_elems +
369 	    leaf->btl_hdr.bth_first * size,
370 	    leaf->btl_hdr.bth_count, value, &idx);
371 
372 	if (where != NULL) {
373 		idx.bti_node = (zfs_btree_hdr_t *)leaf;
374 		*where = idx;
375 	}
376 
377 	return (d);
378 }
379 
380 /*
381  * To explain the following functions, it is useful to understand the four
382  * kinds of shifts used in btree operation. First, a shift is a movement of
383  * elements within a node. It is used to create gaps for inserting new
384  * elements and children, or cover gaps created when things are removed. A
385  * shift has two fundamental properties, each of which can be one of two
386  * values, making four types of shifts.  There is the direction of the shift
387  * (left or right) and the shape of the shift (parallelogram or isoceles
388  * trapezoid (shortened to trapezoid hereafter)). The shape distinction only
389  * applies to shifts of core nodes.
390  *
391  * The names derive from the following imagining of the layout of a node:
392  *
393  *  Elements:       *   *   *   *   *   *   *   ...   *   *   *
394  *  Children:     *   *   *   *   *   *   *   *   ...   *   *   *
395  *
396  * This layout follows from the fact that the elements act as separators
397  * between pairs of children, and that children root subtrees "below" the
398  * current node. A left and right shift are fairly self-explanatory; a left
399  * shift moves things to the left, while a right shift moves things to the
400  * right. A parallelogram shift is a shift with the same number of elements
401  * and children being moved, while a trapezoid shift is a shift that moves one
402  * more children than elements. An example follows:
403  *
404  * A parallelogram shift could contain the following:
405  *      _______________
406  *      \*   *   *   * \ *   *   *   ...   *   *   *
407  *     * \ *   *   *   *\  *   *   *   ...   *   *   *
408  *        ---------------
409  * A trapezoid shift could contain the following:
410  *          ___________
411  *       * / *   *   * \ *   *   *   ...   *   *   *
412  *     *  / *  *   *   *\  *   *   *   ...   *   *   *
413  *        ---------------
414  *
415  * Note that a parallelogram shift is always shaped like a "left-leaning"
416  * parallelogram, where the starting index of the children being moved is
417  * always one higher than the starting index of the elements being moved. No
418  * "right-leaning" parallelogram shifts are needed (shifts where the starting
419  * element index and starting child index being moved are the same) to achieve
420  * any btree operations, so we ignore them.
421  */
422 
423 enum bt_shift_shape {
424 	BSS_TRAPEZOID,
425 	BSS_PARALLELOGRAM
426 };
427 
428 enum bt_shift_direction {
429 	BSD_LEFT,
430 	BSD_RIGHT
431 };
432 
433 /*
434  * Shift elements and children in the provided core node by off spots.  The
435  * first element moved is idx, and count elements are moved. The shape of the
436  * shift is determined by shape. The direction is determined by dir.
437  */
438 static inline void
bt_shift_core(zfs_btree_t * tree,zfs_btree_core_t * node,uint32_t idx,uint32_t count,uint32_t off,enum bt_shift_shape shape,enum bt_shift_direction dir)439 bt_shift_core(zfs_btree_t *tree, zfs_btree_core_t *node, uint32_t idx,
440     uint32_t count, uint32_t off, enum bt_shift_shape shape,
441     enum bt_shift_direction dir)
442 {
443 	size_t size = tree->bt_elem_size;
444 	ASSERT(zfs_btree_is_core(&node->btc_hdr));
445 
446 	uint8_t *e_start = node->btc_elems + idx * size;
447 	uint8_t *e_out = (dir == BSD_LEFT ? e_start - off * size :
448 	    e_start + off * size);
449 	bmov(e_start, e_out, count * size);
450 
451 	zfs_btree_hdr_t **c_start = node->btc_children + idx +
452 	    (shape == BSS_TRAPEZOID ? 0 : 1);
453 	zfs_btree_hdr_t **c_out = (dir == BSD_LEFT ? c_start - off :
454 	    c_start + off);
455 	uint32_t c_count = count + (shape == BSS_TRAPEZOID ? 1 : 0);
456 	bmov(c_start, c_out, c_count * sizeof (*c_start));
457 }
458 
459 /*
460  * Shift elements and children in the provided core node left by one spot.
461  * The first element moved is idx, and count elements are moved. The
462  * shape of the shift is determined by trap; true if the shift is a trapezoid,
463  * false if it is a parallelogram.
464  */
465 static inline void
bt_shift_core_left(zfs_btree_t * tree,zfs_btree_core_t * node,uint32_t idx,uint32_t count,enum bt_shift_shape shape)466 bt_shift_core_left(zfs_btree_t *tree, zfs_btree_core_t *node, uint32_t idx,
467     uint32_t count, enum bt_shift_shape shape)
468 {
469 	bt_shift_core(tree, node, idx, count, 1, shape, BSD_LEFT);
470 }
471 
472 /*
473  * Shift elements and children in the provided core node right by one spot.
474  * Starts with elements[idx] and children[idx] and one more child than element.
475  */
476 static inline void
bt_shift_core_right(zfs_btree_t * tree,zfs_btree_core_t * node,uint32_t idx,uint32_t count,enum bt_shift_shape shape)477 bt_shift_core_right(zfs_btree_t *tree, zfs_btree_core_t *node, uint32_t idx,
478     uint32_t count, enum bt_shift_shape shape)
479 {
480 	bt_shift_core(tree, node, idx, count, 1, shape, BSD_RIGHT);
481 }
482 
483 /*
484  * Shift elements and children in the provided leaf node by off spots.
485  * The first element moved is idx, and count elements are moved. The direction
486  * is determined by left.
487  */
488 static inline void
bt_shift_leaf(zfs_btree_t * tree,zfs_btree_leaf_t * node,uint32_t idx,uint32_t count,uint32_t off,enum bt_shift_direction dir)489 bt_shift_leaf(zfs_btree_t *tree, zfs_btree_leaf_t *node, uint32_t idx,
490     uint32_t count, uint32_t off, enum bt_shift_direction dir)
491 {
492 	size_t size = tree->bt_elem_size;
493 	zfs_btree_hdr_t *hdr = &node->btl_hdr;
494 	ASSERT(!zfs_btree_is_core(hdr));
495 
496 	if (count == 0)
497 		return;
498 	uint8_t *start = node->btl_elems + (hdr->bth_first + idx) * size;
499 	uint8_t *out = (dir == BSD_LEFT ? start - off * size :
500 	    start + off * size);
501 	bmov(start, out, count * size);
502 }
503 
504 /*
505  * Grow leaf for n new elements before idx.
506  */
507 static void
bt_grow_leaf(zfs_btree_t * tree,zfs_btree_leaf_t * leaf,uint32_t idx,uint32_t n)508 bt_grow_leaf(zfs_btree_t *tree, zfs_btree_leaf_t *leaf, uint32_t idx,
509     uint32_t n)
510 {
511 	zfs_btree_hdr_t *hdr = &leaf->btl_hdr;
512 	ASSERT(!zfs_btree_is_core(hdr));
513 	ASSERT3U(idx, <=, hdr->bth_count);
514 	uint32_t capacity = tree->bt_leaf_cap;
515 	ASSERT3U(hdr->bth_count + n, <=, capacity);
516 	boolean_t cl = (hdr->bth_first >= n);
517 	boolean_t cr = (hdr->bth_first + hdr->bth_count + n <= capacity);
518 
519 	if (cl && (!cr || idx <= hdr->bth_count / 2)) {
520 		/* Grow left. */
521 		hdr->bth_first -= n;
522 		bt_shift_leaf(tree, leaf, n, idx, n, BSD_LEFT);
523 	} else if (cr) {
524 		/* Grow right. */
525 		bt_shift_leaf(tree, leaf, idx, hdr->bth_count - idx, n,
526 		    BSD_RIGHT);
527 	} else {
528 		/* Grow both ways. */
529 		uint32_t fn = hdr->bth_first -
530 		    (capacity - (hdr->bth_count + n)) / 2;
531 		hdr->bth_first -= fn;
532 		bt_shift_leaf(tree, leaf, fn, idx, fn, BSD_LEFT);
533 		bt_shift_leaf(tree, leaf, fn + idx, hdr->bth_count - idx,
534 		    n - fn, BSD_RIGHT);
535 	}
536 	hdr->bth_count += n;
537 }
538 
539 /*
540  * Shrink leaf for count elements starting from idx.
541  */
542 static void
bt_shrink_leaf(zfs_btree_t * tree,zfs_btree_leaf_t * leaf,uint32_t idx,uint32_t n)543 bt_shrink_leaf(zfs_btree_t *tree, zfs_btree_leaf_t *leaf, uint32_t idx,
544     uint32_t n)
545 {
546 	zfs_btree_hdr_t *hdr = &leaf->btl_hdr;
547 	ASSERT(!zfs_btree_is_core(hdr));
548 	ASSERT3U(idx, <=, hdr->bth_count);
549 	ASSERT3U(idx + n, <=, hdr->bth_count);
550 
551 	if (idx <= (hdr->bth_count - n) / 2) {
552 		bt_shift_leaf(tree, leaf, 0, idx, n, BSD_RIGHT);
553 		zfs_btree_poison_node_at(tree, hdr, 0, n);
554 		hdr->bth_first += n;
555 	} else {
556 		bt_shift_leaf(tree, leaf, idx + n, hdr->bth_count - idx - n, n,
557 		    BSD_LEFT);
558 		zfs_btree_poison_node_at(tree, hdr, hdr->bth_count - n, n);
559 	}
560 	hdr->bth_count -= n;
561 }
562 
563 /*
564  * Move children and elements from one core node to another. The shape
565  * parameter behaves the same as it does in the shift logic.
566  */
567 static inline void
bt_transfer_core(zfs_btree_t * tree,zfs_btree_core_t * source,uint32_t sidx,uint32_t count,zfs_btree_core_t * dest,uint32_t didx,enum bt_shift_shape shape)568 bt_transfer_core(zfs_btree_t *tree, zfs_btree_core_t *source, uint32_t sidx,
569     uint32_t count, zfs_btree_core_t *dest, uint32_t didx,
570     enum bt_shift_shape shape)
571 {
572 	size_t size = tree->bt_elem_size;
573 	ASSERT(zfs_btree_is_core(&source->btc_hdr));
574 	ASSERT(zfs_btree_is_core(&dest->btc_hdr));
575 
576 	bcpy(source->btc_elems + sidx * size, dest->btc_elems + didx * size,
577 	    count * size);
578 
579 	uint32_t c_count = count + (shape == BSS_TRAPEZOID ? 1 : 0);
580 	bcpy(source->btc_children + sidx + (shape == BSS_TRAPEZOID ? 0 : 1),
581 	    dest->btc_children + didx + (shape == BSS_TRAPEZOID ? 0 : 1),
582 	    c_count * sizeof (*source->btc_children));
583 }
584 
585 static inline void
bt_transfer_leaf(zfs_btree_t * tree,zfs_btree_leaf_t * source,uint32_t sidx,uint32_t count,zfs_btree_leaf_t * dest,uint32_t didx)586 bt_transfer_leaf(zfs_btree_t *tree, zfs_btree_leaf_t *source, uint32_t sidx,
587     uint32_t count, zfs_btree_leaf_t *dest, uint32_t didx)
588 {
589 	size_t size = tree->bt_elem_size;
590 	ASSERT(!zfs_btree_is_core(&source->btl_hdr));
591 	ASSERT(!zfs_btree_is_core(&dest->btl_hdr));
592 
593 	bcpy(source->btl_elems + (source->btl_hdr.bth_first + sidx) * size,
594 	    dest->btl_elems + (dest->btl_hdr.bth_first + didx) * size,
595 	    count * size);
596 }
597 
598 /*
599  * Find the first element in the subtree rooted at hdr, return its value and
600  * put its location in where if non-null.
601  */
602 static void *
zfs_btree_first_helper(zfs_btree_t * tree,zfs_btree_hdr_t * hdr,zfs_btree_index_t * where)603 zfs_btree_first_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr,
604     zfs_btree_index_t *where)
605 {
606 	zfs_btree_hdr_t *node;
607 
608 	for (node = hdr; zfs_btree_is_core(node);
609 	    node = ((zfs_btree_core_t *)node)->btc_children[0])
610 		;
611 
612 	ASSERT(!zfs_btree_is_core(node));
613 	zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)node;
614 	if (where != NULL) {
615 		where->bti_node = node;
616 		where->bti_offset = 0;
617 		where->bti_before = B_FALSE;
618 	}
619 	return (&leaf->btl_elems[node->bth_first * tree->bt_elem_size]);
620 }
621 
622 /* Insert an element and a child into a core node at the given offset. */
623 static void
zfs_btree_insert_core_impl(zfs_btree_t * tree,zfs_btree_core_t * parent,uint32_t offset,zfs_btree_hdr_t * new_node,void * buf)624 zfs_btree_insert_core_impl(zfs_btree_t *tree, zfs_btree_core_t *parent,
625     uint32_t offset, zfs_btree_hdr_t *new_node, void *buf)
626 {
627 	size_t size = tree->bt_elem_size;
628 	zfs_btree_hdr_t *par_hdr = &parent->btc_hdr;
629 	ASSERT3P(par_hdr, ==, new_node->bth_parent);
630 	ASSERT3U(par_hdr->bth_count, <, BTREE_CORE_ELEMS);
631 
632 	if (zfs_btree_verify_intensity >= 5) {
633 		zfs_btree_verify_poison_at(tree, par_hdr,
634 		    par_hdr->bth_count);
635 	}
636 	/* Shift existing elements and children */
637 	uint32_t count = par_hdr->bth_count - offset;
638 	bt_shift_core_right(tree, parent, offset, count,
639 	    BSS_PARALLELOGRAM);
640 
641 	/* Insert new values */
642 	parent->btc_children[offset + 1] = new_node;
643 	bcpy(buf, parent->btc_elems + offset * size, size);
644 	par_hdr->bth_count++;
645 }
646 
647 /*
648  * Insert new_node into the parent of old_node directly after old_node, with
649  * buf as the dividing element between the two.
650  */
651 static void
zfs_btree_insert_into_parent(zfs_btree_t * tree,zfs_btree_hdr_t * old_node,zfs_btree_hdr_t * new_node,void * buf)652 zfs_btree_insert_into_parent(zfs_btree_t *tree, zfs_btree_hdr_t *old_node,
653     zfs_btree_hdr_t *new_node, void *buf)
654 {
655 	ASSERT3P(old_node->bth_parent, ==, new_node->bth_parent);
656 	size_t size = tree->bt_elem_size;
657 	zfs_btree_core_t *parent = old_node->bth_parent;
658 
659 	/*
660 	 * If this is the root node we were splitting, we create a new root
661 	 * and increase the height of the tree.
662 	 */
663 	if (parent == NULL) {
664 		ASSERT3P(old_node, ==, tree->bt_root);
665 		tree->bt_num_nodes++;
666 		zfs_btree_core_t *new_root =
667 		    kmem_alloc(sizeof (zfs_btree_core_t) + BTREE_CORE_ELEMS *
668 		    size, KM_SLEEP);
669 		zfs_btree_hdr_t *new_root_hdr = &new_root->btc_hdr;
670 		new_root_hdr->bth_parent = NULL;
671 		new_root_hdr->bth_first = -1;
672 		new_root_hdr->bth_count = 1;
673 
674 		old_node->bth_parent = new_node->bth_parent = new_root;
675 		new_root->btc_children[0] = old_node;
676 		new_root->btc_children[1] = new_node;
677 		bcpy(buf, new_root->btc_elems, size);
678 
679 		tree->bt_height++;
680 		tree->bt_root = new_root_hdr;
681 		zfs_btree_poison_node(tree, new_root_hdr);
682 		return;
683 	}
684 
685 	/*
686 	 * Since we have the new separator, binary search for where to put
687 	 * new_node.
688 	 */
689 	zfs_btree_hdr_t *par_hdr = &parent->btc_hdr;
690 	zfs_btree_index_t idx;
691 	ASSERT(zfs_btree_is_core(par_hdr));
692 	VERIFY3P(tree->bt_find_in_buf(tree, parent->btc_elems,
693 	    par_hdr->bth_count, buf, &idx), ==, NULL);
694 	ASSERT(idx.bti_before);
695 	uint32_t offset = idx.bti_offset;
696 	ASSERT3U(offset, <=, par_hdr->bth_count);
697 	ASSERT3P(parent->btc_children[offset], ==, old_node);
698 
699 	/*
700 	 * If the parent isn't full, shift things to accommodate our insertions
701 	 * and return.
702 	 */
703 	if (par_hdr->bth_count != BTREE_CORE_ELEMS) {
704 		zfs_btree_insert_core_impl(tree, parent, offset, new_node, buf);
705 		return;
706 	}
707 
708 	/*
709 	 * We need to split this core node into two. Currently there are
710 	 * BTREE_CORE_ELEMS + 1 child nodes, and we are adding one for
711 	 * BTREE_CORE_ELEMS + 2. Some of the children will be part of the
712 	 * current node, and the others will be moved to the new core node.
713 	 * There are BTREE_CORE_ELEMS + 1 elements including the new one. One
714 	 * will be used as the new separator in our parent, and the others
715 	 * will be split among the two core nodes.
716 	 *
717 	 * Usually we will split the node in half evenly, with
718 	 * BTREE_CORE_ELEMS/2 elements in each node. If we're bulk loading, we
719 	 * instead move only about a quarter of the elements (and children) to
720 	 * the new node. Since the average state after a long time is a 3/4
721 	 * full node, shortcutting directly to that state improves efficiency.
722 	 *
723 	 * We do this in two stages: first we split into two nodes, and then we
724 	 * reuse our existing logic to insert the new element and child.
725 	 */
726 	uint32_t move_count = MAX((BTREE_CORE_ELEMS / (tree->bt_bulk == NULL ?
727 	    2 : 4)) - 1, 2);
728 	uint32_t keep_count = BTREE_CORE_ELEMS - move_count - 1;
729 	ASSERT3U(BTREE_CORE_ELEMS - move_count, >=, 2);
730 	tree->bt_num_nodes++;
731 	zfs_btree_core_t *new_parent = kmem_alloc(sizeof (zfs_btree_core_t) +
732 	    BTREE_CORE_ELEMS * size, KM_SLEEP);
733 	zfs_btree_hdr_t *new_par_hdr = &new_parent->btc_hdr;
734 	new_par_hdr->bth_parent = par_hdr->bth_parent;
735 	new_par_hdr->bth_first = -1;
736 	new_par_hdr->bth_count = move_count;
737 	zfs_btree_poison_node(tree, new_par_hdr);
738 
739 	par_hdr->bth_count = keep_count;
740 
741 	bt_transfer_core(tree, parent, keep_count + 1, move_count, new_parent,
742 	    0, BSS_TRAPEZOID);
743 
744 	/* Store the new separator in a buffer. */
745 	uint8_t *tmp_buf = kmem_alloc(size, KM_SLEEP);
746 	bcpy(parent->btc_elems + keep_count * size, tmp_buf,
747 	    size);
748 	zfs_btree_poison_node(tree, par_hdr);
749 
750 	if (offset < keep_count) {
751 		/* Insert the new node into the left half */
752 		zfs_btree_insert_core_impl(tree, parent, offset, new_node,
753 		    buf);
754 
755 		/*
756 		 * Move the new separator to the existing buffer.
757 		 */
758 		bcpy(tmp_buf, buf, size);
759 	} else if (offset > keep_count) {
760 		/* Insert the new node into the right half */
761 		new_node->bth_parent = new_parent;
762 		zfs_btree_insert_core_impl(tree, new_parent,
763 		    offset - keep_count - 1, new_node, buf);
764 
765 		/*
766 		 * Move the new separator to the existing buffer.
767 		 */
768 		bcpy(tmp_buf, buf, size);
769 	} else {
770 		/*
771 		 * Move the new separator into the right half, and replace it
772 		 * with buf. We also need to shift back the elements in the
773 		 * right half to accommodate new_node.
774 		 */
775 		bt_shift_core_right(tree, new_parent, 0, move_count,
776 		    BSS_TRAPEZOID);
777 		new_parent->btc_children[0] = new_node;
778 		bcpy(tmp_buf, new_parent->btc_elems, size);
779 		new_par_hdr->bth_count++;
780 	}
781 	kmem_free(tmp_buf, size);
782 	zfs_btree_poison_node(tree, par_hdr);
783 
784 	for (uint32_t i = 0; i <= new_parent->btc_hdr.bth_count; i++)
785 		new_parent->btc_children[i]->bth_parent = new_parent;
786 
787 	for (uint32_t i = 0; i <= parent->btc_hdr.bth_count; i++)
788 		ASSERT3P(parent->btc_children[i]->bth_parent, ==, parent);
789 
790 	/*
791 	 * Now that the node is split, we need to insert the new node into its
792 	 * parent. This may cause further splitting.
793 	 */
794 	zfs_btree_insert_into_parent(tree, &parent->btc_hdr,
795 	    &new_parent->btc_hdr, buf);
796 }
797 
798 /* Insert an element into a leaf node at the given offset. */
799 static void
zfs_btree_insert_leaf_impl(zfs_btree_t * tree,zfs_btree_leaf_t * leaf,uint32_t idx,const void * value)800 zfs_btree_insert_leaf_impl(zfs_btree_t *tree, zfs_btree_leaf_t *leaf,
801     uint32_t idx, const void *value)
802 {
803 	size_t size = tree->bt_elem_size;
804 	zfs_btree_hdr_t *hdr = &leaf->btl_hdr;
805 	ASSERT3U(leaf->btl_hdr.bth_count, <, tree->bt_leaf_cap);
806 
807 	if (zfs_btree_verify_intensity >= 5) {
808 		zfs_btree_verify_poison_at(tree, &leaf->btl_hdr,
809 		    leaf->btl_hdr.bth_count);
810 	}
811 
812 	bt_grow_leaf(tree, leaf, idx, 1);
813 	uint8_t *start = leaf->btl_elems + (hdr->bth_first + idx) * size;
814 	bcpy(value, start, size);
815 }
816 
817 static void
818 zfs_btree_verify_order_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr);
819 
820 /* Helper function for inserting a new value into leaf at the given index. */
821 static void
zfs_btree_insert_into_leaf(zfs_btree_t * tree,zfs_btree_leaf_t * leaf,const void * value,uint32_t idx)822 zfs_btree_insert_into_leaf(zfs_btree_t *tree, zfs_btree_leaf_t *leaf,
823     const void *value, uint32_t idx)
824 {
825 	size_t size = tree->bt_elem_size;
826 	uint32_t capacity = tree->bt_leaf_cap;
827 
828 	/*
829 	 * If the leaf isn't full, shift the elements after idx and insert
830 	 * value.
831 	 */
832 	if (leaf->btl_hdr.bth_count != capacity) {
833 		zfs_btree_insert_leaf_impl(tree, leaf, idx, value);
834 		return;
835 	}
836 
837 	/*
838 	 * Otherwise, we split the leaf node into two nodes. If we're not bulk
839 	 * inserting, each is of size (capacity / 2).  If we are bulk
840 	 * inserting, we move a quarter of the elements to the new node so
841 	 * inserts into the old node don't cause immediate splitting but the
842 	 * tree stays relatively dense. Since the average state after a long
843 	 * time is a 3/4 full node, shortcutting directly to that state
844 	 * improves efficiency.  At the end of the bulk insertion process
845 	 * we'll need to go through and fix up any nodes (the last leaf and
846 	 * its ancestors, potentially) that are below the minimum.
847 	 *
848 	 * In either case, we're left with one extra element. The leftover
849 	 * element will become the new dividing element between the two nodes.
850 	 */
851 	uint32_t move_count = MAX(capacity / (tree->bt_bulk ? 4 : 2), 1) - 1;
852 	uint32_t keep_count = capacity - move_count - 1;
853 	ASSERT3U(keep_count, >=, 1);
854 	/* If we insert on left. move one more to keep leaves balanced.  */
855 	if (idx < keep_count) {
856 		keep_count--;
857 		move_count++;
858 	}
859 	tree->bt_num_nodes++;
860 	zfs_btree_leaf_t *new_leaf = zfs_btree_leaf_alloc(tree);
861 	zfs_btree_hdr_t *new_hdr = &new_leaf->btl_hdr;
862 	new_hdr->bth_parent = leaf->btl_hdr.bth_parent;
863 	new_hdr->bth_first = (tree->bt_bulk ? 0 : capacity / 4) +
864 	    (idx >= keep_count && idx <= keep_count + move_count / 2);
865 	new_hdr->bth_count = move_count;
866 	zfs_btree_poison_node(tree, new_hdr);
867 
868 	if (tree->bt_bulk != NULL && leaf == tree->bt_bulk)
869 		tree->bt_bulk = new_leaf;
870 
871 	/* Copy the back part to the new leaf. */
872 	bt_transfer_leaf(tree, leaf, keep_count + 1, move_count, new_leaf, 0);
873 
874 	/* We store the new separator in a buffer we control for simplicity. */
875 	uint8_t *buf = kmem_alloc(size, KM_SLEEP);
876 	bcpy(leaf->btl_elems + (leaf->btl_hdr.bth_first + keep_count) * size,
877 	    buf, size);
878 
879 	bt_shrink_leaf(tree, leaf, keep_count, 1 + move_count);
880 
881 	if (idx < keep_count) {
882 		/* Insert into the existing leaf. */
883 		zfs_btree_insert_leaf_impl(tree, leaf, idx, value);
884 	} else if (idx > keep_count) {
885 		/* Insert into the new leaf. */
886 		zfs_btree_insert_leaf_impl(tree, new_leaf, idx - keep_count -
887 		    1, value);
888 	} else {
889 		/*
890 		 * Insert planned separator into the new leaf, and use
891 		 * the new value as the new separator.
892 		 */
893 		zfs_btree_insert_leaf_impl(tree, new_leaf, 0, buf);
894 		bcpy(value, buf, size);
895 	}
896 
897 	/*
898 	 * Now that the node is split, we need to insert the new node into its
899 	 * parent. This may cause further splitting, bur only of core nodes.
900 	 */
901 	zfs_btree_insert_into_parent(tree, &leaf->btl_hdr, &new_leaf->btl_hdr,
902 	    buf);
903 	kmem_free(buf, size);
904 }
905 
906 static uint32_t
zfs_btree_find_parent_idx(zfs_btree_t * tree,zfs_btree_hdr_t * hdr)907 zfs_btree_find_parent_idx(zfs_btree_t *tree, zfs_btree_hdr_t *hdr)
908 {
909 	void *buf;
910 	if (zfs_btree_is_core(hdr)) {
911 		buf = ((zfs_btree_core_t *)hdr)->btc_elems;
912 	} else {
913 		buf = ((zfs_btree_leaf_t *)hdr)->btl_elems +
914 		    hdr->bth_first * tree->bt_elem_size;
915 	}
916 	zfs_btree_index_t idx;
917 	zfs_btree_core_t *parent = hdr->bth_parent;
918 	VERIFY3P(tree->bt_find_in_buf(tree, parent->btc_elems,
919 	    parent->btc_hdr.bth_count, buf, &idx), ==, NULL);
920 	ASSERT(idx.bti_before);
921 	ASSERT3U(idx.bti_offset, <=, parent->btc_hdr.bth_count);
922 	ASSERT3P(parent->btc_children[idx.bti_offset], ==, hdr);
923 	return (idx.bti_offset);
924 }
925 
926 /*
927  * Take the b-tree out of bulk insert mode. During bulk-insert mode, some
928  * nodes may violate the invariant that non-root nodes must be at least half
929  * full. All nodes violating this invariant should be the last node in their
930  * particular level. To correct the invariant, we take values from their left
931  * neighbor until they are half full. They must have a left neighbor at their
932  * level because the last node at a level is not the first node unless it's
933  * the root.
934  */
935 static void
zfs_btree_bulk_finish(zfs_btree_t * tree)936 zfs_btree_bulk_finish(zfs_btree_t *tree)
937 {
938 	ASSERT3P(tree->bt_bulk, !=, NULL);
939 	ASSERT3P(tree->bt_root, !=, NULL);
940 	zfs_btree_leaf_t *leaf = tree->bt_bulk;
941 	zfs_btree_hdr_t *hdr = &leaf->btl_hdr;
942 	zfs_btree_core_t *parent = hdr->bth_parent;
943 	size_t size = tree->bt_elem_size;
944 	uint32_t capacity = tree->bt_leaf_cap;
945 
946 	/*
947 	 * The invariant doesn't apply to the root node, if that's the only
948 	 * node in the tree we're done.
949 	 */
950 	if (parent == NULL) {
951 		tree->bt_bulk = NULL;
952 		return;
953 	}
954 
955 	/* First, take elements to rebalance the leaf node. */
956 	if (hdr->bth_count < capacity / 2) {
957 		/*
958 		 * First, find the left neighbor. The simplest way to do this
959 		 * is to call zfs_btree_prev twice; the first time finds some
960 		 * ancestor of this node, and the second time finds the left
961 		 * neighbor. The ancestor found is the lowest common ancestor
962 		 * of leaf and the neighbor.
963 		 */
964 		zfs_btree_index_t idx = {
965 			.bti_node = hdr,
966 			.bti_offset = 0
967 		};
968 		VERIFY3P(zfs_btree_prev(tree, &idx, &idx), !=, NULL);
969 		ASSERT(zfs_btree_is_core(idx.bti_node));
970 		zfs_btree_core_t *common = (zfs_btree_core_t *)idx.bti_node;
971 		uint32_t common_idx = idx.bti_offset;
972 
973 		VERIFY3P(zfs_btree_prev(tree, &idx, &idx), !=, NULL);
974 		ASSERT(!zfs_btree_is_core(idx.bti_node));
975 		zfs_btree_leaf_t *l_neighbor = (zfs_btree_leaf_t *)idx.bti_node;
976 		zfs_btree_hdr_t *l_hdr = idx.bti_node;
977 		uint32_t move_count = (capacity / 2) - hdr->bth_count;
978 		ASSERT3U(l_neighbor->btl_hdr.bth_count - move_count, >=,
979 		    capacity / 2);
980 
981 		if (zfs_btree_verify_intensity >= 5) {
982 			for (uint32_t i = 0; i < move_count; i++) {
983 				zfs_btree_verify_poison_at(tree, hdr,
984 				    leaf->btl_hdr.bth_count + i);
985 			}
986 		}
987 
988 		/* First, shift elements in leaf back. */
989 		bt_grow_leaf(tree, leaf, 0, move_count);
990 
991 		/* Next, move the separator from the common ancestor to leaf. */
992 		uint8_t *separator = common->btc_elems + common_idx * size;
993 		uint8_t *out = leaf->btl_elems +
994 		    (hdr->bth_first + move_count - 1) * size;
995 		bcpy(separator, out, size);
996 
997 		/*
998 		 * Now we move elements from the tail of the left neighbor to
999 		 * fill the remaining spots in leaf.
1000 		 */
1001 		bt_transfer_leaf(tree, l_neighbor, l_hdr->bth_count -
1002 		    (move_count - 1), move_count - 1, leaf, 0);
1003 
1004 		/*
1005 		 * Finally, move the new last element in the left neighbor to
1006 		 * the separator.
1007 		 */
1008 		bcpy(l_neighbor->btl_elems + (l_hdr->bth_first +
1009 		    l_hdr->bth_count - move_count) * size, separator, size);
1010 
1011 		/* Adjust the node's counts, and we're done. */
1012 		bt_shrink_leaf(tree, l_neighbor, l_hdr->bth_count - move_count,
1013 		    move_count);
1014 
1015 		ASSERT3U(l_hdr->bth_count, >=, capacity / 2);
1016 		ASSERT3U(hdr->bth_count, >=, capacity / 2);
1017 	}
1018 
1019 	/*
1020 	 * Now we have to rebalance any ancestors of leaf that may also
1021 	 * violate the invariant.
1022 	 */
1023 	capacity = BTREE_CORE_ELEMS;
1024 	while (parent->btc_hdr.bth_parent != NULL) {
1025 		zfs_btree_core_t *cur = parent;
1026 		zfs_btree_hdr_t *hdr = &cur->btc_hdr;
1027 		parent = hdr->bth_parent;
1028 		/*
1029 		 * If the invariant isn't violated, move on to the next
1030 		 * ancestor.
1031 		 */
1032 		if (hdr->bth_count >= capacity / 2)
1033 			continue;
1034 
1035 		/*
1036 		 * Because the smallest number of nodes we can move when
1037 		 * splitting is 2, we never need to worry about not having a
1038 		 * left sibling (a sibling is a neighbor with the same parent).
1039 		 */
1040 		uint32_t parent_idx = zfs_btree_find_parent_idx(tree, hdr);
1041 		ASSERT3U(parent_idx, >, 0);
1042 		zfs_btree_core_t *l_neighbor =
1043 		    (zfs_btree_core_t *)parent->btc_children[parent_idx - 1];
1044 		uint32_t move_count = (capacity / 2) - hdr->bth_count;
1045 		ASSERT3U(l_neighbor->btc_hdr.bth_count - move_count, >=,
1046 		    capacity / 2);
1047 
1048 		if (zfs_btree_verify_intensity >= 5) {
1049 			for (uint32_t i = 0; i < move_count; i++) {
1050 				zfs_btree_verify_poison_at(tree, hdr,
1051 				    hdr->bth_count + i);
1052 			}
1053 		}
1054 		/* First, shift things in the right node back. */
1055 		bt_shift_core(tree, cur, 0, hdr->bth_count, move_count,
1056 		    BSS_TRAPEZOID, BSD_RIGHT);
1057 
1058 		/* Next, move the separator to the right node. */
1059 		uint8_t *separator = parent->btc_elems + ((parent_idx - 1) *
1060 		    size);
1061 		uint8_t *e_out = cur->btc_elems + ((move_count - 1) * size);
1062 		bcpy(separator, e_out, size);
1063 
1064 		/*
1065 		 * Now, move elements and children from the left node to the
1066 		 * right.  We move one more child than elements.
1067 		 */
1068 		move_count--;
1069 		uint32_t move_idx = l_neighbor->btc_hdr.bth_count - move_count;
1070 		bt_transfer_core(tree, l_neighbor, move_idx, move_count, cur, 0,
1071 		    BSS_TRAPEZOID);
1072 
1073 		/*
1074 		 * Finally, move the last element in the left node to the
1075 		 * separator's position.
1076 		 */
1077 		move_idx--;
1078 		bcpy(l_neighbor->btc_elems + move_idx * size, separator, size);
1079 
1080 		l_neighbor->btc_hdr.bth_count -= move_count + 1;
1081 		hdr->bth_count += move_count + 1;
1082 
1083 		ASSERT3U(l_neighbor->btc_hdr.bth_count, >=, capacity / 2);
1084 		ASSERT3U(hdr->bth_count, >=, capacity / 2);
1085 
1086 		zfs_btree_poison_node(tree, &l_neighbor->btc_hdr);
1087 
1088 		for (uint32_t i = 0; i <= hdr->bth_count; i++)
1089 			cur->btc_children[i]->bth_parent = cur;
1090 	}
1091 
1092 	tree->bt_bulk = NULL;
1093 	zfs_btree_verify(tree);
1094 }
1095 
1096 /*
1097  * Insert value into tree at the location specified by where.
1098  */
1099 void
zfs_btree_add_idx(zfs_btree_t * tree,const void * value,const zfs_btree_index_t * where)1100 zfs_btree_add_idx(zfs_btree_t *tree, const void *value,
1101     const zfs_btree_index_t *where)
1102 {
1103 	zfs_btree_index_t idx = {0};
1104 
1105 	/* If we're not inserting in the last leaf, end bulk insert mode. */
1106 	if (tree->bt_bulk != NULL) {
1107 		if (where->bti_node != &tree->bt_bulk->btl_hdr) {
1108 			zfs_btree_bulk_finish(tree);
1109 			VERIFY3P(zfs_btree_find(tree, value, &idx), ==, NULL);
1110 			where = &idx;
1111 		}
1112 	}
1113 
1114 	tree->bt_num_elems++;
1115 	/*
1116 	 * If this is the first element in the tree, create a leaf root node
1117 	 * and add the value to it.
1118 	 */
1119 	if (where->bti_node == NULL) {
1120 		ASSERT3U(tree->bt_num_elems, ==, 1);
1121 		ASSERT3S(tree->bt_height, ==, -1);
1122 		ASSERT0P(tree->bt_root);
1123 		ASSERT0(where->bti_offset);
1124 
1125 		tree->bt_num_nodes++;
1126 		zfs_btree_leaf_t *leaf = zfs_btree_leaf_alloc(tree);
1127 		tree->bt_root = &leaf->btl_hdr;
1128 		tree->bt_height++;
1129 
1130 		zfs_btree_hdr_t *hdr = &leaf->btl_hdr;
1131 		hdr->bth_parent = NULL;
1132 		hdr->bth_first = 0;
1133 		hdr->bth_count = 0;
1134 		zfs_btree_poison_node(tree, hdr);
1135 
1136 		zfs_btree_insert_into_leaf(tree, leaf, value, 0);
1137 		tree->bt_bulk = leaf;
1138 	} else if (!zfs_btree_is_core(where->bti_node)) {
1139 		/*
1140 		 * If we're inserting into a leaf, go directly to the helper
1141 		 * function.
1142 		 */
1143 		zfs_btree_insert_into_leaf(tree,
1144 		    (zfs_btree_leaf_t *)where->bti_node, value,
1145 		    where->bti_offset);
1146 	} else {
1147 		/*
1148 		 * If we're inserting into a core node, we can't just shift
1149 		 * the existing element in that slot in the same node without
1150 		 * breaking our ordering invariants. Instead we place the new
1151 		 * value in the node at that spot and then insert the old
1152 		 * separator into the first slot in the subtree to the right.
1153 		 */
1154 		zfs_btree_core_t *node = (zfs_btree_core_t *)where->bti_node;
1155 
1156 		/*
1157 		 * We can ignore bti_before, because either way the value
1158 		 * should end up in bti_offset.
1159 		 */
1160 		uint32_t off = where->bti_offset;
1161 		zfs_btree_hdr_t *subtree = node->btc_children[off + 1];
1162 		size_t size = tree->bt_elem_size;
1163 		uint8_t *buf = kmem_alloc(size, KM_SLEEP);
1164 		bcpy(node->btc_elems + off * size, buf, size);
1165 		bcpy(value, node->btc_elems + off * size, size);
1166 
1167 		/*
1168 		 * Find the first slot in the subtree to the right, insert
1169 		 * there.
1170 		 */
1171 		zfs_btree_index_t new_idx;
1172 		VERIFY3P(zfs_btree_first_helper(tree, subtree, &new_idx), !=,
1173 		    NULL);
1174 		ASSERT0(new_idx.bti_offset);
1175 		ASSERT(!zfs_btree_is_core(new_idx.bti_node));
1176 		zfs_btree_insert_into_leaf(tree,
1177 		    (zfs_btree_leaf_t *)new_idx.bti_node, buf, 0);
1178 		kmem_free(buf, size);
1179 	}
1180 	zfs_btree_verify(tree);
1181 }
1182 
1183 /*
1184  * Return the first element in the tree, and put its location in where if
1185  * non-null.
1186  */
1187 void *
zfs_btree_first(zfs_btree_t * tree,zfs_btree_index_t * where)1188 zfs_btree_first(zfs_btree_t *tree, zfs_btree_index_t *where)
1189 {
1190 	if (tree->bt_height == -1) {
1191 		ASSERT0(tree->bt_num_elems);
1192 		return (NULL);
1193 	}
1194 	return (zfs_btree_first_helper(tree, tree->bt_root, where));
1195 }
1196 
1197 /*
1198  * Find the last element in the subtree rooted at hdr, return its value and
1199  * put its location in where if non-null.
1200  */
1201 static void *
zfs_btree_last_helper(zfs_btree_t * btree,zfs_btree_hdr_t * hdr,zfs_btree_index_t * where)1202 zfs_btree_last_helper(zfs_btree_t *btree, zfs_btree_hdr_t *hdr,
1203     zfs_btree_index_t *where)
1204 {
1205 	zfs_btree_hdr_t *node;
1206 
1207 	for (node = hdr; zfs_btree_is_core(node); node =
1208 	    ((zfs_btree_core_t *)node)->btc_children[node->bth_count])
1209 		;
1210 
1211 	zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)node;
1212 	if (where != NULL) {
1213 		where->bti_node = node;
1214 		where->bti_offset = node->bth_count - 1;
1215 		where->bti_before = B_FALSE;
1216 	}
1217 	return (leaf->btl_elems + (node->bth_first + node->bth_count - 1) *
1218 	    btree->bt_elem_size);
1219 }
1220 
1221 /*
1222  * Return the last element in the tree, and put its location in where if
1223  * non-null.
1224  */
1225 void *
zfs_btree_last(zfs_btree_t * tree,zfs_btree_index_t * where)1226 zfs_btree_last(zfs_btree_t *tree, zfs_btree_index_t *where)
1227 {
1228 	if (tree->bt_height == -1) {
1229 		ASSERT0(tree->bt_num_elems);
1230 		return (NULL);
1231 	}
1232 	return (zfs_btree_last_helper(tree, tree->bt_root, where));
1233 }
1234 
1235 /*
1236  * This function contains the logic to find the next node in the tree. A
1237  * helper function is used because there are multiple internal consumemrs of
1238  * this logic. The done_func is used by zfs_btree_destroy_nodes to clean up each
1239  * node after we've finished with it.
1240  */
1241 static void *
zfs_btree_next_helper(zfs_btree_t * tree,const zfs_btree_index_t * idx,zfs_btree_index_t * out_idx,void (* done_func)(zfs_btree_t *,zfs_btree_hdr_t *))1242 zfs_btree_next_helper(zfs_btree_t *tree, const zfs_btree_index_t *idx,
1243     zfs_btree_index_t *out_idx,
1244     void (*done_func)(zfs_btree_t *, zfs_btree_hdr_t *))
1245 {
1246 	if (idx->bti_node == NULL) {
1247 		ASSERT3S(tree->bt_height, ==, -1);
1248 		return (NULL);
1249 	}
1250 
1251 	uint32_t offset = idx->bti_offset;
1252 	if (!zfs_btree_is_core(idx->bti_node)) {
1253 		/*
1254 		 * When finding the next element of an element in a leaf,
1255 		 * there are two cases. If the element isn't the last one in
1256 		 * the leaf, in which case we just return the next element in
1257 		 * the leaf. Otherwise, we need to traverse up our parents
1258 		 * until we find one where our ancestor isn't the last child
1259 		 * of its parent. Once we do, the next element is the
1260 		 * separator after our ancestor in its parent.
1261 		 */
1262 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)idx->bti_node;
1263 		uint32_t new_off = offset + (idx->bti_before ? 0 : 1);
1264 		if (leaf->btl_hdr.bth_count > new_off) {
1265 			out_idx->bti_node = &leaf->btl_hdr;
1266 			out_idx->bti_offset = new_off;
1267 			out_idx->bti_before = B_FALSE;
1268 			return (leaf->btl_elems + (leaf->btl_hdr.bth_first +
1269 			    new_off) * tree->bt_elem_size);
1270 		}
1271 
1272 		zfs_btree_hdr_t *prev = &leaf->btl_hdr;
1273 		for (zfs_btree_core_t *node = leaf->btl_hdr.bth_parent;
1274 		    node != NULL; node = node->btc_hdr.bth_parent) {
1275 			zfs_btree_hdr_t *hdr = &node->btc_hdr;
1276 			ASSERT(zfs_btree_is_core(hdr));
1277 			uint32_t i = zfs_btree_find_parent_idx(tree, prev);
1278 			if (done_func != NULL)
1279 				done_func(tree, prev);
1280 			if (i == hdr->bth_count) {
1281 				prev = hdr;
1282 				continue;
1283 			}
1284 			out_idx->bti_node = hdr;
1285 			out_idx->bti_offset = i;
1286 			out_idx->bti_before = B_FALSE;
1287 			return (node->btc_elems + i * tree->bt_elem_size);
1288 		}
1289 		if (done_func != NULL)
1290 			done_func(tree, prev);
1291 		/*
1292 		 * We've traversed all the way up and been at the end of the
1293 		 * node every time, so this was the last element in the tree.
1294 		 */
1295 		return (NULL);
1296 	}
1297 
1298 	/* If we were before an element in a core node, return that element. */
1299 	ASSERT(zfs_btree_is_core(idx->bti_node));
1300 	zfs_btree_core_t *node = (zfs_btree_core_t *)idx->bti_node;
1301 	if (idx->bti_before) {
1302 		out_idx->bti_before = B_FALSE;
1303 		return (node->btc_elems + offset * tree->bt_elem_size);
1304 	}
1305 
1306 	/*
1307 	 * The next element from one in a core node is the first element in
1308 	 * the subtree just to the right of the separator.
1309 	 */
1310 	zfs_btree_hdr_t *child = node->btc_children[offset + 1];
1311 	return (zfs_btree_first_helper(tree, child, out_idx));
1312 }
1313 
1314 /*
1315  * Return the next valued node in the tree.  The same address can be safely
1316  * passed for idx and out_idx.
1317  */
1318 void *
zfs_btree_next(zfs_btree_t * tree,const zfs_btree_index_t * idx,zfs_btree_index_t * out_idx)1319 zfs_btree_next(zfs_btree_t *tree, const zfs_btree_index_t *idx,
1320     zfs_btree_index_t *out_idx)
1321 {
1322 	return (zfs_btree_next_helper(tree, idx, out_idx, NULL));
1323 }
1324 
1325 /*
1326  * Return the previous valued node in the tree.  The same value can be safely
1327  * passed for idx and out_idx.
1328  */
1329 void *
zfs_btree_prev(zfs_btree_t * tree,const zfs_btree_index_t * idx,zfs_btree_index_t * out_idx)1330 zfs_btree_prev(zfs_btree_t *tree, const zfs_btree_index_t *idx,
1331     zfs_btree_index_t *out_idx)
1332 {
1333 	if (idx->bti_node == NULL) {
1334 		ASSERT3S(tree->bt_height, ==, -1);
1335 		return (NULL);
1336 	}
1337 
1338 	uint32_t offset = idx->bti_offset;
1339 	if (!zfs_btree_is_core(idx->bti_node)) {
1340 		/*
1341 		 * When finding the previous element of an element in a leaf,
1342 		 * there are two cases. If the element isn't the first one in
1343 		 * the leaf, in which case we just return the previous element
1344 		 * in the leaf. Otherwise, we need to traverse up our parents
1345 		 * until we find one where our previous ancestor isn't the
1346 		 * first child. Once we do, the previous element is the
1347 		 * separator after our previous ancestor.
1348 		 */
1349 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)idx->bti_node;
1350 		if (offset != 0) {
1351 			out_idx->bti_node = &leaf->btl_hdr;
1352 			out_idx->bti_offset = offset - 1;
1353 			out_idx->bti_before = B_FALSE;
1354 			return (leaf->btl_elems + (leaf->btl_hdr.bth_first +
1355 			    offset - 1) * tree->bt_elem_size);
1356 		}
1357 		zfs_btree_hdr_t *prev = &leaf->btl_hdr;
1358 		for (zfs_btree_core_t *node = leaf->btl_hdr.bth_parent;
1359 		    node != NULL; node = node->btc_hdr.bth_parent) {
1360 			zfs_btree_hdr_t *hdr = &node->btc_hdr;
1361 			ASSERT(zfs_btree_is_core(hdr));
1362 			uint32_t i = zfs_btree_find_parent_idx(tree, prev);
1363 			if (i == 0) {
1364 				prev = hdr;
1365 				continue;
1366 			}
1367 			out_idx->bti_node = hdr;
1368 			out_idx->bti_offset = i - 1;
1369 			out_idx->bti_before = B_FALSE;
1370 			return (node->btc_elems + (i - 1) * tree->bt_elem_size);
1371 		}
1372 		/*
1373 		 * We've traversed all the way up and been at the start of the
1374 		 * node every time, so this was the first node in the tree.
1375 		 */
1376 		return (NULL);
1377 	}
1378 
1379 	/*
1380 	 * The previous element from one in a core node is the last element in
1381 	 * the subtree just to the left of the separator.
1382 	 */
1383 	ASSERT(zfs_btree_is_core(idx->bti_node));
1384 	zfs_btree_core_t *node = (zfs_btree_core_t *)idx->bti_node;
1385 	zfs_btree_hdr_t *child = node->btc_children[offset];
1386 	return (zfs_btree_last_helper(tree, child, out_idx));
1387 }
1388 
1389 /*
1390  * Get the value at the provided index in the tree.
1391  *
1392  * Note that the value returned from this function can be mutated, but only
1393  * if it will not change the ordering of the element with respect to any other
1394  * elements that could be in the tree.
1395  */
1396 void *
zfs_btree_get(zfs_btree_t * tree,zfs_btree_index_t * idx)1397 zfs_btree_get(zfs_btree_t *tree, zfs_btree_index_t *idx)
1398 {
1399 	ASSERT(!idx->bti_before);
1400 	size_t size = tree->bt_elem_size;
1401 	if (!zfs_btree_is_core(idx->bti_node)) {
1402 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)idx->bti_node;
1403 		return (leaf->btl_elems + (leaf->btl_hdr.bth_first +
1404 		    idx->bti_offset) * size);
1405 	}
1406 	zfs_btree_core_t *node = (zfs_btree_core_t *)idx->bti_node;
1407 	return (node->btc_elems + idx->bti_offset * size);
1408 }
1409 
1410 /* Add the given value to the tree. Must not already be in the tree. */
1411 void
zfs_btree_add(zfs_btree_t * tree,const void * node)1412 zfs_btree_add(zfs_btree_t *tree, const void *node)
1413 {
1414 	zfs_btree_index_t where = {0};
1415 	VERIFY3P(zfs_btree_find(tree, node, &where), ==, NULL);
1416 	zfs_btree_add_idx(tree, node, &where);
1417 }
1418 
1419 /* Helper function to free a tree node. */
1420 static void
zfs_btree_node_destroy(zfs_btree_t * tree,zfs_btree_hdr_t * node)1421 zfs_btree_node_destroy(zfs_btree_t *tree, zfs_btree_hdr_t *node)
1422 {
1423 	tree->bt_num_nodes--;
1424 	if (!zfs_btree_is_core(node)) {
1425 		zfs_btree_leaf_free(tree, node);
1426 	} else {
1427 		kmem_free(node, sizeof (zfs_btree_core_t) +
1428 		    BTREE_CORE_ELEMS * tree->bt_elem_size);
1429 	}
1430 }
1431 
1432 /*
1433  * Remove the rm_hdr and the separator to its left from the parent node. The
1434  * buffer that rm_hdr was stored in may already be freed, so its contents
1435  * cannot be accessed.
1436  */
1437 static void
zfs_btree_remove_from_node(zfs_btree_t * tree,zfs_btree_core_t * node,zfs_btree_hdr_t * rm_hdr)1438 zfs_btree_remove_from_node(zfs_btree_t *tree, zfs_btree_core_t *node,
1439     zfs_btree_hdr_t *rm_hdr)
1440 {
1441 	size_t size = tree->bt_elem_size;
1442 	uint32_t min_count = (BTREE_CORE_ELEMS / 2) - 1;
1443 	zfs_btree_hdr_t *hdr = &node->btc_hdr;
1444 	/*
1445 	 * If the node is the root node and rm_hdr is one of two children,
1446 	 * promote the other child to the root.
1447 	 */
1448 	if (hdr->bth_parent == NULL && hdr->bth_count <= 1) {
1449 		ASSERT3U(hdr->bth_count, ==, 1);
1450 		ASSERT3P(tree->bt_root, ==, node);
1451 		ASSERT3P(node->btc_children[1], ==, rm_hdr);
1452 		tree->bt_root = node->btc_children[0];
1453 		node->btc_children[0]->bth_parent = NULL;
1454 		zfs_btree_node_destroy(tree, hdr);
1455 		tree->bt_height--;
1456 		return;
1457 	}
1458 
1459 	uint32_t idx;
1460 	for (idx = 0; idx <= hdr->bth_count; idx++) {
1461 		if (node->btc_children[idx] == rm_hdr)
1462 			break;
1463 	}
1464 	ASSERT3U(idx, <=, hdr->bth_count);
1465 
1466 	/*
1467 	 * If the node is the root or it has more than the minimum number of
1468 	 * children, just remove the child and separator, and return.
1469 	 */
1470 	if (hdr->bth_parent == NULL ||
1471 	    hdr->bth_count > min_count) {
1472 		/*
1473 		 * Shift the element and children to the right of rm_hdr to
1474 		 * the left by one spot.
1475 		 */
1476 		bt_shift_core_left(tree, node, idx, hdr->bth_count - idx,
1477 		    BSS_PARALLELOGRAM);
1478 		hdr->bth_count--;
1479 		zfs_btree_poison_node_at(tree, hdr, hdr->bth_count, 1);
1480 		return;
1481 	}
1482 
1483 	ASSERT3U(hdr->bth_count, ==, min_count);
1484 
1485 	/*
1486 	 * Now we try to take a node from a neighbor. We check left, then
1487 	 * right. If the neighbor exists and has more than the minimum number
1488 	 * of elements, we move the separator between us and them to our
1489 	 * node, move their closest element (last for left, first for right)
1490 	 * to the separator, and move their closest child to our node. Along
1491 	 * the way we need to collapse the gap made by idx, and (for our right
1492 	 * neighbor) the gap made by removing their first element and child.
1493 	 *
1494 	 * Note: this logic currently doesn't support taking from a neighbor
1495 	 * that isn't a sibling (i.e. a neighbor with a different
1496 	 * parent). This isn't critical functionality, but may be worth
1497 	 * implementing in the future for completeness' sake.
1498 	 */
1499 	zfs_btree_core_t *parent = hdr->bth_parent;
1500 	uint32_t parent_idx = zfs_btree_find_parent_idx(tree, hdr);
1501 
1502 	zfs_btree_hdr_t *l_hdr = (parent_idx == 0 ? NULL :
1503 	    parent->btc_children[parent_idx - 1]);
1504 	if (l_hdr != NULL && l_hdr->bth_count > min_count) {
1505 		/* We can take a node from the left neighbor. */
1506 		ASSERT(zfs_btree_is_core(l_hdr));
1507 		zfs_btree_core_t *neighbor = (zfs_btree_core_t *)l_hdr;
1508 
1509 		/*
1510 		 * Start by shifting the elements and children in the current
1511 		 * node to the right by one spot.
1512 		 */
1513 		bt_shift_core_right(tree, node, 0, idx - 1, BSS_TRAPEZOID);
1514 
1515 		/*
1516 		 * Move the separator between node and neighbor to the first
1517 		 * element slot in the current node.
1518 		 */
1519 		uint8_t *separator = parent->btc_elems + (parent_idx - 1) *
1520 		    size;
1521 		bcpy(separator, node->btc_elems, size);
1522 
1523 		/* Move the last child of neighbor to our first child slot. */
1524 		node->btc_children[0] =
1525 		    neighbor->btc_children[l_hdr->bth_count];
1526 		node->btc_children[0]->bth_parent = node;
1527 
1528 		/* Move the last element of neighbor to the separator spot. */
1529 		uint8_t *take_elem = neighbor->btc_elems +
1530 		    (l_hdr->bth_count - 1) * size;
1531 		bcpy(take_elem, separator, size);
1532 		l_hdr->bth_count--;
1533 		zfs_btree_poison_node_at(tree, l_hdr, l_hdr->bth_count, 1);
1534 		return;
1535 	}
1536 
1537 	zfs_btree_hdr_t *r_hdr = (parent_idx == parent->btc_hdr.bth_count ?
1538 	    NULL : parent->btc_children[parent_idx + 1]);
1539 	if (r_hdr != NULL && r_hdr->bth_count > min_count) {
1540 		/* We can take a node from the right neighbor. */
1541 		ASSERT(zfs_btree_is_core(r_hdr));
1542 		zfs_btree_core_t *neighbor = (zfs_btree_core_t *)r_hdr;
1543 
1544 		/*
1545 		 * Shift elements in node left by one spot to overwrite rm_hdr
1546 		 * and the separator before it.
1547 		 */
1548 		bt_shift_core_left(tree, node, idx, hdr->bth_count - idx,
1549 		    BSS_PARALLELOGRAM);
1550 
1551 		/*
1552 		 * Move the separator between node and neighbor to the last
1553 		 * element spot in node.
1554 		 */
1555 		uint8_t *separator = parent->btc_elems + parent_idx * size;
1556 		bcpy(separator, node->btc_elems + (hdr->bth_count - 1) * size,
1557 		    size);
1558 
1559 		/*
1560 		 * Move the first child of neighbor to the last child spot in
1561 		 * node.
1562 		 */
1563 		node->btc_children[hdr->bth_count] = neighbor->btc_children[0];
1564 		node->btc_children[hdr->bth_count]->bth_parent = node;
1565 
1566 		/* Move the first element of neighbor to the separator spot. */
1567 		uint8_t *take_elem = neighbor->btc_elems;
1568 		bcpy(take_elem, separator, size);
1569 		r_hdr->bth_count--;
1570 
1571 		/*
1572 		 * Shift the elements and children of neighbor to cover the
1573 		 * stolen elements.
1574 		 */
1575 		bt_shift_core_left(tree, neighbor, 1, r_hdr->bth_count,
1576 		    BSS_TRAPEZOID);
1577 		zfs_btree_poison_node_at(tree, r_hdr, r_hdr->bth_count, 1);
1578 		return;
1579 	}
1580 
1581 	/*
1582 	 * In this case, neither of our neighbors can spare an element, so we
1583 	 * need to merge with one of them. We prefer the left one,
1584 	 * arbitrarily. Move the separator into the leftmost merging node
1585 	 * (which may be us or the left neighbor), and then move the right
1586 	 * merging node's elements. Once that's done, we go back and delete
1587 	 * the element we're removing. Finally, go into the parent and delete
1588 	 * the right merging node and the separator. This may cause further
1589 	 * merging.
1590 	 */
1591 	zfs_btree_hdr_t *new_rm_hdr, *keep_hdr;
1592 	uint32_t new_idx = idx;
1593 	if (l_hdr != NULL) {
1594 		keep_hdr = l_hdr;
1595 		new_rm_hdr = hdr;
1596 		new_idx += keep_hdr->bth_count + 1;
1597 	} else {
1598 		ASSERT3P(r_hdr, !=, NULL);
1599 		keep_hdr = hdr;
1600 		new_rm_hdr = r_hdr;
1601 		parent_idx++;
1602 	}
1603 
1604 	ASSERT(zfs_btree_is_core(keep_hdr));
1605 	ASSERT(zfs_btree_is_core(new_rm_hdr));
1606 
1607 	zfs_btree_core_t *keep = (zfs_btree_core_t *)keep_hdr;
1608 	zfs_btree_core_t *rm = (zfs_btree_core_t *)new_rm_hdr;
1609 
1610 	if (zfs_btree_verify_intensity >= 5) {
1611 		for (uint32_t i = 0; i < new_rm_hdr->bth_count + 1; i++) {
1612 			zfs_btree_verify_poison_at(tree, keep_hdr,
1613 			    keep_hdr->bth_count + i);
1614 		}
1615 	}
1616 
1617 	/* Move the separator into the left node. */
1618 	uint8_t *e_out = keep->btc_elems + keep_hdr->bth_count * size;
1619 	uint8_t *separator = parent->btc_elems + (parent_idx - 1) *
1620 	    size;
1621 	bcpy(separator, e_out, size);
1622 	keep_hdr->bth_count++;
1623 
1624 	/* Move all our elements and children into the left node. */
1625 	bt_transfer_core(tree, rm, 0, new_rm_hdr->bth_count, keep,
1626 	    keep_hdr->bth_count, BSS_TRAPEZOID);
1627 
1628 	uint32_t old_count = keep_hdr->bth_count;
1629 
1630 	/* Update bookkeeping */
1631 	keep_hdr->bth_count += new_rm_hdr->bth_count;
1632 	ASSERT3U(keep_hdr->bth_count, ==, (min_count * 2) + 1);
1633 
1634 	/*
1635 	 * Shift the element and children to the right of rm_hdr to
1636 	 * the left by one spot.
1637 	 */
1638 	ASSERT3P(keep->btc_children[new_idx], ==, rm_hdr);
1639 	bt_shift_core_left(tree, keep, new_idx, keep_hdr->bth_count - new_idx,
1640 	    BSS_PARALLELOGRAM);
1641 	keep_hdr->bth_count--;
1642 
1643 	/* Reparent all our children to point to the left node. */
1644 	zfs_btree_hdr_t **new_start = keep->btc_children +
1645 	    old_count - 1;
1646 	for (uint32_t i = 0; i < new_rm_hdr->bth_count + 1; i++)
1647 		new_start[i]->bth_parent = keep;
1648 	for (uint32_t i = 0; i <= keep_hdr->bth_count; i++) {
1649 		ASSERT3P(keep->btc_children[i]->bth_parent, ==, keep);
1650 		ASSERT3P(keep->btc_children[i], !=, rm_hdr);
1651 	}
1652 	zfs_btree_poison_node_at(tree, keep_hdr, keep_hdr->bth_count, 1);
1653 
1654 	new_rm_hdr->bth_count = 0;
1655 	zfs_btree_remove_from_node(tree, parent, new_rm_hdr);
1656 	zfs_btree_node_destroy(tree, new_rm_hdr);
1657 }
1658 
1659 /* Remove the element at the specific location. */
1660 void
zfs_btree_remove_idx(zfs_btree_t * tree,zfs_btree_index_t * where)1661 zfs_btree_remove_idx(zfs_btree_t *tree, zfs_btree_index_t *where)
1662 {
1663 	size_t size = tree->bt_elem_size;
1664 	zfs_btree_hdr_t *hdr = where->bti_node;
1665 	uint32_t idx = where->bti_offset;
1666 
1667 	ASSERT(!where->bti_before);
1668 	if (tree->bt_bulk != NULL) {
1669 		/*
1670 		 * Leave bulk insert mode. Note that our index would be
1671 		 * invalid after we correct the tree, so we copy the value
1672 		 * we're planning to remove and find it again after
1673 		 * bulk_finish.
1674 		 */
1675 		uint8_t *value = zfs_btree_get(tree, where);
1676 		uint8_t *tmp = kmem_alloc(size, KM_SLEEP);
1677 		bcpy(value, tmp, size);
1678 		zfs_btree_bulk_finish(tree);
1679 		VERIFY3P(zfs_btree_find(tree, tmp, where), !=, NULL);
1680 		kmem_free(tmp, size);
1681 		hdr = where->bti_node;
1682 		idx = where->bti_offset;
1683 	}
1684 
1685 	tree->bt_num_elems--;
1686 	/*
1687 	 * If the element happens to be in a core node, we move a leaf node's
1688 	 * element into its place and then remove the leaf node element. This
1689 	 * makes the rebalance logic not need to be recursive both upwards and
1690 	 * downwards.
1691 	 */
1692 	if (zfs_btree_is_core(hdr)) {
1693 		zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
1694 		zfs_btree_hdr_t *left_subtree = node->btc_children[idx];
1695 		void *new_value = zfs_btree_last_helper(tree, left_subtree,
1696 		    where);
1697 		ASSERT3P(new_value, !=, NULL);
1698 
1699 		bcpy(new_value, node->btc_elems + idx * size, size);
1700 
1701 		hdr = where->bti_node;
1702 		idx = where->bti_offset;
1703 		ASSERT(!where->bti_before);
1704 	}
1705 
1706 	/*
1707 	 * First, we'll update the leaf's metadata. Then, we shift any
1708 	 * elements after the idx to the left. After that, we rebalance if
1709 	 * needed.
1710 	 */
1711 	ASSERT(!zfs_btree_is_core(hdr));
1712 	zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)hdr;
1713 	ASSERT3U(hdr->bth_count, >, 0);
1714 
1715 	uint32_t min_count = (tree->bt_leaf_cap / 2) - 1;
1716 
1717 	/*
1718 	 * If we're over the minimum size or this is the root, just overwrite
1719 	 * the value and return.
1720 	 */
1721 	if (hdr->bth_count > min_count || hdr->bth_parent == NULL) {
1722 		bt_shrink_leaf(tree, leaf, idx, 1);
1723 		if (hdr->bth_parent == NULL) {
1724 			ASSERT0(tree->bt_height);
1725 			if (hdr->bth_count == 0) {
1726 				tree->bt_root = NULL;
1727 				tree->bt_height--;
1728 				zfs_btree_node_destroy(tree, &leaf->btl_hdr);
1729 			}
1730 		}
1731 		zfs_btree_verify(tree);
1732 		return;
1733 	}
1734 	ASSERT3U(hdr->bth_count, ==, min_count);
1735 
1736 	/*
1737 	 * Now we try to take a node from a sibling. We check left, then
1738 	 * right. If they exist and have more than the minimum number of
1739 	 * elements, we move the separator between us and them to our node
1740 	 * and move their closest element (last for left, first for right) to
1741 	 * the separator. Along the way we need to collapse the gap made by
1742 	 * idx, and (for our right neighbor) the gap made by removing their
1743 	 * first element.
1744 	 *
1745 	 * Note: this logic currently doesn't support taking from a neighbor
1746 	 * that isn't a sibling. This isn't critical functionality, but may be
1747 	 * worth implementing in the future for completeness' sake.
1748 	 */
1749 	zfs_btree_core_t *parent = hdr->bth_parent;
1750 	uint32_t parent_idx = zfs_btree_find_parent_idx(tree, hdr);
1751 
1752 	zfs_btree_hdr_t *l_hdr = (parent_idx == 0 ? NULL :
1753 	    parent->btc_children[parent_idx - 1]);
1754 	if (l_hdr != NULL && l_hdr->bth_count > min_count) {
1755 		/* We can take a node from the left neighbor. */
1756 		ASSERT(!zfs_btree_is_core(l_hdr));
1757 		zfs_btree_leaf_t *neighbor = (zfs_btree_leaf_t *)l_hdr;
1758 
1759 		/*
1760 		 * Move our elements back by one spot to make room for the
1761 		 * stolen element and overwrite the element being removed.
1762 		 */
1763 		bt_shift_leaf(tree, leaf, 0, idx, 1, BSD_RIGHT);
1764 
1765 		/* Move the separator to our first spot. */
1766 		uint8_t *separator = parent->btc_elems + (parent_idx - 1) *
1767 		    size;
1768 		bcpy(separator, leaf->btl_elems + hdr->bth_first * size, size);
1769 
1770 		/* Move our neighbor's last element to the separator. */
1771 		uint8_t *take_elem = neighbor->btl_elems +
1772 		    (l_hdr->bth_first + l_hdr->bth_count - 1) * size;
1773 		bcpy(take_elem, separator, size);
1774 
1775 		/* Delete our neighbor's last element. */
1776 		bt_shrink_leaf(tree, neighbor, l_hdr->bth_count - 1, 1);
1777 		zfs_btree_verify(tree);
1778 		return;
1779 	}
1780 
1781 	zfs_btree_hdr_t *r_hdr = (parent_idx == parent->btc_hdr.bth_count ?
1782 	    NULL : parent->btc_children[parent_idx + 1]);
1783 	if (r_hdr != NULL && r_hdr->bth_count > min_count) {
1784 		/* We can take a node from the right neighbor. */
1785 		ASSERT(!zfs_btree_is_core(r_hdr));
1786 		zfs_btree_leaf_t *neighbor = (zfs_btree_leaf_t *)r_hdr;
1787 
1788 		/*
1789 		 * Move our elements after the element being removed forwards
1790 		 * by one spot to make room for the stolen element and
1791 		 * overwrite the element being removed.
1792 		 */
1793 		bt_shift_leaf(tree, leaf, idx + 1, hdr->bth_count - idx - 1,
1794 		    1, BSD_LEFT);
1795 
1796 		/* Move the separator between us to our last spot. */
1797 		uint8_t *separator = parent->btc_elems + parent_idx * size;
1798 		bcpy(separator, leaf->btl_elems + (hdr->bth_first +
1799 		    hdr->bth_count - 1) * size, size);
1800 
1801 		/* Move our neighbor's first element to the separator. */
1802 		uint8_t *take_elem = neighbor->btl_elems +
1803 		    r_hdr->bth_first * size;
1804 		bcpy(take_elem, separator, size);
1805 
1806 		/* Delete our neighbor's first element. */
1807 		bt_shrink_leaf(tree, neighbor, 0, 1);
1808 		zfs_btree_verify(tree);
1809 		return;
1810 	}
1811 
1812 	/*
1813 	 * In this case, neither of our neighbors can spare an element, so we
1814 	 * need to merge with one of them. We prefer the left one, arbitrarily.
1815 	 * After remove we move the separator into the leftmost merging node
1816 	 * (which may be us or the left neighbor), and then move the right
1817 	 * merging node's elements. Once that's done, we go back and delete
1818 	 * the element we're removing. Finally, go into the parent and delete
1819 	 * the right merging node and the separator. This may cause further
1820 	 * merging.
1821 	 */
1822 	zfs_btree_hdr_t *rm_hdr, *k_hdr;
1823 	if (l_hdr != NULL) {
1824 		k_hdr = l_hdr;
1825 		rm_hdr = hdr;
1826 	} else {
1827 		ASSERT3P(r_hdr, !=, NULL);
1828 		k_hdr = hdr;
1829 		rm_hdr = r_hdr;
1830 		parent_idx++;
1831 	}
1832 	ASSERT(!zfs_btree_is_core(k_hdr));
1833 	ASSERT(!zfs_btree_is_core(rm_hdr));
1834 	ASSERT3U(k_hdr->bth_count, ==, min_count);
1835 	ASSERT3U(rm_hdr->bth_count, ==, min_count);
1836 	zfs_btree_leaf_t *keep = (zfs_btree_leaf_t *)k_hdr;
1837 	zfs_btree_leaf_t *rm = (zfs_btree_leaf_t *)rm_hdr;
1838 
1839 	if (zfs_btree_verify_intensity >= 5) {
1840 		for (uint32_t i = 0; i < rm_hdr->bth_count + 1; i++) {
1841 			zfs_btree_verify_poison_at(tree, k_hdr,
1842 			    k_hdr->bth_count + i);
1843 		}
1844 	}
1845 
1846 	/*
1847 	 * Remove the value from the node.  It will go below the minimum,
1848 	 * but we'll fix it in no time.
1849 	 */
1850 	bt_shrink_leaf(tree, leaf, idx, 1);
1851 
1852 	/* Prepare space for elements to be moved from the right. */
1853 	uint32_t k_count = k_hdr->bth_count;
1854 	bt_grow_leaf(tree, keep, k_count, 1 + rm_hdr->bth_count);
1855 	ASSERT3U(k_hdr->bth_count, ==, min_count * 2);
1856 
1857 	/* Move the separator into the first open spot. */
1858 	uint8_t *out = keep->btl_elems + (k_hdr->bth_first + k_count) * size;
1859 	uint8_t *separator = parent->btc_elems + (parent_idx - 1) * size;
1860 	bcpy(separator, out, size);
1861 
1862 	/* Move our elements to the left neighbor. */
1863 	bt_transfer_leaf(tree, rm, 0, rm_hdr->bth_count, keep, k_count + 1);
1864 
1865 	/* Remove the emptied node from the parent. */
1866 	zfs_btree_remove_from_node(tree, parent, rm_hdr);
1867 	zfs_btree_node_destroy(tree, rm_hdr);
1868 	zfs_btree_verify(tree);
1869 }
1870 
1871 /* Remove the given value from the tree. */
1872 void
zfs_btree_remove(zfs_btree_t * tree,const void * value)1873 zfs_btree_remove(zfs_btree_t *tree, const void *value)
1874 {
1875 	zfs_btree_index_t where = {0};
1876 	VERIFY3P(zfs_btree_find(tree, value, &where), !=, NULL);
1877 	zfs_btree_remove_idx(tree, &where);
1878 }
1879 
1880 /* Return the number of elements in the tree. */
1881 ulong_t
zfs_btree_numnodes(zfs_btree_t * tree)1882 zfs_btree_numnodes(zfs_btree_t *tree)
1883 {
1884 	return (tree->bt_num_elems);
1885 }
1886 
1887 /*
1888  * This function is used to visit all the elements in the tree before
1889  * destroying the tree. This allows the calling code to perform any cleanup it
1890  * needs to do. This is more efficient than just removing the first element
1891  * over and over, because it removes all rebalancing. Once the destroy_nodes()
1892  * function has been called, no other btree operations are valid until it
1893  * returns NULL, which point the only valid operation is zfs_btree_destroy().
1894  *
1895  * example:
1896  *
1897  *      zfs_btree_index_t *cookie = NULL;
1898  *      my_data_t *node;
1899  *
1900  *      while ((node = zfs_btree_destroy_nodes(tree, &cookie)) != NULL)
1901  *              free(node->ptr);
1902  *      zfs_btree_destroy(tree);
1903  *
1904  */
1905 void *
zfs_btree_destroy_nodes(zfs_btree_t * tree,zfs_btree_index_t ** cookie)1906 zfs_btree_destroy_nodes(zfs_btree_t *tree, zfs_btree_index_t **cookie)
1907 {
1908 	if (*cookie == NULL) {
1909 		if (tree->bt_height == -1)
1910 			return (NULL);
1911 		*cookie = kmem_alloc(sizeof (**cookie), KM_SLEEP);
1912 		return (zfs_btree_first(tree, *cookie));
1913 	}
1914 
1915 	void *rval = zfs_btree_next_helper(tree, *cookie, *cookie,
1916 	    zfs_btree_node_destroy);
1917 	if (rval == NULL)   {
1918 		tree->bt_root = NULL;
1919 		tree->bt_height = -1;
1920 		tree->bt_num_elems = 0;
1921 		kmem_free(*cookie, sizeof (**cookie));
1922 		tree->bt_bulk = NULL;
1923 	}
1924 	return (rval);
1925 }
1926 
1927 static void
zfs_btree_clear_helper(zfs_btree_t * tree,zfs_btree_hdr_t * hdr)1928 zfs_btree_clear_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr)
1929 {
1930 	if (zfs_btree_is_core(hdr)) {
1931 		zfs_btree_core_t *btc = (zfs_btree_core_t *)hdr;
1932 		for (uint32_t i = 0; i <= hdr->bth_count; i++)
1933 			zfs_btree_clear_helper(tree, btc->btc_children[i]);
1934 	}
1935 
1936 	zfs_btree_node_destroy(tree, hdr);
1937 }
1938 
1939 void
zfs_btree_clear(zfs_btree_t * tree)1940 zfs_btree_clear(zfs_btree_t *tree)
1941 {
1942 	if (tree->bt_root == NULL) {
1943 		ASSERT0(tree->bt_num_elems);
1944 		return;
1945 	}
1946 
1947 	zfs_btree_clear_helper(tree, tree->bt_root);
1948 	tree->bt_num_elems = 0;
1949 	tree->bt_root = NULL;
1950 	tree->bt_num_nodes = 0;
1951 	tree->bt_height = -1;
1952 	tree->bt_bulk = NULL;
1953 }
1954 
1955 void
zfs_btree_destroy(zfs_btree_t * tree)1956 zfs_btree_destroy(zfs_btree_t *tree)
1957 {
1958 	ASSERT0(tree->bt_num_elems);
1959 	ASSERT0P(tree->bt_root);
1960 }
1961 
1962 /* Verify that every child of this node has the correct parent pointer. */
1963 static void
zfs_btree_verify_pointers_helper(zfs_btree_t * tree,zfs_btree_hdr_t * hdr)1964 zfs_btree_verify_pointers_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr)
1965 {
1966 	if (!zfs_btree_is_core(hdr))
1967 		return;
1968 
1969 	zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
1970 	for (uint32_t i = 0; i <= hdr->bth_count; i++) {
1971 		VERIFY3P(node->btc_children[i]->bth_parent, ==, hdr);
1972 		zfs_btree_verify_pointers_helper(tree, node->btc_children[i]);
1973 	}
1974 }
1975 
1976 /* Verify that every node has the correct parent pointer. */
1977 static void
zfs_btree_verify_pointers(zfs_btree_t * tree)1978 zfs_btree_verify_pointers(zfs_btree_t *tree)
1979 {
1980 	if (tree->bt_height == -1) {
1981 		VERIFY0P(tree->bt_root);
1982 		return;
1983 	}
1984 	VERIFY0P(tree->bt_root->bth_parent);
1985 	zfs_btree_verify_pointers_helper(tree, tree->bt_root);
1986 }
1987 
1988 /*
1989  * Verify that all the current node and its children satisfy the count
1990  * invariants, and return the total count in the subtree rooted in this node.
1991  */
1992 static uint64_t
zfs_btree_verify_counts_helper(zfs_btree_t * tree,zfs_btree_hdr_t * hdr)1993 zfs_btree_verify_counts_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr)
1994 {
1995 	if (!zfs_btree_is_core(hdr)) {
1996 		if (tree->bt_root != hdr && tree->bt_bulk &&
1997 		    hdr != &tree->bt_bulk->btl_hdr) {
1998 			VERIFY3U(hdr->bth_count, >=, tree->bt_leaf_cap / 2 - 1);
1999 		}
2000 
2001 		return (hdr->bth_count);
2002 	} else {
2003 
2004 		zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
2005 		uint64_t ret = hdr->bth_count;
2006 		if (tree->bt_root != hdr && tree->bt_bulk == NULL)
2007 			VERIFY3P(hdr->bth_count, >=, BTREE_CORE_ELEMS / 2 - 1);
2008 		for (uint32_t i = 0; i <= hdr->bth_count; i++) {
2009 			ret += zfs_btree_verify_counts_helper(tree,
2010 			    node->btc_children[i]);
2011 		}
2012 
2013 		return (ret);
2014 	}
2015 }
2016 
2017 /*
2018  * Verify that all nodes satisfy the invariants and that the total number of
2019  * elements is correct.
2020  */
2021 static void
zfs_btree_verify_counts(zfs_btree_t * tree)2022 zfs_btree_verify_counts(zfs_btree_t *tree)
2023 {
2024 	EQUIV(tree->bt_num_elems == 0, tree->bt_height == -1);
2025 	if (tree->bt_height == -1) {
2026 		return;
2027 	}
2028 	VERIFY3P(zfs_btree_verify_counts_helper(tree, tree->bt_root), ==,
2029 	    tree->bt_num_elems);
2030 }
2031 
2032 /*
2033  * Check that the subtree rooted at this node has a uniform height. Returns
2034  * the number of nodes under this node, to help verify bt_num_nodes.
2035  */
2036 static uint64_t
zfs_btree_verify_height_helper(zfs_btree_t * tree,zfs_btree_hdr_t * hdr,int32_t height)2037 zfs_btree_verify_height_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr,
2038     int32_t height)
2039 {
2040 	if (!zfs_btree_is_core(hdr)) {
2041 		VERIFY0(height);
2042 		return (1);
2043 	}
2044 
2045 	zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
2046 	uint64_t ret = 1;
2047 	for (uint32_t i = 0; i <= hdr->bth_count; i++) {
2048 		ret += zfs_btree_verify_height_helper(tree,
2049 		    node->btc_children[i], height - 1);
2050 	}
2051 	return (ret);
2052 }
2053 
2054 /*
2055  * Check that the tree rooted at this node has a uniform height, and that the
2056  * bt_height in the tree is correct.
2057  */
2058 static void
zfs_btree_verify_height(zfs_btree_t * tree)2059 zfs_btree_verify_height(zfs_btree_t *tree)
2060 {
2061 	EQUIV(tree->bt_height == -1, tree->bt_root == NULL);
2062 	if (tree->bt_height == -1) {
2063 		return;
2064 	}
2065 
2066 	VERIFY3U(zfs_btree_verify_height_helper(tree, tree->bt_root,
2067 	    tree->bt_height), ==, tree->bt_num_nodes);
2068 }
2069 
2070 /*
2071  * Check that the elements in this node are sorted, and that if this is a core
2072  * node, the separators are properly between the subtrees they separaate and
2073  * that the children also satisfy this requirement.
2074  */
2075 static void
zfs_btree_verify_order_helper(zfs_btree_t * tree,zfs_btree_hdr_t * hdr)2076 zfs_btree_verify_order_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr)
2077 {
2078 	size_t size = tree->bt_elem_size;
2079 	if (!zfs_btree_is_core(hdr)) {
2080 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)hdr;
2081 		for (uint32_t i = 1; i < hdr->bth_count; i++) {
2082 			VERIFY3S(tree->bt_compar(leaf->btl_elems +
2083 			    (hdr->bth_first + i - 1) * size,
2084 			    leaf->btl_elems +
2085 			    (hdr->bth_first + i) * size), ==, -1);
2086 		}
2087 		return;
2088 	}
2089 
2090 	zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
2091 	for (uint32_t i = 1; i < hdr->bth_count; i++) {
2092 		VERIFY3S(tree->bt_compar(node->btc_elems + (i - 1) * size,
2093 		    node->btc_elems + i * size), ==, -1);
2094 	}
2095 	for (uint32_t i = 0; i < hdr->bth_count; i++) {
2096 		uint8_t *left_child_last = NULL;
2097 		zfs_btree_hdr_t *left_child_hdr = node->btc_children[i];
2098 		if (zfs_btree_is_core(left_child_hdr)) {
2099 			zfs_btree_core_t *left_child =
2100 			    (zfs_btree_core_t *)left_child_hdr;
2101 			left_child_last = left_child->btc_elems +
2102 			    (left_child_hdr->bth_count - 1) * size;
2103 		} else {
2104 			zfs_btree_leaf_t *left_child =
2105 			    (zfs_btree_leaf_t *)left_child_hdr;
2106 			left_child_last = left_child->btl_elems +
2107 			    (left_child_hdr->bth_first +
2108 			    left_child_hdr->bth_count - 1) * size;
2109 		}
2110 		int comp = tree->bt_compar(node->btc_elems + i * size,
2111 		    left_child_last);
2112 		if (comp <= 0) {
2113 			panic("btree: compar returned %d (expected 1) at "
2114 			    "%px %d: compar(%px,  %px)", comp, node, i,
2115 			    node->btc_elems + i * size, left_child_last);
2116 		}
2117 
2118 		uint8_t *right_child_first = NULL;
2119 		zfs_btree_hdr_t *right_child_hdr = node->btc_children[i + 1];
2120 		if (zfs_btree_is_core(right_child_hdr)) {
2121 			zfs_btree_core_t *right_child =
2122 			    (zfs_btree_core_t *)right_child_hdr;
2123 			right_child_first = right_child->btc_elems;
2124 		} else {
2125 			zfs_btree_leaf_t *right_child =
2126 			    (zfs_btree_leaf_t *)right_child_hdr;
2127 			right_child_first = right_child->btl_elems +
2128 			    right_child_hdr->bth_first * size;
2129 		}
2130 		comp = tree->bt_compar(node->btc_elems + i * size,
2131 		    right_child_first);
2132 		if (comp >= 0) {
2133 			panic("btree: compar returned %d (expected -1) at "
2134 			    "%px %d: compar(%px,  %px)", comp, node, i,
2135 			    node->btc_elems + i * size, right_child_first);
2136 		}
2137 	}
2138 	for (uint32_t i = 0; i <= hdr->bth_count; i++)
2139 		zfs_btree_verify_order_helper(tree, node->btc_children[i]);
2140 }
2141 
2142 /* Check that all elements in the tree are in sorted order. */
2143 static void
zfs_btree_verify_order(zfs_btree_t * tree)2144 zfs_btree_verify_order(zfs_btree_t *tree)
2145 {
2146 	EQUIV(tree->bt_height == -1, tree->bt_root == NULL);
2147 	if (tree->bt_height == -1) {
2148 		return;
2149 	}
2150 
2151 	zfs_btree_verify_order_helper(tree, tree->bt_root);
2152 }
2153 
2154 #ifdef ZFS_DEBUG
2155 /* Check that all unused memory is poisoned correctly. */
2156 static void
zfs_btree_verify_poison_helper(zfs_btree_t * tree,zfs_btree_hdr_t * hdr)2157 zfs_btree_verify_poison_helper(zfs_btree_t *tree, zfs_btree_hdr_t *hdr)
2158 {
2159 	size_t size = tree->bt_elem_size;
2160 	if (!zfs_btree_is_core(hdr)) {
2161 		zfs_btree_leaf_t *leaf = (zfs_btree_leaf_t *)hdr;
2162 		for (size_t i = 0; i < hdr->bth_first * size; i++)
2163 			VERIFY3U(leaf->btl_elems[i], ==, 0x0f);
2164 		size_t esize = tree->bt_leaf_size -
2165 		    offsetof(zfs_btree_leaf_t, btl_elems);
2166 		for (size_t i = (hdr->bth_first + hdr->bth_count) * size;
2167 		    i < esize; i++)
2168 			VERIFY3U(leaf->btl_elems[i], ==, 0x0f);
2169 	} else {
2170 		zfs_btree_core_t *node = (zfs_btree_core_t *)hdr;
2171 		for (size_t i = hdr->bth_count * size;
2172 		    i < BTREE_CORE_ELEMS * size; i++)
2173 			VERIFY3U(node->btc_elems[i], ==, 0x0f);
2174 
2175 		for (uint32_t i = hdr->bth_count + 1; i <= BTREE_CORE_ELEMS;
2176 		    i++) {
2177 			VERIFY3P(node->btc_children[i], ==,
2178 			    (zfs_btree_hdr_t *)BTREE_POISON);
2179 		}
2180 
2181 		for (uint32_t i = 0; i <= hdr->bth_count; i++) {
2182 			zfs_btree_verify_poison_helper(tree,
2183 			    node->btc_children[i]);
2184 		}
2185 	}
2186 }
2187 #endif
2188 
2189 /* Check that unused memory in the tree is still poisoned. */
2190 static void
zfs_btree_verify_poison(zfs_btree_t * tree)2191 zfs_btree_verify_poison(zfs_btree_t *tree)
2192 {
2193 #ifdef ZFS_DEBUG
2194 	if (tree->bt_height == -1)
2195 		return;
2196 	zfs_btree_verify_poison_helper(tree, tree->bt_root);
2197 #else
2198 	(void) tree;
2199 #endif
2200 }
2201 
2202 void
zfs_btree_verify(zfs_btree_t * tree)2203 zfs_btree_verify(zfs_btree_t *tree)
2204 {
2205 	if (zfs_btree_verify_intensity == 0)
2206 		return;
2207 	zfs_btree_verify_height(tree);
2208 	if (zfs_btree_verify_intensity == 1)
2209 		return;
2210 	zfs_btree_verify_pointers(tree);
2211 	if (zfs_btree_verify_intensity == 2)
2212 		return;
2213 	zfs_btree_verify_counts(tree);
2214 	if (zfs_btree_verify_intensity == 3)
2215 		return;
2216 	zfs_btree_verify_order(tree);
2217 
2218 	if (zfs_btree_verify_intensity == 4)
2219 		return;
2220 	zfs_btree_verify_poison(tree);
2221 }
2222 
2223 ZFS_MODULE_PARAM(zfs, zfs_, btree_verify_intensity, UINT, ZMOD_RW,
2224 	"Enable btree verification. Levels above 4 require ZFS be built "
2225 	"with debugging");
2226