Home | History | Annotate | Line # | Download | only in kern
subr_extent.c revision 1.27
      1 /*	$NetBSD: subr_extent.c,v 1.27 1999/06/07 02:25:05 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996, 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe and Matthias Drochner.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * General purpose extent manager.
     41  */
     42 
     43 #ifdef _KERNEL
     44 #include <sys/param.h>
     45 #include <sys/extent.h>
     46 #include <sys/malloc.h>
     47 #include <sys/pool.h>
     48 #include <sys/time.h>
     49 #include <sys/systm.h>
     50 #include <sys/proc.h>
     51 #include <sys/lock.h>
     52 #elif defined(_EXTENT_TESTING)
     53 /*
     54  * user-land definitions, so it can fit into a testing harness.
     55  */
     56 #include <sys/param.h>
     57 #include <sys/pool.h>
     58 #include <sys/extent.h>
     59 #include <errno.h>
     60 #include <stdlib.h>
     61 #include <stdio.h>
     62 
     63 #define	malloc(s, t, flags)		malloc(s)
     64 #define	free(p, t)			free(p)
     65 #define	tsleep(chan, pri, str, timo)	(EWOULDBLOCK)
     66 #define	wakeup(chan)			((void)0)
     67 #define	pool_get(pool, flags)		malloc(pool->pr_size,0,0)
     68 #define	pool_put(pool, rp)		free(rp,0)
     69 #define	panic(a)			printf(a)
     70 #define	splhigh()			(1)
     71 #define	splx(s)				((void)(s))
     72 #endif
     73 
     74 static	pool_handle_t expool_create __P((void));
     75 static	void extent_insert_and_optimize __P((struct extent *, u_long, u_long,
     76 	    int, struct extent_region *, struct extent_region *));
     77 static	struct extent_region *extent_alloc_region_descriptor
     78 	    __P((struct extent *, int));
     79 static	void extent_free_region_descriptor __P((struct extent *,
     80 	    struct extent_region *));
     81 
     82 static pool_handle_t expool;
     83 
     84 /*
     85  * Macro to align to an arbitrary power-of-two boundary.
     86  */
     87 #define EXTENT_ALIGN(_start, _align, _skew)		\
     88 	(((((_start) - (_skew)) + ((_align) - 1)) & (-(_align))) + (_skew))
     89 
     90 /*
     91  * Create the extent_region pool.
     92  * (This is deferred until one of our callers thinks we can malloc()).
     93  */
     94 
     95 static pool_handle_t expool_create()
     96 {
     97 #if defined(_KERNEL)
     98 	expool = pool_create(sizeof(struct extent_region), 0, 0,
     99 			     0, "extent", 0, 0, 0, 0);
    100 #else
    101 	expool = (pool_handle_t)malloc(sizeof(*expool),0,0);
    102 	expool->pr_size = sizeof(struct extent_region);
    103 #endif
    104 	return (expool);
    105 }
    106 
    107 /*
    108  * Allocate and initialize an extent map.
    109  */
    110 struct extent *
    111 extent_create(name, start, end, mtype, storage, storagesize, flags)
    112 	const char *name;
    113 	u_long start, end;
    114 	int mtype;
    115 	caddr_t storage;
    116 	size_t storagesize;
    117 	int flags;
    118 {
    119 	struct extent *ex;
    120 	caddr_t cp = storage;
    121 	size_t sz = storagesize;
    122 	struct extent_region *rp;
    123 	int fixed_extent = (storage != NULL);
    124 	int s;
    125 
    126 #ifdef DIAGNOSTIC
    127 	/* Check arguments. */
    128 	if (name == NULL)
    129 		panic("extent_create: name == NULL");
    130 	if (end < start) {
    131 		printf("extent_create: extent `%s', start 0x%lx, end 0x%lx\n",
    132 		    name, start, end);
    133 		panic("extent_create: end < start");
    134 	}
    135 	if (fixed_extent && (storagesize < sizeof(struct extent_fixed)))
    136 		panic("extent_create: fixed extent, bad storagesize 0x%lx",
    137 		    (u_long)storagesize);
    138 	if (fixed_extent == 0 && (storagesize != 0 || storage != NULL))
    139 		panic("extent_create: storage provided for non-fixed");
    140 #endif
    141 
    142 	/* Allocate extent descriptor. */
    143 	if (fixed_extent) {
    144 		struct extent_fixed *fex;
    145 
    146 		memset(storage, 0, storagesize);
    147 
    148 		/*
    149 		 * Align all descriptors on "long" boundaries.
    150 		 */
    151 		fex = (struct extent_fixed *)cp;
    152 		ex = (struct extent *)fex;
    153 		cp += ALIGN(sizeof(struct extent_fixed));
    154 		sz -= ALIGN(sizeof(struct extent_fixed));
    155 		fex->fex_storage = storage;
    156 		fex->fex_storagesize = storagesize;
    157 
    158 		/*
    159 		 * In a fixed extent, we have to pre-allocate region
    160 		 * descriptors and place them in the extent's freelist.
    161 		 */
    162 		LIST_INIT(&fex->fex_freelist);
    163 		while (sz >= ALIGN(sizeof(struct extent_region))) {
    164 			rp = (struct extent_region *)cp;
    165 			cp += ALIGN(sizeof(struct extent_region));
    166 			sz -= ALIGN(sizeof(struct extent_region));
    167 			LIST_INSERT_HEAD(&fex->fex_freelist, rp, er_link);
    168 		}
    169 	} else {
    170 		s = splhigh();
    171 		if (expool == NULL)
    172 			expool_create();
    173 		splx(s);
    174 		if (expool == NULL)
    175 			return (NULL);
    176 
    177 		ex = (struct extent *)malloc(sizeof(struct extent),
    178 		    mtype, (flags & EX_WAITOK) ? M_WAITOK : M_NOWAIT);
    179 		if (ex == NULL)
    180 			return (NULL);
    181 	}
    182 
    183 	/* Fill in the extent descriptor and return it to the caller. */
    184 	simple_lock_init(&ex->ex_slock);
    185 	LIST_INIT(&ex->ex_regions);
    186 	ex->ex_name = name;
    187 	ex->ex_start = start;
    188 	ex->ex_end = end;
    189 	ex->ex_mtype = mtype;
    190 	ex->ex_flags = 0;
    191 	if (fixed_extent)
    192 		ex->ex_flags |= EXF_FIXED;
    193 	if (flags & EX_NOCOALESCE)
    194 		ex->ex_flags |= EXF_NOCOALESCE;
    195 	return (ex);
    196 }
    197 
    198 /*
    199  * Destroy an extent map.
    200  * Since we're freeing the data, there can't be any references
    201  * so we don't need any locking.
    202  */
    203 void
    204 extent_destroy(ex)
    205 	struct extent *ex;
    206 {
    207 	struct extent_region *rp, *orp;
    208 
    209 #ifdef DIAGNOSTIC
    210 	/* Check arguments. */
    211 	if (ex == NULL)
    212 		panic("extent_destroy: NULL extent");
    213 #endif
    214 
    215 	/* Free all region descriptors in extent. */
    216 	for (rp = ex->ex_regions.lh_first; rp != NULL; ) {
    217 		orp = rp;
    218 		rp = rp->er_link.le_next;
    219 		LIST_REMOVE(orp, er_link);
    220 		extent_free_region_descriptor(ex, orp);
    221 	}
    222 
    223 	/* If we're not a fixed extent, free the extent descriptor itself. */
    224 	if ((ex->ex_flags & EXF_FIXED) == 0)
    225 		free(ex, ex->ex_mtype);
    226 }
    227 
    228 /*
    229  * Insert a region descriptor into the sorted region list after the
    230  * entry "after" or at the head of the list (if "after" is NULL).
    231  * The region descriptor we insert is passed in "rp".  We must
    232  * allocate the region descriptor before calling this function!
    233  * If we don't need the region descriptor, it will be freed here.
    234  */
    235 static void
    236 extent_insert_and_optimize(ex, start, size, flags, after, rp)
    237 	struct extent *ex;
    238 	u_long start, size;
    239 	int flags;
    240 	struct extent_region *after, *rp;
    241 {
    242 	struct extent_region *nextr;
    243 	int appended = 0;
    244 
    245 	if (after == NULL) {
    246 		/*
    247 		 * We're the first in the region list.  If there's
    248 		 * a region after us, attempt to coalesce to save
    249 		 * descriptor overhead.
    250 		 */
    251 		if (((ex->ex_flags & EXF_NOCOALESCE) == 0) &&
    252 		    (ex->ex_regions.lh_first != NULL) &&
    253 		    ((start + size) == ex->ex_regions.lh_first->er_start)) {
    254 			/*
    255 			 * We can coalesce.  Prepend us to the first region.
    256 			 */
    257 			ex->ex_regions.lh_first->er_start = start;
    258 			extent_free_region_descriptor(ex, rp);
    259 			return;
    260 		}
    261 
    262 		/*
    263 		 * Can't coalesce.  Fill in the region descriptor
    264 		 * in, and insert us at the head of the region list.
    265 		 */
    266 		rp->er_start = start;
    267 		rp->er_end = start + (size - 1);
    268 		LIST_INSERT_HEAD(&ex->ex_regions, rp, er_link);
    269 		return;
    270 	}
    271 
    272 	/*
    273 	 * If EXF_NOCOALESCE is set, coalescing is disallowed.
    274 	 */
    275 	if (ex->ex_flags & EXF_NOCOALESCE)
    276 		goto cant_coalesce;
    277 
    278 	/*
    279 	 * Attempt to coalesce with the region before us.
    280 	 */
    281 	if ((after->er_end + 1) == start) {
    282 		/*
    283 		 * We can coalesce.  Append ourselves and make
    284 		 * note of it.
    285 		 */
    286 		after->er_end = start + (size - 1);
    287 		appended = 1;
    288 	}
    289 
    290 	/*
    291 	 * Attempt to coalesce with the region after us.
    292 	 */
    293 	if ((after->er_link.le_next != NULL) &&
    294 	    ((start + size) == after->er_link.le_next->er_start)) {
    295 		/*
    296 		 * We can coalesce.  Note that if we appended ourselves
    297 		 * to the previous region, we exactly fit the gap, and
    298 		 * can free the "next" region descriptor.
    299 		 */
    300 		if (appended) {
    301 			/*
    302 			 * Yup, we can free it up.
    303 			 */
    304 			after->er_end = after->er_link.le_next->er_end;
    305 			nextr = after->er_link.le_next;
    306 			LIST_REMOVE(nextr, er_link);
    307 			extent_free_region_descriptor(ex, nextr);
    308 		} else {
    309 			/*
    310 			 * Nope, just prepend us to the next region.
    311 			 */
    312 			after->er_link.le_next->er_start = start;
    313 		}
    314 
    315 		extent_free_region_descriptor(ex, rp);
    316 		return;
    317 	}
    318 
    319 	/*
    320 	 * We weren't able to coalesce with the next region, but
    321 	 * we don't need to allocate a region descriptor if we
    322 	 * appended ourselves to the previous region.
    323 	 */
    324 	if (appended) {
    325 		extent_free_region_descriptor(ex, rp);
    326 		return;
    327 	}
    328 
    329  cant_coalesce:
    330 
    331 	/*
    332 	 * Fill in the region descriptor and insert ourselves
    333 	 * into the region list.
    334 	 */
    335 	rp->er_start = start;
    336 	rp->er_end = start + (size - 1);
    337 	LIST_INSERT_AFTER(after, rp, er_link);
    338 }
    339 
    340 /*
    341  * Allocate a specific region in an extent map.
    342  */
    343 int
    344 extent_alloc_region(ex, start, size, flags)
    345 	struct extent *ex;
    346 	u_long start, size;
    347 	int flags;
    348 {
    349 	struct extent_region *rp, *last, *myrp;
    350 	u_long end = start + (size - 1);
    351 	int error;
    352 
    353 #ifdef DIAGNOSTIC
    354 	/* Check arguments. */
    355 	if (ex == NULL)
    356 		panic("extent_alloc_region: NULL extent");
    357 	if (size < 1) {
    358 		printf("extent_alloc_region: extent `%s', size 0x%lx\n",
    359 		    ex->ex_name, size);
    360 		panic("extent_alloc_region: bad size");
    361 	}
    362 	if (end < start) {
    363 		printf(
    364 		 "extent_alloc_region: extent `%s', start 0x%lx, size 0x%lx\n",
    365 		 ex->ex_name, start, size);
    366 		panic("extent_alloc_region: overflow");
    367 	}
    368 #endif
    369 
    370 	/*
    371 	 * Make sure the requested region lies within the
    372 	 * extent.
    373 	 *
    374 	 * We don't lock to check the range, because those values
    375 	 * are never modified, and if another thread deletes the
    376 	 * extent, we're screwed anyway.
    377 	 */
    378 	if ((start < ex->ex_start) || (end > ex->ex_end)) {
    379 #ifdef DIAGNOSTIC
    380 		printf("extent_alloc_region: extent `%s' (0x%lx - 0x%lx)\n",
    381 		    ex->ex_name, ex->ex_start, ex->ex_end);
    382 		printf("extent_alloc_region: start 0x%lx, end 0x%lx\n",
    383 		    start, end);
    384 		panic("extent_alloc_region: region lies outside extent");
    385 #else
    386 		return (EINVAL);
    387 #endif
    388 	}
    389 
    390 	/*
    391 	 * Allocate the region descriptor.  It will be freed later
    392 	 * if we can coalesce with another region.  Don't lock before
    393 	 * here!  This could block.
    394 	 */
    395 	myrp = extent_alloc_region_descriptor(ex, flags);
    396 	if (myrp == NULL) {
    397 #ifdef DIAGNOSTIC
    398 		printf(
    399 		    "extent_alloc_region: can't allocate region descriptor\n");
    400 #endif
    401 		return (ENOMEM);
    402 	}
    403 
    404  alloc_start:
    405 	simple_lock(&ex->ex_slock);
    406 
    407 	/*
    408 	 * Attempt to place ourselves in the desired area of the
    409 	 * extent.  We save ourselves some work by keeping the list sorted.
    410 	 * In other words, if the start of the current region is greater
    411 	 * than the end of our region, we don't have to search any further.
    412 	 */
    413 
    414 	/*
    415 	 * Keep a pointer to the last region we looked at so
    416 	 * that we don't have to traverse the list again when
    417 	 * we insert ourselves.  If "last" is NULL when we
    418 	 * finally insert ourselves, we go at the head of the
    419 	 * list.  See extent_insert_and_optimize() for details.
    420 	 */
    421 	last = NULL;
    422 
    423 	for (rp = ex->ex_regions.lh_first; rp != NULL;
    424 	    rp = rp->er_link.le_next) {
    425 		if (rp->er_start > end) {
    426 			/*
    427 			 * We lie before this region and don't
    428 			 * conflict.
    429 			 */
    430 			break;
    431 		}
    432 
    433 		/*
    434 		 * The current region begins before we end.
    435 		 * Check for a conflict.
    436 		 */
    437 		if (rp->er_end >= start) {
    438 			/*
    439 			 * We conflict.  If we can (and want to) wait,
    440 			 * do so.
    441 			 */
    442 			if (flags & EX_WAITSPACE) {
    443 				ex->ex_flags |= EXF_WANTED;
    444 				simple_unlock(&ex->ex_slock);
    445 				error = tsleep(ex,
    446 				    PRIBIO | ((flags & EX_CATCH) ? PCATCH : 0),
    447 				    "extnt", 0);
    448 				if (error)
    449 					return (error);
    450 				goto alloc_start;
    451 			}
    452 			extent_free_region_descriptor(ex, myrp);
    453 			simple_unlock(&ex->ex_slock);
    454 			return (EAGAIN);
    455 		}
    456 		/*
    457 		 * We don't conflict, but this region lies before
    458 		 * us.  Keep a pointer to this region, and keep
    459 		 * trying.
    460 		 */
    461 		last = rp;
    462 	}
    463 
    464 	/*
    465 	 * We don't conflict with any regions.  "last" points
    466 	 * to the region we fall after, or is NULL if we belong
    467 	 * at the beginning of the region list.  Insert ourselves.
    468 	 */
    469 	extent_insert_and_optimize(ex, start, size, flags, last, myrp);
    470 	simple_unlock(&ex->ex_slock);
    471 	return (0);
    472 }
    473 
    474 /*
    475  * Macro to check (x + y) <= z.  This check is designed to fail
    476  * if an overflow occurs.
    477  */
    478 #define LE_OV(x, y, z)	((((x) + (y)) >= (x)) && (((x) + (y)) <= (z)))
    479 
    480 /*
    481  * Allocate a region in an extent map subregion.
    482  *
    483  * If EX_FAST is specified, we return the first fit in the map.
    484  * Otherwise, we try to minimize fragmentation by finding the
    485  * smallest gap that will hold the request.
    486  *
    487  * The allocated region is aligned to "alignment", which must be
    488  * a power of 2.
    489  */
    490 int
    491 extent_alloc_subregion1(ex, substart, subend, size, alignment, skew, boundary,
    492     flags, result)
    493 	struct extent *ex;
    494 	u_long substart, subend, size, alignment, skew, boundary;
    495 	int flags;
    496 	u_long *result;
    497 {
    498 	struct extent_region *rp, *myrp, *last, *bestlast;
    499 	u_long newstart, newend, beststart, bestovh, ovh;
    500 	u_long dontcross;
    501 	int error;
    502 
    503 #ifdef DIAGNOSTIC
    504 	/*
    505 	 * Check arguments.
    506 	 *
    507 	 * We don't lock to check these, because these values
    508 	 * are never modified, and if another thread deletes the
    509 	 * extent, we're screwed anyway.
    510 	 */
    511 	if (ex == NULL)
    512 		panic("extent_alloc_subregion: NULL extent");
    513 	if (result == NULL)
    514 		panic("extent_alloc_subregion: NULL result pointer");
    515 	if ((substart < ex->ex_start) || (substart > ex->ex_end) ||
    516 	    (subend > ex->ex_end) || (subend < ex->ex_start)) {
    517   printf("extent_alloc_subregion: extent `%s', ex_start 0x%lx, ex_end 0x%lx\n",
    518 		    ex->ex_name, ex->ex_start, ex->ex_end);
    519 		printf("extent_alloc_subregion: substart 0x%lx, subend 0x%lx\n",
    520 		    substart, subend);
    521 		panic("extent_alloc_subregion: bad subregion");
    522 	}
    523 	if ((size < 1) || ((size - 1) > (subend - substart))) {
    524 		printf("extent_alloc_subregion: extent `%s', size 0x%lx\n",
    525 		    ex->ex_name, size);
    526 		panic("extent_alloc_subregion: bad size");
    527 	}
    528 	if (alignment == 0)
    529 		panic("extent_alloc_subregion: bad alignment");
    530 	if (boundary && (boundary < size)) {
    531 		printf(
    532 		    "extent_alloc_subregion: extent `%s', size 0x%lx,
    533 		    boundary 0x%lx\n", ex->ex_name, size, boundary);
    534 		panic("extent_alloc_subregion: bad boundary");
    535 	}
    536 #endif
    537 
    538 	/*
    539 	 * Allocate the region descriptor.  It will be freed later
    540 	 * if we can coalesce with another region.  Don't lock before
    541 	 * here!  This could block.
    542 	 */
    543 	myrp = extent_alloc_region_descriptor(ex, flags);
    544 	if (myrp == NULL) {
    545 #ifdef DIAGNOSTIC
    546 		printf(
    547 		 "extent_alloc_subregion: can't allocate region descriptor\n");
    548 #endif
    549 		return (ENOMEM);
    550 	}
    551 
    552  alloc_start:
    553 	simple_lock(&ex->ex_slock);
    554 
    555 	/*
    556 	 * Keep a pointer to the last region we looked at so
    557 	 * that we don't have to traverse the list again when
    558 	 * we insert ourselves.  If "last" is NULL when we
    559 	 * finally insert ourselves, we go at the head of the
    560 	 * list.  See extent_insert_and_optimize() for deatails.
    561 	 */
    562 	last = NULL;
    563 
    564 	/*
    565 	 * Keep track of size and location of the smallest
    566 	 * chunk we fit in.
    567 	 *
    568 	 * Since the extent can be as large as the numeric range
    569 	 * of the CPU (0 - 0xffffffff for 32-bit systems), the
    570 	 * best overhead value can be the maximum unsigned integer.
    571 	 * Thus, we initialize "bestovh" to 0, since we insert ourselves
    572 	 * into the region list immediately on an exact match (which
    573 	 * is the only case where "bestovh" would be set to 0).
    574 	 */
    575 	bestovh = 0;
    576 	beststart = 0;
    577 	bestlast = NULL;
    578 
    579 	/*
    580 	 * For N allocated regions, we must make (N + 1)
    581 	 * checks for unallocated space.  The first chunk we
    582 	 * check is the area from the beginning of the subregion
    583 	 * to the first allocated region after that point.
    584 	 */
    585 	newstart = EXTENT_ALIGN(substart, alignment, skew);
    586 	if (newstart < ex->ex_start) {
    587 #ifdef DIAGNOSTIC
    588 		printf(
    589       "extent_alloc_subregion: extent `%s' (0x%lx - 0x%lx), alignment 0x%lx\n",
    590 		 ex->ex_name, ex->ex_start, ex->ex_end, alignment);
    591 		simple_unlock(&ex->ex_slock);
    592 		panic("extent_alloc_subregion: overflow after alignment");
    593 #else
    594 		extent_free_region_descriptor(ex, myrp);
    595 		simple_unlock(&ex->ex_slock);
    596 		return (EINVAL);
    597 #endif
    598 	}
    599 
    600 	/*
    601 	 * Find the first allocated region that begins on or after
    602 	 * the subregion start, advancing the "last" pointer along
    603 	 * the way.
    604 	 */
    605 	for (rp = ex->ex_regions.lh_first; rp != NULL;
    606 	     rp = rp->er_link.le_next) {
    607 		if (rp->er_start >= newstart)
    608 			break;
    609 		last = rp;
    610 	}
    611 
    612 	/*
    613 	 * Relocate the start of our candidate region to the end of
    614 	 * the last allocated region (if there was one overlapping
    615 	 * our subrange).
    616 	 */
    617 	if (last != NULL && last->er_end >= newstart)
    618 		newstart = EXTENT_ALIGN((last->er_end + 1), alignment, skew);
    619 
    620 	for (; rp != NULL; rp = rp->er_link.le_next) {
    621 		/*
    622 		 * Check the chunk before "rp".  Note that our
    623 		 * comparison is safe from overflow conditions.
    624 		 */
    625 		if (LE_OV(newstart, size, rp->er_start)) {
    626 			/*
    627 			 * Do a boundary check, if necessary.  Note
    628 			 * that a region may *begin* on the boundary,
    629 			 * but it must end before the boundary.
    630 			 */
    631 			if (boundary) {
    632 				newend = newstart + (size - 1);
    633 
    634 				/*
    635 				 * Calculate the next boundary after the start
    636 				 * of this region.
    637 				 */
    638 				dontcross = EXTENT_ALIGN(newstart+1, boundary,
    639 				    (flags & EX_BOUNDZERO) ? 0 : ex->ex_start)
    640 				    - 1;
    641 
    642 #if 0
    643 				printf("newstart=%x newend=%x ex_start=%x ex_end=%x boundary=%x dontcross=%x\n",
    644 				    newstart, newend, ex->ex_start, ex->ex_end,
    645 				    boundary, dontcross);
    646 #endif
    647 
    648 				if (newend > dontcross) {
    649 					/*
    650 					 * Candidate region crosses boundary.
    651 					 * Throw away the leading part and see
    652 					 * if we still fit.
    653 					 */
    654 					newstart = dontcross + 1;
    655 					newend = newstart + (size - 1);
    656 					dontcross += boundary;
    657 					if (!LE_OV(newstart, size, rp->er_start))
    658 						continue;
    659 				}
    660 
    661 				/*
    662 				 * If we run past the end of
    663 				 * the extent or the boundary
    664 				 * overflows, then the request
    665 				 * can't fit.
    666 				 */
    667 				if (dontcross > ex->ex_end ||
    668 				    dontcross < newstart)
    669 					goto fail;
    670 			}
    671 
    672 			/*
    673 			 * We would fit into this space.  Calculate
    674 			 * the overhead (wasted space).  If we exactly
    675 			 * fit, or we're taking the first fit, insert
    676 			 * ourselves into the region list.
    677 			 */
    678 			ovh = rp->er_start - newstart - size;
    679 			if ((flags & EX_FAST) || (ovh == 0))
    680 				goto found;
    681 
    682 			/*
    683 			 * Don't exactly fit, but check to see
    684 			 * if we're better than any current choice.
    685 			 */
    686 			if ((bestovh == 0) || (ovh < bestovh)) {
    687 				bestovh = ovh;
    688 				beststart = newstart;
    689 				bestlast = last;
    690 			}
    691 		}
    692 
    693 		/*
    694 		 * Skip past the current region and check again.
    695 		 */
    696 		newstart = EXTENT_ALIGN((rp->er_end + 1), alignment, skew);
    697 		if (newstart < rp->er_end) {
    698 			/*
    699 			 * Overflow condition.  Don't error out, since
    700 			 * we might have a chunk of space that we can
    701 			 * use.
    702 			 */
    703 			goto fail;
    704 		}
    705 
    706 		last = rp;
    707 	}
    708 
    709 	/*
    710 	 * The final check is from the current starting point to the
    711 	 * end of the subregion.  If there were no allocated regions,
    712 	 * "newstart" is set to the beginning of the subregion, or
    713 	 * just past the end of the last allocated region, adjusted
    714 	 * for alignment in either case.
    715 	 */
    716 	if (LE_OV(newstart, (size - 1), subend)) {
    717 		/*
    718 		 * Do a boundary check, if necessary.  Note
    719 		 * that a region may *begin* on the boundary,
    720 		 * but it must end before the boundary.
    721 		 */
    722 		if (boundary) {
    723 			newend = newstart + (size - 1);
    724 
    725 			/*
    726 			 * Calculate the next boundary after the start
    727 			 * of this region.
    728 			 */
    729 			dontcross = EXTENT_ALIGN(newstart+1, boundary,
    730 			    (flags & EX_BOUNDZERO) ? 0 : ex->ex_start)
    731 			    - 1;
    732 
    733 #if 0
    734 			printf("newstart=%x newend=%x ex_start=%x ex_end=%x boundary=%x dontcross=%x\n",
    735 			    newstart, newend, ex->ex_start, ex->ex_end,
    736 			    boundary, dontcross);
    737 #endif
    738 
    739 			if (newend > dontcross) {
    740 				/*
    741 				 * Candidate region crosses boundary.
    742 				 * Throw away the leading part and see
    743 				 * if we still fit.
    744 				 */
    745 				newstart = dontcross + 1;
    746 				newend = newstart + (size - 1);
    747 				dontcross += boundary;
    748 				if (!LE_OV(newstart, (size - 1), subend))
    749 					goto fail;
    750 			}
    751 
    752 			/*
    753 			 * If we run past the end of
    754 			 * the extent or the boundary
    755 			 * overflows, then the request
    756 			 * can't fit.
    757 			 */
    758 			if (dontcross > ex->ex_end ||
    759 			    dontcross < newstart)
    760 				goto fail;
    761 		}
    762 
    763 		/*
    764 		 * We would fit into this space.  Calculate
    765 		 * the overhead (wasted space).  If we exactly
    766 		 * fit, or we're taking the first fit, insert
    767 		 * ourselves into the region list.
    768 		 */
    769 		ovh = ex->ex_end - newstart - (size - 1);
    770 		if ((flags & EX_FAST) || (ovh == 0))
    771 			goto found;
    772 
    773 		/*
    774 		 * Don't exactly fit, but check to see
    775 		 * if we're better than any current choice.
    776 		 */
    777 		if ((bestovh == 0) || (ovh < bestovh)) {
    778 			bestovh = ovh;
    779 			beststart = newstart;
    780 			bestlast = last;
    781 		}
    782 	}
    783 
    784  fail:
    785 	/*
    786 	 * One of the following two conditions have
    787 	 * occurred:
    788 	 *
    789 	 *	There is no chunk large enough to hold the request.
    790 	 *
    791 	 *	If EX_FAST was not specified, there is not an
    792 	 *	exact match for the request.
    793 	 *
    794 	 * Note that if we reach this point and EX_FAST is
    795 	 * set, then we know there is no space in the extent for
    796 	 * the request.
    797 	 */
    798 	if (((flags & EX_FAST) == 0) && (bestovh != 0)) {
    799 		/*
    800 		 * We have a match that's "good enough".
    801 		 */
    802 		newstart = beststart;
    803 		last = bestlast;
    804 		goto found;
    805 	}
    806 
    807 	/*
    808 	 * No space currently available.  Wait for it to free up,
    809 	 * if possible.
    810 	 */
    811 	if (flags & EX_WAITSPACE) {
    812 		ex->ex_flags |= EXF_WANTED;
    813 		simple_unlock(&ex->ex_slock);
    814 		error = tsleep(ex,
    815 		    PRIBIO | ((flags & EX_CATCH) ? PCATCH : 0), "extnt", 0);
    816 		if (error)
    817 			return (error);
    818 		goto alloc_start;
    819 	}
    820 
    821 	extent_free_region_descriptor(ex, myrp);
    822 	simple_unlock(&ex->ex_slock);
    823 	return (EAGAIN);
    824 
    825  found:
    826 	/*
    827 	 * Insert ourselves into the region list.
    828 	 */
    829 	extent_insert_and_optimize(ex, newstart, size, flags, last, myrp);
    830 	simple_unlock(&ex->ex_slock);
    831 	*result = newstart;
    832 	return (0);
    833 }
    834 
    835 int
    836 extent_free(ex, start, size, flags)
    837 	struct extent *ex;
    838 	u_long start, size;
    839 	int flags;
    840 {
    841 	struct extent_region *rp, *nrp = NULL;
    842 	u_long end = start + (size - 1);
    843 	int exflags;
    844 
    845 #ifdef DIAGNOSTIC
    846 	/*
    847 	 * Check arguments.
    848 	 *
    849 	 * We don't lock to check these, because these values
    850 	 * are never modified, and if another thread deletes the
    851 	 * extent, we're screwed anyway.
    852 	 */
    853 	if (ex == NULL)
    854 		panic("extent_free: NULL extent");
    855 	if ((start < ex->ex_start) || (start > ex->ex_end)) {
    856 		extent_print(ex);
    857 		printf("extent_free: extent `%s', start 0x%lx, size 0x%lx\n",
    858 		    ex->ex_name, start, size);
    859 		panic("extent_free: extent `%s', region not within extent",
    860 		    ex->ex_name);
    861 	}
    862 	/* Check for an overflow. */
    863 	if (end < start) {
    864 		extent_print(ex);
    865 		printf("extent_free: extent `%s', start 0x%lx, size 0x%lx\n",
    866 		    ex->ex_name, start, size);
    867 		panic("extent_free: overflow");
    868 	}
    869 #endif
    870 
    871 	/*
    872 	 * If we're allowing coalescing, we must allocate a region
    873 	 * descriptor now, since it might block.
    874 	 *
    875 	 * XXX Make a static, create-time flags word, so we don't
    876 	 * XXX have to lock to read it!
    877 	 */
    878 	simple_lock(&ex->ex_slock);
    879 	exflags = ex->ex_flags;
    880 	simple_unlock(&ex->ex_slock);
    881 
    882 	if ((exflags & EXF_NOCOALESCE) == 0) {
    883 		/* Allocate a region descriptor. */
    884 		nrp = extent_alloc_region_descriptor(ex, flags);
    885 		if (nrp == NULL)
    886 			return (ENOMEM);
    887 	}
    888 
    889 	simple_lock(&ex->ex_slock);
    890 
    891 	/*
    892 	 * Find region and deallocate.  Several possibilities:
    893 	 *
    894 	 *	1. (start == er_start) && (end == er_end):
    895 	 *	   Free descriptor.
    896 	 *
    897 	 *	2. (start == er_start) && (end < er_end):
    898 	 *	   Adjust er_start.
    899 	 *
    900 	 *	3. (start > er_start) && (end == er_end):
    901 	 *	   Adjust er_end.
    902 	 *
    903 	 *	4. (start > er_start) && (end < er_end):
    904 	 *	   Fragment region.  Requires descriptor alloc.
    905 	 *
    906 	 * Cases 2, 3, and 4 require that the EXF_NOCOALESCE flag
    907 	 * is not set.
    908 	 */
    909 	for (rp = ex->ex_regions.lh_first; rp != NULL;
    910 	    rp = rp->er_link.le_next) {
    911 		/*
    912 		 * Save ourselves some comparisons; does the current
    913 		 * region end before chunk to be freed begins?  If so,
    914 		 * then we haven't found the appropriate region descriptor.
    915 		 */
    916 		if (rp->er_end < start)
    917 			continue;
    918 
    919 		/*
    920 		 * Save ourselves some traversal; does the current
    921 		 * region begin after the chunk to be freed ends?  If so,
    922 		 * then we've already passed any possible region descriptors
    923 		 * that might have contained the chunk to be freed.
    924 		 */
    925 		if (rp->er_start > end)
    926 			break;
    927 
    928 		/* Case 1. */
    929 		if ((start == rp->er_start) && (end == rp->er_end)) {
    930 			LIST_REMOVE(rp, er_link);
    931 			extent_free_region_descriptor(ex, rp);
    932 			goto done;
    933 		}
    934 
    935 		/*
    936 		 * The following cases all require that EXF_NOCOALESCE
    937 		 * is not set.
    938 		 */
    939 		if (ex->ex_flags & EXF_NOCOALESCE)
    940 			continue;
    941 
    942 		/* Case 2. */
    943 		if ((start == rp->er_start) && (end < rp->er_end)) {
    944 			rp->er_start = (end + 1);
    945 			goto done;
    946 		}
    947 
    948 		/* Case 3. */
    949 		if ((start > rp->er_start) && (end == rp->er_end)) {
    950 			rp->er_end = (start - 1);
    951 			goto done;
    952 		}
    953 
    954 		/* Case 4. */
    955 		if ((start > rp->er_start) && (end < rp->er_end)) {
    956 			/* Fill in new descriptor. */
    957 			nrp->er_start = end + 1;
    958 			nrp->er_end = rp->er_end;
    959 
    960 			/* Adjust current descriptor. */
    961 			rp->er_end = start - 1;
    962 
    963 			/* Insert new descriptor after current. */
    964 			LIST_INSERT_AFTER(rp, nrp, er_link);
    965 
    966 			/* We used the new descriptor, so don't free it below */
    967 			nrp = NULL;
    968 			goto done;
    969 		}
    970 	}
    971 
    972 	/* Region not found, or request otherwise invalid. */
    973 	simple_unlock(&ex->ex_slock);
    974 	extent_print(ex);
    975 	printf("extent_free: start 0x%lx, end 0x%lx\n", start, end);
    976 	panic("extent_free: region not found");
    977 
    978  done:
    979 	if (nrp != NULL)
    980 		extent_free_region_descriptor(ex, nrp);
    981 	if (ex->ex_flags & EXF_WANTED) {
    982 		ex->ex_flags &= ~EXF_WANTED;
    983 		wakeup(ex);
    984 	}
    985 	simple_unlock(&ex->ex_slock);
    986 	return (0);
    987 }
    988 
    989 /*
    990  * Allocate an extent region descriptor.  EXTENT MUST NOT BE LOCKED,
    991  * AS THIS FUNCTION MAY BLOCK!  We will handle any locking we may need.
    992  */
    993 static struct extent_region *
    994 extent_alloc_region_descriptor(ex, flags)
    995 	struct extent *ex;
    996 	int flags;
    997 {
    998 	struct extent_region *rp;
    999 	int exflags;
   1000 	int s;
   1001 
   1002 	/*
   1003 	 * XXX Make a static, create-time flags word, so we don't
   1004 	 * XXX have to lock to read it!
   1005 	 */
   1006 	simple_lock(&ex->ex_slock);
   1007 	exflags = ex->ex_flags;
   1008 	simple_unlock(&ex->ex_slock);
   1009 
   1010 	if (exflags & EXF_FIXED) {
   1011 		struct extent_fixed *fex = (struct extent_fixed *)ex;
   1012 
   1013 		for (;;) {
   1014 			simple_lock(&ex->ex_slock);
   1015 			if ((rp = fex->fex_freelist.lh_first) != NULL) {
   1016 				/*
   1017 				 * Don't muck with flags after pulling it off
   1018 				 * the freelist; it may have been dynamically
   1019 				 * allocated, and kindly given to us.  We
   1020 				 * need to remember that information.
   1021 				 */
   1022 				LIST_REMOVE(rp, er_link);
   1023 				simple_unlock(&ex->ex_slock);
   1024 				return (rp);
   1025 			}
   1026 			if (flags & EX_MALLOCOK) {
   1027 				simple_unlock(&ex->ex_slock);
   1028 				goto alloc;
   1029 			}
   1030 			if ((flags & EX_WAITOK) == 0) {
   1031 				simple_unlock(&ex->ex_slock);
   1032 				return (NULL);
   1033 			}
   1034 			ex->ex_flags |= EXF_FLWANTED;
   1035 			simple_unlock(&ex->ex_slock);
   1036 			if (tsleep(&fex->fex_freelist,
   1037 			    PRIBIO | ((flags & EX_CATCH) ? PCATCH : 0),
   1038 			    "extnt", 0))
   1039 				return (NULL);
   1040 		}
   1041 	}
   1042 
   1043  alloc:
   1044 	s = splhigh();
   1045 	if (expool == NULL && !expool_create()) {
   1046 		splx(s);
   1047 		return (NULL);
   1048 	}
   1049 
   1050 	rp = pool_get(expool, (flags & EX_WAITOK) ? PR_WAITOK : 0);
   1051 	splx(s);
   1052 
   1053 	if (rp != NULL)
   1054 		rp->er_flags = ER_ALLOC;
   1055 
   1056 	return (rp);
   1057 }
   1058 
   1059 /*
   1060  * Free an extent region descriptor.  EXTENT _MUST_ BE LOCKED!  This
   1061  * is safe as we do not block here.
   1062  */
   1063 static void
   1064 extent_free_region_descriptor(ex, rp)
   1065 	struct extent *ex;
   1066 	struct extent_region *rp;
   1067 {
   1068 	int s;
   1069 
   1070 	if (ex->ex_flags & EXF_FIXED) {
   1071 		struct extent_fixed *fex = (struct extent_fixed *)ex;
   1072 
   1073 		/*
   1074 		 * If someone's waiting for a region descriptor,
   1075 		 * be nice and give them this one, rather than
   1076 		 * just free'ing it back to the system.
   1077 		 */
   1078 		if (rp->er_flags & ER_ALLOC) {
   1079 			if (ex->ex_flags & EXF_FLWANTED) {
   1080 				/* Clear all but ER_ALLOC flag. */
   1081 				rp->er_flags = ER_ALLOC;
   1082 				LIST_INSERT_HEAD(&fex->fex_freelist, rp,
   1083 				    er_link);
   1084 				goto wake_em_up;
   1085 			} else {
   1086 				s = splhigh();
   1087 				pool_put(expool, rp);
   1088 				splx(s);
   1089 			}
   1090 		} else {
   1091 			/* Clear all flags. */
   1092 			rp->er_flags = 0;
   1093 			LIST_INSERT_HEAD(&fex->fex_freelist, rp, er_link);
   1094 		}
   1095 
   1096 		if (ex->ex_flags & EXF_FLWANTED) {
   1097  wake_em_up:
   1098 			ex->ex_flags &= ~EXF_FLWANTED;
   1099 			wakeup(&fex->fex_freelist);
   1100 		}
   1101 		return;
   1102 	}
   1103 
   1104 	/*
   1105 	 * We know it's dynamically allocated if we get here.
   1106 	 */
   1107 	s = splhigh();
   1108 	pool_put(expool, rp);
   1109 	splx(s);
   1110 }
   1111 
   1112 void
   1113 extent_print(ex)
   1114 	struct extent *ex;
   1115 {
   1116 	struct extent_region *rp;
   1117 
   1118 	if (ex == NULL)
   1119 		panic("extent_print: NULL extent");
   1120 
   1121 	simple_lock(&ex->ex_slock);
   1122 
   1123 	printf("extent `%s' (0x%lx - 0x%lx), flags = 0x%x\n", ex->ex_name,
   1124 	    ex->ex_start, ex->ex_end, ex->ex_flags);
   1125 
   1126 	for (rp = ex->ex_regions.lh_first; rp != NULL;
   1127 	    rp = rp->er_link.le_next)
   1128 		printf("     0x%lx - 0x%lx\n", rp->er_start, rp->er_end);
   1129 
   1130 	simple_unlock(&ex->ex_slock);
   1131 }
   1132