xref: /freebsd/sys/kern/subr_rman.c (revision ee41f1b1cf5e3d4f586cb85b46123b416275862c)
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  * $FreeBSD$
30  */
31 
32 /*
33  * The kernel resource manager.  This code is responsible for keeping track
34  * of hardware resources which are apportioned out to various drivers.
35  * It does not actually assign those resources, and it is not expected
36  * that end-device drivers will call into this code directly.  Rather,
37  * the code which implements the buses that those devices are attached to,
38  * and the code which manages CPU resources, will call this code, and the
39  * end-device drivers will make upcalls to that code to actually perform
40  * the allocation.
41  *
42  * There are two sorts of resources managed by this code.  The first is
43  * the more familiar array (RMAN_ARRAY) type; resources in this class
44  * consist of a sequence of individually-allocatable objects which have
45  * been numbered in some well-defined order.  Most of the resources
46  * are of this type, as it is the most familiar.  The second type is
47  * called a gauge (RMAN_GAUGE), and models fungible resources (i.e.,
48  * resources in which each instance is indistinguishable from every
49  * other instance).  The principal anticipated application of gauges
50  * is in the context of power consumption, where a bus may have a specific
51  * power budget which all attached devices share.  RMAN_GAUGE is not
52  * implemented yet.
53  *
54  * For array resources, we make one simplifying assumption: two clients
55  * sharing the same resource must use the same range of indices.  That
56  * is to say, sharing of overlapping-but-not-identical regions is not
57  * permitted.
58  */
59 
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/kernel.h>
63 #include <sys/lock.h>
64 #include <sys/malloc.h>
65 #include <sys/mutex.h>
66 #include <sys/bus.h>		/* XXX debugging */
67 #include <machine/bus.h>
68 #include <sys/rman.h>
69 
70 #ifdef RMAN_DEBUG
71 #define DPRINTF(params) printf##params
72 #else
73 #define DPRINTF(params)
74 #endif
75 
76 static MALLOC_DEFINE(M_RMAN, "rman", "Resource manager");
77 
78 struct	rman_head rman_head;
79 static	struct mtx rman_mtx; /* mutex to protect rman_head */
80 static	int int_rman_activate_resource(struct rman *rm, struct resource *r,
81 				       struct resource **whohas);
82 static	int int_rman_deactivate_resource(struct resource *r);
83 static	int int_rman_release_resource(struct rman *rm, struct resource *r);
84 
85 int
86 rman_init(struct rman *rm)
87 {
88 	static int once;
89 
90 	if (once == 0) {
91 		once = 1;
92 		TAILQ_INIT(&rman_head);
93 		mtx_init(&rman_mtx, "rman head", MTX_DEF);
94 	}
95 
96 	if (rm->rm_type == RMAN_UNINIT)
97 		panic("rman_init");
98 	if (rm->rm_type == RMAN_GAUGE)
99 		panic("implement RMAN_GAUGE");
100 
101 	TAILQ_INIT(&rm->rm_list);
102 	rm->rm_mtx = malloc(sizeof *rm->rm_mtx, M_RMAN, M_NOWAIT);
103 	if (rm->rm_mtx == 0)
104 		return ENOMEM;
105 	mtx_init(rm->rm_mtx, "rman", MTX_DEF);
106 
107 	mtx_lock(&rman_mtx);
108 	TAILQ_INSERT_TAIL(&rman_head, rm, rm_link);
109 	mtx_unlock(&rman_mtx);
110 	return 0;
111 }
112 
113 /*
114  * NB: this interface is not robust against programming errors which
115  * add multiple copies of the same region.
116  */
117 int
118 rman_manage_region(struct rman *rm, u_long start, u_long end)
119 {
120 	struct resource *r, *s;
121 
122 	r = malloc(sizeof *r, M_RMAN, M_NOWAIT | M_ZERO);
123 	if (r == 0)
124 		return ENOMEM;
125 	r->r_sharehead = 0;
126 	r->r_start = start;
127 	r->r_end = end;
128 	r->r_flags = 0;
129 	r->r_dev = 0;
130 	r->r_rm = rm;
131 
132 	mtx_lock(rm->rm_mtx);
133 	for (s = TAILQ_FIRST(&rm->rm_list);
134 	     s && s->r_end < r->r_start;
135 	     s = TAILQ_NEXT(s, r_link))
136 		;
137 
138 	if (s == NULL) {
139 		TAILQ_INSERT_TAIL(&rm->rm_list, r, r_link);
140 	} else {
141 		TAILQ_INSERT_BEFORE(s, r, r_link);
142 	}
143 
144 	mtx_unlock(rm->rm_mtx);
145 	return 0;
146 }
147 
148 int
149 rman_fini(struct rman *rm)
150 {
151 	struct resource *r;
152 
153 	mtx_lock(rm->rm_mtx);
154 	TAILQ_FOREACH(r, &rm->rm_list, r_link) {
155 		if (r->r_flags & RF_ALLOCATED) {
156 			mtx_unlock(rm->rm_mtx);
157 			return EBUSY;
158 		}
159 	}
160 
161 	/*
162 	 * There really should only be one of these if we are in this
163 	 * state and the code is working properly, but it can't hurt.
164 	 */
165 	while (!TAILQ_EMPTY(&rm->rm_list)) {
166 		r = TAILQ_FIRST(&rm->rm_list);
167 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
168 		free(r, M_RMAN);
169 	}
170 	mtx_unlock(rm->rm_mtx);
171 	mtx_lock(&rman_mtx);
172 	TAILQ_REMOVE(&rman_head, rm, rm_link);
173 	mtx_unlock(&rman_mtx);
174 	mtx_destroy(rm->rm_mtx);
175 	free(rm->rm_mtx, M_RMAN);
176 
177 	return 0;
178 }
179 
180 struct resource *
181 rman_reserve_resource(struct rman *rm, u_long start, u_long end, u_long count,
182 		      u_int flags, struct device *dev)
183 {
184 	u_int	want_activate;
185 	struct	resource *r, *s, *rv;
186 	u_long	rstart, rend;
187 
188 	rv = 0;
189 
190 	DPRINTF(("rman_reserve_resource: <%s> request: [%#lx, %#lx], length "
191 	       "%#lx, flags %u, device %s%d\n", rm->rm_descr, start, end,
192 	       count, flags, device_get_name(dev), device_get_unit(dev)));
193 	want_activate = (flags & RF_ACTIVE);
194 	flags &= ~RF_ACTIVE;
195 
196 	mtx_lock(rm->rm_mtx);
197 
198 	for (r = TAILQ_FIRST(&rm->rm_list);
199 	     r && r->r_end < start;
200 	     r = TAILQ_NEXT(r, r_link))
201 		;
202 
203 	if (r == NULL) {
204 		DPRINTF(("could not find a region\n"));
205 		goto out;
206 	}
207 
208 	/*
209 	 * First try to find an acceptable totally-unshared region.
210 	 */
211 	for (s = r; s; s = TAILQ_NEXT(s, r_link)) {
212 		DPRINTF(("considering [%#lx, %#lx]\n", s->r_start, s->r_end));
213 		if (s->r_start > end) {
214 			DPRINTF(("s->r_start (%#lx) > end (%#lx)\n", s->r_start, end));
215 			break;
216 		}
217 		if (s->r_flags & RF_ALLOCATED) {
218 			DPRINTF(("region is allocated\n"));
219 			continue;
220 		}
221 		rstart = max(s->r_start, start);
222 		rstart = (rstart + ((1ul << RF_ALIGNMENT(flags))) - 1) &
223 		    ~((1ul << RF_ALIGNMENT(flags)) - 1);
224 		rend = min(s->r_end, max(rstart + count, end));
225 		DPRINTF(("truncated region: [%#lx, %#lx]; size %#lx (requested %#lx)\n",
226 		       rstart, rend, (rend - rstart + 1), count));
227 
228 		if ((rend - rstart + 1) >= count) {
229 			DPRINTF(("candidate region: [%#lx, %#lx], size %#lx\n",
230 			       rend, rstart, (rend - rstart + 1)));
231 			if ((s->r_end - s->r_start + 1) == count) {
232 				DPRINTF(("candidate region is entire chunk\n"));
233 				rv = s;
234 				rv->r_flags |= RF_ALLOCATED | flags;
235 				rv->r_dev = dev;
236 				goto out;
237 			}
238 
239 			/*
240 			 * If s->r_start < rstart and
241 			 *    s->r_end > rstart + count - 1, then
242 			 * we need to split the region into three pieces
243 			 * (the middle one will get returned to the user).
244 			 * Otherwise, we are allocating at either the
245 			 * beginning or the end of s, so we only need to
246 			 * split it in two.  The first case requires
247 			 * two new allocations; the second requires but one.
248 			 */
249 			rv = malloc(sizeof *rv, M_RMAN, M_NOWAIT | M_ZERO);
250 			if (rv == 0)
251 				goto out;
252 			rv->r_start = rstart;
253 			rv->r_end = rstart + count - 1;
254 			rv->r_flags = flags | RF_ALLOCATED;
255 			rv->r_dev = dev;
256 			rv->r_sharehead = 0;
257 			rv->r_rm = rm;
258 
259 			if (s->r_start < rv->r_start && s->r_end > rv->r_end) {
260 				DPRINTF(("splitting region in three parts: "
261 				       "[%#lx, %#lx]; [%#lx, %#lx]; [%#lx, %#lx]\n",
262 				       s->r_start, rv->r_start - 1,
263 				       rv->r_start, rv->r_end,
264 				       rv->r_end + 1, s->r_end));
265 				/*
266 				 * We are allocating in the middle.
267 				 */
268 				r = malloc(sizeof *r, M_RMAN, M_NOWAIT|M_ZERO);
269 				if (r == 0) {
270 					free(rv, M_RMAN);
271 					rv = 0;
272 					goto out;
273 				}
274 				r->r_start = rv->r_end + 1;
275 				r->r_end = s->r_end;
276 				r->r_flags = s->r_flags;
277 				r->r_dev = 0;
278 				r->r_sharehead = 0;
279 				r->r_rm = rm;
280 				s->r_end = rv->r_start - 1;
281 				TAILQ_INSERT_AFTER(&rm->rm_list, s, rv,
282 						     r_link);
283 				TAILQ_INSERT_AFTER(&rm->rm_list, rv, r,
284 						     r_link);
285 			} else if (s->r_start == rv->r_start) {
286 				DPRINTF(("allocating from the beginning\n"));
287 				/*
288 				 * We are allocating at the beginning.
289 				 */
290 				s->r_start = rv->r_end + 1;
291 				TAILQ_INSERT_BEFORE(s, rv, r_link);
292 			} else {
293 				DPRINTF(("allocating at the end\n"));
294 				/*
295 				 * We are allocating at the end.
296 				 */
297 				s->r_end = rv->r_start - 1;
298 				TAILQ_INSERT_AFTER(&rm->rm_list, s, rv,
299 						     r_link);
300 			}
301 			goto out;
302 		}
303 	}
304 
305 	/*
306 	 * Now find an acceptable shared region, if the client's requirements
307 	 * allow sharing.  By our implementation restriction, a candidate
308 	 * region must match exactly by both size and sharing type in order
309 	 * to be considered compatible with the client's request.  (The
310 	 * former restriction could probably be lifted without too much
311 	 * additional work, but this does not seem warranted.)
312 	 */
313 	DPRINTF(("no unshared regions found\n"));
314 	if ((flags & (RF_SHAREABLE | RF_TIMESHARE)) == 0)
315 		goto out;
316 
317 	for (s = r; s; s = TAILQ_NEXT(s, r_link)) {
318 		if (s->r_start > end)
319 			break;
320 		if ((s->r_flags & flags) != flags)
321 			continue;
322 		rstart = max(s->r_start, start);
323 		rend = min(s->r_end, max(start + count, end));
324 		if (s->r_start >= start && s->r_end <= end
325 		    && (s->r_end - s->r_start + 1) == count) {
326 			rv = malloc(sizeof *rv, M_RMAN, M_NOWAIT | M_ZERO);
327 			if (rv == 0)
328 				goto out;
329 			rv->r_start = s->r_start;
330 			rv->r_end = s->r_end;
331 			rv->r_flags = s->r_flags &
332 				(RF_ALLOCATED | RF_SHAREABLE | RF_TIMESHARE);
333 			rv->r_dev = dev;
334 			rv->r_rm = rm;
335 			if (s->r_sharehead == 0) {
336 				s->r_sharehead = malloc(sizeof *s->r_sharehead,
337 						M_RMAN, M_NOWAIT | M_ZERO);
338 				if (s->r_sharehead == 0) {
339 					free(rv, M_RMAN);
340 					rv = 0;
341 					goto out;
342 				}
343 				LIST_INIT(s->r_sharehead);
344 				LIST_INSERT_HEAD(s->r_sharehead, s,
345 						 r_sharelink);
346 				s->r_flags |= RF_FIRSTSHARE;
347 			}
348 			rv->r_sharehead = s->r_sharehead;
349 			LIST_INSERT_HEAD(s->r_sharehead, rv, r_sharelink);
350 			goto out;
351 		}
352 	}
353 
354 	/*
355 	 * We couldn't find anything.
356 	 */
357 out:
358 	/*
359 	 * If the user specified RF_ACTIVE in the initial flags,
360 	 * which is reflected in `want_activate', we attempt to atomically
361 	 * activate the resource.  If this fails, we release the resource
362 	 * and indicate overall failure.  (This behavior probably doesn't
363 	 * make sense for RF_TIMESHARE-type resources.)
364 	 */
365 	if (rv && want_activate) {
366 		struct resource *whohas;
367 		if (int_rman_activate_resource(rm, rv, &whohas)) {
368 			int_rman_release_resource(rm, rv);
369 			rv = 0;
370 		}
371 	}
372 
373 	mtx_unlock(rm->rm_mtx);
374 	return (rv);
375 }
376 
377 static int
378 int_rman_activate_resource(struct rman *rm, struct resource *r,
379 			   struct resource **whohas)
380 {
381 	struct resource *s;
382 	int ok;
383 
384 	/*
385 	 * If we are not timesharing, then there is nothing much to do.
386 	 * If we already have the resource, then there is nothing at all to do.
387 	 * If we are not on a sharing list with anybody else, then there is
388 	 * little to do.
389 	 */
390 	if ((r->r_flags & RF_TIMESHARE) == 0
391 	    || (r->r_flags & RF_ACTIVE) != 0
392 	    || r->r_sharehead == 0) {
393 		r->r_flags |= RF_ACTIVE;
394 		return 0;
395 	}
396 
397 	ok = 1;
398 	for (s = LIST_FIRST(r->r_sharehead); s && ok;
399 	     s = LIST_NEXT(s, r_sharelink)) {
400 		if ((s->r_flags & RF_ACTIVE) != 0) {
401 			ok = 0;
402 			*whohas = s;
403 		}
404 	}
405 	if (ok) {
406 		r->r_flags |= RF_ACTIVE;
407 		return 0;
408 	}
409 	return EBUSY;
410 }
411 
412 int
413 rman_activate_resource(struct resource *r)
414 {
415 	int rv;
416 	struct resource *whohas;
417 	struct rman *rm;
418 
419 	rm = r->r_rm;
420 	mtx_lock(rm->rm_mtx);
421 	rv = int_rman_activate_resource(rm, r, &whohas);
422 	mtx_unlock(rm->rm_mtx);
423 	return rv;
424 }
425 
426 int
427 rman_await_resource(struct resource *r, int pri, int timo)
428 {
429 	int	rv, s;
430 	struct	resource *whohas;
431 	struct	rman *rm;
432 
433 	rm = r->r_rm;
434 	for (;;) {
435 		mtx_lock(rm->rm_mtx);
436 		rv = int_rman_activate_resource(rm, r, &whohas);
437 		if (rv != EBUSY)
438 			return (rv);	/* returns with mutex held */
439 
440 		if (r->r_sharehead == 0)
441 			panic("rman_await_resource");
442 		/*
443 		 * splhigh hopefully will prevent a race between
444 		 * mtx_unlock and tsleep where a process
445 		 * could conceivably get in and release the resource
446 		 * before we have a chance to sleep on it.
447 		 */
448 		s = splhigh();
449 		whohas->r_flags |= RF_WANTED;
450 		mtx_unlock(rm->rm_mtx);
451 		rv = tsleep(r->r_sharehead, pri, "rmwait", timo);
452 		if (rv) {
453 			splx(s);
454 			return rv;
455 		}
456 		mtx_lock(rm->rm_mtx);
457 		splx(s);
458 	}
459 }
460 
461 static int
462 int_rman_deactivate_resource(struct resource *r)
463 {
464 	struct	rman *rm;
465 
466 	rm = r->r_rm;
467 	r->r_flags &= ~RF_ACTIVE;
468 	if (r->r_flags & RF_WANTED) {
469 		r->r_flags &= ~RF_WANTED;
470 		wakeup(r->r_sharehead);
471 	}
472 	return 0;
473 }
474 
475 int
476 rman_deactivate_resource(struct resource *r)
477 {
478 	struct	rman *rm;
479 
480 	rm = r->r_rm;
481 	mtx_lock(rm->rm_mtx);
482 	int_rman_deactivate_resource(r);
483 	mtx_unlock(rm->rm_mtx);
484 	return 0;
485 }
486 
487 static int
488 int_rman_release_resource(struct rman *rm, struct resource *r)
489 {
490 	struct	resource *s, *t;
491 
492 	if (r->r_flags & RF_ACTIVE)
493 		int_rman_deactivate_resource(r);
494 
495 	/*
496 	 * Check for a sharing list first.  If there is one, then we don't
497 	 * have to think as hard.
498 	 */
499 	if (r->r_sharehead) {
500 		/*
501 		 * If a sharing list exists, then we know there are at
502 		 * least two sharers.
503 		 *
504 		 * If we are in the main circleq, appoint someone else.
505 		 */
506 		LIST_REMOVE(r, r_sharelink);
507 		s = LIST_FIRST(r->r_sharehead);
508 		if (r->r_flags & RF_FIRSTSHARE) {
509 			s->r_flags |= RF_FIRSTSHARE;
510 			TAILQ_INSERT_BEFORE(r, s, r_link);
511 			TAILQ_REMOVE(&rm->rm_list, r, r_link);
512 		}
513 
514 		/*
515 		 * Make sure that the sharing list goes away completely
516 		 * if the resource is no longer being shared at all.
517 		 */
518 		if (LIST_NEXT(s, r_sharelink) == 0) {
519 			free(s->r_sharehead, M_RMAN);
520 			s->r_sharehead = 0;
521 			s->r_flags &= ~RF_FIRSTSHARE;
522 		}
523 		goto out;
524 	}
525 
526 	/*
527 	 * Look at the adjacent resources in the list and see if our
528 	 * segment can be merged with any of them.
529 	 */
530 	s = TAILQ_PREV(r, resource_head, r_link);
531 	t = TAILQ_NEXT(r, r_link);
532 
533 	if (s != NULL && (s->r_flags & RF_ALLOCATED) == 0
534 	    && t != NULL && (t->r_flags & RF_ALLOCATED) == 0) {
535 		/*
536 		 * Merge all three segments.
537 		 */
538 		s->r_end = t->r_end;
539 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
540 		TAILQ_REMOVE(&rm->rm_list, t, r_link);
541 		free(t, M_RMAN);
542 	} else if (s != NULL && (s->r_flags & RF_ALLOCATED) == 0) {
543 		/*
544 		 * Merge previous segment with ours.
545 		 */
546 		s->r_end = r->r_end;
547 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
548 	} else if (t != NULL && (t->r_flags & RF_ALLOCATED) == 0) {
549 		/*
550 		 * Merge next segment with ours.
551 		 */
552 		t->r_start = r->r_start;
553 		TAILQ_REMOVE(&rm->rm_list, r, r_link);
554 	} else {
555 		/*
556 		 * At this point, we know there is nothing we
557 		 * can potentially merge with, because on each
558 		 * side, there is either nothing there or what is
559 		 * there is still allocated.  In that case, we don't
560 		 * want to remove r from the list; we simply want to
561 		 * change it to an unallocated region and return
562 		 * without freeing anything.
563 		 */
564 		r->r_flags &= ~RF_ALLOCATED;
565 		return 0;
566 	}
567 
568 out:
569 	free(r, M_RMAN);
570 	return 0;
571 }
572 
573 int
574 rman_release_resource(struct resource *r)
575 {
576 	int	rv;
577 	struct	rman *rm = r->r_rm;
578 
579 	mtx_lock(rm->rm_mtx);
580 	rv = int_rman_release_resource(rm, r);
581 	mtx_unlock(rm->rm_mtx);
582 	return (rv);
583 }
584 
585 uint32_t
586 rman_make_alignment_flags(uint32_t size)
587 {
588 	int	i;
589 
590 	/*
591 	 * Find the hightest bit set, and add one if more than one bit
592 	 * set.  We're effectively computing the ceil(log2(size)) here.
593 	 */
594 	for (i = 32; i > 0; i--)
595 		if ((1 << i) & size)
596 			break;
597 	if (~(1 << i) & size)
598 		i++;
599 
600 	return(RF_ALIGNMENT_LOG2(i));
601 }
602