xref: /freebsd/sys/kern/subr_blist.c (revision d6b92ffa)
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  *	64), 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 affected 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 static daddr_t	blst_leaf_alloc(blmeta_t *scan, daddr_t blk, int count,
124 		    daddr_t cursor);
125 static daddr_t	blst_meta_alloc(blmeta_t *scan, daddr_t blk, daddr_t count,
126 		    daddr_t radix, daddr_t skip, daddr_t cursor);
127 static void blst_leaf_free(blmeta_t *scan, daddr_t relblk, int count);
128 static void blst_meta_free(blmeta_t *scan, daddr_t freeBlk, daddr_t count,
129 		    daddr_t radix, daddr_t skip, daddr_t blk);
130 static void blst_copy(blmeta_t *scan, daddr_t blk, daddr_t radix,
131 		    daddr_t skip, blist_t dest, daddr_t count);
132 static daddr_t blst_leaf_fill(blmeta_t *scan, daddr_t blk, int count);
133 static daddr_t blst_meta_fill(blmeta_t *scan, daddr_t allocBlk, daddr_t count,
134 		    daddr_t radix, daddr_t skip, daddr_t blk);
135 static daddr_t	blst_radix_init(blmeta_t *scan, daddr_t radix, daddr_t skip,
136 		    daddr_t count);
137 #ifndef _KERNEL
138 static void	blst_radix_print(blmeta_t *scan, daddr_t blk, daddr_t radix,
139 		    daddr_t skip, int tab);
140 #endif
141 
142 #ifdef _KERNEL
143 static MALLOC_DEFINE(M_SWAP, "SWAP", "Swap space");
144 #endif
145 
146 /*
147  * blist_create() - create a blist capable of handling up to the specified
148  *		    number of blocks
149  *
150  *	blocks - must be greater than 0
151  * 	flags  - malloc flags
152  *
153  *	The smallest blist consists of a single leaf node capable of
154  *	managing BLIST_BMAP_RADIX blocks.
155  */
156 blist_t
157 blist_create(daddr_t blocks, int flags)
158 {
159 	blist_t bl;
160 	daddr_t nodes, radix, skip;
161 
162 	/*
163 	 * Calculate radix and skip field used for scanning.
164 	 */
165 	radix = BLIST_BMAP_RADIX;
166 	skip = 0;
167 	while (radix < blocks) {
168 		radix *= BLIST_META_RADIX;
169 		skip = (skip + 1) * BLIST_META_RADIX;
170 	}
171 	nodes = 1 + blst_radix_init(NULL, radix, skip, blocks);
172 
173 	bl = malloc(sizeof(struct blist), M_SWAP, flags);
174 	if (bl == NULL)
175 		return (NULL);
176 
177 	bl->bl_blocks = blocks;
178 	bl->bl_radix = radix;
179 	bl->bl_skip = skip;
180 	bl->bl_cursor = 0;
181 	bl->bl_root = malloc(nodes * sizeof(blmeta_t), M_SWAP, flags);
182 	if (bl->bl_root == NULL) {
183 		free(bl, M_SWAP);
184 		return (NULL);
185 	}
186 	blst_radix_init(bl->bl_root, radix, skip, blocks);
187 
188 #if defined(BLIST_DEBUG)
189 	printf(
190 		"BLIST representing %lld blocks (%lld MB of swap)"
191 		", requiring %lldK of ram\n",
192 		(long long)bl->bl_blocks,
193 		(long long)bl->bl_blocks * 4 / 1024,
194 		(long long)(nodes * sizeof(blmeta_t) + 1023) / 1024
195 	);
196 	printf("BLIST raw radix tree contains %lld records\n",
197 	    (long long)nodes);
198 #endif
199 
200 	return (bl);
201 }
202 
203 void
204 blist_destroy(blist_t bl)
205 {
206 	free(bl->bl_root, M_SWAP);
207 	free(bl, M_SWAP);
208 }
209 
210 /*
211  * blist_alloc() -   reserve space in the block bitmap.  Return the base
212  *		     of a contiguous region or SWAPBLK_NONE if space could
213  *		     not be allocated.
214  */
215 daddr_t
216 blist_alloc(blist_t bl, daddr_t count)
217 {
218 	daddr_t blk;
219 
220 	/*
221 	 * This loop iterates at most twice.  An allocation failure in the
222 	 * first iteration leads to a second iteration only if the cursor was
223 	 * non-zero.  When the cursor is zero, an allocation failure will
224 	 * reduce the hint, stopping further iterations.
225 	 */
226 	while (count <= bl->bl_root->bm_bighint) {
227 		if (bl->bl_radix == BLIST_BMAP_RADIX)
228 			blk = blst_leaf_alloc(bl->bl_root, 0, count,
229 			    bl->bl_cursor);
230 		else
231 			blk = blst_meta_alloc(bl->bl_root, 0, count,
232 			    bl->bl_radix, bl->bl_skip, bl->bl_cursor);
233 		if (blk != SWAPBLK_NONE) {
234 			bl->bl_cursor = blk + count;
235 			return (blk);
236 		} else if (bl->bl_cursor != 0)
237 			bl->bl_cursor = 0;
238 	}
239 	return (SWAPBLK_NONE);
240 }
241 
242 /*
243  * blist_avail() -	return the number of free blocks.
244  */
245 daddr_t
246 blist_avail(blist_t bl)
247 {
248 
249 	if (bl->bl_radix == BLIST_BMAP_RADIX)
250 		return (bitcount64(bl->bl_root->u.bmu_bitmap));
251 	else
252 		return (bl->bl_root->u.bmu_avail);
253 }
254 
255 /*
256  * blist_free() -	free up space in the block bitmap.  Return the base
257  *		     	of a contiguous region.  Panic if an inconsistancy is
258  *			found.
259  */
260 void
261 blist_free(blist_t bl, daddr_t blkno, daddr_t count)
262 {
263 	if (bl) {
264 		if (bl->bl_radix == BLIST_BMAP_RADIX)
265 			blst_leaf_free(bl->bl_root, blkno, count);
266 		else
267 			blst_meta_free(bl->bl_root, blkno, count,
268 			    bl->bl_radix, bl->bl_skip, 0);
269 	}
270 }
271 
272 /*
273  * blist_fill() -	mark a region in the block bitmap as off-limits
274  *			to the allocator (i.e. allocate it), ignoring any
275  *			existing allocations.  Return the number of blocks
276  *			actually filled that were free before the call.
277  */
278 daddr_t
279 blist_fill(blist_t bl, daddr_t blkno, daddr_t count)
280 {
281 	daddr_t filled;
282 
283 	if (bl) {
284 		if (bl->bl_radix == BLIST_BMAP_RADIX)
285 			filled = blst_leaf_fill(bl->bl_root, blkno, count);
286 		else
287 			filled = blst_meta_fill(bl->bl_root, blkno, count,
288 			    bl->bl_radix, bl->bl_skip, 0);
289 		return (filled);
290 	}
291 	return (0);
292 }
293 
294 /*
295  * blist_resize() -	resize an existing radix tree to handle the
296  *			specified number of blocks.  This will reallocate
297  *			the tree and transfer the previous bitmap to the new
298  *			one.  When extending the tree you can specify whether
299  *			the new blocks are to left allocated or freed.
300  */
301 void
302 blist_resize(blist_t *pbl, daddr_t count, int freenew, int flags)
303 {
304     blist_t newbl = blist_create(count, flags);
305     blist_t save = *pbl;
306 
307     *pbl = newbl;
308     if (count > save->bl_blocks)
309 	    count = save->bl_blocks;
310     blst_copy(save->bl_root, 0, save->bl_radix, save->bl_skip, newbl, count);
311 
312     /*
313      * If resizing upwards, should we free the new space or not?
314      */
315     if (freenew && count < newbl->bl_blocks) {
316 	    blist_free(newbl, count, newbl->bl_blocks - count);
317     }
318     blist_destroy(save);
319 }
320 
321 #ifdef BLIST_DEBUG
322 
323 /*
324  * blist_print()    - dump radix tree
325  */
326 void
327 blist_print(blist_t bl)
328 {
329 	printf("BLIST {\n");
330 	blst_radix_print(bl->bl_root, 0, bl->bl_radix, bl->bl_skip, 4);
331 	printf("}\n");
332 }
333 
334 #endif
335 
336 /************************************************************************
337  *			  ALLOCATION SUPPORT FUNCTIONS			*
338  ************************************************************************
339  *
340  *	These support functions do all the actual work.  They may seem
341  *	rather longish, but that's because I've commented them up.  The
342  *	actual code is straight forward.
343  *
344  */
345 
346 /*
347  * blist_leaf_alloc() -	allocate at a leaf in the radix tree (a bitmap).
348  *
349  *	This is the core of the allocator and is optimized for the
350  *	BLIST_BMAP_RADIX block allocation case.  Otherwise, execution
351  *	time is proportional to log2(count) + log2(BLIST_BMAP_RADIX).
352  */
353 static daddr_t
354 blst_leaf_alloc(blmeta_t *scan, daddr_t blk, int count, daddr_t cursor)
355 {
356 	u_daddr_t mask;
357 	int count1, hi, lo, mid, num_shifts, range1, range_ext;
358 
359 	if (count == BLIST_BMAP_RADIX) {
360 		/*
361 		 * Optimize allocation of BLIST_BMAP_RADIX bits.  If this wasn't
362 		 * a special case, then forming the final value of 'mask' below
363 		 * would require special handling to avoid an invalid left shift
364 		 * when count equals the number of bits in mask.
365 		 */
366 		if (~scan->u.bmu_bitmap != 0) {
367 			scan->bm_bighint = BLIST_BMAP_RADIX - 1;
368 			return (SWAPBLK_NONE);
369 		}
370 		if (cursor != blk)
371 			return (SWAPBLK_NONE);
372 		scan->u.bmu_bitmap = 0;
373 		scan->bm_bighint = 0;
374 		return (blk);
375 	}
376 	range1 = 0;
377 	count1 = count - 1;
378 	num_shifts = fls(count1);
379 	mask = scan->u.bmu_bitmap;
380 	while (mask != 0 && num_shifts > 0) {
381 		/*
382 		 * If bit i is set in mask, then bits in [i, i+range1] are set
383 		 * in scan->u.bmu_bitmap.  The value of range1 is equal to
384 		 * count1 >> num_shifts.  Grow range and reduce num_shifts to 0,
385 		 * while preserving these invariants.  The updates to mask leave
386 		 * fewer bits set, but each bit that remains set represents a
387 		 * longer string of consecutive bits set in scan->u.bmu_bitmap.
388 		 */
389 		num_shifts--;
390 		range_ext = range1 + ((count1 >> num_shifts) & 1);
391 		mask &= mask >> range_ext;
392 		range1 += range_ext;
393 	}
394 	if (mask == 0) {
395 		/*
396 		 * Update bighint.  There is no allocation bigger than range1
397 		 * available in this leaf.
398 		 */
399 		scan->bm_bighint = range1;
400 		return (SWAPBLK_NONE);
401 	}
402 
403 	/*
404 	 * Discard any candidates that appear before the cursor.
405 	 */
406 	lo = cursor - blk;
407 	mask &= ~(u_daddr_t)0 << lo;
408 
409 	if (mask == 0)
410 		return (SWAPBLK_NONE);
411 
412 	/*
413 	 * The least significant set bit in mask marks the start of the first
414 	 * available range of sufficient size.  Clear all the bits but that one,
415 	 * and then perform a binary search to find its position.
416 	 */
417 	mask &= -mask;
418 	hi = BLIST_BMAP_RADIX - count1;
419 	while (lo + 1 < hi) {
420 		mid = (lo + hi) >> 1;
421 		if ((mask >> mid) != 0)
422 			lo = mid;
423 		else
424 			hi = mid;
425 	}
426 
427 	/*
428 	 * Set in mask exactly the bits being allocated, and clear them from
429 	 * the set of available bits.
430 	 */
431 	mask = (mask << count) - mask;
432 	scan->u.bmu_bitmap &= ~mask;
433 	return (blk + lo);
434 }
435 
436 /*
437  * blist_meta_alloc() -	allocate at a meta in the radix tree.
438  *
439  *	Attempt to allocate at a meta node.  If we can't, we update
440  *	bighint and return a failure.  Updating bighint optimize future
441  *	calls that hit this node.  We have to check for our collapse cases
442  *	and we have a few optimizations strewn in as well.
443  */
444 static daddr_t
445 blst_meta_alloc(blmeta_t *scan, daddr_t blk, daddr_t count, daddr_t radix,
446     daddr_t skip, daddr_t cursor)
447 {
448 	daddr_t i, next_skip, r;
449 	int child;
450 	bool scan_from_start;
451 
452 	if (scan->u.bmu_avail < count) {
453 		/*
454 		 * The meta node's hint must be too large if the allocation
455 		 * exceeds the number of free blocks.  Reduce the hint, and
456 		 * return failure.
457 		 */
458 		scan->bm_bighint = scan->u.bmu_avail;
459 		return (SWAPBLK_NONE);
460 	}
461 	next_skip = skip / BLIST_META_RADIX;
462 
463 	/*
464 	 * An ALL-FREE meta node requires special handling before allocating
465 	 * any of its blocks.
466 	 */
467 	if (scan->u.bmu_avail == radix) {
468 		radix /= BLIST_META_RADIX;
469 
470 		/*
471 		 * Reinitialize each of the meta node's children.  An ALL-FREE
472 		 * meta node cannot have a terminator in any subtree.
473 		 */
474 		for (i = 1; i <= skip; i += next_skip) {
475 			if (next_skip == 1)
476 				scan[i].u.bmu_bitmap = (u_daddr_t)-1;
477 			else
478 				scan[i].u.bmu_avail = radix;
479 			scan[i].bm_bighint = radix;
480 		}
481 	} else {
482 		radix /= BLIST_META_RADIX;
483 	}
484 
485 	if (count > radix) {
486 		/*
487 		 * The allocation exceeds the number of blocks that are
488 		 * managed by a subtree of this meta node.
489 		 */
490 		panic("allocation too large");
491 	}
492 	scan_from_start = cursor == blk;
493 	child = (cursor - blk) / radix;
494 	blk += child * radix;
495 	for (i = 1 + child * next_skip; i <= skip; i += next_skip) {
496 		if (count <= scan[i].bm_bighint) {
497 			/*
498 			 * The allocation might fit in the i'th subtree.
499 			 */
500 			if (next_skip == 1) {
501 				r = blst_leaf_alloc(&scan[i], blk, count,
502 				    cursor > blk ? cursor : blk);
503 			} else {
504 				r = blst_meta_alloc(&scan[i], blk, count,
505 				    radix, next_skip - 1, cursor > blk ?
506 				    cursor : blk);
507 			}
508 			if (r != SWAPBLK_NONE) {
509 				scan->u.bmu_avail -= count;
510 				return (r);
511 			}
512 		} else if (scan[i].bm_bighint == (daddr_t)-1) {
513 			/*
514 			 * Terminator
515 			 */
516 			break;
517 		}
518 		blk += radix;
519 	}
520 
521 	/*
522 	 * We couldn't allocate count in this subtree, update bighint.
523 	 */
524 	if (scan_from_start && scan->bm_bighint >= count)
525 		scan->bm_bighint = count - 1;
526 
527 	return (SWAPBLK_NONE);
528 }
529 
530 /*
531  * BLST_LEAF_FREE() -	free allocated block from leaf bitmap
532  *
533  */
534 static void
535 blst_leaf_free(blmeta_t *scan, daddr_t blk, int count)
536 {
537 	/*
538 	 * free some data in this bitmap
539 	 *
540 	 * e.g.
541 	 *	0000111111111110000
542 	 *          \_________/\__/
543 	 *		v        n
544 	 */
545 	int n = blk & (BLIST_BMAP_RADIX - 1);
546 	u_daddr_t mask;
547 
548 	mask = ((u_daddr_t)-1 << n) &
549 	    ((u_daddr_t)-1 >> (BLIST_BMAP_RADIX - count - n));
550 
551 	if (scan->u.bmu_bitmap & mask)
552 		panic("blst_radix_free: freeing free block");
553 	scan->u.bmu_bitmap |= mask;
554 
555 	/*
556 	 * We could probably do a better job here.  We are required to make
557 	 * bighint at least as large as the biggest contiguous block of
558 	 * data.  If we just shoehorn it, a little extra overhead will
559 	 * be incured on the next allocation (but only that one typically).
560 	 */
561 	scan->bm_bighint = BLIST_BMAP_RADIX;
562 }
563 
564 /*
565  * BLST_META_FREE() - free allocated blocks from radix tree meta info
566  *
567  *	This support routine frees a range of blocks from the bitmap.
568  *	The range must be entirely enclosed by this radix node.  If a
569  *	meta node, we break the range down recursively to free blocks
570  *	in subnodes (which means that this code can free an arbitrary
571  *	range whereas the allocation code cannot allocate an arbitrary
572  *	range).
573  */
574 static void
575 blst_meta_free(blmeta_t *scan, daddr_t freeBlk, daddr_t count, daddr_t radix,
576     daddr_t skip, daddr_t blk)
577 {
578 	daddr_t i, next_skip, v;
579 	int child;
580 
581 	next_skip = skip / BLIST_META_RADIX;
582 
583 	if (scan->u.bmu_avail == 0) {
584 		/*
585 		 * ALL-ALLOCATED special case, with possible
586 		 * shortcut to ALL-FREE special case.
587 		 */
588 		scan->u.bmu_avail = count;
589 		scan->bm_bighint = count;
590 
591 		if (count != radix)  {
592 			for (i = 1; i <= skip; i += next_skip) {
593 				if (scan[i].bm_bighint == (daddr_t)-1)
594 					break;
595 				scan[i].bm_bighint = 0;
596 				if (next_skip == 1) {
597 					scan[i].u.bmu_bitmap = 0;
598 				} else {
599 					scan[i].u.bmu_avail = 0;
600 				}
601 			}
602 			/* fall through */
603 		}
604 	} else {
605 		scan->u.bmu_avail += count;
606 		/* scan->bm_bighint = radix; */
607 	}
608 
609 	/*
610 	 * ALL-FREE special case.
611 	 */
612 
613 	if (scan->u.bmu_avail == radix)
614 		return;
615 	if (scan->u.bmu_avail > radix)
616 		panic("blst_meta_free: freeing already free blocks (%lld) %lld/%lld",
617 		    (long long)count, (long long)scan->u.bmu_avail,
618 		    (long long)radix);
619 
620 	/*
621 	 * Break the free down into its components
622 	 */
623 
624 	radix /= BLIST_META_RADIX;
625 
626 	child = (freeBlk - blk) / radix;
627 	blk += child * radix;
628 	i = 1 + child * next_skip;
629 	while (i <= skip && blk < freeBlk + count) {
630 		v = blk + radix - freeBlk;
631 		if (v > count)
632 			v = count;
633 
634 		if (scan->bm_bighint == (daddr_t)-1)
635 			panic("blst_meta_free: freeing unexpected range");
636 
637 		if (next_skip == 1) {
638 			blst_leaf_free(&scan[i], freeBlk, v);
639 		} else {
640 			blst_meta_free(&scan[i], freeBlk, v, radix, next_skip - 1, blk);
641 		}
642 		if (scan->bm_bighint < scan[i].bm_bighint)
643 		    scan->bm_bighint = scan[i].bm_bighint;
644 		count -= v;
645 		freeBlk += v;
646 		blk += radix;
647 		i += next_skip;
648 	}
649 }
650 
651 /*
652  * BLIST_RADIX_COPY() - copy one radix tree to another
653  *
654  *	Locates free space in the source tree and frees it in the destination
655  *	tree.  The space may not already be free in the destination.
656  */
657 static void
658 blst_copy(blmeta_t *scan, daddr_t blk, daddr_t radix, daddr_t skip,
659     blist_t dest, daddr_t count)
660 {
661 	daddr_t i, next_skip;
662 
663 	/*
664 	 * Leaf node
665 	 */
666 
667 	if (radix == BLIST_BMAP_RADIX) {
668 		u_daddr_t v = scan->u.bmu_bitmap;
669 
670 		if (v == (u_daddr_t)-1) {
671 			blist_free(dest, blk, count);
672 		} else if (v != 0) {
673 			int i;
674 
675 			for (i = 0; i < BLIST_BMAP_RADIX && i < count; ++i) {
676 				if (v & ((u_daddr_t)1 << i))
677 					blist_free(dest, blk + i, 1);
678 			}
679 		}
680 		return;
681 	}
682 
683 	/*
684 	 * Meta node
685 	 */
686 
687 	if (scan->u.bmu_avail == 0) {
688 		/*
689 		 * Source all allocated, leave dest allocated
690 		 */
691 		return;
692 	}
693 	if (scan->u.bmu_avail == radix) {
694 		/*
695 		 * Source all free, free entire dest
696 		 */
697 		if (count < radix)
698 			blist_free(dest, blk, count);
699 		else
700 			blist_free(dest, blk, radix);
701 		return;
702 	}
703 
704 
705 	radix /= BLIST_META_RADIX;
706 	next_skip = skip / BLIST_META_RADIX;
707 
708 	for (i = 1; count && i <= skip; i += next_skip) {
709 		if (scan[i].bm_bighint == (daddr_t)-1)
710 			break;
711 
712 		if (count >= radix) {
713 			blst_copy(&scan[i], blk, radix, next_skip - 1, dest,
714 			    radix);
715 			count -= radix;
716 		} else {
717 			if (count) {
718 				blst_copy(&scan[i], blk, radix, next_skip - 1,
719 				    dest, count);
720 			}
721 			count = 0;
722 		}
723 		blk += radix;
724 	}
725 }
726 
727 /*
728  * BLST_LEAF_FILL() -	allocate specific blocks in leaf bitmap
729  *
730  *	This routine allocates all blocks in the specified range
731  *	regardless of any existing allocations in that range.  Returns
732  *	the number of blocks allocated by the call.
733  */
734 static daddr_t
735 blst_leaf_fill(blmeta_t *scan, daddr_t blk, int count)
736 {
737 	int n = blk & (BLIST_BMAP_RADIX - 1);
738 	daddr_t nblks;
739 	u_daddr_t mask;
740 
741 	mask = ((u_daddr_t)-1 << n) &
742 	    ((u_daddr_t)-1 >> (BLIST_BMAP_RADIX - count - n));
743 
744 	/* Count the number of blocks that we are allocating. */
745 	nblks = bitcount64(scan->u.bmu_bitmap & mask);
746 
747 	scan->u.bmu_bitmap &= ~mask;
748 	return (nblks);
749 }
750 
751 /*
752  * BLIST_META_FILL() -	allocate specific blocks at a meta node
753  *
754  *	This routine allocates the specified range of blocks,
755  *	regardless of any existing allocations in the range.  The
756  *	range must be within the extent of this node.  Returns the
757  *	number of blocks allocated by the call.
758  */
759 static daddr_t
760 blst_meta_fill(blmeta_t *scan, daddr_t allocBlk, daddr_t count, daddr_t radix,
761     daddr_t skip, daddr_t blk)
762 {
763 	daddr_t i, nblks, next_skip, v;
764 	int child;
765 
766 	if (count > radix) {
767 		/*
768 		 * The allocation exceeds the number of blocks that are
769 		 * managed by this meta node.
770 		 */
771 		panic("allocation too large");
772 	}
773 	if (count == radix || scan->u.bmu_avail == 0)  {
774 		/*
775 		 * ALL-ALLOCATED special case
776 		 */
777 		nblks = scan->u.bmu_avail;
778 		scan->u.bmu_avail = 0;
779 		scan->bm_bighint = 0;
780 		return nblks;
781 	}
782 	next_skip = skip / BLIST_META_RADIX;
783 
784 	/*
785 	 * An ALL-FREE meta node requires special handling before allocating
786 	 * any of its blocks.
787 	 */
788 	if (scan->u.bmu_avail == radix) {
789 		radix /= BLIST_META_RADIX;
790 
791 		/*
792 		 * Reinitialize each of the meta node's children.  An ALL-FREE
793 		 * meta node cannot have a terminator in any subtree.
794 		 */
795 		for (i = 1; i <= skip; i += next_skip) {
796 			if (next_skip == 1) {
797 				scan[i].u.bmu_bitmap = (u_daddr_t)-1;
798 				scan[i].bm_bighint = BLIST_BMAP_RADIX;
799 			} else {
800 				scan[i].bm_bighint = radix;
801 				scan[i].u.bmu_avail = radix;
802 			}
803 		}
804 	} else {
805 		radix /= BLIST_META_RADIX;
806 	}
807 
808 	nblks = 0;
809 	child = (allocBlk - blk) / radix;
810 	blk += child * radix;
811 	i = 1 + child * next_skip;
812 	while (i <= skip && blk < allocBlk + count) {
813 		v = blk + radix - allocBlk;
814 		if (v > count)
815 			v = count;
816 
817 		if (scan->bm_bighint == (daddr_t)-1)
818 			panic("blst_meta_fill: filling unexpected range");
819 
820 		if (next_skip == 1) {
821 			nblks += blst_leaf_fill(&scan[i], allocBlk, v);
822 		} else {
823 			nblks += blst_meta_fill(&scan[i], allocBlk, v,
824 			    radix, next_skip - 1, blk);
825 		}
826 		count -= v;
827 		allocBlk += v;
828 		blk += radix;
829 		i += next_skip;
830 	}
831 	scan->u.bmu_avail -= nblks;
832 	return nblks;
833 }
834 
835 /*
836  * BLST_RADIX_INIT() - initialize radix tree
837  *
838  *	Initialize our meta structures and bitmaps and calculate the exact
839  *	amount of space required to manage 'count' blocks - this space may
840  *	be considerably less than the calculated radix due to the large
841  *	RADIX values we use.
842  */
843 static daddr_t
844 blst_radix_init(blmeta_t *scan, daddr_t radix, daddr_t skip, daddr_t count)
845 {
846 	daddr_t i, memindex, next_skip;
847 
848 	memindex = 0;
849 
850 	/*
851 	 * Leaf node
852 	 */
853 
854 	if (radix == BLIST_BMAP_RADIX) {
855 		if (scan) {
856 			scan->bm_bighint = 0;
857 			scan->u.bmu_bitmap = 0;
858 		}
859 		return (memindex);
860 	}
861 
862 	/*
863 	 * Meta node.  If allocating the entire object we can special
864 	 * case it.  However, we need to figure out how much memory
865 	 * is required to manage 'count' blocks, so we continue on anyway.
866 	 */
867 
868 	if (scan) {
869 		scan->bm_bighint = 0;
870 		scan->u.bmu_avail = 0;
871 	}
872 
873 	radix /= BLIST_META_RADIX;
874 	next_skip = skip / BLIST_META_RADIX;
875 
876 	for (i = 1; i <= skip; i += next_skip) {
877 		if (count >= radix) {
878 			/*
879 			 * Allocate the entire object
880 			 */
881 			memindex = i +
882 			    blst_radix_init(((scan) ? &scan[i] : NULL), radix,
883 			    next_skip - 1, radix);
884 			count -= radix;
885 		} else if (count > 0) {
886 			/*
887 			 * Allocate a partial object
888 			 */
889 			memindex = i +
890 			    blst_radix_init(((scan) ? &scan[i] : NULL), radix,
891 			    next_skip - 1, count);
892 			count = 0;
893 		} else {
894 			/*
895 			 * Add terminator and break out
896 			 */
897 			if (scan)
898 				scan[i].bm_bighint = (daddr_t)-1;
899 			break;
900 		}
901 	}
902 	if (memindex < i)
903 		memindex = i;
904 	return (memindex);
905 }
906 
907 #ifdef BLIST_DEBUG
908 
909 static void
910 blst_radix_print(blmeta_t *scan, daddr_t blk, daddr_t radix, daddr_t skip,
911     int tab)
912 {
913 	daddr_t i, next_skip;
914 
915 	if (radix == BLIST_BMAP_RADIX) {
916 		printf(
917 		    "%*.*s(%08llx,%lld): bitmap %016llx big=%lld\n",
918 		    tab, tab, "",
919 		    (long long)blk, (long long)radix,
920 		    (long long)scan->u.bmu_bitmap,
921 		    (long long)scan->bm_bighint
922 		);
923 		return;
924 	}
925 
926 	if (scan->u.bmu_avail == 0) {
927 		printf(
928 		    "%*.*s(%08llx,%lld) ALL ALLOCATED\n",
929 		    tab, tab, "",
930 		    (long long)blk,
931 		    (long long)radix
932 		);
933 		return;
934 	}
935 	if (scan->u.bmu_avail == radix) {
936 		printf(
937 		    "%*.*s(%08llx,%lld) ALL FREE\n",
938 		    tab, tab, "",
939 		    (long long)blk,
940 		    (long long)radix
941 		);
942 		return;
943 	}
944 
945 	printf(
946 	    "%*.*s(%08llx,%lld): subtree (%lld/%lld) big=%lld {\n",
947 	    tab, tab, "",
948 	    (long long)blk, (long long)radix,
949 	    (long long)scan->u.bmu_avail,
950 	    (long long)radix,
951 	    (long long)scan->bm_bighint
952 	);
953 
954 	radix /= BLIST_META_RADIX;
955 	next_skip = skip / BLIST_META_RADIX;
956 	tab += 4;
957 
958 	for (i = 1; i <= skip; i += next_skip) {
959 		if (scan[i].bm_bighint == (daddr_t)-1) {
960 			printf(
961 			    "%*.*s(%08llx,%lld): Terminator\n",
962 			    tab, tab, "",
963 			    (long long)blk, (long long)radix
964 			);
965 			break;
966 		}
967 		blst_radix_print(&scan[i], blk, radix, next_skip - 1, tab);
968 		blk += radix;
969 	}
970 	tab -= 4;
971 
972 	printf(
973 	    "%*.*s}\n",
974 	    tab, tab, ""
975 	);
976 }
977 
978 #endif
979 
980 #ifdef BLIST_DEBUG
981 
982 int
983 main(int ac, char **av)
984 {
985 	int size = 1024;
986 	int i;
987 	blist_t bl;
988 
989 	for (i = 1; i < ac; ++i) {
990 		const char *ptr = av[i];
991 		if (*ptr != '-') {
992 			size = strtol(ptr, NULL, 0);
993 			continue;
994 		}
995 		ptr += 2;
996 		fprintf(stderr, "Bad option: %s\n", ptr - 2);
997 		exit(1);
998 	}
999 	bl = blist_create(size, M_WAITOK);
1000 	blist_free(bl, 0, size);
1001 
1002 	for (;;) {
1003 		char buf[1024];
1004 		long long da = 0;
1005 		long long count = 0;
1006 
1007 		printf("%lld/%lld/%lld> ", (long long)blist_avail(bl),
1008 		    (long long)size, (long long)bl->bl_radix);
1009 		fflush(stdout);
1010 		if (fgets(buf, sizeof(buf), stdin) == NULL)
1011 			break;
1012 		switch(buf[0]) {
1013 		case 'r':
1014 			if (sscanf(buf + 1, "%lld", &count) == 1) {
1015 				blist_resize(&bl, count, 1, M_WAITOK);
1016 			} else {
1017 				printf("?\n");
1018 			}
1019 		case 'p':
1020 			blist_print(bl);
1021 			break;
1022 		case 'a':
1023 			if (sscanf(buf + 1, "%lld", &count) == 1) {
1024 				daddr_t blk = blist_alloc(bl, count);
1025 				printf("    R=%08llx\n", (long long)blk);
1026 			} else {
1027 				printf("?\n");
1028 			}
1029 			break;
1030 		case 'f':
1031 			if (sscanf(buf + 1, "%llx %lld", &da, &count) == 2) {
1032 				blist_free(bl, da, count);
1033 			} else {
1034 				printf("?\n");
1035 			}
1036 			break;
1037 		case 'l':
1038 			if (sscanf(buf + 1, "%llx %lld", &da, &count) == 2) {
1039 				printf("    n=%jd\n",
1040 				    (intmax_t)blist_fill(bl, da, count));
1041 			} else {
1042 				printf("?\n");
1043 			}
1044 			break;
1045 		case '?':
1046 		case 'h':
1047 			puts(
1048 			    "p          -print\n"
1049 			    "a %d       -allocate\n"
1050 			    "f %x %d    -free\n"
1051 			    "l %x %d    -fill\n"
1052 			    "r %d       -resize\n"
1053 			    "h/?        -help"
1054 			);
1055 			break;
1056 		default:
1057 			printf("?\n");
1058 			break;
1059 		}
1060 	}
1061 	return(0);
1062 }
1063 
1064 void
1065 panic(const char *ctl, ...)
1066 {
1067 	va_list va;
1068 
1069 	va_start(va, ctl);
1070 	vfprintf(stderr, ctl, va);
1071 	fprintf(stderr, "\n");
1072 	va_end(va);
1073 	exit(1);
1074 }
1075 
1076 #endif
1077