xref: /netbsd-src/sys/kern/subr_extent.c (revision 17306b8fd0952c7489f93f0230818481e5a1e2c9)
1 /*	$NetBSD: subr_extent.c,v 1.42 2001/06/05 04:39:56 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 1996, 1998 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe and Matthias Drochner.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the NetBSD
21  *	Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * General purpose extent manager.
41  */
42 
43 #ifdef _KERNEL
44 #include <sys/param.h>
45 #include <sys/extent.h>
46 #include <sys/malloc.h>
47 #include <sys/pool.h>
48 #include <sys/time.h>
49 #include <sys/systm.h>
50 #include <sys/proc.h>
51 #include <sys/lock.h>
52 
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, 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 	 * For N allocated regions, we must make (N + 1)
627 	 * checks for unallocated space.  The first chunk we
628 	 * check is the area from the beginning of the subregion
629 	 * to the first allocated region after that point.
630 	 */
631 	newstart = EXTENT_ALIGN(substart, alignment, skew);
632 	if (newstart < ex->ex_start) {
633 #ifdef DIAGNOSTIC
634 		printf(
635       "extent_alloc_subregion: extent `%s' (0x%lx - 0x%lx), alignment 0x%lx\n",
636 		 ex->ex_name, ex->ex_start, ex->ex_end, alignment);
637 		simple_unlock(&ex->ex_slock);
638 		panic("extent_alloc_subregion: overflow after alignment");
639 #else
640 		extent_free_region_descriptor(ex, myrp);
641 		simple_unlock(&ex->ex_slock);
642 		return (EINVAL);
643 #endif
644 	}
645 
646 	/*
647 	 * Find the first allocated region that begins on or after
648 	 * the subregion start, advancing the "last" pointer along
649 	 * the way.
650 	 */
651 	for (rp = ex->ex_regions.lh_first; rp != NULL;
652 	     rp = rp->er_link.le_next) {
653 		if (rp->er_start >= newstart)
654 			break;
655 		last = rp;
656 	}
657 
658 	/*
659 	 * Relocate the start of our candidate region to the end of
660 	 * the last allocated region (if there was one overlapping
661 	 * our subrange).
662 	 */
663 	if (last != NULL && last->er_end >= newstart)
664 		newstart = EXTENT_ALIGN((last->er_end + 1), alignment, skew);
665 
666 	for (; rp != NULL; rp = rp->er_link.le_next) {
667 		/*
668 		 * Check the chunk before "rp".  Note that our
669 		 * comparison is safe from overflow conditions.
670 		 */
671 		if (LE_OV(newstart, size, rp->er_start)) {
672 			/*
673 			 * Do a boundary check, if necessary.  Note
674 			 * that a region may *begin* on the boundary,
675 			 * but it must end before the boundary.
676 			 */
677 			if (boundary) {
678 				newend = newstart + (size - 1);
679 
680 				/*
681 				 * Calculate the next boundary after the start
682 				 * of this region.
683 				 */
684 				dontcross = EXTENT_ALIGN(newstart+1, boundary,
685 				    (flags & EX_BOUNDZERO) ? 0 : ex->ex_start)
686 				    - 1;
687 
688 #if 0
689 				printf("newstart=%lx newend=%lx ex_start=%lx ex_end=%lx boundary=%lx dontcross=%lx\n",
690 				    newstart, newend, ex->ex_start, ex->ex_end,
691 				    boundary, dontcross);
692 #endif
693 
694 				/* Check for overflow */
695 				if (dontcross < ex->ex_start)
696 					dontcross = ex->ex_end;
697 				else if (newend > dontcross) {
698 					/*
699 					 * Candidate region crosses boundary.
700 					 * Throw away the leading part and see
701 					 * if we still fit.
702 					 */
703 					newstart = dontcross + 1;
704 					newend = newstart + (size - 1);
705 					dontcross += boundary;
706 					if (!LE_OV(newstart, size, rp->er_start))
707 						continue;
708 				}
709 
710 				/*
711 				 * If we run past the end of
712 				 * the extent or the boundary
713 				 * overflows, then the request
714 				 * can't fit.
715 				 */
716 				if (newstart + size - 1 > ex->ex_end ||
717 				    dontcross < newstart)
718 					goto fail;
719 			}
720 
721 			/*
722 			 * We would fit into this space.  Calculate
723 			 * the overhead (wasted space).  If we exactly
724 			 * fit, or we're taking the first fit, insert
725 			 * ourselves into the region list.
726 			 */
727 			ovh = rp->er_start - newstart - size;
728 			if ((flags & EX_FAST) || (ovh == 0))
729 				goto found;
730 
731 			/*
732 			 * Don't exactly fit, but check to see
733 			 * if we're better than any current choice.
734 			 */
735 			if ((bestovh == 0) || (ovh < bestovh)) {
736 				bestovh = ovh;
737 				beststart = newstart;
738 				bestlast = last;
739 			}
740 		}
741 
742 		/*
743 		 * Skip past the current region and check again.
744 		 */
745 		newstart = EXTENT_ALIGN((rp->er_end + 1), alignment, skew);
746 		if (newstart < rp->er_end) {
747 			/*
748 			 * Overflow condition.  Don't error out, since
749 			 * we might have a chunk of space that we can
750 			 * use.
751 			 */
752 			goto fail;
753 		}
754 
755 		last = rp;
756 	}
757 
758 	/*
759 	 * The final check is from the current starting point to the
760 	 * end of the subregion.  If there were no allocated regions,
761 	 * "newstart" is set to the beginning of the subregion, or
762 	 * just past the end of the last allocated region, adjusted
763 	 * for alignment in either case.
764 	 */
765 	if (LE_OV(newstart, (size - 1), subend)) {
766 		/*
767 		 * Do a boundary check, if necessary.  Note
768 		 * that a region may *begin* on the boundary,
769 		 * but it must end before the boundary.
770 		 */
771 		if (boundary) {
772 			newend = newstart + (size - 1);
773 
774 			/*
775 			 * Calculate the next boundary after the start
776 			 * of this region.
777 			 */
778 			dontcross = EXTENT_ALIGN(newstart+1, boundary,
779 			    (flags & EX_BOUNDZERO) ? 0 : ex->ex_start)
780 			    - 1;
781 
782 #if 0
783 			printf("newstart=%lx newend=%lx ex_start=%lx ex_end=%lx boundary=%lx dontcross=%lx\n",
784 			    newstart, newend, ex->ex_start, ex->ex_end,
785 			    boundary, dontcross);
786 #endif
787 
788 			/* Check for overflow */
789 			if (dontcross < ex->ex_start)
790 				dontcross = ex->ex_end;
791 			else if (newend > dontcross) {
792 				/*
793 				 * Candidate region crosses boundary.
794 				 * Throw away the leading part and see
795 				 * if we still fit.
796 				 */
797 				newstart = dontcross + 1;
798 				newend = newstart + (size - 1);
799 				dontcross += boundary;
800 				if (!LE_OV(newstart, (size - 1), subend))
801 					goto fail;
802 			}
803 
804 			/*
805 			 * If we run past the end of
806 			 * the extent or the boundary
807 			 * overflows, then the request
808 			 * can't fit.
809 			 */
810 			if (newstart + size - 1 > ex->ex_end ||
811 			    dontcross < newstart)
812 				goto fail;
813 		}
814 
815 		/*
816 		 * We would fit into this space.  Calculate
817 		 * the overhead (wasted space).  If we exactly
818 		 * fit, or we're taking the first fit, insert
819 		 * ourselves into the region list.
820 		 */
821 		ovh = ex->ex_end - newstart - (size - 1);
822 		if ((flags & EX_FAST) || (ovh == 0))
823 			goto found;
824 
825 		/*
826 		 * Don't exactly fit, but check to see
827 		 * if we're better than any current choice.
828 		 */
829 		if ((bestovh == 0) || (ovh < bestovh)) {
830 			bestovh = ovh;
831 			beststart = newstart;
832 			bestlast = last;
833 		}
834 	}
835 
836  fail:
837 	/*
838 	 * One of the following two conditions have
839 	 * occurred:
840 	 *
841 	 *	There is no chunk large enough to hold the request.
842 	 *
843 	 *	If EX_FAST was not specified, there is not an
844 	 *	exact match for the request.
845 	 *
846 	 * Note that if we reach this point and EX_FAST is
847 	 * set, then we know there is no space in the extent for
848 	 * the request.
849 	 */
850 	if (((flags & EX_FAST) == 0) && (bestovh != 0)) {
851 		/*
852 		 * We have a match that's "good enough".
853 		 */
854 		newstart = beststart;
855 		last = bestlast;
856 		goto found;
857 	}
858 
859 	/*
860 	 * No space currently available.  Wait for it to free up,
861 	 * if possible.
862 	 */
863 	if (flags & EX_WAITSPACE) {
864 		ex->ex_flags |= EXF_WANTED;
865 		error = ltsleep(ex,
866 		    PNORELOCK | PRIBIO | ((flags & EX_CATCH) ? PCATCH : 0),
867 		    "extnt", 0, &ex->ex_slock);
868 		if (error)
869 			return (error);
870 		goto alloc_start;
871 	}
872 
873 	extent_free_region_descriptor(ex, myrp);
874 	simple_unlock(&ex->ex_slock);
875 	return (EAGAIN);
876 
877  found:
878 	/*
879 	 * Insert ourselves into the region list.
880 	 */
881 	extent_insert_and_optimize(ex, newstart, size, flags, last, myrp);
882 	simple_unlock(&ex->ex_slock);
883 	*result = newstart;
884 	return (0);
885 }
886 
887 int
888 extent_free(ex, start, size, flags)
889 	struct extent *ex;
890 	u_long start, size;
891 	int flags;
892 {
893 	struct extent_region *rp, *nrp = NULL;
894 	u_long end = start + (size - 1);
895 	int exflags;
896 
897 #ifdef DIAGNOSTIC
898 	/*
899 	 * Check arguments.
900 	 *
901 	 * We don't lock to check these, because these values
902 	 * are never modified, and if another thread deletes the
903 	 * extent, we're screwed anyway.
904 	 */
905 	if (ex == NULL)
906 		panic("extent_free: NULL extent");
907 	if ((start < ex->ex_start) || (start > ex->ex_end)) {
908 		extent_print(ex);
909 		printf("extent_free: extent `%s', start 0x%lx, size 0x%lx\n",
910 		    ex->ex_name, start, size);
911 		panic("extent_free: extent `%s', region not within extent",
912 		    ex->ex_name);
913 	}
914 	/* Check for an overflow. */
915 	if (end < start) {
916 		extent_print(ex);
917 		printf("extent_free: extent `%s', start 0x%lx, size 0x%lx\n",
918 		    ex->ex_name, start, size);
919 		panic("extent_free: overflow");
920 	}
921 #endif
922 
923 	/*
924 	 * If we're allowing coalescing, we must allocate a region
925 	 * descriptor now, since it might block.
926 	 *
927 	 * XXX Make a static, create-time flags word, so we don't
928 	 * XXX have to lock to read it!
929 	 */
930 	simple_lock(&ex->ex_slock);
931 	exflags = ex->ex_flags;
932 	simple_unlock(&ex->ex_slock);
933 
934 	if ((exflags & EXF_NOCOALESCE) == 0) {
935 		/* Allocate a region descriptor. */
936 		nrp = extent_alloc_region_descriptor(ex, flags);
937 		if (nrp == NULL)
938 			return (ENOMEM);
939 	}
940 
941 	simple_lock(&ex->ex_slock);
942 
943 	/*
944 	 * Find region and deallocate.  Several possibilities:
945 	 *
946 	 *	1. (start == er_start) && (end == er_end):
947 	 *	   Free descriptor.
948 	 *
949 	 *	2. (start == er_start) && (end < er_end):
950 	 *	   Adjust er_start.
951 	 *
952 	 *	3. (start > er_start) && (end == er_end):
953 	 *	   Adjust er_end.
954 	 *
955 	 *	4. (start > er_start) && (end < er_end):
956 	 *	   Fragment region.  Requires descriptor alloc.
957 	 *
958 	 * Cases 2, 3, and 4 require that the EXF_NOCOALESCE flag
959 	 * is not set.
960 	 */
961 	for (rp = ex->ex_regions.lh_first; rp != NULL;
962 	    rp = rp->er_link.le_next) {
963 		/*
964 		 * Save ourselves some comparisons; does the current
965 		 * region end before chunk to be freed begins?  If so,
966 		 * then we haven't found the appropriate region descriptor.
967 		 */
968 		if (rp->er_end < start)
969 			continue;
970 
971 		/*
972 		 * Save ourselves some traversal; does the current
973 		 * region begin after the chunk to be freed ends?  If so,
974 		 * then we've already passed any possible region descriptors
975 		 * that might have contained the chunk to be freed.
976 		 */
977 		if (rp->er_start > end)
978 			break;
979 
980 		/* Case 1. */
981 		if ((start == rp->er_start) && (end == rp->er_end)) {
982 			LIST_REMOVE(rp, er_link);
983 			extent_free_region_descriptor(ex, rp);
984 			goto done;
985 		}
986 
987 		/*
988 		 * The following cases all require that EXF_NOCOALESCE
989 		 * is not set.
990 		 */
991 		if (ex->ex_flags & EXF_NOCOALESCE)
992 			continue;
993 
994 		/* Case 2. */
995 		if ((start == rp->er_start) && (end < rp->er_end)) {
996 			rp->er_start = (end + 1);
997 			goto done;
998 		}
999 
1000 		/* Case 3. */
1001 		if ((start > rp->er_start) && (end == rp->er_end)) {
1002 			rp->er_end = (start - 1);
1003 			goto done;
1004 		}
1005 
1006 		/* Case 4. */
1007 		if ((start > rp->er_start) && (end < rp->er_end)) {
1008 			/* Fill in new descriptor. */
1009 			nrp->er_start = end + 1;
1010 			nrp->er_end = rp->er_end;
1011 
1012 			/* Adjust current descriptor. */
1013 			rp->er_end = start - 1;
1014 
1015 			/* Insert new descriptor after current. */
1016 			LIST_INSERT_AFTER(rp, nrp, er_link);
1017 
1018 			/* We used the new descriptor, so don't free it below */
1019 			nrp = NULL;
1020 			goto done;
1021 		}
1022 	}
1023 
1024 	/* Region not found, or request otherwise invalid. */
1025 	simple_unlock(&ex->ex_slock);
1026 	extent_print(ex);
1027 	printf("extent_free: start 0x%lx, end 0x%lx\n", start, end);
1028 	panic("extent_free: region not found");
1029 
1030  done:
1031 	if (nrp != NULL)
1032 		extent_free_region_descriptor(ex, nrp);
1033 	if (ex->ex_flags & EXF_WANTED) {
1034 		ex->ex_flags &= ~EXF_WANTED;
1035 		wakeup(ex);
1036 	}
1037 	simple_unlock(&ex->ex_slock);
1038 	return (0);
1039 }
1040 
1041 /*
1042  * Allocate an extent region descriptor.  EXTENT MUST NOT BE LOCKED,
1043  * AS THIS FUNCTION MAY BLOCK!  We will handle any locking we may need.
1044  */
1045 static struct extent_region *
1046 extent_alloc_region_descriptor(ex, flags)
1047 	struct extent *ex;
1048 	int flags;
1049 {
1050 	struct extent_region *rp;
1051 	int exflags;
1052 	int s;
1053 
1054 	/*
1055 	 * If the kernel memory allocator is not yet running, we can't
1056 	 * use it (obviously).
1057 	 */
1058 	if (KMEM_IS_RUNNING == 0)
1059 		flags &= ~EX_MALLOCOK;
1060 
1061 	/*
1062 	 * XXX Make a static, create-time flags word, so we don't
1063 	 * XXX have to lock to read it!
1064 	 */
1065 	simple_lock(&ex->ex_slock);
1066 	exflags = ex->ex_flags;
1067 	simple_unlock(&ex->ex_slock);
1068 
1069 	if (exflags & EXF_FIXED) {
1070 		struct extent_fixed *fex = (struct extent_fixed *)ex;
1071 
1072 		for (;;) {
1073 			simple_lock(&ex->ex_slock);
1074 			if ((rp = fex->fex_freelist.lh_first) != NULL) {
1075 				/*
1076 				 * Don't muck with flags after pulling it off
1077 				 * the freelist; it may have been dynamically
1078 				 * allocated, and kindly given to us.  We
1079 				 * need to remember that information.
1080 				 */
1081 				LIST_REMOVE(rp, er_link);
1082 				simple_unlock(&ex->ex_slock);
1083 				return (rp);
1084 			}
1085 			if (flags & EX_MALLOCOK) {
1086 				simple_unlock(&ex->ex_slock);
1087 				goto alloc;
1088 			}
1089 			if ((flags & EX_WAITOK) == 0) {
1090 				simple_unlock(&ex->ex_slock);
1091 				return (NULL);
1092 			}
1093 			ex->ex_flags |= EXF_FLWANTED;
1094 			if (ltsleep(&fex->fex_freelist,
1095 			    PNORELOCK| PRIBIO | ((flags & EX_CATCH) ? PCATCH : 0),
1096 			    "extnt", 0, &ex->ex_slock))
1097 				return (NULL);
1098 		}
1099 	}
1100 
1101  alloc:
1102 	s = splhigh();
1103 	if (expool_initialized == 0)
1104 		expool_init();
1105 	rp = pool_get(&expool, (flags & EX_WAITOK) ? PR_WAITOK : 0);
1106 	splx(s);
1107 
1108 	if (rp != NULL)
1109 		rp->er_flags = ER_ALLOC;
1110 
1111 	return (rp);
1112 }
1113 
1114 /*
1115  * Free an extent region descriptor.  EXTENT _MUST_ BE LOCKED!  This
1116  * is safe as we do not block here.
1117  */
1118 static void
1119 extent_free_region_descriptor(ex, rp)
1120 	struct extent *ex;
1121 	struct extent_region *rp;
1122 {
1123 	int s;
1124 
1125 	if (ex->ex_flags & EXF_FIXED) {
1126 		struct extent_fixed *fex = (struct extent_fixed *)ex;
1127 
1128 		/*
1129 		 * If someone's waiting for a region descriptor,
1130 		 * be nice and give them this one, rather than
1131 		 * just free'ing it back to the system.
1132 		 */
1133 		if (rp->er_flags & ER_ALLOC) {
1134 			if (ex->ex_flags & EXF_FLWANTED) {
1135 				/* Clear all but ER_ALLOC flag. */
1136 				rp->er_flags = ER_ALLOC;
1137 				LIST_INSERT_HEAD(&fex->fex_freelist, rp,
1138 				    er_link);
1139 				goto wake_em_up;
1140 			} else {
1141 				s = splhigh();
1142 				pool_put(&expool, rp);
1143 				splx(s);
1144 			}
1145 		} else {
1146 			/* Clear all flags. */
1147 			rp->er_flags = 0;
1148 			LIST_INSERT_HEAD(&fex->fex_freelist, rp, er_link);
1149 		}
1150 
1151 		if (ex->ex_flags & EXF_FLWANTED) {
1152  wake_em_up:
1153 			ex->ex_flags &= ~EXF_FLWANTED;
1154 			wakeup(&fex->fex_freelist);
1155 		}
1156 		return;
1157 	}
1158 
1159 	/*
1160 	 * We know it's dynamically allocated if we get here.
1161 	 */
1162 	s = splhigh();
1163 	pool_put(&expool, rp);
1164 	splx(s);
1165 }
1166 
1167 void
1168 extent_print(ex)
1169 	struct extent *ex;
1170 {
1171 	struct extent_region *rp;
1172 
1173 	if (ex == NULL)
1174 		panic("extent_print: NULL extent");
1175 
1176 	simple_lock(&ex->ex_slock);
1177 
1178 	printf("extent `%s' (0x%lx - 0x%lx), flags = 0x%x\n", ex->ex_name,
1179 	    ex->ex_start, ex->ex_end, ex->ex_flags);
1180 
1181 	for (rp = ex->ex_regions.lh_first; rp != NULL;
1182 	    rp = rp->er_link.le_next)
1183 		printf("     0x%lx - 0x%lx\n", rp->er_start, rp->er_end);
1184 
1185 	simple_unlock(&ex->ex_slock);
1186 }
1187