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