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