xref: /freebsd/sys/kern/subr_rman.c (revision 53b70c86)
1 /*-
2  * Copyright 1998 Massachusetts Institute of Technology
3  *
4  * Permission to use, copy, modify, and distribute this software and
5  * its documentation for any purpose and without fee is hereby
6  * granted, provided that both the above copyright notice and this
7  * permission notice appear in all copies, that both the above
8  * copyright notice and this permission notice appear in all
9  * supporting documentation, and that the name of M.I.T. not be used
10  * in advertising or publicity pertaining to distribution of the
11  * software without specific, written prior permission.  M.I.T. makes
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied
14  * warranty.
15  *
16  * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
17  * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
20  * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * The kernel resource manager.  This code is responsible for keeping track
32  * of hardware resources which are apportioned out to various drivers.
33  * It does not actually assign those resources, and it is not expected
34  * that end-device drivers will call into this code directly.  Rather,
35  * the code which implements the buses that those devices are attached to,
36  * and the code which manages CPU resources, will call this code, and the
37  * end-device drivers will make upcalls to that code to actually perform
38  * the allocation.
39  *
40  * There are two sorts of resources managed by this code.  The first is
41  * the more familiar array (RMAN_ARRAY) type; resources in this class
42  * consist of a sequence of individually-allocatable objects which have
43  * been numbered in some well-defined order.  Most of the resources
44  * are of this type, as it is the most familiar.  The second type is
45  * called a gauge (RMAN_GAUGE), and models fungible resources (i.e.,
46  * resources in which each instance is indistinguishable from every
47  * other instance).  The principal anticipated application of gauges
48  * is in the context of power consumption, where a bus may have a specific
49  * power budget which all attached devices share.  RMAN_GAUGE is not
50  * implemented yet.
51  *
52  * For array resources, we make one simplifying assumption: two clients
53  * sharing the same resource must use the same range of indices.  That
54  * is to say, sharing of overlapping-but-not-identical regions is not
55  * permitted.
56  */
57 
58 #include "opt_ddb.h"
59 
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
62 
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/limits.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mutex.h>
70 #include <sys/bus.h>		/* XXX debugging */
71 #include <machine/bus.h>
72 #include <sys/rman.h>
73 #include <sys/sysctl.h>
74 
75 #ifdef DDB
76 #include <ddb/ddb.h>
77 #endif
78 
79 /*
80  * We use a linked list rather than a bitmap because we need to be able to
81  * represent potentially huge objects (like all of a processor's physical
82  * address space).
83  */
84 struct resource_i {
85 	struct resource		r_r;
86 	TAILQ_ENTRY(resource_i)	r_link;
87 	LIST_ENTRY(resource_i)	r_sharelink;
88 	LIST_HEAD(, resource_i)	*r_sharehead;
89 	rman_res_t	r_start;	/* index of the first entry in this resource */
90 	rman_res_t	r_end;		/* index of the last entry (inclusive) */
91 	u_int	r_flags;
92 	void	*r_virtual;	/* virtual address of this resource */
93 	void	*r_irq_cookie;	/* interrupt cookie for this (interrupt) resource */
94 	device_t r_dev;	/* device which has allocated this resource */
95 	struct rman *r_rm;	/* resource manager from whence this came */
96 	int	r_rid;		/* optional rid for this resource. */
97 };
98 
99 static int rman_debug = 0;
100 SYSCTL_INT(_debug, OID_AUTO, rman_debug, CTLFLAG_RWTUN,
101     &rman_debug, 0, "rman debug");
102 
103 #define DPRINTF(params) if (rman_debug) printf params
104 
105 static MALLOC_DEFINE(M_RMAN, "rman", "Resource manager");
106 
107 struct rman_head rman_head;
108 static struct mtx rman_mtx; /* mutex to protect rman_head */
109 static int int_rman_release_resource(struct rman *rm, struct resource_i *r);
110 
111 static __inline struct resource_i *
112 int_alloc_resource(int malloc_flag)
113 {
114 	struct resource_i *r;
115 
116 	r = malloc(sizeof *r, M_RMAN, malloc_flag | M_ZERO);
117 	if (r != NULL) {
118 		r->r_r.__r_i = r;
119 	}
120 	return (r);
121 }
122 
123 int
124 rman_init(struct rman *rm)
125 {
126 	static int once = 0;
127 
128 	if (once == 0) {
129 		once = 1;
130 		TAILQ_INIT(&rman_head);
131 		mtx_init(&rman_mtx, "rman head", NULL, MTX_DEF);
132 	}
133 
134 	if (rm->rm_start == 0 && rm->rm_end == 0)
135 		rm->rm_end = ~0;
136 	if (rm->rm_type == RMAN_UNINIT)
137 		panic("rman_init");
138 	if (rm->rm_type == RMAN_GAUGE)
139 		panic("implement RMAN_GAUGE");
140 
141 	TAILQ_INIT(&rm->rm_list);
142 	rm->rm_mtx = malloc(sizeof *rm->rm_mtx, M_RMAN, M_NOWAIT | M_ZERO);
143 	if (rm->rm_mtx == NULL)
144 		return ENOMEM;
145 	mtx_init(rm->rm_mtx, "rman", NULL, MTX_DEF);
146 
147 	mtx_lock(&rman_mtx);
148 	TAILQ_INSERT_TAIL(&rman_head, rm, rm_link);
149 	mtx_unlock(&rman_mtx);
150 	return 0;
151 }
152 
153 int
154 rman_manage_region(struct rman *rm, rman_res_t start, rman_res_t end)
155 {
156 	struct resource_i *r, *s, *t;
157 	int rv = 0;
158 
159 	DPRINTF(("rman_manage_region: <%s> request: start %#jx, end %#jx\n",
160 	    rm->rm_descr, start, end));
161 	if (start < rm->rm_start || end > rm->rm_end)
162 		return EINVAL;
163 	r = int_alloc_resource(M_NOWAIT);
164 	if (r == NULL)
165 		return ENOMEM;
166 	r->r_start = start;
167 	r->r_end = end;
168 	r->r_rm = rm;
169 
170 	mtx_lock(rm->rm_mtx);
171 
172 	/* Skip entries before us. */
173 	TAILQ_FOREACH(s, &rm->rm_list, r_link) {
174 		if (s->r_end == ~0)
175 			break;
176 		if (s->r_end + 1 >= r->r_start)
177 			break;
178 	}
179 
180 	/* If we ran off the end of the list, insert at the tail. */
181 	if (s == NULL) {
182 		TAILQ_INSERT_TAIL(&rm->rm_list, r, r_link);
183 	} else {
184 		/* Check for any overlap with the current region. */
185 		if (r->r_start <= s->r_end && r->r_end >= s->r_start) {
186 			rv = EBUSY;
187 			goto out;
188 		}
189 
190 		/* Check for any overlap with the next region. */
191 		t = TAILQ_NEXT(s, r_link);
192 		if (t && r->r_start <= t->r_end && r->r_end >= t->r_start) {
193 			rv = EBUSY;
194 			goto out;
195 		}
196 
197 		/*
198 		 * See if this region can be merged with the next region.  If
199 		 * not, clear the pointer.
200 		 */
201 		if (t && (r->r_end + 1 != t->r_start || t->r_flags != 0))
202 			t = NULL;
203 
204 		/* See if we can merge with the current region. */
205 		if (s->r_end + 1 == r->r_start && s->r_flags == 0) {
206 			/* Can we merge all 3 regions? */
207 			if (t != NULL) {
208 				s->r_end = t->r_end;
209 				TAILQ_REMOVE(&rm->rm_list, t, r_link);
210 				free(r, M_RMAN);
211 				free(t, M_RMAN);
212 			} else {
213 				s->r_end = r->r_end;
214 				free(r, M_RMAN);
215 			}
216 		} else if (t != NULL) {
217 			/* Can we merge with just the next region? */
218 			t->r_start = r->r_start;
219 			free(r, M_RMAN);
220 		} else if (s->r_end < r->r_start) {
221 			TAILQ_INSERT_AFTER(&rm->rm_list, s, r, r_link);
222 		} else {
223 			TAILQ_INSERT_BEFORE(s, r, r_link);
224 		}
225 	}
226 out:
227 	mtx_unlock(rm->rm_mtx);
228 	return rv;
229 }
230 
231 int
232 rman_init_from_resource(struct rman *rm, struct resource *r)
233 {
234 	int rv;
235 
236 	if ((rv = rman_init(rm)) != 0)
237 		return (rv);
238 	return (rman_manage_region(rm, r->__r_i->r_start, r->__r_i->r_end));
239 }
240 
241 int
242 rman_fini(struct rman *rm)
243 {
244 	struct resource_i *r;
245 
246 	mtx_lock(rm->rm_mtx);
247 	TAILQ_FOREACH(r, &rm->rm_list, r_link) {
248 		if (r->r_flags & RF_ALLOCATED) {
249 			mtx_unlock(rm->rm_mtx);
250 			return EBUSY;
251 		}
252 	}
253 
254 	/*
255 	 * There really should only be one of these if we are in this
256 	 * state and the code is working properly, but it can't hurt.
257 	 */
258 	while (!TAILQ_EMPTY(&rm->rm_list)) {
259 		r = TAILQ_FIRST(&rm->rm_list);
260 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
261 		free(r, M_RMAN);
262 	}
263 	mtx_unlock(rm->rm_mtx);
264 	mtx_lock(&rman_mtx);
265 	TAILQ_REMOVE(&rman_head, rm, rm_link);
266 	mtx_unlock(&rman_mtx);
267 	mtx_destroy(rm->rm_mtx);
268 	free(rm->rm_mtx, M_RMAN);
269 
270 	return 0;
271 }
272 
273 int
274 rman_first_free_region(struct rman *rm, rman_res_t *start, rman_res_t *end)
275 {
276 	struct resource_i *r;
277 
278 	mtx_lock(rm->rm_mtx);
279 	TAILQ_FOREACH(r, &rm->rm_list, r_link) {
280 		if (!(r->r_flags & RF_ALLOCATED)) {
281 			*start = r->r_start;
282 			*end = r->r_end;
283 			mtx_unlock(rm->rm_mtx);
284 			return (0);
285 		}
286 	}
287 	mtx_unlock(rm->rm_mtx);
288 	return (ENOENT);
289 }
290 
291 int
292 rman_last_free_region(struct rman *rm, rman_res_t *start, rman_res_t *end)
293 {
294 	struct resource_i *r;
295 
296 	mtx_lock(rm->rm_mtx);
297 	TAILQ_FOREACH_REVERSE(r, &rm->rm_list, resource_head, r_link) {
298 		if (!(r->r_flags & RF_ALLOCATED)) {
299 			*start = r->r_start;
300 			*end = r->r_end;
301 			mtx_unlock(rm->rm_mtx);
302 			return (0);
303 		}
304 	}
305 	mtx_unlock(rm->rm_mtx);
306 	return (ENOENT);
307 }
308 
309 /* Shrink or extend one or both ends of an allocated resource. */
310 int
311 rman_adjust_resource(struct resource *rr, rman_res_t start, rman_res_t end)
312 {
313 	struct resource_i *r, *s, *t, *new;
314 	struct rman *rm;
315 
316 	/* Not supported for shared resources. */
317 	r = rr->__r_i;
318 	if (r->r_flags & RF_SHAREABLE)
319 		return (EINVAL);
320 
321 	/*
322 	 * This does not support wholesale moving of a resource.  At
323 	 * least part of the desired new range must overlap with the
324 	 * existing resource.
325 	 */
326 	if (end < r->r_start || r->r_end < start)
327 		return (EINVAL);
328 
329 	/*
330 	 * Find the two resource regions immediately adjacent to the
331 	 * allocated resource.
332 	 */
333 	rm = r->r_rm;
334 	mtx_lock(rm->rm_mtx);
335 #ifdef INVARIANTS
336 	TAILQ_FOREACH(s, &rm->rm_list, r_link) {
337 		if (s == r)
338 			break;
339 	}
340 	if (s == NULL)
341 		panic("resource not in list");
342 #endif
343 	s = TAILQ_PREV(r, resource_head, r_link);
344 	t = TAILQ_NEXT(r, r_link);
345 	KASSERT(s == NULL || s->r_end + 1 == r->r_start,
346 	    ("prev resource mismatch"));
347 	KASSERT(t == NULL || r->r_end + 1 == t->r_start,
348 	    ("next resource mismatch"));
349 
350 	/*
351 	 * See if the changes are permitted.  Shrinking is always allowed,
352 	 * but growing requires sufficient room in the adjacent region.
353 	 */
354 	if (start < r->r_start && (s == NULL || (s->r_flags & RF_ALLOCATED) ||
355 	    s->r_start > start)) {
356 		mtx_unlock(rm->rm_mtx);
357 		return (EBUSY);
358 	}
359 	if (end > r->r_end && (t == NULL || (t->r_flags & RF_ALLOCATED) ||
360 	    t->r_end < end)) {
361 		mtx_unlock(rm->rm_mtx);
362 		return (EBUSY);
363 	}
364 
365 	/*
366 	 * While holding the lock, grow either end of the resource as
367 	 * needed and shrink either end if the shrinking does not require
368 	 * allocating a new resource.  We can safely drop the lock and then
369 	 * insert a new range to handle the shrinking case afterwards.
370 	 */
371 	if (start < r->r_start ||
372 	    (start > r->r_start && s != NULL && !(s->r_flags & RF_ALLOCATED))) {
373 		KASSERT(s->r_flags == 0, ("prev is busy"));
374 		r->r_start = start;
375 		if (s->r_start == start) {
376 			TAILQ_REMOVE(&rm->rm_list, s, r_link);
377 			free(s, M_RMAN);
378 		} else
379 			s->r_end = start - 1;
380 	}
381 	if (end > r->r_end ||
382 	    (end < r->r_end && t != NULL && !(t->r_flags & RF_ALLOCATED))) {
383 		KASSERT(t->r_flags == 0, ("next is busy"));
384 		r->r_end = end;
385 		if (t->r_end == end) {
386 			TAILQ_REMOVE(&rm->rm_list, t, r_link);
387 			free(t, M_RMAN);
388 		} else
389 			t->r_start = end + 1;
390 	}
391 	mtx_unlock(rm->rm_mtx);
392 
393 	/*
394 	 * Handle the shrinking cases that require allocating a new
395 	 * resource to hold the newly-free region.  We have to recheck
396 	 * if we still need this new region after acquiring the lock.
397 	 */
398 	if (start > r->r_start) {
399 		new = int_alloc_resource(M_WAITOK);
400 		new->r_start = r->r_start;
401 		new->r_end = start - 1;
402 		new->r_rm = rm;
403 		mtx_lock(rm->rm_mtx);
404 		r->r_start = start;
405 		s = TAILQ_PREV(r, resource_head, r_link);
406 		if (s != NULL && !(s->r_flags & RF_ALLOCATED)) {
407 			s->r_end = start - 1;
408 			free(new, M_RMAN);
409 		} else
410 			TAILQ_INSERT_BEFORE(r, new, r_link);
411 		mtx_unlock(rm->rm_mtx);
412 	}
413 	if (end < r->r_end) {
414 		new = int_alloc_resource(M_WAITOK);
415 		new->r_start = end + 1;
416 		new->r_end = r->r_end;
417 		new->r_rm = rm;
418 		mtx_lock(rm->rm_mtx);
419 		r->r_end = end;
420 		t = TAILQ_NEXT(r, r_link);
421 		if (t != NULL && !(t->r_flags & RF_ALLOCATED)) {
422 			t->r_start = end + 1;
423 			free(new, M_RMAN);
424 		} else
425 			TAILQ_INSERT_AFTER(&rm->rm_list, r, new, r_link);
426 		mtx_unlock(rm->rm_mtx);
427 	}
428 	return (0);
429 }
430 
431 #define	SHARE_TYPE(f)	(f & (RF_SHAREABLE | RF_PREFETCHABLE))
432 
433 struct resource *
434 rman_reserve_resource_bound(struct rman *rm, rman_res_t start, rman_res_t end,
435 			    rman_res_t count, rman_res_t bound, u_int flags,
436 			    device_t dev)
437 {
438 	u_int new_rflags;
439 	struct resource_i *r, *s, *rv;
440 	rman_res_t rstart, rend, amask, bmask;
441 
442 	rv = NULL;
443 
444 	DPRINTF(("rman_reserve_resource_bound: <%s> request: [%#jx, %#jx], "
445 	       "length %#jx, flags %x, device %s\n", rm->rm_descr, start, end,
446 	       count, flags,
447 	       dev == NULL ? "<null>" : device_get_nameunit(dev)));
448 	KASSERT((flags & RF_FIRSTSHARE) == 0,
449 	    ("invalid flags %#x", flags));
450 	new_rflags = (flags & ~RF_FIRSTSHARE) | RF_ALLOCATED;
451 
452 	mtx_lock(rm->rm_mtx);
453 
454 	r = TAILQ_FIRST(&rm->rm_list);
455 	if (r == NULL) {
456 	    DPRINTF(("NULL list head\n"));
457 	} else {
458 	    DPRINTF(("rman_reserve_resource_bound: trying %#jx <%#jx,%#jx>\n",
459 		    r->r_end, start, count-1));
460 	}
461 	for (r = TAILQ_FIRST(&rm->rm_list);
462 	     r && r->r_end < start + count - 1;
463 	     r = TAILQ_NEXT(r, r_link)) {
464 		;
465 		DPRINTF(("rman_reserve_resource_bound: tried %#jx <%#jx,%#jx>\n",
466 			r->r_end, start, count-1));
467 	}
468 
469 	if (r == NULL) {
470 		DPRINTF(("could not find a region\n"));
471 		goto out;
472 	}
473 
474 	amask = (1ull << RF_ALIGNMENT(flags)) - 1;
475 	KASSERT(start <= RM_MAX_END - amask,
476 	    ("start (%#jx) + amask (%#jx) would wrap around", start, amask));
477 
478 	/* If bound is 0, bmask will also be 0 */
479 	bmask = ~(bound - 1);
480 	/*
481 	 * First try to find an acceptable totally-unshared region.
482 	 */
483 	for (s = r; s; s = TAILQ_NEXT(s, r_link)) {
484 		DPRINTF(("considering [%#jx, %#jx]\n", s->r_start, s->r_end));
485 		/*
486 		 * The resource list is sorted, so there is no point in
487 		 * searching further once r_start is too large.
488 		 */
489 		if (s->r_start > end - (count - 1)) {
490 			DPRINTF(("s->r_start (%#jx) + count - 1> end (%#jx)\n",
491 			    s->r_start, end));
492 			break;
493 		}
494 		if (s->r_start > RM_MAX_END - amask) {
495 			DPRINTF(("s->r_start (%#jx) + amask (%#jx) too large\n",
496 			    s->r_start, amask));
497 			break;
498 		}
499 		if (s->r_flags & RF_ALLOCATED) {
500 			DPRINTF(("region is allocated\n"));
501 			continue;
502 		}
503 		rstart = ummax(s->r_start, start);
504 		/*
505 		 * Try to find a region by adjusting to boundary and alignment
506 		 * until both conditions are satisfied. This is not an optimal
507 		 * algorithm, but in most cases it isn't really bad, either.
508 		 */
509 		do {
510 			rstart = (rstart + amask) & ~amask;
511 			if (((rstart ^ (rstart + count - 1)) & bmask) != 0)
512 				rstart += bound - (rstart & ~bmask);
513 		} while ((rstart & amask) != 0 && rstart < end &&
514 		    rstart < s->r_end);
515 		rend = ummin(s->r_end, ummax(rstart + count - 1, end));
516 		if (rstart > rend) {
517 			DPRINTF(("adjusted start exceeds end\n"));
518 			continue;
519 		}
520 		DPRINTF(("truncated region: [%#jx, %#jx]; size %#jx (requested %#jx)\n",
521 		       rstart, rend, (rend - rstart + 1), count));
522 
523 		if ((rend - rstart + 1) >= count) {
524 			DPRINTF(("candidate region: [%#jx, %#jx], size %#jx\n",
525 			       rstart, rend, (rend - rstart + 1)));
526 			if ((s->r_end - s->r_start + 1) == count) {
527 				DPRINTF(("candidate region is entire chunk\n"));
528 				rv = s;
529 				rv->r_flags = new_rflags;
530 				rv->r_dev = dev;
531 				goto out;
532 			}
533 
534 			/*
535 			 * If s->r_start < rstart and
536 			 *    s->r_end > rstart + count - 1, then
537 			 * we need to split the region into three pieces
538 			 * (the middle one will get returned to the user).
539 			 * Otherwise, we are allocating at either the
540 			 * beginning or the end of s, so we only need to
541 			 * split it in two.  The first case requires
542 			 * two new allocations; the second requires but one.
543 			 */
544 			rv = int_alloc_resource(M_NOWAIT);
545 			if (rv == NULL)
546 				goto out;
547 			rv->r_start = rstart;
548 			rv->r_end = rstart + count - 1;
549 			rv->r_flags = new_rflags;
550 			rv->r_dev = dev;
551 			rv->r_rm = rm;
552 
553 			if (s->r_start < rv->r_start && s->r_end > rv->r_end) {
554 				DPRINTF(("splitting region in three parts: "
555 				       "[%#jx, %#jx]; [%#jx, %#jx]; [%#jx, %#jx]\n",
556 				       s->r_start, rv->r_start - 1,
557 				       rv->r_start, rv->r_end,
558 				       rv->r_end + 1, s->r_end));
559 				/*
560 				 * We are allocating in the middle.
561 				 */
562 				r = int_alloc_resource(M_NOWAIT);
563 				if (r == NULL) {
564 					free(rv, M_RMAN);
565 					rv = NULL;
566 					goto out;
567 				}
568 				r->r_start = rv->r_end + 1;
569 				r->r_end = s->r_end;
570 				r->r_flags = s->r_flags;
571 				r->r_rm = rm;
572 				s->r_end = rv->r_start - 1;
573 				TAILQ_INSERT_AFTER(&rm->rm_list, s, rv,
574 						     r_link);
575 				TAILQ_INSERT_AFTER(&rm->rm_list, rv, r,
576 						     r_link);
577 			} else if (s->r_start == rv->r_start) {
578 				DPRINTF(("allocating from the beginning\n"));
579 				/*
580 				 * We are allocating at the beginning.
581 				 */
582 				s->r_start = rv->r_end + 1;
583 				TAILQ_INSERT_BEFORE(s, rv, r_link);
584 			} else {
585 				DPRINTF(("allocating at the end\n"));
586 				/*
587 				 * We are allocating at the end.
588 				 */
589 				s->r_end = rv->r_start - 1;
590 				TAILQ_INSERT_AFTER(&rm->rm_list, s, rv,
591 						     r_link);
592 			}
593 			goto out;
594 		}
595 	}
596 
597 	/*
598 	 * Now find an acceptable shared region, if the client's requirements
599 	 * allow sharing.  By our implementation restriction, a candidate
600 	 * region must match exactly by both size and sharing type in order
601 	 * to be considered compatible with the client's request.  (The
602 	 * former restriction could probably be lifted without too much
603 	 * additional work, but this does not seem warranted.)
604 	 */
605 	DPRINTF(("no unshared regions found\n"));
606 	if ((flags & RF_SHAREABLE) == 0)
607 		goto out;
608 
609 	for (s = r; s && s->r_end <= end; s = TAILQ_NEXT(s, r_link)) {
610 		if (SHARE_TYPE(s->r_flags) == SHARE_TYPE(flags) &&
611 		    s->r_start >= start &&
612 		    (s->r_end - s->r_start + 1) == count &&
613 		    (s->r_start & amask) == 0 &&
614 		    ((s->r_start ^ s->r_end) & bmask) == 0) {
615 			rv = int_alloc_resource(M_NOWAIT);
616 			if (rv == NULL)
617 				goto out;
618 			rv->r_start = s->r_start;
619 			rv->r_end = s->r_end;
620 			rv->r_flags = new_rflags;
621 			rv->r_dev = dev;
622 			rv->r_rm = rm;
623 			if (s->r_sharehead == NULL) {
624 				s->r_sharehead = malloc(sizeof *s->r_sharehead,
625 						M_RMAN, M_NOWAIT | M_ZERO);
626 				if (s->r_sharehead == NULL) {
627 					free(rv, M_RMAN);
628 					rv = NULL;
629 					goto out;
630 				}
631 				LIST_INIT(s->r_sharehead);
632 				LIST_INSERT_HEAD(s->r_sharehead, s,
633 						 r_sharelink);
634 				s->r_flags |= RF_FIRSTSHARE;
635 			}
636 			rv->r_sharehead = s->r_sharehead;
637 			LIST_INSERT_HEAD(s->r_sharehead, rv, r_sharelink);
638 			goto out;
639 		}
640 	}
641 	/*
642 	 * We couldn't find anything.
643 	 */
644 
645 out:
646 	mtx_unlock(rm->rm_mtx);
647 	return (rv == NULL ? NULL : &rv->r_r);
648 }
649 
650 struct resource *
651 rman_reserve_resource(struct rman *rm, rman_res_t start, rman_res_t end,
652 		      rman_res_t count, u_int flags, device_t dev)
653 {
654 
655 	return (rman_reserve_resource_bound(rm, start, end, count, 0, flags,
656 	    dev));
657 }
658 
659 int
660 rman_activate_resource(struct resource *re)
661 {
662 	struct resource_i *r;
663 	struct rman *rm;
664 
665 	r = re->__r_i;
666 	rm = r->r_rm;
667 	mtx_lock(rm->rm_mtx);
668 	r->r_flags |= RF_ACTIVE;
669 	mtx_unlock(rm->rm_mtx);
670 	return 0;
671 }
672 
673 int
674 rman_deactivate_resource(struct resource *r)
675 {
676 	struct rman *rm;
677 
678 	rm = r->__r_i->r_rm;
679 	mtx_lock(rm->rm_mtx);
680 	r->__r_i->r_flags &= ~RF_ACTIVE;
681 	mtx_unlock(rm->rm_mtx);
682 	return 0;
683 }
684 
685 static int
686 int_rman_release_resource(struct rman *rm, struct resource_i *r)
687 {
688 	struct resource_i *s, *t;
689 
690 	if (r->r_flags & RF_ACTIVE)
691 		r->r_flags &= ~RF_ACTIVE;
692 
693 	/*
694 	 * Check for a sharing list first.  If there is one, then we don't
695 	 * have to think as hard.
696 	 */
697 	if (r->r_sharehead) {
698 		/*
699 		 * If a sharing list exists, then we know there are at
700 		 * least two sharers.
701 		 *
702 		 * If we are in the main circleq, appoint someone else.
703 		 */
704 		LIST_REMOVE(r, r_sharelink);
705 		s = LIST_FIRST(r->r_sharehead);
706 		if (r->r_flags & RF_FIRSTSHARE) {
707 			s->r_flags |= RF_FIRSTSHARE;
708 			TAILQ_INSERT_BEFORE(r, s, r_link);
709 			TAILQ_REMOVE(&rm->rm_list, r, r_link);
710 		}
711 
712 		/*
713 		 * Make sure that the sharing list goes away completely
714 		 * if the resource is no longer being shared at all.
715 		 */
716 		if (LIST_NEXT(s, r_sharelink) == NULL) {
717 			free(s->r_sharehead, M_RMAN);
718 			s->r_sharehead = NULL;
719 			s->r_flags &= ~RF_FIRSTSHARE;
720 		}
721 		goto out;
722 	}
723 
724 	/*
725 	 * Look at the adjacent resources in the list and see if our
726 	 * segment can be merged with any of them.  If either of the
727 	 * resources is allocated or is not exactly adjacent then they
728 	 * cannot be merged with our segment.
729 	 */
730 	s = TAILQ_PREV(r, resource_head, r_link);
731 	if (s != NULL && ((s->r_flags & RF_ALLOCATED) != 0 ||
732 	    s->r_end + 1 != r->r_start))
733 		s = NULL;
734 	t = TAILQ_NEXT(r, r_link);
735 	if (t != NULL && ((t->r_flags & RF_ALLOCATED) != 0 ||
736 	    r->r_end + 1 != t->r_start))
737 		t = NULL;
738 
739 	if (s != NULL && t != NULL) {
740 		/*
741 		 * Merge all three segments.
742 		 */
743 		s->r_end = t->r_end;
744 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
745 		TAILQ_REMOVE(&rm->rm_list, t, r_link);
746 		free(t, M_RMAN);
747 	} else if (s != NULL) {
748 		/*
749 		 * Merge previous segment with ours.
750 		 */
751 		s->r_end = r->r_end;
752 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
753 	} else if (t != NULL) {
754 		/*
755 		 * Merge next segment with ours.
756 		 */
757 		t->r_start = r->r_start;
758 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
759 	} else {
760 		/*
761 		 * At this point, we know there is nothing we
762 		 * can potentially merge with, because on each
763 		 * side, there is either nothing there or what is
764 		 * there is still allocated.  In that case, we don't
765 		 * want to remove r from the list; we simply want to
766 		 * change it to an unallocated region and return
767 		 * without freeing anything.
768 		 */
769 		r->r_flags &= ~RF_ALLOCATED;
770 		r->r_dev = NULL;
771 		return 0;
772 	}
773 
774 out:
775 	free(r, M_RMAN);
776 	return 0;
777 }
778 
779 int
780 rman_release_resource(struct resource *re)
781 {
782 	int rv;
783 	struct resource_i *r;
784 	struct rman *rm;
785 
786 	r = re->__r_i;
787 	rm = r->r_rm;
788 	mtx_lock(rm->rm_mtx);
789 	rv = int_rman_release_resource(rm, r);
790 	mtx_unlock(rm->rm_mtx);
791 	return (rv);
792 }
793 
794 uint32_t
795 rman_make_alignment_flags(uint32_t size)
796 {
797 	int i;
798 
799 	/*
800 	 * Find the hightest bit set, and add one if more than one bit
801 	 * set.  We're effectively computing the ceil(log2(size)) here.
802 	 */
803 	for (i = 31; i > 0; i--)
804 		if ((1 << i) & size)
805 			break;
806 	if (~(1 << i) & size)
807 		i++;
808 
809 	return(RF_ALIGNMENT_LOG2(i));
810 }
811 
812 void
813 rman_set_start(struct resource *r, rman_res_t start)
814 {
815 
816 	r->__r_i->r_start = start;
817 }
818 
819 rman_res_t
820 rman_get_start(struct resource *r)
821 {
822 
823 	return (r->__r_i->r_start);
824 }
825 
826 void
827 rman_set_end(struct resource *r, rman_res_t end)
828 {
829 
830 	r->__r_i->r_end = end;
831 }
832 
833 rman_res_t
834 rman_get_end(struct resource *r)
835 {
836 
837 	return (r->__r_i->r_end);
838 }
839 
840 rman_res_t
841 rman_get_size(struct resource *r)
842 {
843 
844 	return (r->__r_i->r_end - r->__r_i->r_start + 1);
845 }
846 
847 u_int
848 rman_get_flags(struct resource *r)
849 {
850 
851 	return (r->__r_i->r_flags);
852 }
853 
854 void
855 rman_set_virtual(struct resource *r, void *v)
856 {
857 
858 	r->__r_i->r_virtual = v;
859 }
860 
861 void *
862 rman_get_virtual(struct resource *r)
863 {
864 
865 	return (r->__r_i->r_virtual);
866 }
867 
868 void
869 rman_set_irq_cookie(struct resource *r, void *c)
870 {
871 
872 	r->__r_i->r_irq_cookie = c;
873 }
874 
875 void *
876 rman_get_irq_cookie(struct resource *r)
877 {
878 
879 	return (r->__r_i->r_irq_cookie);
880 }
881 
882 void
883 rman_set_bustag(struct resource *r, bus_space_tag_t t)
884 {
885 
886 	r->r_bustag = t;
887 }
888 
889 bus_space_tag_t
890 rman_get_bustag(struct resource *r)
891 {
892 
893 	return (r->r_bustag);
894 }
895 
896 void
897 rman_set_bushandle(struct resource *r, bus_space_handle_t h)
898 {
899 
900 	r->r_bushandle = h;
901 }
902 
903 bus_space_handle_t
904 rman_get_bushandle(struct resource *r)
905 {
906 
907 	return (r->r_bushandle);
908 }
909 
910 void
911 rman_set_mapping(struct resource *r, struct resource_map *map)
912 {
913 
914 	KASSERT(rman_get_size(r) == map->r_size,
915 	    ("rman_set_mapping: size mismatch"));
916 	rman_set_bustag(r, map->r_bustag);
917 	rman_set_bushandle(r, map->r_bushandle);
918 	rman_set_virtual(r, map->r_vaddr);
919 }
920 
921 void
922 rman_get_mapping(struct resource *r, struct resource_map *map)
923 {
924 
925 	map->r_bustag = rman_get_bustag(r);
926 	map->r_bushandle = rman_get_bushandle(r);
927 	map->r_size = rman_get_size(r);
928 	map->r_vaddr = rman_get_virtual(r);
929 }
930 
931 void
932 rman_set_rid(struct resource *r, int rid)
933 {
934 
935 	r->__r_i->r_rid = rid;
936 }
937 
938 int
939 rman_get_rid(struct resource *r)
940 {
941 
942 	return (r->__r_i->r_rid);
943 }
944 
945 void
946 rman_set_device(struct resource *r, device_t dev)
947 {
948 
949 	r->__r_i->r_dev = dev;
950 }
951 
952 device_t
953 rman_get_device(struct resource *r)
954 {
955 
956 	return (r->__r_i->r_dev);
957 }
958 
959 int
960 rman_is_region_manager(struct resource *r, struct rman *rm)
961 {
962 
963 	return (r->__r_i->r_rm == rm);
964 }
965 
966 /*
967  * Sysctl interface for scanning the resource lists.
968  *
969  * We take two input parameters; the index into the list of resource
970  * managers, and the resource offset into the list.
971  */
972 static int
973 sysctl_rman(SYSCTL_HANDLER_ARGS)
974 {
975 	int			*name = (int *)arg1;
976 	u_int			namelen = arg2;
977 	int			rman_idx, res_idx;
978 	struct rman		*rm;
979 	struct resource_i	*res;
980 	struct resource_i	*sres;
981 	struct u_rman		urm;
982 	struct u_resource	ures;
983 	int			error;
984 
985 	if (namelen != 3)
986 		return (EINVAL);
987 
988 	if (bus_data_generation_check(name[0]))
989 		return (EINVAL);
990 	rman_idx = name[1];
991 	res_idx = name[2];
992 
993 	/*
994 	 * Find the indexed resource manager
995 	 */
996 	mtx_lock(&rman_mtx);
997 	TAILQ_FOREACH(rm, &rman_head, rm_link) {
998 		if (rman_idx-- == 0)
999 			break;
1000 	}
1001 	mtx_unlock(&rman_mtx);
1002 	if (rm == NULL)
1003 		return (ENOENT);
1004 
1005 	/*
1006 	 * If the resource index is -1, we want details on the
1007 	 * resource manager.
1008 	 */
1009 	if (res_idx == -1) {
1010 		bzero(&urm, sizeof(urm));
1011 		urm.rm_handle = (uintptr_t)rm;
1012 		if (rm->rm_descr != NULL)
1013 			strlcpy(urm.rm_descr, rm->rm_descr, RM_TEXTLEN);
1014 		urm.rm_start = rm->rm_start;
1015 		urm.rm_size = rm->rm_end - rm->rm_start + 1;
1016 		urm.rm_type = rm->rm_type;
1017 
1018 		error = SYSCTL_OUT(req, &urm, sizeof(urm));
1019 		return (error);
1020 	}
1021 
1022 	/*
1023 	 * Find the indexed resource and return it.
1024 	 */
1025 	mtx_lock(rm->rm_mtx);
1026 	TAILQ_FOREACH(res, &rm->rm_list, r_link) {
1027 		if (res->r_sharehead != NULL) {
1028 			LIST_FOREACH(sres, res->r_sharehead, r_sharelink)
1029 				if (res_idx-- == 0) {
1030 					res = sres;
1031 					goto found;
1032 				}
1033 		}
1034 		else if (res_idx-- == 0)
1035 				goto found;
1036 	}
1037 	mtx_unlock(rm->rm_mtx);
1038 	return (ENOENT);
1039 
1040 found:
1041 	bzero(&ures, sizeof(ures));
1042 	ures.r_handle = (uintptr_t)res;
1043 	ures.r_parent = (uintptr_t)res->r_rm;
1044 	ures.r_device = (uintptr_t)res->r_dev;
1045 	if (res->r_dev != NULL) {
1046 		if (device_get_name(res->r_dev) != NULL) {
1047 			snprintf(ures.r_devname, RM_TEXTLEN,
1048 			    "%s%d",
1049 			    device_get_name(res->r_dev),
1050 			    device_get_unit(res->r_dev));
1051 		} else {
1052 			strlcpy(ures.r_devname, "nomatch",
1053 			    RM_TEXTLEN);
1054 		}
1055 	} else {
1056 		ures.r_devname[0] = '\0';
1057 	}
1058 	ures.r_start = res->r_start;
1059 	ures.r_size = res->r_end - res->r_start + 1;
1060 	ures.r_flags = res->r_flags;
1061 
1062 	mtx_unlock(rm->rm_mtx);
1063 	error = SYSCTL_OUT(req, &ures, sizeof(ures));
1064 	return (error);
1065 }
1066 
1067 static SYSCTL_NODE(_hw_bus, OID_AUTO, rman, CTLFLAG_RD | CTLFLAG_MPSAFE,
1068     sysctl_rman,
1069     "kernel resource manager");
1070 
1071 #ifdef DDB
1072 static void
1073 dump_rman_header(struct rman *rm)
1074 {
1075 
1076 	if (db_pager_quit)
1077 		return;
1078 	db_printf("rman %p: %s (0x%jx-0x%jx full range)\n",
1079 	    rm, rm->rm_descr, (rman_res_t)rm->rm_start, (rman_res_t)rm->rm_end);
1080 }
1081 
1082 static void
1083 dump_rman(struct rman *rm)
1084 {
1085 	struct resource_i *r;
1086 	const char *devname;
1087 
1088 	if (db_pager_quit)
1089 		return;
1090 	TAILQ_FOREACH(r, &rm->rm_list, r_link) {
1091 		if (r->r_dev != NULL) {
1092 			devname = device_get_nameunit(r->r_dev);
1093 			if (devname == NULL)
1094 				devname = "nomatch";
1095 		} else
1096 			devname = NULL;
1097 		db_printf("    0x%jx-0x%jx (RID=%d) ",
1098 		    r->r_start, r->r_end, r->r_rid);
1099 		if (devname != NULL)
1100 			db_printf("(%s)\n", devname);
1101 		else
1102 			db_printf("----\n");
1103 		if (db_pager_quit)
1104 			return;
1105 	}
1106 }
1107 
1108 DB_SHOW_COMMAND(rman, db_show_rman)
1109 {
1110 
1111 	if (have_addr) {
1112 		dump_rman_header((struct rman *)addr);
1113 		dump_rman((struct rman *)addr);
1114 	}
1115 }
1116 
1117 DB_SHOW_COMMAND(rmans, db_show_rmans)
1118 {
1119 	struct rman *rm;
1120 
1121 	TAILQ_FOREACH(rm, &rman_head, rm_link) {
1122 		dump_rman_header(rm);
1123 	}
1124 }
1125 
1126 DB_SHOW_ALL_COMMAND(rman, db_show_all_rman)
1127 {
1128 	struct rman *rm;
1129 
1130 	TAILQ_FOREACH(rm, &rman_head, rm_link) {
1131 		dump_rman_header(rm);
1132 		dump_rman(rm);
1133 	}
1134 }
1135 DB_SHOW_ALIAS(allrman, db_show_all_rman);
1136 #endif
1137