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