xref: /freebsd/sys/kern/subr_bus.c (revision 4b2eaea43fec8e8792be611dea204071a10b655a)
1 /*-
2  * Copyright (c) 1997,1998 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include "opt_bus.h"
30 
31 #include <sys/param.h>
32 #include <sys/conf.h>
33 #include <sys/filio.h>
34 #include <sys/lock.h>
35 #include <sys/kernel.h>
36 #include <sys/kobj.h>
37 #include <sys/malloc.h>
38 #include <sys/module.h>
39 #include <sys/mutex.h>
40 #include <sys/poll.h>
41 #include <sys/proc.h>
42 #include <sys/condvar.h>
43 #include <sys/queue.h>
44 #include <machine/bus.h>
45 #include <sys/rman.h>
46 #include <sys/selinfo.h>
47 #include <sys/signalvar.h>
48 #include <sys/sysctl.h>
49 #include <sys/systm.h>
50 #include <sys/uio.h>
51 #include <sys/bus.h>
52 
53 #include <machine/stdarg.h>
54 
55 #include <vm/uma.h>
56 
57 SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW, NULL, NULL);
58 
59 /*
60  * Used to attach drivers to devclasses.
61  */
62 typedef struct driverlink *driverlink_t;
63 struct driverlink {
64     driver_t	*driver;
65     TAILQ_ENTRY(driverlink) link;	/* list of drivers in devclass */
66 };
67 
68 /*
69  * Forward declarations
70  */
71 typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
72 typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
73 typedef TAILQ_HEAD(device_list, device) device_list_t;
74 
75 struct devclass {
76 	TAILQ_ENTRY(devclass) link;
77 	driver_list_t	drivers;     /* bus devclasses store drivers for bus */
78 	char		*name;
79 	device_t	*devices;	/* array of devices indexed by unit */
80 	int		maxunit;	/* size of devices array */
81 };
82 
83 /*
84  * Implementation of device.
85  */
86 struct device {
87 	/*
88 	 * A device is a kernel object. The first field must be the
89 	 * current ops table for the object.
90 	 */
91 	KOBJ_FIELDS;
92 
93 	/*
94 	 * Device hierarchy.
95 	 */
96 	TAILQ_ENTRY(device)	link;		/* list of devices in parent */
97 	TAILQ_ENTRY(device)	devlink;	/* global device list membership */
98 	device_t	parent;
99 	device_list_t	children;	/* list of subordinate devices */
100 
101 	/*
102 	 * Details of this device.
103 	 */
104 	driver_t	*driver;
105 	devclass_t	devclass;	/* device class which we are in */
106 	int		unit;
107 	char*		nameunit;	/* name+unit e.g. foodev0 */
108 	char*		desc;		/* driver specific description */
109 	int		busy;		/* count of calls to device_busy() */
110 	device_state_t	state;
111 	u_int32_t	devflags;  /* api level flags for device_get_flags() */
112 	u_short		flags;
113 #define	DF_ENABLED	1	/* device should be probed/attached */
114 #define	DF_FIXEDCLASS	2	/* devclass specified at create time */
115 #define	DF_WILDCARD	4	/* unit was originally wildcard */
116 #define	DF_DESCMALLOCED	8	/* description was malloced */
117 #define	DF_QUIET	16	/* don't print verbose attach message */
118 #define	DF_DONENOMATCH	32	/* don't execute DEVICE_NOMATCH again */
119 #define	DF_EXTERNALSOFTC 64	/* softc not allocated by us */
120 	u_char	order;		/* order from device_add_child_ordered() */
121 	u_char	pad;
122 	void	*ivars;
123 	void	*softc;
124 };
125 
126 struct device_op_desc {
127 	unsigned int	offset;	/* offset in driver ops */
128 	struct method*	method;	/* internal method implementation */
129 	devop_t		deflt;	/* default implementation */
130 	const char*	name;	/* unique name (for registration) */
131 };
132 
133 static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
134 
135 #ifdef BUS_DEBUG
136 
137 static int bus_debug = 1;
138 TUNABLE_INT("bus.debug", &bus_debug);
139 SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RW, &bus_debug, 0,
140     "Debug bus code");
141 
142 #define PDEBUG(a)	if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
143 #define DEVICENAME(d)	((d)? device_get_name(d): "no device")
144 #define DRIVERNAME(d)	((d)? d->name : "no driver")
145 #define DEVCLANAME(d)	((d)? d->name : "no devclass")
146 
147 /* Produce the indenting, indent*2 spaces plus a '.' ahead of that to
148  * prevent syslog from deleting initial spaces
149  */
150 #define indentprintf(p)	do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
151 
152 static void print_device_short(device_t dev, int indent);
153 static void print_device(device_t dev, int indent);
154 void print_device_tree_short(device_t dev, int indent);
155 void print_device_tree(device_t dev, int indent);
156 static void print_driver_short(driver_t *driver, int indent);
157 static void print_driver(driver_t *driver, int indent);
158 static void print_driver_list(driver_list_t drivers, int indent);
159 static void print_devclass_short(devclass_t dc, int indent);
160 static void print_devclass(devclass_t dc, int indent);
161 void print_devclass_list_short(void);
162 void print_devclass_list(void);
163 
164 #else
165 /* Make the compiler ignore the function calls */
166 #define PDEBUG(a)			/* nop */
167 #define DEVICENAME(d)			/* nop */
168 #define DRIVERNAME(d)			/* nop */
169 #define DEVCLANAME(d)			/* nop */
170 
171 #define print_device_short(d,i)		/* nop */
172 #define print_device(d,i)		/* nop */
173 #define print_device_tree_short(d,i)	/* nop */
174 #define print_device_tree(d,i)		/* nop */
175 #define print_driver_short(d,i)		/* nop */
176 #define print_driver(d,i)		/* nop */
177 #define print_driver_list(d,i)		/* nop */
178 #define print_devclass_short(d,i)	/* nop */
179 #define print_devclass(d,i)		/* nop */
180 #define print_devclass_list_short()	/* nop */
181 #define print_devclass_list()		/* nop */
182 #endif
183 
184 /*
185  * /dev/devctl implementation
186  */
187 
188 /*
189  * This design allows only one reader for /dev/devctl.  This is not desirable
190  * in the long run, but will get a lot of hair out of this implementation.
191  * Maybe we should make this device a clonable device.
192  *
193  * Also note: we specifically do not attach a device to the device_t tree
194  * to avoid potential chicken and egg problems.  One could argue that all
195  * of this belongs to the root node.  One could also further argue that the
196  * sysctl interface that we have not might more properly be an ioctl
197  * interface, but at this stage of the game, I'm not inclined to rock that
198  * boat.
199  *
200  * I'm also not sure that the SIGIO support is done correctly or not, as
201  * I copied it from a driver that had SIGIO support that likely hasn't been
202  * tested since 3.4 or 2.2.8!
203  */
204 
205 static int sysctl_devctl_disable(SYSCTL_HANDLER_ARGS);
206 static int devctl_disable = 0;
207 TUNABLE_INT("hw.bus.devctl_disable", &devctl_disable);
208 SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_disable,
209     CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0, sysctl_devctl_disable,
210     "I", "devctl disable");
211 
212 static d_open_t		devopen;
213 static d_close_t	devclose;
214 static d_read_t		devread;
215 static d_ioctl_t	devioctl;
216 static d_poll_t		devpoll;
217 
218 #define CDEV_MAJOR 173
219 static struct cdevsw dev_cdevsw = {
220 	/* open */	devopen,
221 	/* close */	devclose,
222 	/* read */	devread,
223 	/* write */	nowrite,
224 	/* ioctl */	devioctl,
225 	/* poll */	devpoll,
226 	/* mmap */	nommap,
227 	/* strategy */	nostrategy,
228 	/* name */	"devctl",
229 	/* maj */	CDEV_MAJOR,
230 	/* dump */	nodump,
231 	/* psize */	nopsize,
232 	/* flags */	0,
233 };
234 
235 struct dev_event_info
236 {
237 	char *dei_data;
238 	TAILQ_ENTRY(dev_event_info) dei_link;
239 };
240 
241 TAILQ_HEAD(devq, dev_event_info);
242 
243 struct dev_softc
244 {
245 	int	inuse;
246 	int 	nonblock;
247 	struct mtx mtx;
248 	struct cv cv;
249 	struct selinfo sel;
250 	struct devq devq;
251 	struct proc *async_proc;
252 } devsoftc;
253 
254 dev_t		devctl_dev;
255 
256 static void
257 devinit(void)
258 {
259 	devctl_dev = make_dev(&dev_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
260 	    "devctl");
261 	mtx_init(&devsoftc.mtx, "dev mtx", "devd", MTX_DEF);
262 	cv_init(&devsoftc.cv, "dev cv");
263 	TAILQ_INIT(&devsoftc.devq);
264 }
265 
266 static int
267 devopen(dev_t dev, int oflags, int devtype, d_thread_t *td)
268 {
269 	if (devsoftc.inuse)
270 		return (EBUSY);
271 	/* move to init */
272 	devsoftc.inuse = 1;
273 	devsoftc.nonblock = 0;
274 	devsoftc.async_proc = NULL;
275 	return (0);
276 }
277 
278 static int
279 devclose(dev_t dev, int fflag, int devtype, d_thread_t *td)
280 {
281 	devsoftc.inuse = 0;
282 	mtx_lock(&devsoftc.mtx);
283 	cv_broadcast(&devsoftc.cv);
284 	mtx_unlock(&devsoftc.mtx);
285 
286 	return (0);
287 }
288 
289 /*
290  * The read channel for this device is used to report changes to
291  * userland in realtime.  We are required to free the data as well as
292  * the n1 object because we allocate them separately.  Also note that
293  * we return one record at a time.  If you try to read this device a
294  * character at a time, you will loose the rest of the data.  Listening
295  * programs are expected to cope.
296  */
297 static int
298 devread(dev_t dev, struct uio *uio, int ioflag)
299 {
300 	struct dev_event_info *n1;
301 	int rv;
302 
303 	mtx_lock(&devsoftc.mtx);
304 	while (TAILQ_EMPTY(&devsoftc.devq)) {
305 		if (devsoftc.nonblock) {
306 			mtx_unlock(&devsoftc.mtx);
307 			return (EAGAIN);
308 		}
309 		rv = cv_wait_sig(&devsoftc.cv, &devsoftc.mtx);
310 		if (rv) {
311 			/*
312 			 * Need to translate ERESTART to EINTR here? -- jake
313 			 */
314 			mtx_unlock(&devsoftc.mtx);
315 			return (rv);
316 		}
317 	}
318 	n1 = TAILQ_FIRST(&devsoftc.devq);
319 	TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
320 	mtx_unlock(&devsoftc.mtx);
321 	rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
322 	free(n1->dei_data, M_BUS);
323 	free(n1, M_BUS);
324 	return (rv);
325 }
326 
327 static	int
328 devioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, d_thread_t *td)
329 {
330 	switch (cmd) {
331 
332 	case FIONBIO:
333 		if (*(int*)data)
334 			devsoftc.nonblock = 1;
335 		else
336 			devsoftc.nonblock = 0;
337 		return (0);
338 	case FIOASYNC:
339 		if (*(int*)data)
340 			devsoftc.async_proc = td->td_proc;
341 		else
342 			devsoftc.async_proc = NULL;
343 		return (0);
344 
345 		/* (un)Support for other fcntl() calls. */
346 	case FIOCLEX:
347 	case FIONCLEX:
348 	case FIONREAD:
349 	case FIOSETOWN:
350 	case FIOGETOWN:
351 	default:
352 		break;
353 	}
354 	return (ENOTTY);
355 }
356 
357 static	int
358 devpoll(dev_t dev, int events, d_thread_t *td)
359 {
360 	int	revents = 0;
361 
362 	if (events & (POLLIN | POLLRDNORM))
363 		revents |= events & (POLLIN | POLLRDNORM);
364 
365 	if (events & (POLLOUT | POLLWRNORM))
366 		revents |= events & (POLLOUT | POLLWRNORM);
367 
368 	mtx_lock(&devsoftc.mtx);
369 	if (events & POLLRDBAND)
370 		if (!TAILQ_EMPTY(&devsoftc.devq))
371 			revents |= POLLRDBAND;
372 	mtx_unlock(&devsoftc.mtx);
373 
374 	if (revents == 0)
375 		selrecord(td, &devsoftc.sel);
376 
377 	return (revents);
378 }
379 
380 /*
381  * Common routine that tries to make sending messages as easy as possible.
382  * We allocate memory for the data, copy strings into that, but do not
383  * free it unless there's an error.  The dequeue part of the driver should
384  * free the data.  We don't send data when the device is disabled.  We do
385  * send data, even when we have no listeners, because we wish to avoid
386  * races relating to startup and restart of listening applications.
387  */
388 static void
389 devaddq(const char *type, const char *what, device_t dev)
390 {
391 	struct dev_event_info *n1 = NULL;
392 	char *data = NULL;
393 	char *loc;
394 	const char *parstr;
395 
396 	if (devctl_disable)
397 		return;
398 	n1 = malloc(sizeof(*n1), M_BUS, M_NOWAIT);
399 	if (n1 == NULL)
400 		goto bad;
401 	data = malloc(1024, M_BUS, M_NOWAIT);
402 	if (data == NULL)
403 		goto bad;
404 	loc = malloc(1024, M_BUS, M_NOWAIT);
405 	if (loc == NULL)
406 		goto bad;
407 	*loc = '\0';
408 	bus_child_location_str(dev, loc, 1024);
409 	if (device_get_parent(dev) == NULL)
410 		parstr = ".";	/* Or '/' ? */
411 	else
412 		parstr = device_get_nameunit(device_get_parent(dev));
413 	snprintf(data, 1024, "%s%s at %s on %s\n", type, what, loc, parstr);
414 	free(loc, M_BUS);
415 	n1->dei_data = data;
416 	mtx_lock(&devsoftc.mtx);
417 	TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
418 	cv_broadcast(&devsoftc.cv);
419 	mtx_unlock(&devsoftc.mtx);
420 	selwakeup(&devsoftc.sel);
421 	if (devsoftc.async_proc)
422 		psignal(devsoftc.async_proc, SIGIO);
423 	return;
424 bad:;
425 	free(data, M_BUS);
426 	free(n1, M_BUS);
427 	return;
428 }
429 
430 /*
431  * A device was added to the tree.  We are called just after it successfully
432  * attaches (that is, probe and attach success for this device).  No call
433  * is made if a device is merely parented into the tree.  See devnomatch
434  * if probe fails.  If attach fails, no notification is sent (but maybe
435  * we should have a different message for this).
436  */
437 static void
438 devadded(device_t dev)
439 {
440 	devaddq("+", device_get_nameunit(dev), dev);
441 }
442 
443 /*
444  * A device was removed from the tree.  We are called just before this
445  * happens.
446  */
447 static void
448 devremoved(device_t dev)
449 {
450 	devaddq("-", device_get_nameunit(dev), dev);
451 }
452 
453 /*
454  * Called when there's no match for this device.  This is only called
455  * the first time that no match happens, so we don't keep getitng this
456  * message.  Should that prove to be undesirable, we can change it.
457  * This is called when all drivers that can attach to a given bus
458  * decline to accept this device.  Other errrors may not be detected.
459  */
460 static void
461 devnomatch(device_t dev)
462 {
463 	char *pnp = NULL;
464 
465 	pnp = malloc(1024, M_BUS, M_NOWAIT);
466 	if (pnp == NULL)
467 		return;
468 	*pnp = '\0';
469 	bus_child_pnpinfo_str(dev, pnp, 1024);
470 	devaddq("?", pnp, dev);
471 	free(pnp, M_BUS);
472 	return;
473 }
474 
475 static int
476 sysctl_devctl_disable(SYSCTL_HANDLER_ARGS)
477 {
478 	struct dev_event_info *n1;
479 	int dis, error;
480 
481 	dis = devctl_disable;
482 	error = sysctl_handle_int(oidp, &dis, 0, req);
483 	if (error || !req->newptr)
484 		return (error);
485 	mtx_lock(&devsoftc.mtx);
486 	devctl_disable = dis;
487 	if (dis) {
488 		while (!TAILQ_EMPTY(&devsoftc.devq)) {
489 			n1 = TAILQ_FIRST(&devsoftc.devq);
490 			TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
491 			free(n1->dei_data, M_BUS);
492 			free(n1, M_BUS);
493 		}
494 	}
495 	mtx_unlock(&devsoftc.mtx);
496 	return (0);
497 }
498 
499 /* End of /dev/devctl code */
500 
501 TAILQ_HEAD(,device)	bus_data_devices;
502 static int bus_data_generation = 1;
503 
504 kobj_method_t null_methods[] = {
505 	{ 0, 0 }
506 };
507 
508 DEFINE_CLASS(null, null_methods, 0);
509 
510 /*
511  * Devclass implementation
512  */
513 
514 static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
515 
516 static devclass_t
517 devclass_find_internal(const char *classname, int create)
518 {
519 	devclass_t dc;
520 
521 	PDEBUG(("looking for %s", classname));
522 	if (!classname)
523 		return (NULL);
524 
525 	TAILQ_FOREACH(dc, &devclasses, link) {
526 		if (!strcmp(dc->name, classname))
527 			return (dc);
528 	}
529 
530 	PDEBUG(("%s not found%s", classname, (create? ", creating": "")));
531 	if (create) {
532 		dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
533 		    M_BUS, M_NOWAIT|M_ZERO);
534 		if (!dc)
535 			return (NULL);
536 		dc->name = (char*) (dc + 1);
537 		strcpy(dc->name, classname);
538 		TAILQ_INIT(&dc->drivers);
539 		TAILQ_INSERT_TAIL(&devclasses, dc, link);
540 
541 		bus_data_generation_update();
542 	}
543 
544 	return (dc);
545 }
546 
547 devclass_t
548 devclass_create(const char *classname)
549 {
550 	return (devclass_find_internal(classname, TRUE));
551 }
552 
553 devclass_t
554 devclass_find(const char *classname)
555 {
556 	return (devclass_find_internal(classname, FALSE));
557 }
558 
559 int
560 devclass_add_driver(devclass_t dc, driver_t *driver)
561 {
562 	driverlink_t dl;
563 	int i;
564 
565 	PDEBUG(("%s", DRIVERNAME(driver)));
566 
567 	dl = malloc(sizeof *dl, M_BUS, M_NOWAIT|M_ZERO);
568 	if (!dl)
569 		return (ENOMEM);
570 
571 	/*
572 	 * Compile the driver's methods. Also increase the reference count
573 	 * so that the class doesn't get freed when the last instance
574 	 * goes. This means we can safely use static methods and avoids a
575 	 * double-free in devclass_delete_driver.
576 	 */
577 	kobj_class_compile((kobj_class_t) driver);
578 
579 	/*
580 	 * Make sure the devclass which the driver is implementing exists.
581 	 */
582 	devclass_find_internal(driver->name, TRUE);
583 
584 	dl->driver = driver;
585 	TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
586 	driver->refs++;
587 
588 	/*
589 	 * Call BUS_DRIVER_ADDED for any existing busses in this class.
590 	 */
591 	for (i = 0; i < dc->maxunit; i++)
592 		if (dc->devices[i])
593 			BUS_DRIVER_ADDED(dc->devices[i], driver);
594 
595 	bus_data_generation_update();
596 	return (0);
597 }
598 
599 int
600 devclass_delete_driver(devclass_t busclass, driver_t *driver)
601 {
602 	devclass_t dc = devclass_find(driver->name);
603 	driverlink_t dl;
604 	device_t dev;
605 	int i;
606 	int error;
607 
608 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
609 
610 	if (!dc)
611 		return (0);
612 
613 	/*
614 	 * Find the link structure in the bus' list of drivers.
615 	 */
616 	TAILQ_FOREACH(dl, &busclass->drivers, link) {
617 		if (dl->driver == driver)
618 			break;
619 	}
620 
621 	if (!dl) {
622 		PDEBUG(("%s not found in %s list", driver->name,
623 		    busclass->name));
624 		return (ENOENT);
625 	}
626 
627 	/*
628 	 * Disassociate from any devices.  We iterate through all the
629 	 * devices in the devclass of the driver and detach any which are
630 	 * using the driver and which have a parent in the devclass which
631 	 * we are deleting from.
632 	 *
633 	 * Note that since a driver can be in multiple devclasses, we
634 	 * should not detach devices which are not children of devices in
635 	 * the affected devclass.
636 	 */
637 	for (i = 0; i < dc->maxunit; i++) {
638 		if (dc->devices[i]) {
639 			dev = dc->devices[i];
640 			if (dev->driver == driver && dev->parent &&
641 			    dev->parent->devclass == busclass) {
642 				if ((error = device_detach(dev)) != 0)
643 					return (error);
644 				device_set_driver(dev, NULL);
645 			}
646 		}
647 	}
648 
649 	TAILQ_REMOVE(&busclass->drivers, dl, link);
650 	free(dl, M_BUS);
651 
652 	driver->refs--;
653 	if (driver->refs == 0)
654 		kobj_class_free((kobj_class_t) driver);
655 
656 	bus_data_generation_update();
657 	return (0);
658 }
659 
660 static driverlink_t
661 devclass_find_driver_internal(devclass_t dc, const char *classname)
662 {
663 	driverlink_t dl;
664 
665 	PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
666 
667 	TAILQ_FOREACH(dl, &dc->drivers, link) {
668 		if (!strcmp(dl->driver->name, classname))
669 			return (dl);
670 	}
671 
672 	PDEBUG(("not found"));
673 	return (NULL);
674 }
675 
676 driver_t *
677 devclass_find_driver(devclass_t dc, const char *classname)
678 {
679 	driverlink_t dl;
680 
681 	dl = devclass_find_driver_internal(dc, classname);
682 	if (dl)
683 		return (dl->driver);
684 	return (NULL);
685 }
686 
687 const char *
688 devclass_get_name(devclass_t dc)
689 {
690 	return (dc->name);
691 }
692 
693 device_t
694 devclass_get_device(devclass_t dc, int unit)
695 {
696 	if (dc == NULL || unit < 0 || unit >= dc->maxunit)
697 		return (NULL);
698 	return (dc->devices[unit]);
699 }
700 
701 void *
702 devclass_get_softc(devclass_t dc, int unit)
703 {
704 	device_t dev;
705 
706 	dev = devclass_get_device(dc, unit);
707 	if (!dev)
708 		return (NULL);
709 
710 	return (device_get_softc(dev));
711 }
712 
713 int
714 devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
715 {
716 	int i;
717 	int count;
718 	device_t *list;
719 
720 	count = 0;
721 	for (i = 0; i < dc->maxunit; i++)
722 		if (dc->devices[i])
723 			count++;
724 
725 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
726 	if (!list)
727 		return (ENOMEM);
728 
729 	count = 0;
730 	for (i = 0; i < dc->maxunit; i++) {
731 		if (dc->devices[i]) {
732 			list[count] = dc->devices[i];
733 			count++;
734 		}
735 	}
736 
737 	*devlistp = list;
738 	*devcountp = count;
739 
740 	return (0);
741 }
742 
743 int
744 devclass_get_maxunit(devclass_t dc)
745 {
746 	return (dc->maxunit);
747 }
748 
749 int
750 devclass_find_free_unit(devclass_t dc, int unit)
751 {
752 	if (dc == NULL)
753 		return (unit);
754 	while (unit < dc->maxunit && dc->devices[unit] != NULL)
755 		unit++;
756 	return (unit);
757 }
758 
759 static int
760 devclass_alloc_unit(devclass_t dc, int *unitp)
761 {
762 	int unit = *unitp;
763 
764 	PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
765 
766 	/* If we were given a wired unit number, check for existing device */
767 	/* XXX imp XXX */
768 	if (unit != -1) {
769 		if (unit >= 0 && unit < dc->maxunit &&
770 		    dc->devices[unit] != NULL) {
771 			if (bootverbose)
772 				printf("%s: %s%d already exists; skipping it\n",
773 				    dc->name, dc->name, *unitp);
774 			return (EEXIST);
775 		}
776 	} else {
777 		/* Unwired device, find the next available slot for it */
778 		unit = 0;
779 		while (unit < dc->maxunit && dc->devices[unit] != NULL)
780 			unit++;
781 	}
782 
783 	/*
784 	 * We've selected a unit beyond the length of the table, so let's
785 	 * extend the table to make room for all units up to and including
786 	 * this one.
787 	 */
788 	if (unit >= dc->maxunit) {
789 		device_t *newlist;
790 		int newsize;
791 
792 		newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
793 		newlist = malloc(sizeof(device_t) * newsize, M_BUS, M_NOWAIT);
794 		if (!newlist)
795 			return (ENOMEM);
796 		bcopy(dc->devices, newlist, sizeof(device_t) * dc->maxunit);
797 		bzero(newlist + dc->maxunit,
798 		    sizeof(device_t) * (newsize - dc->maxunit));
799 		if (dc->devices)
800 			free(dc->devices, M_BUS);
801 		dc->devices = newlist;
802 		dc->maxunit = newsize;
803 	}
804 	PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
805 
806 	*unitp = unit;
807 	return (0);
808 }
809 
810 static int
811 devclass_add_device(devclass_t dc, device_t dev)
812 {
813 	int buflen, error;
814 
815 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
816 
817 	buflen = snprintf(NULL, 0, "%s%d$", dc->name, dev->unit);
818 	if (buflen < 0)
819 		return (ENOMEM);
820 	dev->nameunit = malloc(buflen, M_BUS, M_NOWAIT|M_ZERO);
821 	if (!dev->nameunit)
822 		return (ENOMEM);
823 
824 	if ((error = devclass_alloc_unit(dc, &dev->unit)) != 0) {
825 		free(dev->nameunit, M_BUS);
826 		dev->nameunit = NULL;
827 		return (error);
828 	}
829 	dc->devices[dev->unit] = dev;
830 	dev->devclass = dc;
831 	snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
832 
833 	return (0);
834 }
835 
836 static int
837 devclass_delete_device(devclass_t dc, device_t dev)
838 {
839 	if (!dc || !dev)
840 		return (0);
841 
842 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
843 
844 	if (dev->devclass != dc || dc->devices[dev->unit] != dev)
845 		panic("devclass_delete_device: inconsistent device class");
846 	dc->devices[dev->unit] = NULL;
847 	if (dev->flags & DF_WILDCARD)
848 		dev->unit = -1;
849 	dev->devclass = NULL;
850 	free(dev->nameunit, M_BUS);
851 	dev->nameunit = NULL;
852 
853 	return (0);
854 }
855 
856 static device_t
857 make_device(device_t parent, const char *name, int unit)
858 {
859 	device_t dev;
860 	devclass_t dc;
861 
862 	PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
863 
864 	if (name) {
865 		dc = devclass_find_internal(name, TRUE);
866 		if (!dc) {
867 			printf("make_device: can't find device class %s\n",
868 			    name);
869 			return (NULL);
870 		}
871 	} else {
872 		dc = NULL;
873 	}
874 
875 	dev = malloc(sizeof(struct device), M_BUS, M_NOWAIT|M_ZERO);
876 	if (!dev)
877 		return (NULL);
878 
879 	dev->parent = parent;
880 	TAILQ_INIT(&dev->children);
881 	kobj_init((kobj_t) dev, &null_class);
882 	dev->driver = NULL;
883 	dev->devclass = NULL;
884 	dev->unit = unit;
885 	dev->nameunit = NULL;
886 	dev->desc = NULL;
887 	dev->busy = 0;
888 	dev->devflags = 0;
889 	dev->flags = DF_ENABLED;
890 	dev->order = 0;
891 	if (unit == -1)
892 		dev->flags |= DF_WILDCARD;
893 	if (name) {
894 		dev->flags |= DF_FIXEDCLASS;
895 		if (devclass_add_device(dc, dev)) {
896 			kobj_delete((kobj_t) dev, M_BUS);
897 			return (NULL);
898 		}
899 	}
900 	dev->ivars = NULL;
901 	dev->softc = NULL;
902 
903 	dev->state = DS_NOTPRESENT;
904 
905 	TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
906 	bus_data_generation_update();
907 
908 	return (dev);
909 }
910 
911 static int
912 device_print_child(device_t dev, device_t child)
913 {
914 	int retval = 0;
915 
916 	if (device_is_alive(child))
917 		retval += BUS_PRINT_CHILD(dev, child);
918 	else
919 		retval += device_printf(child, " not found\n");
920 
921 	return (retval);
922 }
923 
924 device_t
925 device_add_child(device_t dev, const char *name, int unit)
926 {
927 	return (device_add_child_ordered(dev, 0, name, unit));
928 }
929 
930 device_t
931 device_add_child_ordered(device_t dev, int order, const char *name, int unit)
932 {
933 	device_t child;
934 	device_t place;
935 
936 	PDEBUG(("%s at %s with order %d as unit %d",
937 	    name, DEVICENAME(dev), order, unit));
938 
939 	child = make_device(dev, name, unit);
940 	if (child == NULL)
941 		return (child);
942 	child->order = order;
943 
944 	TAILQ_FOREACH(place, &dev->children, link) {
945 		if (place->order > order)
946 			break;
947 	}
948 
949 	if (place) {
950 		/*
951 		 * The device 'place' is the first device whose order is
952 		 * greater than the new child.
953 		 */
954 		TAILQ_INSERT_BEFORE(place, child, link);
955 	} else {
956 		/*
957 		 * The new child's order is greater or equal to the order of
958 		 * any existing device. Add the child to the tail of the list.
959 		 */
960 		TAILQ_INSERT_TAIL(&dev->children, child, link);
961 	}
962 
963 	bus_data_generation_update();
964 	return (child);
965 }
966 
967 int
968 device_delete_child(device_t dev, device_t child)
969 {
970 	int error;
971 	device_t grandchild;
972 
973 	PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
974 
975 	/* remove children first */
976 	while ( (grandchild = TAILQ_FIRST(&child->children)) ) {
977 		error = device_delete_child(child, grandchild);
978 		if (error)
979 			return (error);
980 	}
981 
982 	if ((error = device_detach(child)) != 0)
983 		return (error);
984 	if (child->devclass)
985 		devclass_delete_device(child->devclass, child);
986 	TAILQ_REMOVE(&dev->children, child, link);
987 	TAILQ_REMOVE(&bus_data_devices, child, devlink);
988 	device_set_desc(child, NULL);
989 	kobj_delete((kobj_t) child, M_BUS);
990 
991 	bus_data_generation_update();
992 	return (0);
993 }
994 
995 /*
996  * Find only devices attached to this bus.
997  */
998 device_t
999 device_find_child(device_t dev, const char *classname, int unit)
1000 {
1001 	devclass_t dc;
1002 	device_t child;
1003 
1004 	dc = devclass_find(classname);
1005 	if (!dc)
1006 		return (NULL);
1007 
1008 	child = devclass_get_device(dc, unit);
1009 	if (child && child->parent == dev)
1010 		return (child);
1011 	return (NULL);
1012 }
1013 
1014 static driverlink_t
1015 first_matching_driver(devclass_t dc, device_t dev)
1016 {
1017 	if (dev->devclass)
1018 		return (devclass_find_driver_internal(dc, dev->devclass->name));
1019 	return (TAILQ_FIRST(&dc->drivers));
1020 }
1021 
1022 static driverlink_t
1023 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1024 {
1025 	if (dev->devclass) {
1026 		driverlink_t dl;
1027 		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1028 			if (!strcmp(dev->devclass->name, dl->driver->name))
1029 				return (dl);
1030 		return (NULL);
1031 	}
1032 	return (TAILQ_NEXT(last, link));
1033 }
1034 
1035 static int
1036 device_probe_child(device_t dev, device_t child)
1037 {
1038 	devclass_t dc;
1039 	driverlink_t best = 0;
1040 	driverlink_t dl;
1041 	int result, pri = 0;
1042 	int hasclass = (child->devclass != 0);
1043 
1044 	dc = dev->devclass;
1045 	if (!dc)
1046 		panic("device_probe_child: parent device has no devclass");
1047 
1048 	if (child->state == DS_ALIVE)
1049 		return (0);
1050 
1051 	for (dl = first_matching_driver(dc, child);
1052 	     dl;
1053 	     dl = next_matching_driver(dc, child, dl)) {
1054 		PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1055 		device_set_driver(child, dl->driver);
1056 		if (!hasclass)
1057 			device_set_devclass(child, dl->driver->name);
1058 		result = DEVICE_PROBE(child);
1059 		if (!hasclass)
1060 			device_set_devclass(child, 0);
1061 
1062 		/*
1063 		 * If the driver returns SUCCESS, there can be no higher match
1064 		 * for this device.
1065 		 */
1066 		if (result == 0) {
1067 			best = dl;
1068 			pri = 0;
1069 			break;
1070 		}
1071 
1072 		/*
1073 		 * The driver returned an error so it certainly doesn't match.
1074 		 */
1075 		if (result > 0) {
1076 			device_set_driver(child, 0);
1077 			continue;
1078 		}
1079 
1080 		/*
1081 		 * A priority lower than SUCCESS, remember the best matching
1082 		 * driver. Initialise the value of pri for the first match.
1083 		 */
1084 		if (best == 0 || result > pri) {
1085 			best = dl;
1086 			pri = result;
1087 			continue;
1088 		}
1089 	}
1090 
1091 	/*
1092 	 * If we found a driver, change state and initialise the devclass.
1093 	 */
1094 	if (best) {
1095 		if (!child->devclass)
1096 			device_set_devclass(child, best->driver->name);
1097 		device_set_driver(child, best->driver);
1098 		if (pri < 0) {
1099 			/*
1100 			 * A bit bogus. Call the probe method again to make
1101 			 * sure that we have the right description.
1102 			 */
1103 			DEVICE_PROBE(child);
1104 		}
1105 		child->state = DS_ALIVE;
1106 
1107 		bus_data_generation_update();
1108 		return (0);
1109 	}
1110 
1111 	return (ENXIO);
1112 }
1113 
1114 device_t
1115 device_get_parent(device_t dev)
1116 {
1117 	return (dev->parent);
1118 }
1119 
1120 int
1121 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1122 {
1123 	int count;
1124 	device_t child;
1125 	device_t *list;
1126 
1127 	count = 0;
1128 	TAILQ_FOREACH(child, &dev->children, link) {
1129 		count++;
1130 	}
1131 
1132 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1133 	if (!list)
1134 		return (ENOMEM);
1135 
1136 	count = 0;
1137 	TAILQ_FOREACH(child, &dev->children, link) {
1138 		list[count] = child;
1139 		count++;
1140 	}
1141 
1142 	*devlistp = list;
1143 	*devcountp = count;
1144 
1145 	return (0);
1146 }
1147 
1148 driver_t *
1149 device_get_driver(device_t dev)
1150 {
1151 	return (dev->driver);
1152 }
1153 
1154 devclass_t
1155 device_get_devclass(device_t dev)
1156 {
1157 	return (dev->devclass);
1158 }
1159 
1160 const char *
1161 device_get_name(device_t dev)
1162 {
1163 	if (dev->devclass)
1164 		return (devclass_get_name(dev->devclass));
1165 	return (NULL);
1166 }
1167 
1168 const char *
1169 device_get_nameunit(device_t dev)
1170 {
1171 	return (dev->nameunit);
1172 }
1173 
1174 int
1175 device_get_unit(device_t dev)
1176 {
1177 	return (dev->unit);
1178 }
1179 
1180 const char *
1181 device_get_desc(device_t dev)
1182 {
1183 	return (dev->desc);
1184 }
1185 
1186 u_int32_t
1187 device_get_flags(device_t dev)
1188 {
1189 	return (dev->devflags);
1190 }
1191 
1192 int
1193 device_print_prettyname(device_t dev)
1194 {
1195 	const char *name = device_get_name(dev);
1196 
1197 	if (name == 0)
1198 		return (printf("unknown: "));
1199 	return (printf("%s%d: ", name, device_get_unit(dev)));
1200 }
1201 
1202 int
1203 device_printf(device_t dev, const char * fmt, ...)
1204 {
1205 	va_list ap;
1206 	int retval;
1207 
1208 	retval = device_print_prettyname(dev);
1209 	va_start(ap, fmt);
1210 	retval += vprintf(fmt, ap);
1211 	va_end(ap);
1212 	return (retval);
1213 }
1214 
1215 static void
1216 device_set_desc_internal(device_t dev, const char* desc, int copy)
1217 {
1218 	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
1219 		free(dev->desc, M_BUS);
1220 		dev->flags &= ~DF_DESCMALLOCED;
1221 		dev->desc = NULL;
1222 	}
1223 
1224 	if (copy && desc) {
1225 		dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
1226 		if (dev->desc) {
1227 			strcpy(dev->desc, desc);
1228 			dev->flags |= DF_DESCMALLOCED;
1229 		}
1230 	} else {
1231 		/* Avoid a -Wcast-qual warning */
1232 		dev->desc = (char *)(uintptr_t) desc;
1233 	}
1234 
1235 	bus_data_generation_update();
1236 }
1237 
1238 void
1239 device_set_desc(device_t dev, const char* desc)
1240 {
1241 	device_set_desc_internal(dev, desc, FALSE);
1242 }
1243 
1244 void
1245 device_set_desc_copy(device_t dev, const char* desc)
1246 {
1247 	device_set_desc_internal(dev, desc, TRUE);
1248 }
1249 
1250 void
1251 device_set_flags(device_t dev, u_int32_t flags)
1252 {
1253 	dev->devflags = flags;
1254 }
1255 
1256 void *
1257 device_get_softc(device_t dev)
1258 {
1259 	return (dev->softc);
1260 }
1261 
1262 void
1263 device_set_softc(device_t dev, void *softc)
1264 {
1265 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
1266 		free(dev->softc, M_BUS);
1267 	dev->softc = softc;
1268 	if (dev->softc)
1269 		dev->flags |= DF_EXTERNALSOFTC;
1270 	else
1271 		dev->flags &= ~DF_EXTERNALSOFTC;
1272 }
1273 
1274 void *
1275 device_get_ivars(device_t dev)
1276 {
1277 
1278 	KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
1279 	return (dev->ivars);
1280 }
1281 
1282 void
1283 device_set_ivars(device_t dev, void * ivars)
1284 {
1285 
1286 	KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
1287 	dev->ivars = ivars;
1288 }
1289 
1290 device_state_t
1291 device_get_state(device_t dev)
1292 {
1293 	return (dev->state);
1294 }
1295 
1296 void
1297 device_enable(device_t dev)
1298 {
1299 	dev->flags |= DF_ENABLED;
1300 }
1301 
1302 void
1303 device_disable(device_t dev)
1304 {
1305 	dev->flags &= ~DF_ENABLED;
1306 }
1307 
1308 void
1309 device_busy(device_t dev)
1310 {
1311 	if (dev->state < DS_ATTACHED)
1312 		panic("device_busy: called for unattached device");
1313 	if (dev->busy == 0 && dev->parent)
1314 		device_busy(dev->parent);
1315 	dev->busy++;
1316 	dev->state = DS_BUSY;
1317 }
1318 
1319 void
1320 device_unbusy(device_t dev)
1321 {
1322 	if (dev->state != DS_BUSY)
1323 		panic("device_unbusy: called for non-busy device");
1324 	dev->busy--;
1325 	if (dev->busy == 0) {
1326 		if (dev->parent)
1327 			device_unbusy(dev->parent);
1328 		dev->state = DS_ATTACHED;
1329 	}
1330 }
1331 
1332 void
1333 device_quiet(device_t dev)
1334 {
1335 	dev->flags |= DF_QUIET;
1336 }
1337 
1338 void
1339 device_verbose(device_t dev)
1340 {
1341 	dev->flags &= ~DF_QUIET;
1342 }
1343 
1344 int
1345 device_is_quiet(device_t dev)
1346 {
1347 	return ((dev->flags & DF_QUIET) != 0);
1348 }
1349 
1350 int
1351 device_is_enabled(device_t dev)
1352 {
1353 	return ((dev->flags & DF_ENABLED) != 0);
1354 }
1355 
1356 int
1357 device_is_alive(device_t dev)
1358 {
1359 	return (dev->state >= DS_ALIVE);
1360 }
1361 
1362 int
1363 device_set_devclass(device_t dev, const char *classname)
1364 {
1365 	devclass_t dc;
1366 	int error;
1367 
1368 	if (!classname) {
1369 		if (dev->devclass)
1370 			devclass_delete_device(dev->devclass, dev);
1371 		return (0);
1372 	}
1373 
1374 	if (dev->devclass) {
1375 		printf("device_set_devclass: device class already set\n");
1376 		return (EINVAL);
1377 	}
1378 
1379 	dc = devclass_find_internal(classname, TRUE);
1380 	if (!dc)
1381 		return (ENOMEM);
1382 
1383 	error = devclass_add_device(dc, dev);
1384 
1385 	bus_data_generation_update();
1386 	return (error);
1387 }
1388 
1389 int
1390 device_set_driver(device_t dev, driver_t *driver)
1391 {
1392 	if (dev->state >= DS_ATTACHED)
1393 		return (EBUSY);
1394 
1395 	if (dev->driver == driver)
1396 		return (0);
1397 
1398 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
1399 		free(dev->softc, M_BUS);
1400 		dev->softc = NULL;
1401 	}
1402 	kobj_delete((kobj_t) dev, 0);
1403 	dev->driver = driver;
1404 	if (driver) {
1405 		kobj_init((kobj_t) dev, (kobj_class_t) driver);
1406 		if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
1407 			dev->softc = malloc(driver->size, M_BUS,
1408 			    M_NOWAIT | M_ZERO);
1409 			if (!dev->softc) {
1410 				kobj_delete((kobj_t) dev, 0);
1411 				kobj_init((kobj_t) dev, &null_class);
1412 				dev->driver = NULL;
1413 				return (ENOMEM);
1414 			}
1415 		}
1416 	} else {
1417 		kobj_init((kobj_t) dev, &null_class);
1418 	}
1419 
1420 	bus_data_generation_update();
1421 	return (0);
1422 }
1423 
1424 int
1425 device_probe_and_attach(device_t dev)
1426 {
1427 	device_t bus = dev->parent;
1428 	int error = 0;
1429 	int hasclass = (dev->devclass != 0);
1430 
1431 	if (dev->state >= DS_ALIVE)
1432 		return (0);
1433 
1434 	if (dev->flags & DF_ENABLED) {
1435 		error = device_probe_child(bus, dev);
1436 		if (!error) {
1437 			if (!device_is_quiet(dev))
1438 				device_print_child(bus, dev);
1439 			error = DEVICE_ATTACH(dev);
1440 			if (!error) {
1441 				dev->state = DS_ATTACHED;
1442 				devadded(dev);
1443 			} else {
1444 				printf("device_probe_and_attach: %s%d attach returned %d\n",
1445 				    dev->driver->name, dev->unit, error);
1446 				/* Unset the class; set in device_probe_child */
1447 				if (!hasclass)
1448 					device_set_devclass(dev, 0);
1449 				device_set_driver(dev, NULL);
1450 				dev->state = DS_NOTPRESENT;
1451 			}
1452 		} else {
1453 			if (!(dev->flags & DF_DONENOMATCH)) {
1454 				BUS_PROBE_NOMATCH(bus, dev);
1455 				devnomatch(dev);
1456 				dev->flags |= DF_DONENOMATCH;
1457 			}
1458 		}
1459 	} else {
1460 		if (bootverbose) {
1461 			device_print_prettyname(dev);
1462 			printf("not probed (disabled)\n");
1463 		}
1464 	}
1465 
1466 	return (error);
1467 }
1468 
1469 int
1470 device_detach(device_t dev)
1471 {
1472 	int error;
1473 
1474 	PDEBUG(("%s", DEVICENAME(dev)));
1475 	if (dev->state == DS_BUSY)
1476 		return (EBUSY);
1477 	if (dev->state != DS_ATTACHED)
1478 		return (0);
1479 
1480 	if ((error = DEVICE_DETACH(dev)) != 0)
1481 		return (error);
1482 	devremoved(dev);
1483 	device_printf(dev, "detached\n");
1484 	if (dev->parent)
1485 		BUS_CHILD_DETACHED(dev->parent, dev);
1486 
1487 	if (!(dev->flags & DF_FIXEDCLASS))
1488 		devclass_delete_device(dev->devclass, dev);
1489 
1490 	dev->state = DS_NOTPRESENT;
1491 	device_set_driver(dev, NULL);
1492 
1493 	return (0);
1494 }
1495 
1496 int
1497 device_shutdown(device_t dev)
1498 {
1499 	if (dev->state < DS_ATTACHED)
1500 		return (0);
1501 	return (DEVICE_SHUTDOWN(dev));
1502 }
1503 
1504 int
1505 device_set_unit(device_t dev, int unit)
1506 {
1507 	devclass_t dc;
1508 	int err;
1509 
1510 	dc = device_get_devclass(dev);
1511 	if (unit < dc->maxunit && dc->devices[unit])
1512 		return (EBUSY);
1513 	err = devclass_delete_device(dc, dev);
1514 	if (err)
1515 		return (err);
1516 	dev->unit = unit;
1517 	err = devclass_add_device(dc, dev);
1518 	if (err)
1519 		return (err);
1520 
1521 	bus_data_generation_update();
1522 	return (0);
1523 }
1524 
1525 /*======================================*/
1526 /*
1527  * Some useful method implementations to make life easier for bus drivers.
1528  */
1529 
1530 void
1531 resource_list_init(struct resource_list *rl)
1532 {
1533 	SLIST_INIT(rl);
1534 }
1535 
1536 void
1537 resource_list_free(struct resource_list *rl)
1538 {
1539 	struct resource_list_entry *rle;
1540 
1541 	while ((rle = SLIST_FIRST(rl)) != NULL) {
1542 		if (rle->res)
1543 			panic("resource_list_free: resource entry is busy");
1544 		SLIST_REMOVE_HEAD(rl, link);
1545 		free(rle, M_BUS);
1546 	}
1547 }
1548 
1549 int
1550 resource_list_add_next(struct resource_list *rl, int type, u_long start,
1551     u_long end, u_long count)
1552 {
1553 	int rid;
1554 
1555 	rid = 0;
1556 	while (resource_list_find(rl, type, rid) != NULL)
1557 		rid++;
1558 	resource_list_add(rl, type, rid, start, end, count);
1559 	return (rid);
1560 }
1561 
1562 void
1563 resource_list_add(struct resource_list *rl, int type, int rid,
1564     u_long start, u_long end, u_long count)
1565 {
1566 	struct resource_list_entry *rle;
1567 
1568 	rle = resource_list_find(rl, type, rid);
1569 	if (!rle) {
1570 		rle = malloc(sizeof(struct resource_list_entry), M_BUS,
1571 		    M_NOWAIT);
1572 		if (!rle)
1573 			panic("resource_list_add: can't record entry");
1574 		SLIST_INSERT_HEAD(rl, rle, link);
1575 		rle->type = type;
1576 		rle->rid = rid;
1577 		rle->res = NULL;
1578 	}
1579 
1580 	if (rle->res)
1581 		panic("resource_list_add: resource entry is busy");
1582 
1583 	rle->start = start;
1584 	rle->end = end;
1585 	rle->count = count;
1586 }
1587 
1588 struct resource_list_entry *
1589 resource_list_find(struct resource_list *rl, int type, int rid)
1590 {
1591 	struct resource_list_entry *rle;
1592 
1593 	SLIST_FOREACH(rle, rl, link) {
1594 		if (rle->type == type && rle->rid == rid)
1595 			return (rle);
1596 	}
1597 	return (NULL);
1598 }
1599 
1600 void
1601 resource_list_delete(struct resource_list *rl, int type, int rid)
1602 {
1603 	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
1604 
1605 	if (rle) {
1606 		if (rle->res != NULL)
1607 			panic("resource_list_delete: resource has not been released");
1608 		SLIST_REMOVE(rl, rle, resource_list_entry, link);
1609 		free(rle, M_BUS);
1610 	}
1611 }
1612 
1613 struct resource *
1614 resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
1615     int type, int *rid, u_long start, u_long end, u_long count, u_int flags)
1616 {
1617 	struct resource_list_entry *rle = 0;
1618 	int passthrough = (device_get_parent(child) != bus);
1619 	int isdefault = (start == 0UL && end == ~0UL);
1620 
1621 	if (passthrough) {
1622 		return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
1623 		    type, rid, start, end, count, flags));
1624 	}
1625 
1626 	rle = resource_list_find(rl, type, *rid);
1627 
1628 	if (!rle)
1629 		return (NULL);		/* no resource of that type/rid */
1630 
1631 	if (rle->res)
1632 		panic("resource_list_alloc: resource entry is busy");
1633 
1634 	if (isdefault) {
1635 		start = rle->start;
1636 		count = ulmax(count, rle->count);
1637 		end = ulmax(rle->end, start + count - 1);
1638 	}
1639 
1640 	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
1641 	    type, rid, start, end, count, flags);
1642 
1643 	/*
1644 	 * Record the new range.
1645 	 */
1646 	if (rle->res) {
1647 		rle->start = rman_get_start(rle->res);
1648 		rle->end = rman_get_end(rle->res);
1649 		rle->count = count;
1650 	}
1651 
1652 	return (rle->res);
1653 }
1654 
1655 int
1656 resource_list_release(struct resource_list *rl, device_t bus, device_t child,
1657     int type, int rid, struct resource *res)
1658 {
1659 	struct resource_list_entry *rle = 0;
1660 	int passthrough = (device_get_parent(child) != bus);
1661 	int error;
1662 
1663 	if (passthrough) {
1664 		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
1665 		    type, rid, res));
1666 	}
1667 
1668 	rle = resource_list_find(rl, type, rid);
1669 
1670 	if (!rle)
1671 		panic("resource_list_release: can't find resource");
1672 	if (!rle->res)
1673 		panic("resource_list_release: resource entry is not busy");
1674 
1675 	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
1676 	    type, rid, res);
1677 	if (error)
1678 		return (error);
1679 
1680 	rle->res = NULL;
1681 	return (0);
1682 }
1683 
1684 int
1685 resource_list_print_type(struct resource_list *rl, const char *name, int type,
1686     const char *format)
1687 {
1688 	struct resource_list_entry *rle;
1689 	int printed, retval;
1690 
1691 	printed = 0;
1692 	retval = 0;
1693 	/* Yes, this is kinda cheating */
1694 	SLIST_FOREACH(rle, rl, link) {
1695 		if (rle->type == type) {
1696 			if (printed == 0)
1697 				retval += printf(" %s ", name);
1698 			else
1699 				retval += printf(",");
1700 			printed++;
1701 			retval += printf(format, rle->start);
1702 			if (rle->count > 1) {
1703 				retval += printf("-");
1704 				retval += printf(format, rle->start +
1705 						 rle->count - 1);
1706 			}
1707 		}
1708 	}
1709 	return (retval);
1710 }
1711 
1712 /*
1713  * Call DEVICE_IDENTIFY for each driver.
1714  */
1715 int
1716 bus_generic_probe(device_t dev)
1717 {
1718 	devclass_t dc = dev->devclass;
1719 	driverlink_t dl;
1720 
1721 	TAILQ_FOREACH(dl, &dc->drivers, link) {
1722 		DEVICE_IDENTIFY(dl->driver, dev);
1723 	}
1724 
1725 	return (0);
1726 }
1727 
1728 int
1729 bus_generic_attach(device_t dev)
1730 {
1731 	device_t child;
1732 
1733 	TAILQ_FOREACH(child, &dev->children, link) {
1734 		device_probe_and_attach(child);
1735 	}
1736 
1737 	return (0);
1738 }
1739 
1740 int
1741 bus_generic_detach(device_t dev)
1742 {
1743 	device_t child;
1744 	int error;
1745 
1746 	if (dev->state != DS_ATTACHED)
1747 		return (EBUSY);
1748 
1749 	TAILQ_FOREACH(child, &dev->children, link) {
1750 		if ((error = device_detach(child)) != 0)
1751 			return (error);
1752 	}
1753 
1754 	return (0);
1755 }
1756 
1757 int
1758 bus_generic_shutdown(device_t dev)
1759 {
1760 	device_t child;
1761 
1762 	TAILQ_FOREACH(child, &dev->children, link) {
1763 		device_shutdown(child);
1764 	}
1765 
1766 	return (0);
1767 }
1768 
1769 int
1770 bus_generic_suspend(device_t dev)
1771 {
1772 	int		error;
1773 	device_t	child, child2;
1774 
1775 	TAILQ_FOREACH(child, &dev->children, link) {
1776 		error = DEVICE_SUSPEND(child);
1777 		if (error) {
1778 			for (child2 = TAILQ_FIRST(&dev->children);
1779 			     child2 && child2 != child;
1780 			     child2 = TAILQ_NEXT(child2, link))
1781 				DEVICE_RESUME(child2);
1782 			return (error);
1783 		}
1784 	}
1785 	return (0);
1786 }
1787 
1788 int
1789 bus_generic_resume(device_t dev)
1790 {
1791 	device_t	child;
1792 
1793 	TAILQ_FOREACH(child, &dev->children, link) {
1794 		DEVICE_RESUME(child);
1795 		/* if resume fails, there's nothing we can usefully do... */
1796 	}
1797 	return (0);
1798 }
1799 
1800 int
1801 bus_print_child_header (device_t dev, device_t child)
1802 {
1803 	int	retval = 0;
1804 
1805 	if (device_get_desc(child)) {
1806 		retval += device_printf(child, "<%s>", device_get_desc(child));
1807 	} else {
1808 		retval += printf("%s", device_get_nameunit(child));
1809 	}
1810 
1811 	return (retval);
1812 }
1813 
1814 int
1815 bus_print_child_footer (device_t dev, device_t child)
1816 {
1817 	return (printf(" on %s\n", device_get_nameunit(dev)));
1818 }
1819 
1820 int
1821 bus_generic_print_child(device_t dev, device_t child)
1822 {
1823 	int	retval = 0;
1824 
1825 	retval += bus_print_child_header(dev, child);
1826 	retval += bus_print_child_footer(dev, child);
1827 
1828 	return (retval);
1829 }
1830 
1831 int
1832 bus_generic_read_ivar(device_t dev, device_t child, int index,
1833     uintptr_t * result)
1834 {
1835 	return (ENOENT);
1836 }
1837 
1838 int
1839 bus_generic_write_ivar(device_t dev, device_t child, int index,
1840     uintptr_t value)
1841 {
1842 	return (ENOENT);
1843 }
1844 
1845 struct resource_list *
1846 bus_generic_get_resource_list (device_t dev, device_t child)
1847 {
1848 	return (NULL);
1849 }
1850 
1851 void
1852 bus_generic_driver_added(device_t dev, driver_t *driver)
1853 {
1854 	device_t child;
1855 
1856 	DEVICE_IDENTIFY(driver, dev);
1857 	TAILQ_FOREACH(child, &dev->children, link) {
1858 		if (child->state == DS_NOTPRESENT)
1859 			device_probe_and_attach(child);
1860 	}
1861 }
1862 
1863 int
1864 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
1865     int flags, driver_intr_t *intr, void *arg, void **cookiep)
1866 {
1867 	/* Propagate up the bus hierarchy until someone handles it. */
1868 	if (dev->parent)
1869 		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
1870 		    intr, arg, cookiep));
1871 	return (EINVAL);
1872 }
1873 
1874 int
1875 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
1876     void *cookie)
1877 {
1878 	/* Propagate up the bus hierarchy until someone handles it. */
1879 	if (dev->parent)
1880 		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
1881 	return (EINVAL);
1882 }
1883 
1884 struct resource *
1885 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
1886     u_long start, u_long end, u_long count, u_int flags)
1887 {
1888 	/* Propagate up the bus hierarchy until someone handles it. */
1889 	if (dev->parent)
1890 		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
1891 		    start, end, count, flags));
1892 	return (NULL);
1893 }
1894 
1895 int
1896 bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
1897     struct resource *r)
1898 {
1899 	/* Propagate up the bus hierarchy until someone handles it. */
1900 	if (dev->parent)
1901 		return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
1902 		    r));
1903 	return (EINVAL);
1904 }
1905 
1906 int
1907 bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
1908     struct resource *r)
1909 {
1910 	/* Propagate up the bus hierarchy until someone handles it. */
1911 	if (dev->parent)
1912 		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
1913 		    r));
1914 	return (EINVAL);
1915 }
1916 
1917 int
1918 bus_generic_deactivate_resource(device_t dev, device_t child, int type,
1919     int rid, struct resource *r)
1920 {
1921 	/* Propagate up the bus hierarchy until someone handles it. */
1922 	if (dev->parent)
1923 		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
1924 		    r));
1925 	return (EINVAL);
1926 }
1927 
1928 int
1929 bus_generic_rl_get_resource (device_t dev, device_t child, int type, int rid,
1930     u_long *startp, u_long *countp)
1931 {
1932 	struct resource_list *		rl = NULL;
1933 	struct resource_list_entry *	rle = NULL;
1934 
1935 	rl = BUS_GET_RESOURCE_LIST(dev, child);
1936 	if (!rl)
1937 		return (EINVAL);
1938 
1939 	rle = resource_list_find(rl, type, rid);
1940 	if (!rle)
1941 		return (ENOENT);
1942 
1943 	if (startp)
1944 		*startp = rle->start;
1945 	if (countp)
1946 		*countp = rle->count;
1947 
1948 	return (0);
1949 }
1950 
1951 int
1952 bus_generic_rl_set_resource (device_t dev, device_t child, int type, int rid,
1953     u_long start, u_long count)
1954 {
1955 	struct resource_list *		rl = NULL;
1956 
1957 	rl = BUS_GET_RESOURCE_LIST(dev, child);
1958 	if (!rl)
1959 		return (EINVAL);
1960 
1961 	resource_list_add(rl, type, rid, start, (start + count - 1), count);
1962 
1963 	return (0);
1964 }
1965 
1966 void
1967 bus_generic_rl_delete_resource (device_t dev, device_t child, int type, int rid)
1968 {
1969 	struct resource_list *		rl = NULL;
1970 
1971 	rl = BUS_GET_RESOURCE_LIST(dev, child);
1972 	if (!rl)
1973 		return;
1974 
1975 	resource_list_delete(rl, type, rid);
1976 
1977 	return;
1978 }
1979 
1980 int
1981 bus_generic_rl_release_resource (device_t dev, device_t child, int type,
1982     int rid, struct resource *r)
1983 {
1984 	struct resource_list *		rl = NULL;
1985 
1986 	rl = BUS_GET_RESOURCE_LIST(dev, child);
1987 	if (!rl)
1988 		return (EINVAL);
1989 
1990 	return (resource_list_release(rl, dev, child, type, rid, r));
1991 }
1992 
1993 struct resource *
1994 bus_generic_rl_alloc_resource (device_t dev, device_t child, int type,
1995     int *rid, u_long start, u_long end, u_long count, u_int flags)
1996 {
1997 	struct resource_list *		rl = NULL;
1998 
1999 	rl = BUS_GET_RESOURCE_LIST(dev, child);
2000 	if (!rl)
2001 		return (NULL);
2002 
2003 	return (resource_list_alloc(rl, dev, child, type, rid,
2004 	    start, end, count, flags));
2005 }
2006 
2007 int
2008 bus_generic_child_present(device_t bus, device_t child)
2009 {
2010 	return (BUS_CHILD_PRESENT(device_get_parent(bus), bus));
2011 }
2012 
2013 /*
2014  * Some convenience functions to make it easier for drivers to use the
2015  * resource-management functions.  All these really do is hide the
2016  * indirection through the parent's method table, making for slightly
2017  * less-wordy code.  In the future, it might make sense for this code
2018  * to maintain some sort of a list of resources allocated by each device.
2019  */
2020 struct resource *
2021 bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
2022     u_long count, u_int flags)
2023 {
2024 	if (dev->parent == 0)
2025 		return (0);
2026 	return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
2027 	    count, flags));
2028 }
2029 
2030 int
2031 bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
2032 {
2033 	if (dev->parent == 0)
2034 		return (EINVAL);
2035 	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2036 }
2037 
2038 int
2039 bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
2040 {
2041 	if (dev->parent == 0)
2042 		return (EINVAL);
2043 	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2044 }
2045 
2046 int
2047 bus_release_resource(device_t dev, int type, int rid, struct resource *r)
2048 {
2049 	if (dev->parent == 0)
2050 		return (EINVAL);
2051 	return (BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
2052 }
2053 
2054 int
2055 bus_setup_intr(device_t dev, struct resource *r, int flags,
2056     driver_intr_t handler, void *arg, void **cookiep)
2057 {
2058 	if (dev->parent == 0)
2059 		return (EINVAL);
2060 	return (BUS_SETUP_INTR(dev->parent, dev, r, flags,
2061 	    handler, arg, cookiep));
2062 }
2063 
2064 int
2065 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
2066 {
2067 	if (dev->parent == 0)
2068 		return (EINVAL);
2069 	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
2070 }
2071 
2072 int
2073 bus_set_resource(device_t dev, int type, int rid,
2074     u_long start, u_long count)
2075 {
2076 	return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
2077 	    start, count));
2078 }
2079 
2080 int
2081 bus_get_resource(device_t dev, int type, int rid,
2082     u_long *startp, u_long *countp)
2083 {
2084 	return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2085 	    startp, countp));
2086 }
2087 
2088 u_long
2089 bus_get_resource_start(device_t dev, int type, int rid)
2090 {
2091 	u_long start, count;
2092 	int error;
2093 
2094 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2095 	    &start, &count);
2096 	if (error)
2097 		return (0);
2098 	return (start);
2099 }
2100 
2101 u_long
2102 bus_get_resource_count(device_t dev, int type, int rid)
2103 {
2104 	u_long start, count;
2105 	int error;
2106 
2107 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2108 	    &start, &count);
2109 	if (error)
2110 		return (0);
2111 	return (count);
2112 }
2113 
2114 void
2115 bus_delete_resource(device_t dev, int type, int rid)
2116 {
2117 	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
2118 }
2119 
2120 int
2121 bus_child_present(device_t child)
2122 {
2123 	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
2124 }
2125 
2126 int
2127 bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
2128 {
2129 	device_t parent;
2130 
2131 	parent = device_get_parent(child);
2132 	if (parent == NULL) {
2133 		*buf = '\0';
2134 		return (0);
2135 	}
2136 	return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
2137 }
2138 
2139 int
2140 bus_child_location_str(device_t child, char *buf, size_t buflen)
2141 {
2142 	device_t parent;
2143 
2144 	parent = device_get_parent(child);
2145 	if (parent == NULL) {
2146 		*buf = '\0';
2147 		return (0);
2148 	}
2149 	return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
2150 }
2151 
2152 static int
2153 root_print_child(device_t dev, device_t child)
2154 {
2155 	int	retval = 0;
2156 
2157 	retval += bus_print_child_header(dev, child);
2158 	retval += printf("\n");
2159 
2160 	return (retval);
2161 }
2162 
2163 static int
2164 root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
2165     void **cookiep)
2166 {
2167 	/*
2168 	 * If an interrupt mapping gets to here something bad has happened.
2169 	 */
2170 	panic("root_setup_intr");
2171 }
2172 
2173 /*
2174  * If we get here, assume that the device is permanant and really is
2175  * present in the system.  Removable bus drivers are expected to intercept
2176  * this call long before it gets here.  We return -1 so that drivers that
2177  * really care can check vs -1 or some ERRNO returned higher in the food
2178  * chain.
2179  */
2180 static int
2181 root_child_present(device_t dev, device_t child)
2182 {
2183 	return (-1);
2184 }
2185 
2186 static kobj_method_t root_methods[] = {
2187 	/* Device interface */
2188 	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
2189 	KOBJMETHOD(device_suspend,	bus_generic_suspend),
2190 	KOBJMETHOD(device_resume,	bus_generic_resume),
2191 
2192 	/* Bus interface */
2193 	KOBJMETHOD(bus_print_child,	root_print_child),
2194 	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
2195 	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
2196 	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
2197 	KOBJMETHOD(bus_child_present,	root_child_present),
2198 
2199 	{ 0, 0 }
2200 };
2201 
2202 static driver_t root_driver = {
2203 	"root",
2204 	root_methods,
2205 	1,			/* no softc */
2206 };
2207 
2208 device_t	root_bus;
2209 devclass_t	root_devclass;
2210 
2211 static int
2212 root_bus_module_handler(module_t mod, int what, void* arg)
2213 {
2214 	switch (what) {
2215 	case MOD_LOAD:
2216 		TAILQ_INIT(&bus_data_devices);
2217 		kobj_class_compile((kobj_class_t) &root_driver);
2218 		root_bus = make_device(NULL, "root", 0);
2219 		root_bus->desc = "System root bus";
2220 		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
2221 		root_bus->driver = &root_driver;
2222 		root_bus->state = DS_ATTACHED;
2223 		root_devclass = devclass_find_internal("root", FALSE);
2224 		devinit();
2225 		return (0);
2226 
2227 	case MOD_SHUTDOWN:
2228 		device_shutdown(root_bus);
2229 		return (0);
2230 	}
2231 
2232 	return (0);
2233 }
2234 
2235 static moduledata_t root_bus_mod = {
2236 	"rootbus",
2237 	root_bus_module_handler,
2238 	0
2239 };
2240 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
2241 
2242 void
2243 root_bus_configure(void)
2244 {
2245 	device_t dev;
2246 
2247 	PDEBUG(("."));
2248 
2249 	TAILQ_FOREACH(dev, &root_bus->children, link) {
2250 		device_probe_and_attach(dev);
2251 	}
2252 }
2253 
2254 int
2255 driver_module_handler(module_t mod, int what, void *arg)
2256 {
2257 	int error, i;
2258 	struct driver_module_data *dmd;
2259 	devclass_t bus_devclass;
2260 
2261 	dmd = (struct driver_module_data *)arg;
2262 	bus_devclass = devclass_find_internal(dmd->dmd_busname, TRUE);
2263 	error = 0;
2264 
2265 	switch (what) {
2266 	case MOD_LOAD:
2267 		if (dmd->dmd_chainevh)
2268 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
2269 
2270 		for (i = 0; !error && i < dmd->dmd_ndrivers; i++) {
2271 			PDEBUG(("Loading module: driver %s on bus %s",
2272 			    DRIVERNAME(dmd->dmd_drivers[i]), dmd->dmd_busname));
2273 			error = devclass_add_driver(bus_devclass,
2274 			    dmd->dmd_drivers[i]);
2275 		}
2276 		if (error)
2277 			break;
2278 
2279 		/*
2280 		 * The drivers loaded in this way are assumed to all
2281 		 * implement the same devclass.
2282 		 */
2283 		*dmd->dmd_devclass =
2284 		    devclass_find_internal(dmd->dmd_drivers[0]->name, TRUE);
2285 		break;
2286 
2287 	case MOD_UNLOAD:
2288 		for (i = 0; !error && i < dmd->dmd_ndrivers; i++) {
2289 			PDEBUG(("Unloading module: driver %s from bus %s",
2290 			    DRIVERNAME(dmd->dmd_drivers[i]),
2291 			    dmd->dmd_busname));
2292 			error = devclass_delete_driver(bus_devclass,
2293 			    dmd->dmd_drivers[i]);
2294 		}
2295 
2296 		if (!error && dmd->dmd_chainevh)
2297 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
2298 		break;
2299 	}
2300 
2301 	return (error);
2302 }
2303 
2304 #ifdef BUS_DEBUG
2305 
2306 /* the _short versions avoid iteration by not calling anything that prints
2307  * more than oneliners. I love oneliners.
2308  */
2309 
2310 static void
2311 print_device_short(device_t dev, int indent)
2312 {
2313 	if (!dev)
2314 		return;
2315 
2316 	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
2317 	    dev->unit, dev->desc,
2318 	    (dev->parent? "":"no "),
2319 	    (TAILQ_EMPTY(&dev->children)? "no ":""),
2320 	    (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
2321 	    (dev->flags&DF_FIXEDCLASS? "fixed,":""),
2322 	    (dev->flags&DF_WILDCARD? "wildcard,":""),
2323 	    (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
2324 	    (dev->ivars? "":"no "),
2325 	    (dev->softc? "":"no "),
2326 	    dev->busy));
2327 }
2328 
2329 static void
2330 print_device(device_t dev, int indent)
2331 {
2332 	if (!dev)
2333 		return;
2334 
2335 	print_device_short(dev, indent);
2336 
2337 	indentprintf(("Parent:\n"));
2338 	print_device_short(dev->parent, indent+1);
2339 	indentprintf(("Driver:\n"));
2340 	print_driver_short(dev->driver, indent+1);
2341 	indentprintf(("Devclass:\n"));
2342 	print_devclass_short(dev->devclass, indent+1);
2343 }
2344 
2345 void
2346 print_device_tree_short(device_t dev, int indent)
2347 /* print the device and all its children (indented) */
2348 {
2349 	device_t child;
2350 
2351 	if (!dev)
2352 		return;
2353 
2354 	print_device_short(dev, indent);
2355 
2356 	TAILQ_FOREACH(child, &dev->children, link) {
2357 		print_device_tree_short(child, indent+1);
2358 	}
2359 }
2360 
2361 void
2362 print_device_tree(device_t dev, int indent)
2363 /* print the device and all its children (indented) */
2364 {
2365 	device_t child;
2366 
2367 	if (!dev)
2368 		return;
2369 
2370 	print_device(dev, indent);
2371 
2372 	TAILQ_FOREACH(child, &dev->children, link) {
2373 		print_device_tree(child, indent+1);
2374 	}
2375 }
2376 
2377 static void
2378 print_driver_short(driver_t *driver, int indent)
2379 {
2380 	if (!driver)
2381 		return;
2382 
2383 	indentprintf(("driver %s: softc size = %zd\n",
2384 	    driver->name, driver->size));
2385 }
2386 
2387 static void
2388 print_driver(driver_t *driver, int indent)
2389 {
2390 	if (!driver)
2391 		return;
2392 
2393 	print_driver_short(driver, indent);
2394 }
2395 
2396 
2397 static void
2398 print_driver_list(driver_list_t drivers, int indent)
2399 {
2400 	driverlink_t driver;
2401 
2402 	TAILQ_FOREACH(driver, &drivers, link) {
2403 		print_driver(driver->driver, indent);
2404 	}
2405 }
2406 
2407 static void
2408 print_devclass_short(devclass_t dc, int indent)
2409 {
2410 	if ( !dc )
2411 		return;
2412 
2413 	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
2414 }
2415 
2416 static void
2417 print_devclass(devclass_t dc, int indent)
2418 {
2419 	int i;
2420 
2421 	if ( !dc )
2422 		return;
2423 
2424 	print_devclass_short(dc, indent);
2425 	indentprintf(("Drivers:\n"));
2426 	print_driver_list(dc->drivers, indent+1);
2427 
2428 	indentprintf(("Devices:\n"));
2429 	for (i = 0; i < dc->maxunit; i++)
2430 		if (dc->devices[i])
2431 			print_device(dc->devices[i], indent+1);
2432 }
2433 
2434 void
2435 print_devclass_list_short(void)
2436 {
2437 	devclass_t dc;
2438 
2439 	printf("Short listing of devclasses, drivers & devices:\n");
2440 	TAILQ_FOREACH(dc, &devclasses, link) {
2441 		print_devclass_short(dc, 0);
2442 	}
2443 }
2444 
2445 void
2446 print_devclass_list(void)
2447 {
2448 	devclass_t dc;
2449 
2450 	printf("Full listing of devclasses, drivers & devices:\n");
2451 	TAILQ_FOREACH(dc, &devclasses, link) {
2452 		print_devclass(dc, 0);
2453 	}
2454 }
2455 
2456 #endif
2457 
2458 /*
2459  * User-space access to the device tree.
2460  *
2461  * We implement a small set of nodes:
2462  *
2463  * hw.bus			Single integer read method to obtain the
2464  *				current generation count.
2465  * hw.bus.devices		Reads the entire device tree in flat space.
2466  * hw.bus.rman			Resource manager interface
2467  *
2468  * We might like to add the ability to scan devclasses and/or drivers to
2469  * determine what else is currently loaded/available.
2470  */
2471 
2472 static int
2473 sysctl_bus(SYSCTL_HANDLER_ARGS)
2474 {
2475 	struct u_businfo	ubus;
2476 
2477 	ubus.ub_version = BUS_USER_VERSION;
2478 	ubus.ub_generation = bus_data_generation;
2479 
2480 	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
2481 }
2482 SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
2483     "bus-related data");
2484 
2485 static int
2486 sysctl_devices(SYSCTL_HANDLER_ARGS)
2487 {
2488 	int			*name = (int *)arg1;
2489 	u_int			namelen = arg2;
2490 	int			index;
2491 	struct device		*dev;
2492 	struct u_device		udev;	/* XXX this is a bit big */
2493 	int			error;
2494 
2495 	if (namelen != 2)
2496 		return (EINVAL);
2497 
2498 	if (bus_data_generation_check(name[0]))
2499 		return (EINVAL);
2500 
2501 	index = name[1];
2502 
2503 	/*
2504 	 * Scan the list of devices, looking for the requested index.
2505 	 */
2506 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
2507 		if (index-- == 0)
2508 			break;
2509 	}
2510 	if (dev == NULL)
2511 		return (ENOENT);
2512 
2513 	/*
2514 	 * Populate the return array.
2515 	 */
2516 	udev.dv_handle = (uintptr_t)dev;
2517 	udev.dv_parent = (uintptr_t)dev->parent;
2518 	if (dev->nameunit == NULL)
2519 		udev.dv_name[0] = '\0';
2520 	else
2521 		strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
2522 
2523 	if (dev->desc == NULL)
2524 		udev.dv_desc[0] = '\0';
2525 	else
2526 		strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
2527 	if (dev->driver == NULL || dev->driver->name == NULL)
2528 		udev.dv_drivername[0] = '\0';
2529 	else
2530 		strlcpy(udev.dv_drivername, dev->driver->name,
2531 		    sizeof(udev.dv_drivername));
2532 	udev.dv_pnpinfo[0] = '\0';
2533 	udev.dv_location[0] = '\0';
2534 	bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
2535 	bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
2536 	udev.dv_devflags = dev->devflags;
2537 	udev.dv_flags = dev->flags;
2538 	udev.dv_state = dev->state;
2539 	error = SYSCTL_OUT(req, &udev, sizeof(udev));
2540 	return (error);
2541 }
2542 
2543 SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
2544     "system device tree");
2545 
2546 /*
2547  * Sysctl interface for scanning the resource lists.
2548  *
2549  * We take two input parameters; the index into the list of resource
2550  * managers, and the resource offset into the list.
2551  */
2552 static int
2553 sysctl_rman(SYSCTL_HANDLER_ARGS)
2554 {
2555 	int			*name = (int *)arg1;
2556 	u_int			namelen = arg2;
2557 	int			rman_idx, res_idx;
2558 	struct rman		*rm;
2559 	struct resource		*res;
2560 	struct u_rman		urm;
2561 	struct u_resource	ures;
2562 	int			error;
2563 
2564 	if (namelen != 3)
2565 		return (EINVAL);
2566 
2567 	if (bus_data_generation_check(name[0]))
2568 		return (EINVAL);
2569 	rman_idx = name[1];
2570 	res_idx = name[2];
2571 
2572 	/*
2573 	 * Find the indexed resource manager
2574 	 */
2575 	TAILQ_FOREACH(rm, &rman_head, rm_link) {
2576 		if (rman_idx-- == 0)
2577 			break;
2578 	}
2579 	if (rm == NULL)
2580 		return (ENOENT);
2581 
2582 	/*
2583 	 * If the resource index is -1, we want details on the
2584 	 * resource manager.
2585 	 */
2586 	if (res_idx == -1) {
2587 		urm.rm_handle = (uintptr_t)rm;
2588 		strlcpy(urm.rm_descr, rm->rm_descr, RM_TEXTLEN);
2589 		urm.rm_start = rm->rm_start;
2590 		urm.rm_size = rm->rm_end - rm->rm_start + 1;
2591 		urm.rm_type = rm->rm_type;
2592 
2593 		error = SYSCTL_OUT(req, &urm, sizeof(urm));
2594 		return (error);
2595 	}
2596 
2597 	/*
2598 	 * Find the indexed resource and return it.
2599 	 */
2600 	TAILQ_FOREACH(res, &rm->rm_list, r_link) {
2601 		if (res_idx-- == 0) {
2602 			ures.r_handle = (uintptr_t)res;
2603 			ures.r_parent = (uintptr_t)res->r_rm;
2604 			ures.r_device = (uintptr_t)res->r_dev;
2605 			if (res->r_dev != NULL) {
2606 				if (device_get_name(res->r_dev) != NULL) {
2607 					snprintf(ures.r_devname, RM_TEXTLEN,
2608 					    "%s%d",
2609 					    device_get_name(res->r_dev),
2610 					    device_get_unit(res->r_dev));
2611 				} else {
2612 					strlcpy(ures.r_devname, "nomatch",
2613 					    RM_TEXTLEN);
2614 				}
2615 			} else {
2616 				ures.r_devname[0] = '\0';
2617 			}
2618 			ures.r_start = res->r_start;
2619 			ures.r_size = res->r_end - res->r_start + 1;
2620 			ures.r_flags = res->r_flags;
2621 
2622 			error = SYSCTL_OUT(req, &ures, sizeof(ures));
2623 			return (error);
2624 		}
2625 	}
2626 	return (ENOENT);
2627 }
2628 
2629 SYSCTL_NODE(_hw_bus, OID_AUTO, rman, CTLFLAG_RD, sysctl_rman,
2630     "kernel resource manager");
2631 
2632 int
2633 bus_data_generation_check(int generation)
2634 {
2635 	if (generation != bus_data_generation)
2636 		return (1);
2637 
2638 	/* XXX generate optimised lists here? */
2639 	return (0);
2640 }
2641 
2642 void
2643 bus_data_generation_update(void)
2644 {
2645 	bus_data_generation++;
2646 }
2647