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