xref: /freebsd/sys/kern/subr_blist.c (revision f37852c17391fdf0e8309bcf684384dd0d854e43)
1 /*-
2  * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
3  * Redistribution and use in source and binary forms, with or without
4  * modification, are permitted provided that the following conditions
5  * are met:
6  * 1. Redistributions of source code must retain the above copyright
7  *    notice, this list of conditions and the following disclaimer.
8  * 2. Redistributions in binary form must reproduce the above copyright
9  *    notice, this list of conditions and the following disclaimer in the
10  *    documentation and/or other materials provided with the distribution.
11  * 3. Neither the name of the University nor the names of its contributors
12  *    may be used to endorse or promote products derived from this software
13  *    without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
16  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
21  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 /*
28  * BLIST.C -	Bitmap allocator/deallocator, using a radix tree with hinting
29  *
30  *	This module implements a general bitmap allocator/deallocator.  The
31  *	allocator eats around 2 bits per 'block'.  The module does not
32  *	try to interpret the meaning of a 'block' other than to return
33  *	SWAPBLK_NONE on an allocation failure.
34  *
35  *	A radix tree is used to maintain the bitmap.  Two radix constants are
36  *	involved:  One for the bitmaps contained in the leaf nodes (typically
37  *	32), and one for the meta nodes (typically 16).  Both meta and leaf
38  *	nodes have a hint field.  This field gives us a hint as to the largest
39  *	free contiguous range of blocks under the node.  It may contain a
40  *	value that is too high, but will never contain a value that is too
41  *	low.  When the radix tree is searched, allocation failures in subtrees
42  *	update the hint.
43  *
44  *	The radix tree also implements two collapsed states for meta nodes:
45  *	the ALL-ALLOCATED state and the ALL-FREE state.  If a meta node is
46  *	in either of these two states, all information contained underneath
47  *	the node is considered stale.  These states are used to optimize
48  *	allocation and freeing operations.
49  *
50  * 	The hinting greatly increases code efficiency for allocations while
51  *	the general radix structure optimizes both allocations and frees.  The
52  *	radix tree should be able to operate well no matter how much
53  *	fragmentation there is and no matter how large a bitmap is used.
54  *
55  *	The blist code wires all necessary memory at creation time.  Neither
56  *	allocations nor frees require interaction with the memory subsystem.
57  *	The non-blocking features of the blist code are used in the swap code
58  *	(vm/swap_pager.c).
59  *
60  *	LAYOUT: The radix tree is laid out recursively using a
61  *	linear array.  Each meta node is immediately followed (laid out
62  *	sequentially in memory) by BLIST_META_RADIX lower level nodes.  This
63  *	is a recursive structure but one that can be easily scanned through
64  *	a very simple 'skip' calculation.  In order to support large radixes,
65  *	portions of the tree may reside outside our memory allocation.  We
66  *	handle this with an early-termination optimization (when bighint is
67  *	set to -1) on the scan.  The memory allocation is only large enough
68  *	to cover the number of blocks requested at creation time even if it
69  *	must be encompassed in larger root-node radix.
70  *
71  *	NOTE: the allocator cannot currently allocate more than
72  *	BLIST_BMAP_RADIX blocks per call.  It will panic with 'allocation too
73  *	large' if you try.  This is an area that could use improvement.  The
74  *	radix is large enough that this restriction does not effect the swap
75  *	system, though.  Currently only the allocation code is effected by
76  *	this algorithmic unfeature.  The freeing code can handle arbitrary
77  *	ranges.
78  *
79  *	This code can be compiled stand-alone for debugging.
80  */
81 
82 #include <sys/cdefs.h>
83 __FBSDID("$FreeBSD$");
84 
85 #ifdef _KERNEL
86 
87 #include <sys/param.h>
88 #include <sys/systm.h>
89 #include <sys/lock.h>
90 #include <sys/kernel.h>
91 #include <sys/blist.h>
92 #include <sys/malloc.h>
93 #include <sys/proc.h>
94 #include <sys/mutex.h>
95 
96 #else
97 
98 #ifndef BLIST_NO_DEBUG
99 #define BLIST_DEBUG
100 #endif
101 
102 #include <sys/types.h>
103 #include <sys/malloc.h>
104 #include <stdio.h>
105 #include <string.h>
106 #include <stdlib.h>
107 #include <stdarg.h>
108 #include <stdbool.h>
109 
110 #define	bitcount64(x)	__bitcount64((uint64_t)(x))
111 #define malloc(a,b,c)	calloc(a, 1)
112 #define free(a,b)	free(a)
113 
114 #include <sys/blist.h>
115 
116 void panic(const char *ctl, ...);
117 
118 #endif
119 
120 /*
121  * static support functions
122  */
123 
124 static daddr_t	blst_leaf_alloc(blmeta_t *scan, daddr_t blk, int count,
125 		    daddr_t cursor);
126 static daddr_t	blst_meta_alloc(blmeta_t *scan, daddr_t blk, daddr_t count,
127 		    daddr_t radix, daddr_t skip, daddr_t cursor);
128 static void blst_leaf_free(blmeta_t *scan, daddr_t relblk, int count);
129 static void blst_meta_free(blmeta_t *scan, daddr_t freeBlk, daddr_t count,
130 		    daddr_t radix, daddr_t skip, daddr_t blk);
131 static void blst_copy(blmeta_t *scan, daddr_t blk, daddr_t radix,
132 				daddr_t skip, blist_t dest, daddr_t count);
133 static daddr_t blst_leaf_fill(blmeta_t *scan, daddr_t blk, int count);
134 static daddr_t blst_meta_fill(blmeta_t *scan, daddr_t allocBlk, daddr_t count,
135 		    daddr_t radix, daddr_t skip, daddr_t blk);
136 static daddr_t	blst_radix_init(blmeta_t *scan, daddr_t radix, daddr_t skip,
137 		    daddr_t count);
138 #ifndef _KERNEL
139 static void	blst_radix_print(blmeta_t *scan, daddr_t blk, daddr_t radix,
140 		    daddr_t skip, int tab);
141 #endif
142 
143 #ifdef _KERNEL
144 static MALLOC_DEFINE(M_SWAP, "SWAP", "Swap space");
145 #endif
146 
147 /*
148  * blist_create() - create a blist capable of handling up to the specified
149  *		    number of blocks
150  *
151  *	blocks - must be greater than 0
152  * 	flags  - malloc flags
153  *
154  *	The smallest blist consists of a single leaf node capable of
155  *	managing BLIST_BMAP_RADIX blocks.
156  */
157 
158 blist_t
159 blist_create(daddr_t blocks, int flags)
160 {
161 	blist_t bl;
162 	daddr_t nodes, radix, skip;
163 
164 	/*
165 	 * Calculate radix and skip field used for scanning.
166 	 */
167 	radix = BLIST_BMAP_RADIX;
168 	skip = 0;
169 	while (radix < blocks) {
170 		radix *= BLIST_META_RADIX;
171 		skip = (skip + 1) * BLIST_META_RADIX;
172 	}
173 	nodes = 1 + blst_radix_init(NULL, radix, skip, blocks);
174 
175 	bl = malloc(sizeof(struct blist), M_SWAP, flags);
176 	if (bl == NULL)
177 		return (NULL);
178 
179 	bl->bl_blocks = blocks;
180 	bl->bl_radix = radix;
181 	bl->bl_skip = skip;
182 	bl->bl_cursor = 0;
183 	bl->bl_root = malloc(nodes * sizeof(blmeta_t), M_SWAP, flags);
184 	if (bl->bl_root == NULL) {
185 		free(bl, M_SWAP);
186 		return (NULL);
187 	}
188 	blst_radix_init(bl->bl_root, radix, skip, blocks);
189 
190 #if defined(BLIST_DEBUG)
191 	printf(
192 		"BLIST representing %lld blocks (%lld MB of swap)"
193 		", requiring %lldK of ram\n",
194 		(long long)bl->bl_blocks,
195 		(long long)bl->bl_blocks * 4 / 1024,
196 		(long long)(nodes * sizeof(blmeta_t) + 1023) / 1024
197 	);
198 	printf("BLIST raw radix tree contains %lld records\n",
199 	    (long long)nodes);
200 #endif
201 
202 	return (bl);
203 }
204 
205 void
206 blist_destroy(blist_t bl)
207 {
208 	free(bl->bl_root, M_SWAP);
209 	free(bl, M_SWAP);
210 }
211 
212 /*
213  * blist_alloc() -   reserve space in the block bitmap.  Return the base
214  *		     of a contiguous region or SWAPBLK_NONE if space could
215  *		     not be allocated.
216  */
217 
218 daddr_t
219 blist_alloc(blist_t bl, daddr_t count)
220 {
221 	daddr_t blk;
222 
223 	/*
224 	 * This loop iterates at most twice.  An allocation failure in the
225 	 * first iteration leads to a second iteration only if the cursor was
226 	 * non-zero.  When the cursor is zero, an allocation failure will
227 	 * reduce the hint, stopping further iterations.
228 	 */
229 	while (count <= bl->bl_root->bm_bighint) {
230 		if (bl->bl_radix == BLIST_BMAP_RADIX)
231 			blk = blst_leaf_alloc(bl->bl_root, 0, count,
232 			    bl->bl_cursor);
233 		else
234 			blk = blst_meta_alloc(bl->bl_root, 0, count,
235 			    bl->bl_radix, bl->bl_skip, bl->bl_cursor);
236 		if (blk != SWAPBLK_NONE) {
237 			bl->bl_cursor = blk + count;
238 			return (blk);
239 		} else if (bl->bl_cursor != 0)
240 			bl->bl_cursor = 0;
241 	}
242 	return (SWAPBLK_NONE);
243 }
244 
245 /*
246  * blist_avail() -	return the number of free blocks.
247  */
248 
249 daddr_t
250 blist_avail(blist_t bl)
251 {
252 
253 	if (bl->bl_radix == BLIST_BMAP_RADIX)
254 		return (bitcount64(bl->bl_root->u.bmu_bitmap));
255 	else
256 		return (bl->bl_root->u.bmu_avail);
257 }
258 
259 /*
260  * blist_free() -	free up space in the block bitmap.  Return the base
261  *		     	of a contiguous region.  Panic if an inconsistancy is
262  *			found.
263  */
264 
265 void
266 blist_free(blist_t bl, daddr_t blkno, daddr_t count)
267 {
268 	if (bl) {
269 		if (bl->bl_radix == BLIST_BMAP_RADIX)
270 			blst_leaf_free(bl->bl_root, blkno, count);
271 		else
272 			blst_meta_free(bl->bl_root, blkno, count,
273 			    bl->bl_radix, bl->bl_skip, 0);
274 	}
275 }
276 
277 /*
278  * blist_fill() -	mark a region in the block bitmap as off-limits
279  *			to the allocator (i.e. allocate it), ignoring any
280  *			existing allocations.  Return the number of blocks
281  *			actually filled that were free before the call.
282  */
283 
284 daddr_t
285 blist_fill(blist_t bl, daddr_t blkno, daddr_t count)
286 {
287 	daddr_t filled;
288 
289 	if (bl) {
290 		if (bl->bl_radix == BLIST_BMAP_RADIX)
291 			filled = blst_leaf_fill(bl->bl_root, blkno, count);
292 		else
293 			filled = blst_meta_fill(bl->bl_root, blkno, count,
294 			    bl->bl_radix, bl->bl_skip, 0);
295 		return (filled);
296 	}
297 	return (0);
298 }
299 
300 /*
301  * blist_resize() -	resize an existing radix tree to handle the
302  *			specified number of blocks.  This will reallocate
303  *			the tree and transfer the previous bitmap to the new
304  *			one.  When extending the tree you can specify whether
305  *			the new blocks are to left allocated or freed.
306  */
307 
308 void
309 blist_resize(blist_t *pbl, daddr_t count, int freenew, int flags)
310 {
311     blist_t newbl = blist_create(count, flags);
312     blist_t save = *pbl;
313 
314     *pbl = newbl;
315     if (count > save->bl_blocks)
316 	    count = save->bl_blocks;
317     blst_copy(save->bl_root, 0, save->bl_radix, save->bl_skip, newbl, count);
318 
319     /*
320      * If resizing upwards, should we free the new space or not?
321      */
322     if (freenew && count < newbl->bl_blocks) {
323 	    blist_free(newbl, count, newbl->bl_blocks - count);
324     }
325     blist_destroy(save);
326 }
327 
328 #ifdef BLIST_DEBUG
329 
330 /*
331  * blist_print()    - dump radix tree
332  */
333 
334 void
335 blist_print(blist_t bl)
336 {
337 	printf("BLIST {\n");
338 	blst_radix_print(bl->bl_root, 0, bl->bl_radix, bl->bl_skip, 4);
339 	printf("}\n");
340 }
341 
342 #endif
343 
344 /************************************************************************
345  *			  ALLOCATION SUPPORT FUNCTIONS			*
346  ************************************************************************
347  *
348  *	These support functions do all the actual work.  They may seem
349  *	rather longish, but that's because I've commented them up.  The
350  *	actual code is straight forward.
351  *
352  */
353 
354 /*
355  * blist_leaf_alloc() -	allocate at a leaf in the radix tree (a bitmap).
356  *
357  *	This is the core of the allocator and is optimized for the
358  *	BLIST_BMAP_RADIX block allocation case.  Otherwise, execution
359  *	time is proportional to log2(count) + log2(BLIST_BMAP_RADIX).
360  */
361 
362 static daddr_t
363 blst_leaf_alloc(blmeta_t *scan, daddr_t blk, int count, daddr_t cursor)
364 {
365 	u_daddr_t mask;
366 	int count1, hi, lo, mid, num_shifts, range1, range_ext;
367 
368 	if (count == BLIST_BMAP_RADIX) {
369 		/*
370 		 * Optimize allocation of BLIST_BMAP_RADIX bits.  If this wasn't
371 		 * a special case, then forming the final value of 'mask' below
372 		 * would require special handling to avoid an invalid left shift
373 		 * when count equals the number of bits in mask.
374 		 */
375 		if (~scan->u.bmu_bitmap != 0) {
376 			scan->bm_bighint = BLIST_BMAP_RADIX - 1;
377 			return (SWAPBLK_NONE);
378 		}
379 		if (cursor != blk)
380 			return (SWAPBLK_NONE);
381 		scan->u.bmu_bitmap = 0;
382 		scan->bm_bighint = 0;
383 		return (blk);
384 	}
385 	range1 = 0;
386 	count1 = count - 1;
387 	num_shifts = fls(count1);
388 	mask = scan->u.bmu_bitmap;
389 	while (mask != 0 && num_shifts > 0) {
390 		/*
391 		 * If bit i is set in mask, then bits in [i, i+range1] are set
392 		 * in scan->u.bmu_bitmap.  The value of range1 is equal to
393 		 * count1 >> num_shifts.  Grow range and reduce num_shifts to 0,
394 		 * while preserving these invariants.  The updates to mask leave
395 		 * fewer bits set, but each bit that remains set represents a
396 		 * longer string of consecutive bits set in scan->u.bmu_bitmap.
397 		 */
398 		num_shifts--;
399 		range_ext = range1 + ((count1 >> num_shifts) & 1);
400 		mask &= mask >> range_ext;
401 		range1 += range_ext;
402 	}
403 	if (mask == 0) {
404 		/*
405 		 * Update bighint.  There is no allocation bigger than range1
406 		 * available in this leaf.
407 		 */
408 		scan->bm_bighint = range1;
409 		return (SWAPBLK_NONE);
410 	}
411 
412 	/*
413 	 * Discard any candidates that appear before the cursor.
414 	 */
415 	lo = cursor - blk;
416 	mask &= ~(u_daddr_t)0 << lo;
417 
418 	if (mask == 0)
419 		return (SWAPBLK_NONE);
420 
421 	/*
422 	 * The least significant set bit in mask marks the start of the first
423 	 * available range of sufficient size.  Clear all the bits but that one,
424 	 * and then perform a binary search to find its position.
425 	 */
426 	mask &= -mask;
427 	hi = BLIST_BMAP_RADIX - count1;
428 	while (lo + 1 < hi) {
429 		mid = (lo + hi) >> 1;
430 		if ((mask >> mid) != 0)
431 			lo = mid;
432 		else
433 			hi = mid;
434 	}
435 
436 	/*
437 	 * Set in mask exactly the bits being allocated, and clear them from
438 	 * the set of available bits.
439 	 */
440 	mask = (mask << count) - mask;
441 	scan->u.bmu_bitmap &= ~mask;
442 	return (blk + lo);
443 }
444 
445 /*
446  * blist_meta_alloc() -	allocate at a meta in the radix tree.
447  *
448  *	Attempt to allocate at a meta node.  If we can't, we update
449  *	bighint and return a failure.  Updating bighint optimize future
450  *	calls that hit this node.  We have to check for our collapse cases
451  *	and we have a few optimizations strewn in as well.
452  */
453 
454 static daddr_t
455 blst_meta_alloc(blmeta_t *scan, daddr_t blk, daddr_t count, daddr_t radix,
456     daddr_t skip, daddr_t cursor)
457 {
458 	daddr_t i, next_skip, r;
459 	int child;
460 	bool scan_from_start;
461 
462 	if (scan->u.bmu_avail < count) {
463 		/*
464 		 * The meta node's hint must be too large if the allocation
465 		 * exceeds the number of free blocks.  Reduce the hint, and
466 		 * return failure.
467 		 */
468 		scan->bm_bighint = scan->u.bmu_avail;
469 		return (SWAPBLK_NONE);
470 	}
471 	next_skip = skip / BLIST_META_RADIX;
472 
473 	/*
474 	 * An ALL-FREE meta node requires special handling before allocating
475 	 * any of its blocks.
476 	 */
477 	if (scan->u.bmu_avail == radix) {
478 		radix /= BLIST_META_RADIX;
479 
480 		/*
481 		 * Reinitialize each of the meta node's children.  An ALL-FREE
482 		 * meta node cannot have a terminator in any subtree.
483 		 */
484 		for (i = 1; i <= skip; i += next_skip) {
485 			if (next_skip == 1)
486 				scan[i].u.bmu_bitmap = (u_daddr_t)-1;
487 			else
488 				scan[i].u.bmu_avail = radix;
489 			scan[i].bm_bighint = radix;
490 		}
491 	} else {
492 		radix /= BLIST_META_RADIX;
493 	}
494 
495 	if (count > radix) {
496 		/*
497 		 * The allocation exceeds the number of blocks that are
498 		 * managed by a subtree of this meta node.
499 		 */
500 		panic("allocation too large");
501 	}
502 	scan_from_start = cursor == blk;
503 	child = (cursor - blk) / radix;
504 	blk += child * radix;
505 	for (i = 1 + child * next_skip; i <= skip; i += next_skip) {
506 		if (count <= scan[i].bm_bighint) {
507 			/*
508 			 * The allocation might fit in the i'th subtree.
509 			 */
510 			if (next_skip == 1) {
511 				r = blst_leaf_alloc(&scan[i], blk, count,
512 				    cursor > blk ? cursor : blk);
513 			} else {
514 				r = blst_meta_alloc(&scan[i], blk, count,
515 				    radix, next_skip - 1, cursor > blk ?
516 				    cursor : blk);
517 			}
518 			if (r != SWAPBLK_NONE) {
519 				scan->u.bmu_avail -= count;
520 				return (r);
521 			}
522 		} else if (scan[i].bm_bighint == (daddr_t)-1) {
523 			/*
524 			 * Terminator
525 			 */
526 			break;
527 		}
528 		blk += radix;
529 	}
530 
531 	/*
532 	 * We couldn't allocate count in this subtree, update bighint.
533 	 */
534 	if (scan_from_start && scan->bm_bighint >= count)
535 		scan->bm_bighint = count - 1;
536 
537 	return (SWAPBLK_NONE);
538 }
539 
540 /*
541  * BLST_LEAF_FREE() -	free allocated block from leaf bitmap
542  *
543  */
544 
545 static void
546 blst_leaf_free(
547 	blmeta_t *scan,
548 	daddr_t blk,
549 	int count
550 ) {
551 	/*
552 	 * free some data in this bitmap
553 	 *
554 	 * e.g.
555 	 *	0000111111111110000
556 	 *          \_________/\__/
557 	 *		v        n
558 	 */
559 	int n = blk & (BLIST_BMAP_RADIX - 1);
560 	u_daddr_t mask;
561 
562 	mask = ((u_daddr_t)-1 << n) &
563 	    ((u_daddr_t)-1 >> (BLIST_BMAP_RADIX - count - n));
564 
565 	if (scan->u.bmu_bitmap & mask)
566 		panic("blst_radix_free: freeing free block");
567 	scan->u.bmu_bitmap |= mask;
568 
569 	/*
570 	 * We could probably do a better job here.  We are required to make
571 	 * bighint at least as large as the biggest contiguous block of
572 	 * data.  If we just shoehorn it, a little extra overhead will
573 	 * be incured on the next allocation (but only that one typically).
574 	 */
575 	scan->bm_bighint = BLIST_BMAP_RADIX;
576 }
577 
578 /*
579  * BLST_META_FREE() - free allocated blocks from radix tree meta info
580  *
581  *	This support routine frees a range of blocks from the bitmap.
582  *	The range must be entirely enclosed by this radix node.  If a
583  *	meta node, we break the range down recursively to free blocks
584  *	in subnodes (which means that this code can free an arbitrary
585  *	range whereas the allocation code cannot allocate an arbitrary
586  *	range).
587  */
588 
589 static void
590 blst_meta_free(blmeta_t *scan, daddr_t freeBlk, daddr_t count, daddr_t radix,
591     daddr_t skip, daddr_t blk)
592 {
593 	daddr_t i, next_skip, v;
594 	int child;
595 
596 #if 0
597 	printf("free (%llx,%lld) FROM (%llx,%lld)\n",
598 	    (long long)freeBlk, (long long)count,
599 	    (long long)blk, (long long)radix
600 	);
601 #endif
602 	next_skip = skip / BLIST_META_RADIX;
603 
604 	if (scan->u.bmu_avail == 0) {
605 		/*
606 		 * ALL-ALLOCATED special case, with possible
607 		 * shortcut to ALL-FREE special case.
608 		 */
609 		scan->u.bmu_avail = count;
610 		scan->bm_bighint = count;
611 
612 		if (count != radix)  {
613 			for (i = 1; i <= skip; i += next_skip) {
614 				if (scan[i].bm_bighint == (daddr_t)-1)
615 					break;
616 				scan[i].bm_bighint = 0;
617 				if (next_skip == 1) {
618 					scan[i].u.bmu_bitmap = 0;
619 				} else {
620 					scan[i].u.bmu_avail = 0;
621 				}
622 			}
623 			/* fall through */
624 		}
625 	} else {
626 		scan->u.bmu_avail += count;
627 		/* scan->bm_bighint = radix; */
628 	}
629 
630 	/*
631 	 * ALL-FREE special case.
632 	 */
633 
634 	if (scan->u.bmu_avail == radix)
635 		return;
636 	if (scan->u.bmu_avail > radix)
637 		panic("blst_meta_free: freeing already free blocks (%lld) %lld/%lld",
638 		    (long long)count, (long long)scan->u.bmu_avail,
639 		    (long long)radix);
640 
641 	/*
642 	 * Break the free down into its components
643 	 */
644 
645 	radix /= BLIST_META_RADIX;
646 
647 	child = (freeBlk - blk) / radix;
648 	blk += child * radix;
649 	i = 1 + child * next_skip;
650 	while (i <= skip && blk < freeBlk + count) {
651 		v = blk + radix - freeBlk;
652 		if (v > count)
653 			v = count;
654 
655 		if (scan->bm_bighint == (daddr_t)-1)
656 			panic("blst_meta_free: freeing unexpected range");
657 
658 		if (next_skip == 1) {
659 			blst_leaf_free(&scan[i], freeBlk, v);
660 		} else {
661 			blst_meta_free(&scan[i], freeBlk, v, radix, next_skip - 1, blk);
662 		}
663 		if (scan->bm_bighint < scan[i].bm_bighint)
664 		    scan->bm_bighint = scan[i].bm_bighint;
665 		count -= v;
666 		freeBlk += v;
667 		blk += radix;
668 		i += next_skip;
669 	}
670 }
671 
672 /*
673  * BLIST_RADIX_COPY() - copy one radix tree to another
674  *
675  *	Locates free space in the source tree and frees it in the destination
676  *	tree.  The space may not already be free in the destination.
677  */
678 
679 static void blst_copy(
680 	blmeta_t *scan,
681 	daddr_t blk,
682 	daddr_t radix,
683 	daddr_t skip,
684 	blist_t dest,
685 	daddr_t count
686 ) {
687 	daddr_t i, next_skip;
688 
689 	/*
690 	 * Leaf node
691 	 */
692 
693 	if (radix == BLIST_BMAP_RADIX) {
694 		u_daddr_t v = scan->u.bmu_bitmap;
695 
696 		if (v == (u_daddr_t)-1) {
697 			blist_free(dest, blk, count);
698 		} else if (v != 0) {
699 			int i;
700 
701 			for (i = 0; i < BLIST_BMAP_RADIX && i < count; ++i) {
702 				if (v & ((u_daddr_t)1 << i))
703 					blist_free(dest, blk + i, 1);
704 			}
705 		}
706 		return;
707 	}
708 
709 	/*
710 	 * Meta node
711 	 */
712 
713 	if (scan->u.bmu_avail == 0) {
714 		/*
715 		 * Source all allocated, leave dest allocated
716 		 */
717 		return;
718 	}
719 	if (scan->u.bmu_avail == radix) {
720 		/*
721 		 * Source all free, free entire dest
722 		 */
723 		if (count < radix)
724 			blist_free(dest, blk, count);
725 		else
726 			blist_free(dest, blk, radix);
727 		return;
728 	}
729 
730 
731 	radix /= BLIST_META_RADIX;
732 	next_skip = skip / BLIST_META_RADIX;
733 
734 	for (i = 1; count && i <= skip; i += next_skip) {
735 		if (scan[i].bm_bighint == (daddr_t)-1)
736 			break;
737 
738 		if (count >= radix) {
739 			blst_copy(
740 			    &scan[i],
741 			    blk,
742 			    radix,
743 			    next_skip - 1,
744 			    dest,
745 			    radix
746 			);
747 			count -= radix;
748 		} else {
749 			if (count) {
750 				blst_copy(
751 				    &scan[i],
752 				    blk,
753 				    radix,
754 				    next_skip - 1,
755 				    dest,
756 				    count
757 				);
758 			}
759 			count = 0;
760 		}
761 		blk += radix;
762 	}
763 }
764 
765 /*
766  * BLST_LEAF_FILL() -	allocate specific blocks in leaf bitmap
767  *
768  *	This routine allocates all blocks in the specified range
769  *	regardless of any existing allocations in that range.  Returns
770  *	the number of blocks allocated by the call.
771  */
772 
773 static daddr_t
774 blst_leaf_fill(blmeta_t *scan, daddr_t blk, int count)
775 {
776 	int n = blk & (BLIST_BMAP_RADIX - 1);
777 	daddr_t nblks;
778 	u_daddr_t mask;
779 
780 	mask = ((u_daddr_t)-1 << n) &
781 	    ((u_daddr_t)-1 >> (BLIST_BMAP_RADIX - count - n));
782 
783 	/* Count the number of blocks that we are allocating. */
784 	nblks = bitcount64(scan->u.bmu_bitmap & mask);
785 
786 	scan->u.bmu_bitmap &= ~mask;
787 	return (nblks);
788 }
789 
790 /*
791  * BLIST_META_FILL() -	allocate specific blocks at a meta node
792  *
793  *	This routine allocates the specified range of blocks,
794  *	regardless of any existing allocations in the range.  The
795  *	range must be within the extent of this node.  Returns the
796  *	number of blocks allocated by the call.
797  */
798 static daddr_t
799 blst_meta_fill(blmeta_t *scan, daddr_t allocBlk, daddr_t count, daddr_t radix,
800     daddr_t skip, daddr_t blk)
801 {
802 	daddr_t i, nblks, next_skip, v;
803 	int child;
804 
805 	if (count > radix) {
806 		/*
807 		 * The allocation exceeds the number of blocks that are
808 		 * managed by this meta node.
809 		 */
810 		panic("allocation too large");
811 	}
812 	if (count == radix || scan->u.bmu_avail == 0)  {
813 		/*
814 		 * ALL-ALLOCATED special case
815 		 */
816 		nblks = scan->u.bmu_avail;
817 		scan->u.bmu_avail = 0;
818 		scan->bm_bighint = 0;
819 		return nblks;
820 	}
821 	next_skip = skip / BLIST_META_RADIX;
822 
823 	/*
824 	 * An ALL-FREE meta node requires special handling before allocating
825 	 * any of its blocks.
826 	 */
827 	if (scan->u.bmu_avail == radix) {
828 		radix /= BLIST_META_RADIX;
829 
830 		/*
831 		 * Reinitialize each of the meta node's children.  An ALL-FREE
832 		 * meta node cannot have a terminator in any subtree.
833 		 */
834 		for (i = 1; i <= skip; i += next_skip) {
835 			if (next_skip == 1) {
836 				scan[i].u.bmu_bitmap = (u_daddr_t)-1;
837 				scan[i].bm_bighint = BLIST_BMAP_RADIX;
838 			} else {
839 				scan[i].bm_bighint = radix;
840 				scan[i].u.bmu_avail = radix;
841 			}
842 		}
843 	} else {
844 		radix /= BLIST_META_RADIX;
845 	}
846 
847 	nblks = 0;
848 	child = (allocBlk - blk) / radix;
849 	blk += child * radix;
850 	i = 1 + child * next_skip;
851 	while (i <= skip && blk < allocBlk + count) {
852 		v = blk + radix - allocBlk;
853 		if (v > count)
854 			v = count;
855 
856 		if (scan->bm_bighint == (daddr_t)-1)
857 			panic("blst_meta_fill: filling unexpected range");
858 
859 		if (next_skip == 1) {
860 			nblks += blst_leaf_fill(&scan[i], allocBlk, v);
861 		} else {
862 			nblks += blst_meta_fill(&scan[i], allocBlk, v,
863 			    radix, next_skip - 1, blk);
864 		}
865 		count -= v;
866 		allocBlk += v;
867 		blk += radix;
868 		i += next_skip;
869 	}
870 	scan->u.bmu_avail -= nblks;
871 	return nblks;
872 }
873 
874 /*
875  * BLST_RADIX_INIT() - initialize radix tree
876  *
877  *	Initialize our meta structures and bitmaps and calculate the exact
878  *	amount of space required to manage 'count' blocks - this space may
879  *	be considerably less than the calculated radix due to the large
880  *	RADIX values we use.
881  */
882 
883 static daddr_t
884 blst_radix_init(blmeta_t *scan, daddr_t radix, daddr_t skip, daddr_t count)
885 {
886 	daddr_t i, memindex, next_skip;
887 
888 	memindex = 0;
889 
890 	/*
891 	 * Leaf node
892 	 */
893 
894 	if (radix == BLIST_BMAP_RADIX) {
895 		if (scan) {
896 			scan->bm_bighint = 0;
897 			scan->u.bmu_bitmap = 0;
898 		}
899 		return(memindex);
900 	}
901 
902 	/*
903 	 * Meta node.  If allocating the entire object we can special
904 	 * case it.  However, we need to figure out how much memory
905 	 * is required to manage 'count' blocks, so we continue on anyway.
906 	 */
907 
908 	if (scan) {
909 		scan->bm_bighint = 0;
910 		scan->u.bmu_avail = 0;
911 	}
912 
913 	radix /= BLIST_META_RADIX;
914 	next_skip = skip / BLIST_META_RADIX;
915 
916 	for (i = 1; i <= skip; i += next_skip) {
917 		if (count >= radix) {
918 			/*
919 			 * Allocate the entire object
920 			 */
921 			memindex = i + blst_radix_init(
922 			    ((scan) ? &scan[i] : NULL),
923 			    radix,
924 			    next_skip - 1,
925 			    radix
926 			);
927 			count -= radix;
928 		} else if (count > 0) {
929 			/*
930 			 * Allocate a partial object
931 			 */
932 			memindex = i + blst_radix_init(
933 			    ((scan) ? &scan[i] : NULL),
934 			    radix,
935 			    next_skip - 1,
936 			    count
937 			);
938 			count = 0;
939 		} else {
940 			/*
941 			 * Add terminator and break out
942 			 */
943 			if (scan)
944 				scan[i].bm_bighint = (daddr_t)-1;
945 			break;
946 		}
947 	}
948 	if (memindex < i)
949 		memindex = i;
950 	return(memindex);
951 }
952 
953 #ifdef BLIST_DEBUG
954 
955 static void
956 blst_radix_print(blmeta_t *scan, daddr_t blk, daddr_t radix, daddr_t skip,
957     int tab)
958 {
959 	daddr_t i, next_skip;
960 
961 	if (radix == BLIST_BMAP_RADIX) {
962 		printf(
963 		    "%*.*s(%08llx,%lld): bitmap %016llx big=%lld\n",
964 		    tab, tab, "",
965 		    (long long)blk, (long long)radix,
966 		    (long long)scan->u.bmu_bitmap,
967 		    (long long)scan->bm_bighint
968 		);
969 		return;
970 	}
971 
972 	if (scan->u.bmu_avail == 0) {
973 		printf(
974 		    "%*.*s(%08llx,%lld) ALL ALLOCATED\n",
975 		    tab, tab, "",
976 		    (long long)blk,
977 		    (long long)radix
978 		);
979 		return;
980 	}
981 	if (scan->u.bmu_avail == radix) {
982 		printf(
983 		    "%*.*s(%08llx,%lld) ALL FREE\n",
984 		    tab, tab, "",
985 		    (long long)blk,
986 		    (long long)radix
987 		);
988 		return;
989 	}
990 
991 	printf(
992 	    "%*.*s(%08llx,%lld): subtree (%lld/%lld) big=%lld {\n",
993 	    tab, tab, "",
994 	    (long long)blk, (long long)radix,
995 	    (long long)scan->u.bmu_avail,
996 	    (long long)radix,
997 	    (long long)scan->bm_bighint
998 	);
999 
1000 	radix /= BLIST_META_RADIX;
1001 	next_skip = skip / BLIST_META_RADIX;
1002 	tab += 4;
1003 
1004 	for (i = 1; i <= skip; i += next_skip) {
1005 		if (scan[i].bm_bighint == (daddr_t)-1) {
1006 			printf(
1007 			    "%*.*s(%08llx,%lld): Terminator\n",
1008 			    tab, tab, "",
1009 			    (long long)blk, (long long)radix
1010 			);
1011 			break;
1012 		}
1013 		blst_radix_print(
1014 		    &scan[i],
1015 		    blk,
1016 		    radix,
1017 		    next_skip - 1,
1018 		    tab
1019 		);
1020 		blk += radix;
1021 	}
1022 	tab -= 4;
1023 
1024 	printf(
1025 	    "%*.*s}\n",
1026 	    tab, tab, ""
1027 	);
1028 }
1029 
1030 #endif
1031 
1032 #ifdef BLIST_DEBUG
1033 
1034 int
1035 main(int ac, char **av)
1036 {
1037 	int size = 1024;
1038 	int i;
1039 	blist_t bl;
1040 
1041 	for (i = 1; i < ac; ++i) {
1042 		const char *ptr = av[i];
1043 		if (*ptr != '-') {
1044 			size = strtol(ptr, NULL, 0);
1045 			continue;
1046 		}
1047 		ptr += 2;
1048 		fprintf(stderr, "Bad option: %s\n", ptr - 2);
1049 		exit(1);
1050 	}
1051 	bl = blist_create(size, M_WAITOK);
1052 	blist_free(bl, 0, size);
1053 
1054 	for (;;) {
1055 		char buf[1024];
1056 		long long da = 0;
1057 		long long count = 0;
1058 
1059 		printf("%lld/%lld/%lld> ", (long long)blist_avail(bl),
1060 		    (long long)size, (long long)bl->bl_radix);
1061 		fflush(stdout);
1062 		if (fgets(buf, sizeof(buf), stdin) == NULL)
1063 			break;
1064 		switch(buf[0]) {
1065 		case 'r':
1066 			if (sscanf(buf + 1, "%lld", &count) == 1) {
1067 				blist_resize(&bl, count, 1, M_WAITOK);
1068 			} else {
1069 				printf("?\n");
1070 			}
1071 		case 'p':
1072 			blist_print(bl);
1073 			break;
1074 		case 'a':
1075 			if (sscanf(buf + 1, "%lld", &count) == 1) {
1076 				daddr_t blk = blist_alloc(bl, count);
1077 				printf("    R=%08llx\n", (long long)blk);
1078 			} else {
1079 				printf("?\n");
1080 			}
1081 			break;
1082 		case 'f':
1083 			if (sscanf(buf + 1, "%llx %lld", &da, &count) == 2) {
1084 				blist_free(bl, da, count);
1085 			} else {
1086 				printf("?\n");
1087 			}
1088 			break;
1089 		case 'l':
1090 			if (sscanf(buf + 1, "%llx %lld", &da, &count) == 2) {
1091 				printf("    n=%jd\n",
1092 				    (intmax_t)blist_fill(bl, da, count));
1093 			} else {
1094 				printf("?\n");
1095 			}
1096 			break;
1097 		case '?':
1098 		case 'h':
1099 			puts(
1100 			    "p          -print\n"
1101 			    "a %d       -allocate\n"
1102 			    "f %x %d    -free\n"
1103 			    "l %x %d    -fill\n"
1104 			    "r %d       -resize\n"
1105 			    "h/?        -help"
1106 			);
1107 			break;
1108 		default:
1109 			printf("?\n");
1110 			break;
1111 		}
1112 	}
1113 	return(0);
1114 }
1115 
1116 void
1117 panic(const char *ctl, ...)
1118 {
1119 	va_list va;
1120 
1121 	va_start(va, ctl);
1122 	vfprintf(stderr, ctl, va);
1123 	fprintf(stderr, "\n");
1124 	va_end(va);
1125 	exit(1);
1126 }
1127 
1128 #endif
1129 
1130