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