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