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