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