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