xref: /freebsd/sys/kern/subr_bus.c (revision b6de9e91bd2c47efaeec72a08642f8fd99cc7b20)
1 /*-
2  * Copyright (c) 1997,1998,2003 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 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_bus.h"
31 
32 #include <sys/param.h>
33 #include <sys/conf.h>
34 #include <sys/filio.h>
35 #include <sys/lock.h>
36 #include <sys/kernel.h>
37 #include <sys/kobj.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/mutex.h>
41 #include <sys/poll.h>
42 #include <sys/proc.h>
43 #include <sys/condvar.h>
44 #include <sys/queue.h>
45 #include <machine/bus.h>
46 #include <sys/rman.h>
47 #include <sys/selinfo.h>
48 #include <sys/signalvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/systm.h>
51 #include <sys/uio.h>
52 #include <sys/bus.h>
53 
54 #include <machine/stdarg.h>
55 
56 #include <vm/uma.h>
57 
58 SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW, NULL, NULL);
59 SYSCTL_NODE(, OID_AUTO, dev, CTLFLAG_RW, NULL, NULL);
60 
61 /*
62  * Used to attach drivers to devclasses.
63  */
64 typedef struct driverlink *driverlink_t;
65 struct driverlink {
66 	kobj_class_t	driver;
67 	TAILQ_ENTRY(driverlink) link;	/* list of drivers in devclass */
68 };
69 
70 /*
71  * Forward declarations
72  */
73 typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
74 typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
75 typedef TAILQ_HEAD(device_list, device) device_list_t;
76 
77 struct devclass {
78 	TAILQ_ENTRY(devclass) link;
79 	devclass_t	parent;		/* parent in devclass hierarchy */
80 	driver_list_t	drivers;     /* bus devclasses store drivers for bus */
81 	char		*name;
82 	device_t	*devices;	/* array of devices indexed by unit */
83 	int		maxunit;	/* size of devices array */
84 
85 	struct sysctl_ctx_list sysctl_ctx;
86 	struct sysctl_oid *sysctl_tree;
87 };
88 
89 /**
90  * @brief Implementation of device.
91  */
92 struct device {
93 	/*
94 	 * A device is a kernel object. The first field must be the
95 	 * current ops table for the object.
96 	 */
97 	KOBJ_FIELDS;
98 
99 	/*
100 	 * Device hierarchy.
101 	 */
102 	TAILQ_ENTRY(device)	link;	/**< list of devices in parent */
103 	TAILQ_ENTRY(device)	devlink; /**< global device list membership */
104 	device_t	parent;		/**< parent of this device  */
105 	device_list_t	children;	/**< list of child devices */
106 
107 	/*
108 	 * Details of this device.
109 	 */
110 	driver_t	*driver;	/**< current driver */
111 	devclass_t	devclass;	/**< current device class */
112 	int		unit;		/**< current unit number */
113 	char*		nameunit;	/**< name+unit e.g. foodev0 */
114 	char*		desc;		/**< driver specific description */
115 	int		busy;		/**< count of calls to device_busy() */
116 	device_state_t	state;		/**< current device state  */
117 	u_int32_t	devflags;	/**< api level flags for device_get_flags() */
118 	u_short		flags;		/**< internal device flags  */
119 #define	DF_ENABLED	1		/* device should be probed/attached */
120 #define	DF_FIXEDCLASS	2		/* devclass specified at create time */
121 #define	DF_WILDCARD	4		/* unit was originally wildcard */
122 #define	DF_DESCMALLOCED	8		/* description was malloced */
123 #define	DF_QUIET	16		/* don't print verbose attach message */
124 #define	DF_DONENOMATCH	32		/* don't execute DEVICE_NOMATCH again */
125 #define	DF_EXTERNALSOFTC 64		/* softc not allocated by us */
126 #define	DF_REBID	128		/* Can rebid after attach */
127 	u_char	order;			/**< order from device_add_child_ordered() */
128 	u_char	pad;
129 	void	*ivars;			/**< instance variables  */
130 	void	*softc;			/**< current driver's variables  */
131 
132 	struct sysctl_ctx_list sysctl_ctx; /**< state for sysctl variables  */
133 	struct sysctl_oid *sysctl_tree;	/**< state for sysctl variables */
134 };
135 
136 static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
137 static MALLOC_DEFINE(M_BUS_SC, "bus-sc", "Bus data structures, softc");
138 
139 #ifdef BUS_DEBUG
140 
141 static int bus_debug = 1;
142 TUNABLE_INT("bus.debug", &bus_debug);
143 SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RW, &bus_debug, 0,
144     "Debug bus code");
145 
146 #define PDEBUG(a)	if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
147 #define DEVICENAME(d)	((d)? device_get_name(d): "no device")
148 #define DRIVERNAME(d)	((d)? d->name : "no driver")
149 #define DEVCLANAME(d)	((d)? d->name : "no devclass")
150 
151 /**
152  * Produce the indenting, indent*2 spaces plus a '.' ahead of that to
153  * prevent syslog from deleting initial spaces
154  */
155 #define indentprintf(p)	do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
156 
157 static void print_device_short(device_t dev, int indent);
158 static void print_device(device_t dev, int indent);
159 void print_device_tree_short(device_t dev, int indent);
160 void print_device_tree(device_t dev, int indent);
161 static void print_driver_short(driver_t *driver, int indent);
162 static void print_driver(driver_t *driver, int indent);
163 static void print_driver_list(driver_list_t drivers, int indent);
164 static void print_devclass_short(devclass_t dc, int indent);
165 static void print_devclass(devclass_t dc, int indent);
166 void print_devclass_list_short(void);
167 void print_devclass_list(void);
168 
169 #else
170 /* Make the compiler ignore the function calls */
171 #define PDEBUG(a)			/* nop */
172 #define DEVICENAME(d)			/* nop */
173 #define DRIVERNAME(d)			/* nop */
174 #define DEVCLANAME(d)			/* nop */
175 
176 #define print_device_short(d,i)		/* nop */
177 #define print_device(d,i)		/* nop */
178 #define print_device_tree_short(d,i)	/* nop */
179 #define print_device_tree(d,i)		/* nop */
180 #define print_driver_short(d,i)		/* nop */
181 #define print_driver(d,i)		/* nop */
182 #define print_driver_list(d,i)		/* nop */
183 #define print_devclass_short(d,i)	/* nop */
184 #define print_devclass(d,i)		/* nop */
185 #define print_devclass_list_short()	/* nop */
186 #define print_devclass_list()		/* nop */
187 #endif
188 
189 /*
190  * dev sysctl tree
191  */
192 
193 enum {
194 	DEVCLASS_SYSCTL_PARENT,
195 };
196 
197 static int
198 devclass_sysctl_handler(SYSCTL_HANDLER_ARGS)
199 {
200 	devclass_t dc = (devclass_t)arg1;
201 	const char *value;
202 
203 	switch (arg2) {
204 	case DEVCLASS_SYSCTL_PARENT:
205 		value = dc->parent ? dc->parent->name : "";
206 		break;
207 	default:
208 		return (EINVAL);
209 	}
210 	return (SYSCTL_OUT(req, value, strlen(value)));
211 }
212 
213 static void
214 devclass_sysctl_init(devclass_t dc)
215 {
216 
217 	if (dc->sysctl_tree != NULL)
218 		return;
219 	sysctl_ctx_init(&dc->sysctl_ctx);
220 	dc->sysctl_tree = SYSCTL_ADD_NODE(&dc->sysctl_ctx,
221 	    SYSCTL_STATIC_CHILDREN(_dev), OID_AUTO, dc->name,
222 	    CTLFLAG_RD, 0, "");
223 	SYSCTL_ADD_PROC(&dc->sysctl_ctx, SYSCTL_CHILDREN(dc->sysctl_tree),
224 	    OID_AUTO, "%parent", CTLFLAG_RD,
225 	    dc, DEVCLASS_SYSCTL_PARENT, devclass_sysctl_handler, "A",
226 	    "parent class");
227 }
228 
229 enum {
230 	DEVICE_SYSCTL_DESC,
231 	DEVICE_SYSCTL_DRIVER,
232 	DEVICE_SYSCTL_LOCATION,
233 	DEVICE_SYSCTL_PNPINFO,
234 	DEVICE_SYSCTL_PARENT,
235 };
236 
237 static int
238 device_sysctl_handler(SYSCTL_HANDLER_ARGS)
239 {
240 	device_t dev = (device_t)arg1;
241 	const char *value;
242 	char *buf;
243 	int error;
244 
245 	buf = NULL;
246 	switch (arg2) {
247 	case DEVICE_SYSCTL_DESC:
248 		value = dev->desc ? dev->desc : "";
249 		break;
250 	case DEVICE_SYSCTL_DRIVER:
251 		value = dev->driver ? dev->driver->name : "";
252 		break;
253 	case DEVICE_SYSCTL_LOCATION:
254 		value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
255 		bus_child_location_str(dev, buf, 1024);
256 		break;
257 	case DEVICE_SYSCTL_PNPINFO:
258 		value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
259 		bus_child_pnpinfo_str(dev, buf, 1024);
260 		break;
261 	case DEVICE_SYSCTL_PARENT:
262 		value = dev->parent ? dev->parent->nameunit : "";
263 		break;
264 	default:
265 		return (EINVAL);
266 	}
267 	error = SYSCTL_OUT(req, value, strlen(value));
268 	if (buf != NULL)
269 		free(buf, M_BUS);
270 	return (error);
271 }
272 
273 static void
274 device_sysctl_init(device_t dev)
275 {
276 	devclass_t dc = dev->devclass;
277 
278 	if (dev->sysctl_tree != NULL)
279 		return;
280 	devclass_sysctl_init(dc);
281 	sysctl_ctx_init(&dev->sysctl_ctx);
282 	dev->sysctl_tree = SYSCTL_ADD_NODE(&dev->sysctl_ctx,
283 	    SYSCTL_CHILDREN(dc->sysctl_tree), OID_AUTO,
284 	    dev->nameunit + strlen(dc->name),
285 	    CTLFLAG_RD, 0, "");
286 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
287 	    OID_AUTO, "%desc", CTLFLAG_RD,
288 	    dev, DEVICE_SYSCTL_DESC, device_sysctl_handler, "A",
289 	    "device description");
290 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
291 	    OID_AUTO, "%driver", CTLFLAG_RD,
292 	    dev, DEVICE_SYSCTL_DRIVER, device_sysctl_handler, "A",
293 	    "device driver name");
294 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
295 	    OID_AUTO, "%location", CTLFLAG_RD,
296 	    dev, DEVICE_SYSCTL_LOCATION, device_sysctl_handler, "A",
297 	    "device location relative to parent");
298 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
299 	    OID_AUTO, "%pnpinfo", CTLFLAG_RD,
300 	    dev, DEVICE_SYSCTL_PNPINFO, device_sysctl_handler, "A",
301 	    "device identification");
302 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
303 	    OID_AUTO, "%parent", CTLFLAG_RD,
304 	    dev, DEVICE_SYSCTL_PARENT, device_sysctl_handler, "A",
305 	    "parent device");
306 }
307 
308 static void
309 device_sysctl_fini(device_t dev)
310 {
311 	if (dev->sysctl_tree == NULL)
312 		return;
313 	sysctl_ctx_free(&dev->sysctl_ctx);
314 	dev->sysctl_tree = NULL;
315 }
316 
317 /*
318  * /dev/devctl implementation
319  */
320 
321 /*
322  * This design allows only one reader for /dev/devctl.  This is not desirable
323  * in the long run, but will get a lot of hair out of this implementation.
324  * Maybe we should make this device a clonable device.
325  *
326  * Also note: we specifically do not attach a device to the device_t tree
327  * to avoid potential chicken and egg problems.  One could argue that all
328  * of this belongs to the root node.  One could also further argue that the
329  * sysctl interface that we have not might more properly be an ioctl
330  * interface, but at this stage of the game, I'm not inclined to rock that
331  * boat.
332  *
333  * I'm also not sure that the SIGIO support is done correctly or not, as
334  * I copied it from a driver that had SIGIO support that likely hasn't been
335  * tested since 3.4 or 2.2.8!
336  */
337 
338 static int sysctl_devctl_disable(SYSCTL_HANDLER_ARGS);
339 static int devctl_disable = 0;
340 TUNABLE_INT("hw.bus.devctl_disable", &devctl_disable);
341 SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_disable, CTLTYPE_INT | CTLFLAG_RW, 0, 0,
342     sysctl_devctl_disable, "I", "devctl disable");
343 
344 static d_open_t		devopen;
345 static d_close_t	devclose;
346 static d_read_t		devread;
347 static d_ioctl_t	devioctl;
348 static d_poll_t		devpoll;
349 
350 static struct cdevsw dev_cdevsw = {
351 	.d_version =	D_VERSION,
352 	.d_flags =	D_NEEDGIANT,
353 	.d_open =	devopen,
354 	.d_close =	devclose,
355 	.d_read =	devread,
356 	.d_ioctl =	devioctl,
357 	.d_poll =	devpoll,
358 	.d_name =	"devctl",
359 };
360 
361 struct dev_event_info
362 {
363 	char *dei_data;
364 	TAILQ_ENTRY(dev_event_info) dei_link;
365 };
366 
367 TAILQ_HEAD(devq, dev_event_info);
368 
369 static struct dev_softc
370 {
371 	int	inuse;
372 	int	nonblock;
373 	struct mtx mtx;
374 	struct cv cv;
375 	struct selinfo sel;
376 	struct devq devq;
377 	struct proc *async_proc;
378 } devsoftc;
379 
380 static struct cdev *devctl_dev;
381 
382 static void
383 devinit(void)
384 {
385 	devctl_dev = make_dev(&dev_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
386 	    "devctl");
387 	mtx_init(&devsoftc.mtx, "dev mtx", "devd", MTX_DEF);
388 	cv_init(&devsoftc.cv, "dev cv");
389 	TAILQ_INIT(&devsoftc.devq);
390 }
391 
392 static int
393 devopen(struct cdev *dev, int oflags, int devtype, d_thread_t *td)
394 {
395 	if (devsoftc.inuse)
396 		return (EBUSY);
397 	/* move to init */
398 	devsoftc.inuse = 1;
399 	devsoftc.nonblock = 0;
400 	devsoftc.async_proc = NULL;
401 	return (0);
402 }
403 
404 static int
405 devclose(struct cdev *dev, int fflag, int devtype, d_thread_t *td)
406 {
407 	devsoftc.inuse = 0;
408 	mtx_lock(&devsoftc.mtx);
409 	cv_broadcast(&devsoftc.cv);
410 	mtx_unlock(&devsoftc.mtx);
411 
412 	return (0);
413 }
414 
415 /*
416  * The read channel for this device is used to report changes to
417  * userland in realtime.  We are required to free the data as well as
418  * the n1 object because we allocate them separately.  Also note that
419  * we return one record at a time.  If you try to read this device a
420  * character at a time, you will loose the rest of the data.  Listening
421  * programs are expected to cope.
422  */
423 static int
424 devread(struct cdev *dev, struct uio *uio, int ioflag)
425 {
426 	struct dev_event_info *n1;
427 	int rv;
428 
429 	mtx_lock(&devsoftc.mtx);
430 	while (TAILQ_EMPTY(&devsoftc.devq)) {
431 		if (devsoftc.nonblock) {
432 			mtx_unlock(&devsoftc.mtx);
433 			return (EAGAIN);
434 		}
435 		rv = cv_wait_sig(&devsoftc.cv, &devsoftc.mtx);
436 		if (rv) {
437 			/*
438 			 * Need to translate ERESTART to EINTR here? -- jake
439 			 */
440 			mtx_unlock(&devsoftc.mtx);
441 			return (rv);
442 		}
443 	}
444 	n1 = TAILQ_FIRST(&devsoftc.devq);
445 	TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
446 	mtx_unlock(&devsoftc.mtx);
447 	rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
448 	free(n1->dei_data, M_BUS);
449 	free(n1, M_BUS);
450 	return (rv);
451 }
452 
453 static	int
454 devioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, d_thread_t *td)
455 {
456 	switch (cmd) {
457 
458 	case FIONBIO:
459 		if (*(int*)data)
460 			devsoftc.nonblock = 1;
461 		else
462 			devsoftc.nonblock = 0;
463 		return (0);
464 	case FIOASYNC:
465 		if (*(int*)data)
466 			devsoftc.async_proc = td->td_proc;
467 		else
468 			devsoftc.async_proc = NULL;
469 		return (0);
470 
471 		/* (un)Support for other fcntl() calls. */
472 	case FIOCLEX:
473 	case FIONCLEX:
474 	case FIONREAD:
475 	case FIOSETOWN:
476 	case FIOGETOWN:
477 	default:
478 		break;
479 	}
480 	return (ENOTTY);
481 }
482 
483 static	int
484 devpoll(struct cdev *dev, int events, d_thread_t *td)
485 {
486 	int	revents = 0;
487 
488 	mtx_lock(&devsoftc.mtx);
489 	if (events & (POLLIN | POLLRDNORM)) {
490 		if (!TAILQ_EMPTY(&devsoftc.devq))
491 			revents = events & (POLLIN | POLLRDNORM);
492 		else
493 			selrecord(td, &devsoftc.sel);
494 	}
495 	mtx_unlock(&devsoftc.mtx);
496 
497 	return (revents);
498 }
499 
500 /**
501  * @brief Queue data to be read from the devctl device
502  *
503  * Generic interface to queue data to the devctl device.  It is
504  * assumed that @p data is properly formatted.  It is further assumed
505  * that @p data is allocated using the M_BUS malloc type.
506  */
507 void
508 devctl_queue_data(char *data)
509 {
510 	struct dev_event_info *n1 = NULL;
511 	struct proc *p;
512 
513 	n1 = malloc(sizeof(*n1), M_BUS, M_NOWAIT);
514 	if (n1 == NULL)
515 		return;
516 	n1->dei_data = data;
517 	mtx_lock(&devsoftc.mtx);
518 	TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
519 	cv_broadcast(&devsoftc.cv);
520 	mtx_unlock(&devsoftc.mtx);
521 	selwakeup(&devsoftc.sel);
522 	p = devsoftc.async_proc;
523 	if (p != NULL) {
524 		PROC_LOCK(p);
525 		psignal(p, SIGIO);
526 		PROC_UNLOCK(p);
527 	}
528 }
529 
530 /**
531  * @brief Send a 'notification' to userland, using standard ways
532  */
533 void
534 devctl_notify(const char *system, const char *subsystem, const char *type,
535     const char *data)
536 {
537 	int len = 0;
538 	char *msg;
539 
540 	if (system == NULL)
541 		return;		/* BOGUS!  Must specify system. */
542 	if (subsystem == NULL)
543 		return;		/* BOGUS!  Must specify subsystem. */
544 	if (type == NULL)
545 		return;		/* BOGUS!  Must specify type. */
546 	len += strlen(" system=") + strlen(system);
547 	len += strlen(" subsystem=") + strlen(subsystem);
548 	len += strlen(" type=") + strlen(type);
549 	/* add in the data message plus newline. */
550 	if (data != NULL)
551 		len += strlen(data);
552 	len += 3;	/* '!', '\n', and NUL */
553 	msg = malloc(len, M_BUS, M_NOWAIT);
554 	if (msg == NULL)
555 		return;		/* Drop it on the floor */
556 	snprintf(msg, len, "!system=%s subsystem=%s type=%s %s\n", system,
557 	    subsystem, type, data);
558 	devctl_queue_data(msg);
559 }
560 
561 /*
562  * Common routine that tries to make sending messages as easy as possible.
563  * We allocate memory for the data, copy strings into that, but do not
564  * free it unless there's an error.  The dequeue part of the driver should
565  * free the data.  We don't send data when the device is disabled.  We do
566  * send data, even when we have no listeners, because we wish to avoid
567  * races relating to startup and restart of listening applications.
568  *
569  * devaddq is designed to string together the type of event, with the
570  * object of that event, plus the plug and play info and location info
571  * for that event.  This is likely most useful for devices, but less
572  * useful for other consumers of this interface.  Those should use
573  * the devctl_queue_data() interface instead.
574  */
575 static void
576 devaddq(const char *type, const char *what, device_t dev)
577 {
578 	char *data = NULL;
579 	char *loc = NULL;
580 	char *pnp = NULL;
581 	const char *parstr;
582 
583 	if (devctl_disable)
584 		return;
585 	data = malloc(1024, M_BUS, M_NOWAIT);
586 	if (data == NULL)
587 		goto bad;
588 
589 	/* get the bus specific location of this device */
590 	loc = malloc(1024, M_BUS, M_NOWAIT);
591 	if (loc == NULL)
592 		goto bad;
593 	*loc = '\0';
594 	bus_child_location_str(dev, loc, 1024);
595 
596 	/* Get the bus specific pnp info of this device */
597 	pnp = malloc(1024, M_BUS, M_NOWAIT);
598 	if (pnp == NULL)
599 		goto bad;
600 	*pnp = '\0';
601 	bus_child_pnpinfo_str(dev, pnp, 1024);
602 
603 	/* Get the parent of this device, or / if high enough in the tree. */
604 	if (device_get_parent(dev) == NULL)
605 		parstr = ".";	/* Or '/' ? */
606 	else
607 		parstr = device_get_nameunit(device_get_parent(dev));
608 	/* String it all together. */
609 	snprintf(data, 1024, "%s%s at %s %s on %s\n", type, what, loc, pnp,
610 	  parstr);
611 	free(loc, M_BUS);
612 	free(pnp, M_BUS);
613 	devctl_queue_data(data);
614 	return;
615 bad:
616 	free(pnp, M_BUS);
617 	free(loc, M_BUS);
618 	free(data, M_BUS);
619 	return;
620 }
621 
622 /*
623  * A device was added to the tree.  We are called just after it successfully
624  * attaches (that is, probe and attach success for this device).  No call
625  * is made if a device is merely parented into the tree.  See devnomatch
626  * if probe fails.  If attach fails, no notification is sent (but maybe
627  * we should have a different message for this).
628  */
629 static void
630 devadded(device_t dev)
631 {
632 	char *pnp = NULL;
633 	char *tmp = NULL;
634 
635 	pnp = malloc(1024, M_BUS, M_NOWAIT);
636 	if (pnp == NULL)
637 		goto fail;
638 	tmp = malloc(1024, M_BUS, M_NOWAIT);
639 	if (tmp == NULL)
640 		goto fail;
641 	*pnp = '\0';
642 	bus_child_pnpinfo_str(dev, pnp, 1024);
643 	snprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
644 	devaddq("+", tmp, dev);
645 fail:
646 	if (pnp != NULL)
647 		free(pnp, M_BUS);
648 	if (tmp != NULL)
649 		free(tmp, M_BUS);
650 	return;
651 }
652 
653 /*
654  * A device was removed from the tree.  We are called just before this
655  * happens.
656  */
657 static void
658 devremoved(device_t dev)
659 {
660 	char *pnp = NULL;
661 	char *tmp = NULL;
662 
663 	pnp = malloc(1024, M_BUS, M_NOWAIT);
664 	if (pnp == NULL)
665 		goto fail;
666 	tmp = malloc(1024, M_BUS, M_NOWAIT);
667 	if (tmp == NULL)
668 		goto fail;
669 	*pnp = '\0';
670 	bus_child_pnpinfo_str(dev, pnp, 1024);
671 	snprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
672 	devaddq("-", tmp, dev);
673 fail:
674 	if (pnp != NULL)
675 		free(pnp, M_BUS);
676 	if (tmp != NULL)
677 		free(tmp, M_BUS);
678 	return;
679 }
680 
681 /*
682  * Called when there's no match for this device.  This is only called
683  * the first time that no match happens, so we don't keep getitng this
684  * message.  Should that prove to be undesirable, we can change it.
685  * This is called when all drivers that can attach to a given bus
686  * decline to accept this device.  Other errrors may not be detected.
687  */
688 static void
689 devnomatch(device_t dev)
690 {
691 	devaddq("?", "", dev);
692 }
693 
694 static int
695 sysctl_devctl_disable(SYSCTL_HANDLER_ARGS)
696 {
697 	struct dev_event_info *n1;
698 	int dis, error;
699 
700 	dis = devctl_disable;
701 	error = sysctl_handle_int(oidp, &dis, 0, req);
702 	if (error || !req->newptr)
703 		return (error);
704 	mtx_lock(&devsoftc.mtx);
705 	devctl_disable = dis;
706 	if (dis) {
707 		while (!TAILQ_EMPTY(&devsoftc.devq)) {
708 			n1 = TAILQ_FIRST(&devsoftc.devq);
709 			TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
710 			free(n1->dei_data, M_BUS);
711 			free(n1, M_BUS);
712 		}
713 	}
714 	mtx_unlock(&devsoftc.mtx);
715 	return (0);
716 }
717 
718 /* End of /dev/devctl code */
719 
720 TAILQ_HEAD(,device)	bus_data_devices;
721 static int bus_data_generation = 1;
722 
723 kobj_method_t null_methods[] = {
724 	{ 0, 0 }
725 };
726 
727 DEFINE_CLASS(null, null_methods, 0);
728 
729 /*
730  * Devclass implementation
731  */
732 
733 static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
734 
735 
736 /**
737  * @internal
738  * @brief Find or create a device class
739  *
740  * If a device class with the name @p classname exists, return it,
741  * otherwise if @p create is non-zero create and return a new device
742  * class.
743  *
744  * If @p parentname is non-NULL, the parent of the devclass is set to
745  * the devclass of that name.
746  *
747  * @param classname	the devclass name to find or create
748  * @param parentname	the parent devclass name or @c NULL
749  * @param create	non-zero to create a devclass
750  */
751 static devclass_t
752 devclass_find_internal(const char *classname, const char *parentname,
753 		       int create)
754 {
755 	devclass_t dc;
756 
757 	PDEBUG(("looking for %s", classname));
758 	if (!classname)
759 		return (NULL);
760 
761 	TAILQ_FOREACH(dc, &devclasses, link) {
762 		if (!strcmp(dc->name, classname))
763 			break;
764 	}
765 
766 	if (create && !dc) {
767 		PDEBUG(("creating %s", classname));
768 		dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
769 		    M_BUS, M_NOWAIT|M_ZERO);
770 		if (!dc)
771 			return (NULL);
772 		dc->parent = NULL;
773 		dc->name = (char*) (dc + 1);
774 		strcpy(dc->name, classname);
775 		TAILQ_INIT(&dc->drivers);
776 		TAILQ_INSERT_TAIL(&devclasses, dc, link);
777 
778 		bus_data_generation_update();
779 	}
780 	if (parentname && dc && !dc->parent) {
781 		dc->parent = devclass_find_internal(parentname, 0, FALSE);
782 	}
783 
784 	return (dc);
785 }
786 
787 /**
788  * @brief Create a device class
789  *
790  * If a device class with the name @p classname exists, return it,
791  * otherwise create and return a new device class.
792  *
793  * @param classname	the devclass name to find or create
794  */
795 devclass_t
796 devclass_create(const char *classname)
797 {
798 	return (devclass_find_internal(classname, 0, TRUE));
799 }
800 
801 /**
802  * @brief Find a device class
803  *
804  * If a device class with the name @p classname exists, return it,
805  * otherwise return @c NULL.
806  *
807  * @param classname	the devclass name to find
808  */
809 devclass_t
810 devclass_find(const char *classname)
811 {
812 	return (devclass_find_internal(classname, 0, FALSE));
813 }
814 
815 /**
816  * @brief Add a device driver to a device class
817  *
818  * Add a device driver to a devclass. This is normally called
819  * automatically by DRIVER_MODULE(). The BUS_DRIVER_ADDED() method of
820  * all devices in the devclass will be called to allow them to attempt
821  * to re-probe any unmatched children.
822  *
823  * @param dc		the devclass to edit
824  * @param driver	the driver to register
825  */
826 int
827 devclass_add_driver(devclass_t dc, driver_t *driver)
828 {
829 	driverlink_t dl;
830 	int i;
831 
832 	PDEBUG(("%s", DRIVERNAME(driver)));
833 
834 	dl = malloc(sizeof *dl, M_BUS, M_NOWAIT|M_ZERO);
835 	if (!dl)
836 		return (ENOMEM);
837 
838 	/*
839 	 * Compile the driver's methods. Also increase the reference count
840 	 * so that the class doesn't get freed when the last instance
841 	 * goes. This means we can safely use static methods and avoids a
842 	 * double-free in devclass_delete_driver.
843 	 */
844 	kobj_class_compile((kobj_class_t) driver);
845 
846 	/*
847 	 * Make sure the devclass which the driver is implementing exists.
848 	 */
849 	devclass_find_internal(driver->name, 0, TRUE);
850 
851 	dl->driver = driver;
852 	TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
853 	driver->refs++;		/* XXX: kobj_mtx */
854 
855 	/*
856 	 * Call BUS_DRIVER_ADDED for any existing busses in this class.
857 	 */
858 	for (i = 0; i < dc->maxunit; i++)
859 		if (dc->devices[i])
860 			BUS_DRIVER_ADDED(dc->devices[i], driver);
861 
862 	bus_data_generation_update();
863 	return (0);
864 }
865 
866 /**
867  * @brief Delete a device driver from a device class
868  *
869  * Delete a device driver from a devclass. This is normally called
870  * automatically by DRIVER_MODULE().
871  *
872  * If the driver is currently attached to any devices,
873  * devclass_delete_driver() will first attempt to detach from each
874  * device. If one of the detach calls fails, the driver will not be
875  * deleted.
876  *
877  * @param dc		the devclass to edit
878  * @param driver	the driver to unregister
879  */
880 int
881 devclass_delete_driver(devclass_t busclass, driver_t *driver)
882 {
883 	devclass_t dc = devclass_find(driver->name);
884 	driverlink_t dl;
885 	device_t dev;
886 	int i;
887 	int error;
888 
889 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
890 
891 	if (!dc)
892 		return (0);
893 
894 	/*
895 	 * Find the link structure in the bus' list of drivers.
896 	 */
897 	TAILQ_FOREACH(dl, &busclass->drivers, link) {
898 		if (dl->driver == driver)
899 			break;
900 	}
901 
902 	if (!dl) {
903 		PDEBUG(("%s not found in %s list", driver->name,
904 		    busclass->name));
905 		return (ENOENT);
906 	}
907 
908 	/*
909 	 * Disassociate from any devices.  We iterate through all the
910 	 * devices in the devclass of the driver and detach any which are
911 	 * using the driver and which have a parent in the devclass which
912 	 * we are deleting from.
913 	 *
914 	 * Note that since a driver can be in multiple devclasses, we
915 	 * should not detach devices which are not children of devices in
916 	 * the affected devclass.
917 	 */
918 	for (i = 0; i < dc->maxunit; i++) {
919 		if (dc->devices[i]) {
920 			dev = dc->devices[i];
921 			if (dev->driver == driver && dev->parent &&
922 			    dev->parent->devclass == busclass) {
923 				if ((error = device_detach(dev)) != 0)
924 					return (error);
925 				device_set_driver(dev, NULL);
926 			}
927 		}
928 	}
929 
930 	TAILQ_REMOVE(&busclass->drivers, dl, link);
931 	free(dl, M_BUS);
932 
933 	/* XXX: kobj_mtx */
934 	driver->refs--;
935 	if (driver->refs == 0)
936 		kobj_class_free((kobj_class_t) driver);
937 
938 	bus_data_generation_update();
939 	return (0);
940 }
941 
942 /**
943  * @brief Quiesces a set of device drivers from a device class
944  *
945  * Quiesce a device driver from a devclass. This is normally called
946  * automatically by DRIVER_MODULE().
947  *
948  * If the driver is currently attached to any devices,
949  * devclass_quiesece_driver() will first attempt to quiesce each
950  * device.
951  *
952  * @param dc		the devclass to edit
953  * @param driver	the driver to unregister
954  */
955 int
956 devclass_quiesce_driver(devclass_t busclass, driver_t *driver)
957 {
958 	devclass_t dc = devclass_find(driver->name);
959 	driverlink_t dl;
960 	device_t dev;
961 	int i;
962 	int error;
963 
964 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
965 
966 	if (!dc)
967 		return (0);
968 
969 	/*
970 	 * Find the link structure in the bus' list of drivers.
971 	 */
972 	TAILQ_FOREACH(dl, &busclass->drivers, link) {
973 		if (dl->driver == driver)
974 			break;
975 	}
976 
977 	if (!dl) {
978 		PDEBUG(("%s not found in %s list", driver->name,
979 		    busclass->name));
980 		return (ENOENT);
981 	}
982 
983 	/*
984 	 * Quiesce all devices.  We iterate through all the devices in
985 	 * the devclass of the driver and quiesce any which are using
986 	 * the driver and which have a parent in the devclass which we
987 	 * are quiescing.
988 	 *
989 	 * Note that since a driver can be in multiple devclasses, we
990 	 * should not quiesce devices which are not children of
991 	 * devices in the affected devclass.
992 	 */
993 	for (i = 0; i < dc->maxunit; i++) {
994 		if (dc->devices[i]) {
995 			dev = dc->devices[i];
996 			if (dev->driver == driver && dev->parent &&
997 			    dev->parent->devclass == busclass) {
998 				if ((error = device_quiesce(dev)) != 0)
999 					return (error);
1000 			}
1001 		}
1002 	}
1003 
1004 	return (0);
1005 }
1006 
1007 /**
1008  * @internal
1009  */
1010 static driverlink_t
1011 devclass_find_driver_internal(devclass_t dc, const char *classname)
1012 {
1013 	driverlink_t dl;
1014 
1015 	PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
1016 
1017 	TAILQ_FOREACH(dl, &dc->drivers, link) {
1018 		if (!strcmp(dl->driver->name, classname))
1019 			return (dl);
1020 	}
1021 
1022 	PDEBUG(("not found"));
1023 	return (NULL);
1024 }
1025 
1026 /**
1027  * @brief Search a devclass for a driver
1028  *
1029  * This function searches the devclass's list of drivers and returns
1030  * the first driver whose name is @p classname or @c NULL if there is
1031  * no driver of that name.
1032  *
1033  * @param dc		the devclass to search
1034  * @param classname	the driver name to search for
1035  */
1036 kobj_class_t
1037 devclass_find_driver(devclass_t dc, const char *classname)
1038 {
1039 	driverlink_t dl;
1040 
1041 	dl = devclass_find_driver_internal(dc, classname);
1042 	if (dl)
1043 		return (dl->driver);
1044 	return (NULL);
1045 }
1046 
1047 /**
1048  * @brief Return the name of the devclass
1049  */
1050 const char *
1051 devclass_get_name(devclass_t dc)
1052 {
1053 	return (dc->name);
1054 }
1055 
1056 /**
1057  * @brief Find a device given a unit number
1058  *
1059  * @param dc		the devclass to search
1060  * @param unit		the unit number to search for
1061  *
1062  * @returns		the device with the given unit number or @c
1063  *			NULL if there is no such device
1064  */
1065 device_t
1066 devclass_get_device(devclass_t dc, int unit)
1067 {
1068 	if (dc == NULL || unit < 0 || unit >= dc->maxunit)
1069 		return (NULL);
1070 	return (dc->devices[unit]);
1071 }
1072 
1073 /**
1074  * @brief Find the softc field of a device given a unit number
1075  *
1076  * @param dc		the devclass to search
1077  * @param unit		the unit number to search for
1078  *
1079  * @returns		the softc field of the device with the given
1080  *			unit number or @c NULL if there is no such
1081  *			device
1082  */
1083 void *
1084 devclass_get_softc(devclass_t dc, int unit)
1085 {
1086 	device_t dev;
1087 
1088 	dev = devclass_get_device(dc, unit);
1089 	if (!dev)
1090 		return (NULL);
1091 
1092 	return (device_get_softc(dev));
1093 }
1094 
1095 /**
1096  * @brief Get a list of devices in the devclass
1097  *
1098  * An array containing a list of all the devices in the given devclass
1099  * is allocated and returned in @p *devlistp. The number of devices
1100  * in the array is returned in @p *devcountp. The caller should free
1101  * the array using @c free(p, M_TEMP), even if @p *devcountp is 0.
1102  *
1103  * @param dc		the devclass to examine
1104  * @param devlistp	points at location for array pointer return
1105  *			value
1106  * @param devcountp	points at location for array size return value
1107  *
1108  * @retval 0		success
1109  * @retval ENOMEM	the array allocation failed
1110  */
1111 int
1112 devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
1113 {
1114 	int count, i;
1115 	device_t *list;
1116 
1117 	count = devclass_get_count(dc);
1118 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1119 	if (!list)
1120 		return (ENOMEM);
1121 
1122 	count = 0;
1123 	for (i = 0; i < dc->maxunit; i++) {
1124 		if (dc->devices[i]) {
1125 			list[count] = dc->devices[i];
1126 			count++;
1127 		}
1128 	}
1129 
1130 	*devlistp = list;
1131 	*devcountp = count;
1132 
1133 	return (0);
1134 }
1135 
1136 /**
1137  * @brief Get a list of drivers in the devclass
1138  *
1139  * An array containing a list of pointers to all the drivers in the
1140  * given devclass is allocated and returned in @p *listp.  The number
1141  * of drivers in the array is returned in @p *countp. The caller should
1142  * free the array using @c free(p, M_TEMP).
1143  *
1144  * @param dc		the devclass to examine
1145  * @param listp		gives location for array pointer return value
1146  * @param countp	gives location for number of array elements
1147  *			return value
1148  *
1149  * @retval 0		success
1150  * @retval ENOMEM	the array allocation failed
1151  */
1152 int
1153 devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
1154 {
1155 	driverlink_t dl;
1156 	driver_t **list;
1157 	int count;
1158 
1159 	count = 0;
1160 	TAILQ_FOREACH(dl, &dc->drivers, link)
1161 		count++;
1162 	list = malloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
1163 	if (list == NULL)
1164 		return (ENOMEM);
1165 
1166 	count = 0;
1167 	TAILQ_FOREACH(dl, &dc->drivers, link) {
1168 		list[count] = dl->driver;
1169 		count++;
1170 	}
1171 	*listp = list;
1172 	*countp = count;
1173 
1174 	return (0);
1175 }
1176 
1177 /**
1178  * @brief Get the number of devices in a devclass
1179  *
1180  * @param dc		the devclass to examine
1181  */
1182 int
1183 devclass_get_count(devclass_t dc)
1184 {
1185 	int count, i;
1186 
1187 	count = 0;
1188 	for (i = 0; i < dc->maxunit; i++)
1189 		if (dc->devices[i])
1190 			count++;
1191 	return (count);
1192 }
1193 
1194 /**
1195  * @brief Get the maximum unit number used in a devclass
1196  *
1197  * Note that this is one greater than the highest currently-allocated
1198  * unit.
1199  *
1200  * @param dc		the devclass to examine
1201  */
1202 int
1203 devclass_get_maxunit(devclass_t dc)
1204 {
1205 	return (dc->maxunit);
1206 }
1207 
1208 /**
1209  * @brief Find a free unit number in a devclass
1210  *
1211  * This function searches for the first unused unit number greater
1212  * that or equal to @p unit.
1213  *
1214  * @param dc		the devclass to examine
1215  * @param unit		the first unit number to check
1216  */
1217 int
1218 devclass_find_free_unit(devclass_t dc, int unit)
1219 {
1220 	if (dc == NULL)
1221 		return (unit);
1222 	while (unit < dc->maxunit && dc->devices[unit] != NULL)
1223 		unit++;
1224 	return (unit);
1225 }
1226 
1227 /**
1228  * @brief Set the parent of a devclass
1229  *
1230  * The parent class is normally initialised automatically by
1231  * DRIVER_MODULE().
1232  *
1233  * @param dc		the devclass to edit
1234  * @param pdc		the new parent devclass
1235  */
1236 void
1237 devclass_set_parent(devclass_t dc, devclass_t pdc)
1238 {
1239 	dc->parent = pdc;
1240 }
1241 
1242 /**
1243  * @brief Get the parent of a devclass
1244  *
1245  * @param dc		the devclass to examine
1246  */
1247 devclass_t
1248 devclass_get_parent(devclass_t dc)
1249 {
1250 	return (dc->parent);
1251 }
1252 
1253 struct sysctl_ctx_list *
1254 devclass_get_sysctl_ctx(devclass_t dc)
1255 {
1256 	return (&dc->sysctl_ctx);
1257 }
1258 
1259 struct sysctl_oid *
1260 devclass_get_sysctl_tree(devclass_t dc)
1261 {
1262 	return (dc->sysctl_tree);
1263 }
1264 
1265 /**
1266  * @internal
1267  * @brief Allocate a unit number
1268  *
1269  * On entry, @p *unitp is the desired unit number (or @c -1 if any
1270  * will do). The allocated unit number is returned in @p *unitp.
1271 
1272  * @param dc		the devclass to allocate from
1273  * @param unitp		points at the location for the allocated unit
1274  *			number
1275  *
1276  * @retval 0		success
1277  * @retval EEXIST	the requested unit number is already allocated
1278  * @retval ENOMEM	memory allocation failure
1279  */
1280 static int
1281 devclass_alloc_unit(devclass_t dc, int *unitp)
1282 {
1283 	int unit = *unitp;
1284 
1285 	PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
1286 
1287 	/* If we were given a wired unit number, check for existing device */
1288 	/* XXX imp XXX */
1289 	if (unit != -1) {
1290 		if (unit >= 0 && unit < dc->maxunit &&
1291 		    dc->devices[unit] != NULL) {
1292 			if (bootverbose)
1293 				printf("%s: %s%d already exists; skipping it\n",
1294 				    dc->name, dc->name, *unitp);
1295 			return (EEXIST);
1296 		}
1297 	} else {
1298 		/* Unwired device, find the next available slot for it */
1299 		unit = 0;
1300 		while (unit < dc->maxunit && dc->devices[unit] != NULL)
1301 			unit++;
1302 	}
1303 
1304 	/*
1305 	 * We've selected a unit beyond the length of the table, so let's
1306 	 * extend the table to make room for all units up to and including
1307 	 * this one.
1308 	 */
1309 	if (unit >= dc->maxunit) {
1310 		device_t *newlist;
1311 		int newsize;
1312 
1313 		newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
1314 		newlist = malloc(sizeof(device_t) * newsize, M_BUS, M_NOWAIT);
1315 		if (!newlist)
1316 			return (ENOMEM);
1317 		bcopy(dc->devices, newlist, sizeof(device_t) * dc->maxunit);
1318 		bzero(newlist + dc->maxunit,
1319 		    sizeof(device_t) * (newsize - dc->maxunit));
1320 		if (dc->devices)
1321 			free(dc->devices, M_BUS);
1322 		dc->devices = newlist;
1323 		dc->maxunit = newsize;
1324 	}
1325 	PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
1326 
1327 	*unitp = unit;
1328 	return (0);
1329 }
1330 
1331 /**
1332  * @internal
1333  * @brief Add a device to a devclass
1334  *
1335  * A unit number is allocated for the device (using the device's
1336  * preferred unit number if any) and the device is registered in the
1337  * devclass. This allows the device to be looked up by its unit
1338  * number, e.g. by decoding a dev_t minor number.
1339  *
1340  * @param dc		the devclass to add to
1341  * @param dev		the device to add
1342  *
1343  * @retval 0		success
1344  * @retval EEXIST	the requested unit number is already allocated
1345  * @retval ENOMEM	memory allocation failure
1346  */
1347 static int
1348 devclass_add_device(devclass_t dc, device_t dev)
1349 {
1350 	int buflen, error;
1351 
1352 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1353 
1354 	buflen = snprintf(NULL, 0, "%s%d$", dc->name, dev->unit);
1355 	if (buflen < 0)
1356 		return (ENOMEM);
1357 	dev->nameunit = malloc(buflen, M_BUS, M_NOWAIT|M_ZERO);
1358 	if (!dev->nameunit)
1359 		return (ENOMEM);
1360 
1361 	if ((error = devclass_alloc_unit(dc, &dev->unit)) != 0) {
1362 		free(dev->nameunit, M_BUS);
1363 		dev->nameunit = NULL;
1364 		return (error);
1365 	}
1366 	dc->devices[dev->unit] = dev;
1367 	dev->devclass = dc;
1368 	snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
1369 
1370 	return (0);
1371 }
1372 
1373 /**
1374  * @internal
1375  * @brief Delete a device from a devclass
1376  *
1377  * The device is removed from the devclass's device list and its unit
1378  * number is freed.
1379 
1380  * @param dc		the devclass to delete from
1381  * @param dev		the device to delete
1382  *
1383  * @retval 0		success
1384  */
1385 static int
1386 devclass_delete_device(devclass_t dc, device_t dev)
1387 {
1388 	if (!dc || !dev)
1389 		return (0);
1390 
1391 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1392 
1393 	if (dev->devclass != dc || dc->devices[dev->unit] != dev)
1394 		panic("devclass_delete_device: inconsistent device class");
1395 	dc->devices[dev->unit] = NULL;
1396 	if (dev->flags & DF_WILDCARD)
1397 		dev->unit = -1;
1398 	dev->devclass = NULL;
1399 	free(dev->nameunit, M_BUS);
1400 	dev->nameunit = NULL;
1401 
1402 	return (0);
1403 }
1404 
1405 /**
1406  * @internal
1407  * @brief Make a new device and add it as a child of @p parent
1408  *
1409  * @param parent	the parent of the new device
1410  * @param name		the devclass name of the new device or @c NULL
1411  *			to leave the devclass unspecified
1412  * @parem unit		the unit number of the new device of @c -1 to
1413  *			leave the unit number unspecified
1414  *
1415  * @returns the new device
1416  */
1417 static device_t
1418 make_device(device_t parent, const char *name, int unit)
1419 {
1420 	device_t dev;
1421 	devclass_t dc;
1422 
1423 	PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1424 
1425 	if (name) {
1426 		dc = devclass_find_internal(name, 0, TRUE);
1427 		if (!dc) {
1428 			printf("make_device: can't find device class %s\n",
1429 			    name);
1430 			return (NULL);
1431 		}
1432 	} else {
1433 		dc = NULL;
1434 	}
1435 
1436 	dev = malloc(sizeof(struct device), M_BUS, M_NOWAIT|M_ZERO);
1437 	if (!dev)
1438 		return (NULL);
1439 
1440 	dev->parent = parent;
1441 	TAILQ_INIT(&dev->children);
1442 	kobj_init((kobj_t) dev, &null_class);
1443 	dev->driver = NULL;
1444 	dev->devclass = NULL;
1445 	dev->unit = unit;
1446 	dev->nameunit = NULL;
1447 	dev->desc = NULL;
1448 	dev->busy = 0;
1449 	dev->devflags = 0;
1450 	dev->flags = DF_ENABLED;
1451 	dev->order = 0;
1452 	if (unit == -1)
1453 		dev->flags |= DF_WILDCARD;
1454 	if (name) {
1455 		dev->flags |= DF_FIXEDCLASS;
1456 		if (devclass_add_device(dc, dev)) {
1457 			kobj_delete((kobj_t) dev, M_BUS);
1458 			return (NULL);
1459 		}
1460 	}
1461 	dev->ivars = NULL;
1462 	dev->softc = NULL;
1463 
1464 	dev->state = DS_NOTPRESENT;
1465 
1466 	TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1467 	bus_data_generation_update();
1468 
1469 	return (dev);
1470 }
1471 
1472 /**
1473  * @internal
1474  * @brief Print a description of a device.
1475  */
1476 static int
1477 device_print_child(device_t dev, device_t child)
1478 {
1479 	int retval = 0;
1480 
1481 	if (device_is_alive(child))
1482 		retval += BUS_PRINT_CHILD(dev, child);
1483 	else
1484 		retval += device_printf(child, " not found\n");
1485 
1486 	return (retval);
1487 }
1488 
1489 /**
1490  * @brief Create a new device
1491  *
1492  * This creates a new device and adds it as a child of an existing
1493  * parent device. The new device will be added after the last existing
1494  * child with order zero.
1495  *
1496  * @param dev		the device which will be the parent of the
1497  *			new child device
1498  * @param name		devclass name for new device or @c NULL if not
1499  *			specified
1500  * @param unit		unit number for new device or @c -1 if not
1501  *			specified
1502  *
1503  * @returns		the new device
1504  */
1505 device_t
1506 device_add_child(device_t dev, const char *name, int unit)
1507 {
1508 	return (device_add_child_ordered(dev, 0, name, unit));
1509 }
1510 
1511 /**
1512  * @brief Create a new device
1513  *
1514  * This creates a new device and adds it as a child of an existing
1515  * parent device. The new device will be added after the last existing
1516  * child with the same order.
1517  *
1518  * @param dev		the device which will be the parent of the
1519  *			new child device
1520  * @param order		a value which is used to partially sort the
1521  *			children of @p dev - devices created using
1522  *			lower values of @p order appear first in @p
1523  *			dev's list of children
1524  * @param name		devclass name for new device or @c NULL if not
1525  *			specified
1526  * @param unit		unit number for new device or @c -1 if not
1527  *			specified
1528  *
1529  * @returns		the new device
1530  */
1531 device_t
1532 device_add_child_ordered(device_t dev, int order, const char *name, int unit)
1533 {
1534 	device_t child;
1535 	device_t place;
1536 
1537 	PDEBUG(("%s at %s with order %d as unit %d",
1538 	    name, DEVICENAME(dev), order, unit));
1539 
1540 	child = make_device(dev, name, unit);
1541 	if (child == NULL)
1542 		return (child);
1543 	child->order = order;
1544 
1545 	TAILQ_FOREACH(place, &dev->children, link) {
1546 		if (place->order > order)
1547 			break;
1548 	}
1549 
1550 	if (place) {
1551 		/*
1552 		 * The device 'place' is the first device whose order is
1553 		 * greater than the new child.
1554 		 */
1555 		TAILQ_INSERT_BEFORE(place, child, link);
1556 	} else {
1557 		/*
1558 		 * The new child's order is greater or equal to the order of
1559 		 * any existing device. Add the child to the tail of the list.
1560 		 */
1561 		TAILQ_INSERT_TAIL(&dev->children, child, link);
1562 	}
1563 
1564 	bus_data_generation_update();
1565 	return (child);
1566 }
1567 
1568 /**
1569  * @brief Delete a device
1570  *
1571  * This function deletes a device along with all of its children. If
1572  * the device currently has a driver attached to it, the device is
1573  * detached first using device_detach().
1574  *
1575  * @param dev		the parent device
1576  * @param child		the device to delete
1577  *
1578  * @retval 0		success
1579  * @retval non-zero	a unit error code describing the error
1580  */
1581 int
1582 device_delete_child(device_t dev, device_t child)
1583 {
1584 	int error;
1585 	device_t grandchild;
1586 
1587 	PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1588 
1589 	/* remove children first */
1590 	while ( (grandchild = TAILQ_FIRST(&child->children)) ) {
1591 		error = device_delete_child(child, grandchild);
1592 		if (error)
1593 			return (error);
1594 	}
1595 
1596 	if ((error = device_detach(child)) != 0)
1597 		return (error);
1598 	if (child->devclass)
1599 		devclass_delete_device(child->devclass, child);
1600 	TAILQ_REMOVE(&dev->children, child, link);
1601 	TAILQ_REMOVE(&bus_data_devices, child, devlink);
1602 	kobj_delete((kobj_t) child, M_BUS);
1603 
1604 	bus_data_generation_update();
1605 	return (0);
1606 }
1607 
1608 /**
1609  * @brief Find a device given a unit number
1610  *
1611  * This is similar to devclass_get_devices() but only searches for
1612  * devices which have @p dev as a parent.
1613  *
1614  * @param dev		the parent device to search
1615  * @param unit		the unit number to search for.  If the unit is -1,
1616  *			return the first child of @p dev which has name
1617  *			@p classname (that is, the one with the lowest unit.)
1618  *
1619  * @returns		the device with the given unit number or @c
1620  *			NULL if there is no such device
1621  */
1622 device_t
1623 device_find_child(device_t dev, const char *classname, int unit)
1624 {
1625 	devclass_t dc;
1626 	device_t child;
1627 
1628 	dc = devclass_find(classname);
1629 	if (!dc)
1630 		return (NULL);
1631 
1632 	if (unit != -1) {
1633 		child = devclass_get_device(dc, unit);
1634 		if (child && child->parent == dev)
1635 			return (child);
1636 	} else {
1637 		for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
1638 			child = devclass_get_device(dc, unit);
1639 			if (child && child->parent == dev)
1640 				return (child);
1641 		}
1642 	}
1643 	return (NULL);
1644 }
1645 
1646 /**
1647  * @internal
1648  */
1649 static driverlink_t
1650 first_matching_driver(devclass_t dc, device_t dev)
1651 {
1652 	if (dev->devclass)
1653 		return (devclass_find_driver_internal(dc, dev->devclass->name));
1654 	return (TAILQ_FIRST(&dc->drivers));
1655 }
1656 
1657 /**
1658  * @internal
1659  */
1660 static driverlink_t
1661 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1662 {
1663 	if (dev->devclass) {
1664 		driverlink_t dl;
1665 		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1666 			if (!strcmp(dev->devclass->name, dl->driver->name))
1667 				return (dl);
1668 		return (NULL);
1669 	}
1670 	return (TAILQ_NEXT(last, link));
1671 }
1672 
1673 /**
1674  * @internal
1675  */
1676 int
1677 device_probe_child(device_t dev, device_t child)
1678 {
1679 	devclass_t dc;
1680 	driverlink_t best = 0;
1681 	driverlink_t dl;
1682 	int result, pri = 0;
1683 	int hasclass = (child->devclass != 0);
1684 
1685 	GIANT_REQUIRED;
1686 
1687 	dc = dev->devclass;
1688 	if (!dc)
1689 		panic("device_probe_child: parent device has no devclass");
1690 
1691 	/*
1692 	 * If the state is already probed, then return.  However, don't
1693 	 * return if we can rebid this object.
1694 	 */
1695 	if (child->state == DS_ALIVE && (child->flags & DF_REBID) == 0)
1696 		return (0);
1697 
1698 	for (; dc; dc = dc->parent) {
1699 		for (dl = first_matching_driver(dc, child);
1700 		     dl;
1701 		     dl = next_matching_driver(dc, child, dl)) {
1702 			PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1703 			device_set_driver(child, dl->driver);
1704 			if (!hasclass)
1705 				device_set_devclass(child, dl->driver->name);
1706 
1707 			/* Fetch any flags for the device before probing. */
1708 			resource_int_value(dl->driver->name, child->unit,
1709 			    "flags", &child->devflags);
1710 
1711 			result = DEVICE_PROBE(child);
1712 
1713 			/* Reset flags and devclass before the next probe. */
1714 			child->devflags = 0;
1715 			if (!hasclass)
1716 				device_set_devclass(child, 0);
1717 
1718 			/*
1719 			 * If the driver returns SUCCESS, there can be
1720 			 * no higher match for this device.
1721 			 */
1722 			if (result == 0) {
1723 				best = dl;
1724 				pri = 0;
1725 				break;
1726 			}
1727 
1728 			/*
1729 			 * The driver returned an error so it
1730 			 * certainly doesn't match.
1731 			 */
1732 			if (result > 0) {
1733 				device_set_driver(child, 0);
1734 				continue;
1735 			}
1736 
1737 			/*
1738 			 * A priority lower than SUCCESS, remember the
1739 			 * best matching driver. Initialise the value
1740 			 * of pri for the first match.
1741 			 */
1742 			if (best == 0 || result > pri) {
1743 				best = dl;
1744 				pri = result;
1745 				continue;
1746 			}
1747 		}
1748 		/*
1749 		 * If we have an unambiguous match in this devclass,
1750 		 * don't look in the parent.
1751 		 */
1752 		if (best && pri == 0)
1753 			break;
1754 	}
1755 
1756 	/*
1757 	 * If we found a driver, change state and initialise the devclass.
1758 	 */
1759 	/* XXX What happens if we rebid and got no best? */
1760 	if (best) {
1761 		/*
1762 		 * If this device was atached, and we were asked to
1763 		 * rescan, and it is a different driver, then we have
1764 		 * to detach the old driver and reattach this new one.
1765 		 * Note, we don't have to check for DF_REBID here
1766 		 * because if the state is > DS_ALIVE, we know it must
1767 		 * be.
1768 		 *
1769 		 * This assumes that all DF_REBID drivers can have
1770 		 * their probe routine called at any time and that
1771 		 * they are idempotent as well as completely benign in
1772 		 * normal operations.
1773 		 *
1774 		 * We also have to make sure that the detach
1775 		 * succeeded, otherwise we fail the operation (or
1776 		 * maybe it should just fail silently?  I'm torn).
1777 		 */
1778 		if (child->state > DS_ALIVE && best->driver != child->driver)
1779 			if ((result = device_detach(dev)) != 0)
1780 				return (result);
1781 
1782 		/* Set the winning driver, devclass, and flags. */
1783 		if (!child->devclass)
1784 			device_set_devclass(child, best->driver->name);
1785 		device_set_driver(child, best->driver);
1786 		resource_int_value(best->driver->name, child->unit,
1787 		    "flags", &child->devflags);
1788 
1789 		if (pri < 0) {
1790 			/*
1791 			 * A bit bogus. Call the probe method again to make
1792 			 * sure that we have the right description.
1793 			 */
1794 			DEVICE_PROBE(child);
1795 #if 0
1796 			child->flags |= DF_REBID;
1797 #endif
1798 		} else
1799 			child->flags &= ~DF_REBID;
1800 		child->state = DS_ALIVE;
1801 
1802 		bus_data_generation_update();
1803 		return (0);
1804 	}
1805 
1806 	return (ENXIO);
1807 }
1808 
1809 /**
1810  * @brief Return the parent of a device
1811  */
1812 device_t
1813 device_get_parent(device_t dev)
1814 {
1815 	return (dev->parent);
1816 }
1817 
1818 /**
1819  * @brief Get a list of children of a device
1820  *
1821  * An array containing a list of all the children of the given device
1822  * is allocated and returned in @p *devlistp. The number of devices
1823  * in the array is returned in @p *devcountp. The caller should free
1824  * the array using @c free(p, M_TEMP).
1825  *
1826  * @param dev		the device to examine
1827  * @param devlistp	points at location for array pointer return
1828  *			value
1829  * @param devcountp	points at location for array size return value
1830  *
1831  * @retval 0		success
1832  * @retval ENOMEM	the array allocation failed
1833  */
1834 int
1835 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1836 {
1837 	int count;
1838 	device_t child;
1839 	device_t *list;
1840 
1841 	count = 0;
1842 	TAILQ_FOREACH(child, &dev->children, link) {
1843 		count++;
1844 	}
1845 
1846 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1847 	if (!list)
1848 		return (ENOMEM);
1849 
1850 	count = 0;
1851 	TAILQ_FOREACH(child, &dev->children, link) {
1852 		list[count] = child;
1853 		count++;
1854 	}
1855 
1856 	*devlistp = list;
1857 	*devcountp = count;
1858 
1859 	return (0);
1860 }
1861 
1862 /**
1863  * @brief Return the current driver for the device or @c NULL if there
1864  * is no driver currently attached
1865  */
1866 driver_t *
1867 device_get_driver(device_t dev)
1868 {
1869 	return (dev->driver);
1870 }
1871 
1872 /**
1873  * @brief Return the current devclass for the device or @c NULL if
1874  * there is none.
1875  */
1876 devclass_t
1877 device_get_devclass(device_t dev)
1878 {
1879 	return (dev->devclass);
1880 }
1881 
1882 /**
1883  * @brief Return the name of the device's devclass or @c NULL if there
1884  * is none.
1885  */
1886 const char *
1887 device_get_name(device_t dev)
1888 {
1889 	if (dev != NULL && dev->devclass)
1890 		return (devclass_get_name(dev->devclass));
1891 	return (NULL);
1892 }
1893 
1894 /**
1895  * @brief Return a string containing the device's devclass name
1896  * followed by an ascii representation of the device's unit number
1897  * (e.g. @c "foo2").
1898  */
1899 const char *
1900 device_get_nameunit(device_t dev)
1901 {
1902 	return (dev->nameunit);
1903 }
1904 
1905 /**
1906  * @brief Return the device's unit number.
1907  */
1908 int
1909 device_get_unit(device_t dev)
1910 {
1911 	return (dev->unit);
1912 }
1913 
1914 /**
1915  * @brief Return the device's description string
1916  */
1917 const char *
1918 device_get_desc(device_t dev)
1919 {
1920 	return (dev->desc);
1921 }
1922 
1923 /**
1924  * @brief Return the device's flags
1925  */
1926 u_int32_t
1927 device_get_flags(device_t dev)
1928 {
1929 	return (dev->devflags);
1930 }
1931 
1932 struct sysctl_ctx_list *
1933 device_get_sysctl_ctx(device_t dev)
1934 {
1935 	return (&dev->sysctl_ctx);
1936 }
1937 
1938 struct sysctl_oid *
1939 device_get_sysctl_tree(device_t dev)
1940 {
1941 	return (dev->sysctl_tree);
1942 }
1943 
1944 /**
1945  * @brief Print the name of the device followed by a colon and a space
1946  *
1947  * @returns the number of characters printed
1948  */
1949 int
1950 device_print_prettyname(device_t dev)
1951 {
1952 	const char *name = device_get_name(dev);
1953 
1954 	if (name == 0)
1955 		return (printf("unknown: "));
1956 	return (printf("%s%d: ", name, device_get_unit(dev)));
1957 }
1958 
1959 /**
1960  * @brief Print the name of the device followed by a colon, a space
1961  * and the result of calling vprintf() with the value of @p fmt and
1962  * the following arguments.
1963  *
1964  * @returns the number of characters printed
1965  */
1966 int
1967 device_printf(device_t dev, const char * fmt, ...)
1968 {
1969 	va_list ap;
1970 	int retval;
1971 
1972 	retval = device_print_prettyname(dev);
1973 	va_start(ap, fmt);
1974 	retval += vprintf(fmt, ap);
1975 	va_end(ap);
1976 	return (retval);
1977 }
1978 
1979 /**
1980  * @internal
1981  */
1982 static void
1983 device_set_desc_internal(device_t dev, const char* desc, int copy)
1984 {
1985 	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
1986 		free(dev->desc, M_BUS);
1987 		dev->flags &= ~DF_DESCMALLOCED;
1988 		dev->desc = NULL;
1989 	}
1990 
1991 	if (copy && desc) {
1992 		dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
1993 		if (dev->desc) {
1994 			strcpy(dev->desc, desc);
1995 			dev->flags |= DF_DESCMALLOCED;
1996 		}
1997 	} else {
1998 		/* Avoid a -Wcast-qual warning */
1999 		dev->desc = (char *)(uintptr_t) desc;
2000 	}
2001 
2002 	bus_data_generation_update();
2003 }
2004 
2005 /**
2006  * @brief Set the device's description
2007  *
2008  * The value of @c desc should be a string constant that will not
2009  * change (at least until the description is changed in a subsequent
2010  * call to device_set_desc() or device_set_desc_copy()).
2011  */
2012 void
2013 device_set_desc(device_t dev, const char* desc)
2014 {
2015 	device_set_desc_internal(dev, desc, FALSE);
2016 }
2017 
2018 /**
2019  * @brief Set the device's description
2020  *
2021  * The string pointed to by @c desc is copied. Use this function if
2022  * the device description is generated, (e.g. with sprintf()).
2023  */
2024 void
2025 device_set_desc_copy(device_t dev, const char* desc)
2026 {
2027 	device_set_desc_internal(dev, desc, TRUE);
2028 }
2029 
2030 /**
2031  * @brief Set the device's flags
2032  */
2033 void
2034 device_set_flags(device_t dev, u_int32_t flags)
2035 {
2036 	dev->devflags = flags;
2037 }
2038 
2039 /**
2040  * @brief Return the device's softc field
2041  *
2042  * The softc is allocated and zeroed when a driver is attached, based
2043  * on the size field of the driver.
2044  */
2045 void *
2046 device_get_softc(device_t dev)
2047 {
2048 	return (dev->softc);
2049 }
2050 
2051 /**
2052  * @brief Set the device's softc field
2053  *
2054  * Most drivers do not need to use this since the softc is allocated
2055  * automatically when the driver is attached.
2056  */
2057 void
2058 device_set_softc(device_t dev, void *softc)
2059 {
2060 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
2061 		free(dev->softc, M_BUS_SC);
2062 	dev->softc = softc;
2063 	if (dev->softc)
2064 		dev->flags |= DF_EXTERNALSOFTC;
2065 	else
2066 		dev->flags &= ~DF_EXTERNALSOFTC;
2067 }
2068 
2069 /**
2070  * @brief Get the device's ivars field
2071  *
2072  * The ivars field is used by the parent device to store per-device
2073  * state (e.g. the physical location of the device or a list of
2074  * resources).
2075  */
2076 void *
2077 device_get_ivars(device_t dev)
2078 {
2079 
2080 	KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
2081 	return (dev->ivars);
2082 }
2083 
2084 /**
2085  * @brief Set the device's ivars field
2086  */
2087 void
2088 device_set_ivars(device_t dev, void * ivars)
2089 {
2090 
2091 	KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
2092 	dev->ivars = ivars;
2093 }
2094 
2095 /**
2096  * @brief Return the device's state
2097  */
2098 device_state_t
2099 device_get_state(device_t dev)
2100 {
2101 	return (dev->state);
2102 }
2103 
2104 /**
2105  * @brief Set the DF_ENABLED flag for the device
2106  */
2107 void
2108 device_enable(device_t dev)
2109 {
2110 	dev->flags |= DF_ENABLED;
2111 }
2112 
2113 /**
2114  * @brief Clear the DF_ENABLED flag for the device
2115  */
2116 void
2117 device_disable(device_t dev)
2118 {
2119 	dev->flags &= ~DF_ENABLED;
2120 }
2121 
2122 /**
2123  * @brief Increment the busy counter for the device
2124  */
2125 void
2126 device_busy(device_t dev)
2127 {
2128 	if (dev->state < DS_ATTACHED)
2129 		panic("device_busy: called for unattached device");
2130 	if (dev->busy == 0 && dev->parent)
2131 		device_busy(dev->parent);
2132 	dev->busy++;
2133 	dev->state = DS_BUSY;
2134 }
2135 
2136 /**
2137  * @brief Decrement the busy counter for the device
2138  */
2139 void
2140 device_unbusy(device_t dev)
2141 {
2142 	if (dev->state != DS_BUSY)
2143 		panic("device_unbusy: called for non-busy device %s",
2144 		    device_get_nameunit(dev));
2145 	dev->busy--;
2146 	if (dev->busy == 0) {
2147 		if (dev->parent)
2148 			device_unbusy(dev->parent);
2149 		dev->state = DS_ATTACHED;
2150 	}
2151 }
2152 
2153 /**
2154  * @brief Set the DF_QUIET flag for the device
2155  */
2156 void
2157 device_quiet(device_t dev)
2158 {
2159 	dev->flags |= DF_QUIET;
2160 }
2161 
2162 /**
2163  * @brief Clear the DF_QUIET flag for the device
2164  */
2165 void
2166 device_verbose(device_t dev)
2167 {
2168 	dev->flags &= ~DF_QUIET;
2169 }
2170 
2171 /**
2172  * @brief Return non-zero if the DF_QUIET flag is set on the device
2173  */
2174 int
2175 device_is_quiet(device_t dev)
2176 {
2177 	return ((dev->flags & DF_QUIET) != 0);
2178 }
2179 
2180 /**
2181  * @brief Return non-zero if the DF_ENABLED flag is set on the device
2182  */
2183 int
2184 device_is_enabled(device_t dev)
2185 {
2186 	return ((dev->flags & DF_ENABLED) != 0);
2187 }
2188 
2189 /**
2190  * @brief Return non-zero if the device was successfully probed
2191  */
2192 int
2193 device_is_alive(device_t dev)
2194 {
2195 	return (dev->state >= DS_ALIVE);
2196 }
2197 
2198 /**
2199  * @brief Return non-zero if the device currently has a driver
2200  * attached to it
2201  */
2202 int
2203 device_is_attached(device_t dev)
2204 {
2205 	return (dev->state >= DS_ATTACHED);
2206 }
2207 
2208 /**
2209  * @brief Set the devclass of a device
2210  * @see devclass_add_device().
2211  */
2212 int
2213 device_set_devclass(device_t dev, const char *classname)
2214 {
2215 	devclass_t dc;
2216 	int error;
2217 
2218 	if (!classname) {
2219 		if (dev->devclass)
2220 			devclass_delete_device(dev->devclass, dev);
2221 		return (0);
2222 	}
2223 
2224 	if (dev->devclass) {
2225 		printf("device_set_devclass: device class already set\n");
2226 		return (EINVAL);
2227 	}
2228 
2229 	dc = devclass_find_internal(classname, 0, TRUE);
2230 	if (!dc)
2231 		return (ENOMEM);
2232 
2233 	error = devclass_add_device(dc, dev);
2234 
2235 	bus_data_generation_update();
2236 	return (error);
2237 }
2238 
2239 /**
2240  * @brief Set the driver of a device
2241  *
2242  * @retval 0		success
2243  * @retval EBUSY	the device already has a driver attached
2244  * @retval ENOMEM	a memory allocation failure occurred
2245  */
2246 int
2247 device_set_driver(device_t dev, driver_t *driver)
2248 {
2249 	if (dev->state >= DS_ATTACHED)
2250 		return (EBUSY);
2251 
2252 	if (dev->driver == driver)
2253 		return (0);
2254 
2255 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
2256 		free(dev->softc, M_BUS_SC);
2257 		dev->softc = NULL;
2258 	}
2259 	kobj_delete((kobj_t) dev, 0);
2260 	dev->driver = driver;
2261 	if (driver) {
2262 		kobj_init((kobj_t) dev, (kobj_class_t) driver);
2263 		if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
2264 			dev->softc = malloc(driver->size, M_BUS_SC,
2265 			    M_NOWAIT | M_ZERO);
2266 			if (!dev->softc) {
2267 				kobj_delete((kobj_t) dev, 0);
2268 				kobj_init((kobj_t) dev, &null_class);
2269 				dev->driver = NULL;
2270 				return (ENOMEM);
2271 			}
2272 		}
2273 	} else {
2274 		kobj_init((kobj_t) dev, &null_class);
2275 	}
2276 
2277 	bus_data_generation_update();
2278 	return (0);
2279 }
2280 
2281 /**
2282  * @brief Probe a device and attach a driver if possible
2283  *
2284  * This function is the core of the device autoconfiguration
2285  * system. Its purpose is to select a suitable driver for a device and
2286  * then call that driver to initialise the hardware appropriately. The
2287  * driver is selected by calling the DEVICE_PROBE() method of a set of
2288  * candidate drivers and then choosing the driver which returned the
2289  * best value. This driver is then attached to the device using
2290  * device_attach().
2291  *
2292  * The set of suitable drivers is taken from the list of drivers in
2293  * the parent device's devclass. If the device was originally created
2294  * with a specific class name (see device_add_child()), only drivers
2295  * with that name are probed, otherwise all drivers in the devclass
2296  * are probed. If no drivers return successful probe values in the
2297  * parent devclass, the search continues in the parent of that
2298  * devclass (see devclass_get_parent()) if any.
2299  *
2300  * @param dev		the device to initialise
2301  *
2302  * @retval 0		success
2303  * @retval ENXIO	no driver was found
2304  * @retval ENOMEM	memory allocation failure
2305  * @retval non-zero	some other unix error code
2306  */
2307 int
2308 device_probe_and_attach(device_t dev)
2309 {
2310 	int error;
2311 
2312 	GIANT_REQUIRED;
2313 
2314 	if (dev->state >= DS_ALIVE && (dev->flags & DF_REBID) == 0)
2315 		return (0);
2316 
2317 	if (!(dev->flags & DF_ENABLED)) {
2318 		if (bootverbose && device_get_name(dev) != NULL) {
2319 			device_print_prettyname(dev);
2320 			printf("not probed (disabled)\n");
2321 		}
2322 		return (0);
2323 	}
2324 	if ((error = device_probe_child(dev->parent, dev)) != 0) {
2325 		if (!(dev->flags & DF_DONENOMATCH)) {
2326 			BUS_PROBE_NOMATCH(dev->parent, dev);
2327 			devnomatch(dev);
2328 			dev->flags |= DF_DONENOMATCH;
2329 		}
2330 		return (error);
2331 	}
2332 	error = device_attach(dev);
2333 
2334 	return (error);
2335 }
2336 
2337 /**
2338  * @brief Attach a device driver to a device
2339  *
2340  * This function is a wrapper around the DEVICE_ATTACH() driver
2341  * method. In addition to calling DEVICE_ATTACH(), it initialises the
2342  * device's sysctl tree, optionally prints a description of the device
2343  * and queues a notification event for user-based device management
2344  * services.
2345  *
2346  * Normally this function is only called internally from
2347  * device_probe_and_attach().
2348  *
2349  * @param dev		the device to initialise
2350  *
2351  * @retval 0		success
2352  * @retval ENXIO	no driver was found
2353  * @retval ENOMEM	memory allocation failure
2354  * @retval non-zero	some other unix error code
2355  */
2356 int
2357 device_attach(device_t dev)
2358 {
2359 	int error;
2360 
2361 	device_sysctl_init(dev);
2362 	if (!device_is_quiet(dev))
2363 		device_print_child(dev->parent, dev);
2364 	if ((error = DEVICE_ATTACH(dev)) != 0) {
2365 		printf("device_attach: %s%d attach returned %d\n",
2366 		    dev->driver->name, dev->unit, error);
2367 		/* Unset the class; set in device_probe_child */
2368 		if (dev->devclass == 0)
2369 			device_set_devclass(dev, 0);
2370 		device_set_driver(dev, NULL);
2371 		device_sysctl_fini(dev);
2372 		dev->state = DS_NOTPRESENT;
2373 		return (error);
2374 	}
2375 	dev->state = DS_ATTACHED;
2376 	devadded(dev);
2377 	return (0);
2378 }
2379 
2380 /**
2381  * @brief Detach a driver from a device
2382  *
2383  * This function is a wrapper around the DEVICE_DETACH() driver
2384  * method. If the call to DEVICE_DETACH() succeeds, it calls
2385  * BUS_CHILD_DETACHED() for the parent of @p dev, queues a
2386  * notification event for user-based device management services and
2387  * cleans up the device's sysctl tree.
2388  *
2389  * @param dev		the device to un-initialise
2390  *
2391  * @retval 0		success
2392  * @retval ENXIO	no driver was found
2393  * @retval ENOMEM	memory allocation failure
2394  * @retval non-zero	some other unix error code
2395  */
2396 int
2397 device_detach(device_t dev)
2398 {
2399 	int error;
2400 
2401 	GIANT_REQUIRED;
2402 
2403 	PDEBUG(("%s", DEVICENAME(dev)));
2404 	if (dev->state == DS_BUSY)
2405 		return (EBUSY);
2406 	if (dev->state != DS_ATTACHED)
2407 		return (0);
2408 
2409 	if ((error = DEVICE_DETACH(dev)) != 0)
2410 		return (error);
2411 	devremoved(dev);
2412 	device_printf(dev, "detached\n");
2413 	if (dev->parent)
2414 		BUS_CHILD_DETACHED(dev->parent, dev);
2415 
2416 	if (!(dev->flags & DF_FIXEDCLASS))
2417 		devclass_delete_device(dev->devclass, dev);
2418 
2419 	dev->state = DS_NOTPRESENT;
2420 	device_set_driver(dev, NULL);
2421 	device_set_desc(dev, NULL);
2422 	device_sysctl_fini(dev);
2423 
2424 	return (0);
2425 }
2426 
2427 /**
2428  * @brief Tells a driver to quiesce itself.
2429  *
2430  * This function is a wrapper around the DEVICE_QUIESCE() driver
2431  * method. If the call to DEVICE_QUIESCE() succeeds.
2432  *
2433  * @param dev		the device to quiesce
2434  *
2435  * @retval 0		success
2436  * @retval ENXIO	no driver was found
2437  * @retval ENOMEM	memory allocation failure
2438  * @retval non-zero	some other unix error code
2439  */
2440 int
2441 device_quiesce(device_t dev)
2442 {
2443 
2444 	PDEBUG(("%s", DEVICENAME(dev)));
2445 	if (dev->state == DS_BUSY)
2446 		return (EBUSY);
2447 	if (dev->state != DS_ATTACHED)
2448 		return (0);
2449 
2450 	return (DEVICE_QUIESCE(dev));
2451 }
2452 
2453 /**
2454  * @brief Notify a device of system shutdown
2455  *
2456  * This function calls the DEVICE_SHUTDOWN() driver method if the
2457  * device currently has an attached driver.
2458  *
2459  * @returns the value returned by DEVICE_SHUTDOWN()
2460  */
2461 int
2462 device_shutdown(device_t dev)
2463 {
2464 	if (dev->state < DS_ATTACHED)
2465 		return (0);
2466 	return (DEVICE_SHUTDOWN(dev));
2467 }
2468 
2469 /**
2470  * @brief Set the unit number of a device
2471  *
2472  * This function can be used to override the unit number used for a
2473  * device (e.g. to wire a device to a pre-configured unit number).
2474  */
2475 int
2476 device_set_unit(device_t dev, int unit)
2477 {
2478 	devclass_t dc;
2479 	int err;
2480 
2481 	dc = device_get_devclass(dev);
2482 	if (unit < dc->maxunit && dc->devices[unit])
2483 		return (EBUSY);
2484 	err = devclass_delete_device(dc, dev);
2485 	if (err)
2486 		return (err);
2487 	dev->unit = unit;
2488 	err = devclass_add_device(dc, dev);
2489 	if (err)
2490 		return (err);
2491 
2492 	bus_data_generation_update();
2493 	return (0);
2494 }
2495 
2496 /*======================================*/
2497 /*
2498  * Some useful method implementations to make life easier for bus drivers.
2499  */
2500 
2501 /**
2502  * @brief Initialise a resource list.
2503  *
2504  * @param rl		the resource list to initialise
2505  */
2506 void
2507 resource_list_init(struct resource_list *rl)
2508 {
2509 	STAILQ_INIT(rl);
2510 }
2511 
2512 /**
2513  * @brief Reclaim memory used by a resource list.
2514  *
2515  * This function frees the memory for all resource entries on the list
2516  * (if any).
2517  *
2518  * @param rl		the resource list to free
2519  */
2520 void
2521 resource_list_free(struct resource_list *rl)
2522 {
2523 	struct resource_list_entry *rle;
2524 
2525 	while ((rle = STAILQ_FIRST(rl)) != NULL) {
2526 		if (rle->res)
2527 			panic("resource_list_free: resource entry is busy");
2528 		STAILQ_REMOVE_HEAD(rl, link);
2529 		free(rle, M_BUS);
2530 	}
2531 }
2532 
2533 /**
2534  * @brief Add a resource entry.
2535  *
2536  * This function adds a resource entry using the given @p type, @p
2537  * start, @p end and @p count values. A rid value is chosen by
2538  * searching sequentially for the first unused rid starting at zero.
2539  *
2540  * @param rl		the resource list to edit
2541  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2542  * @param start		the start address of the resource
2543  * @param end		the end address of the resource
2544  * @param count		XXX end-start+1
2545  */
2546 int
2547 resource_list_add_next(struct resource_list *rl, int type, u_long start,
2548     u_long end, u_long count)
2549 {
2550 	int rid;
2551 
2552 	rid = 0;
2553 	while (resource_list_find(rl, type, rid) != NULL)
2554 		rid++;
2555 	resource_list_add(rl, type, rid, start, end, count);
2556 	return (rid);
2557 }
2558 
2559 /**
2560  * @brief Add or modify a resource entry.
2561  *
2562  * If an existing entry exists with the same type and rid, it will be
2563  * modified using the given values of @p start, @p end and @p
2564  * count. If no entry exists, a new one will be created using the
2565  * given values.  The resource list entry that matches is then returned.
2566  *
2567  * @param rl		the resource list to edit
2568  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2569  * @param rid		the resource identifier
2570  * @param start		the start address of the resource
2571  * @param end		the end address of the resource
2572  * @param count		XXX end-start+1
2573  */
2574 struct resource_list_entry *
2575 resource_list_add(struct resource_list *rl, int type, int rid,
2576     u_long start, u_long end, u_long count)
2577 {
2578 	struct resource_list_entry *rle;
2579 
2580 	rle = resource_list_find(rl, type, rid);
2581 	if (!rle) {
2582 		rle = malloc(sizeof(struct resource_list_entry), M_BUS,
2583 		    M_NOWAIT);
2584 		if (!rle)
2585 			panic("resource_list_add: can't record entry");
2586 		STAILQ_INSERT_TAIL(rl, rle, link);
2587 		rle->type = type;
2588 		rle->rid = rid;
2589 		rle->res = NULL;
2590 	}
2591 
2592 	if (rle->res)
2593 		panic("resource_list_add: resource entry is busy");
2594 
2595 	rle->start = start;
2596 	rle->end = end;
2597 	rle->count = count;
2598 	return (rle);
2599 }
2600 
2601 /**
2602  * @brief Find a resource entry by type and rid.
2603  *
2604  * @param rl		the resource list to search
2605  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2606  * @param rid		the resource identifier
2607  *
2608  * @returns the resource entry pointer or NULL if there is no such
2609  * entry.
2610  */
2611 struct resource_list_entry *
2612 resource_list_find(struct resource_list *rl, int type, int rid)
2613 {
2614 	struct resource_list_entry *rle;
2615 
2616 	STAILQ_FOREACH(rle, rl, link) {
2617 		if (rle->type == type && rle->rid == rid)
2618 			return (rle);
2619 	}
2620 	return (NULL);
2621 }
2622 
2623 /**
2624  * @brief Delete a resource entry.
2625  *
2626  * @param rl		the resource list to edit
2627  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2628  * @param rid		the resource identifier
2629  */
2630 void
2631 resource_list_delete(struct resource_list *rl, int type, int rid)
2632 {
2633 	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
2634 
2635 	if (rle) {
2636 		if (rle->res != NULL)
2637 			panic("resource_list_delete: resource has not been released");
2638 		STAILQ_REMOVE(rl, rle, resource_list_entry, link);
2639 		free(rle, M_BUS);
2640 	}
2641 }
2642 
2643 /**
2644  * @brief Helper function for implementing BUS_ALLOC_RESOURCE()
2645  *
2646  * Implement BUS_ALLOC_RESOURCE() by looking up a resource from the list
2647  * and passing the allocation up to the parent of @p bus. This assumes
2648  * that the first entry of @c device_get_ivars(child) is a struct
2649  * resource_list. This also handles 'passthrough' allocations where a
2650  * child is a remote descendant of bus by passing the allocation up to
2651  * the parent of bus.
2652  *
2653  * Typically, a bus driver would store a list of child resources
2654  * somewhere in the child device's ivars (see device_get_ivars()) and
2655  * its implementation of BUS_ALLOC_RESOURCE() would find that list and
2656  * then call resource_list_alloc() to perform the allocation.
2657  *
2658  * @param rl		the resource list to allocate from
2659  * @param bus		the parent device of @p child
2660  * @param child		the device which is requesting an allocation
2661  * @param type		the type of resource to allocate
2662  * @param rid		a pointer to the resource identifier
2663  * @param start		hint at the start of the resource range - pass
2664  *			@c 0UL for any start address
2665  * @param end		hint at the end of the resource range - pass
2666  *			@c ~0UL for any end address
2667  * @param count		hint at the size of range required - pass @c 1
2668  *			for any size
2669  * @param flags		any extra flags to control the resource
2670  *			allocation - see @c RF_XXX flags in
2671  *			<sys/rman.h> for details
2672  *
2673  * @returns		the resource which was allocated or @c NULL if no
2674  *			resource could be allocated
2675  */
2676 struct resource *
2677 resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
2678     int type, int *rid, u_long start, u_long end, u_long count, u_int flags)
2679 {
2680 	struct resource_list_entry *rle = 0;
2681 	int passthrough = (device_get_parent(child) != bus);
2682 	int isdefault = (start == 0UL && end == ~0UL);
2683 
2684 	if (passthrough) {
2685 		return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2686 		    type, rid, start, end, count, flags));
2687 	}
2688 
2689 	rle = resource_list_find(rl, type, *rid);
2690 
2691 	if (!rle)
2692 		return (NULL);		/* no resource of that type/rid */
2693 
2694 	if (rle->res)
2695 		panic("resource_list_alloc: resource entry is busy");
2696 
2697 	if (isdefault) {
2698 		start = rle->start;
2699 		count = ulmax(count, rle->count);
2700 		end = ulmax(rle->end, start + count - 1);
2701 	}
2702 
2703 	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2704 	    type, rid, start, end, count, flags);
2705 
2706 	/*
2707 	 * Record the new range.
2708 	 */
2709 	if (rle->res) {
2710 		rle->start = rman_get_start(rle->res);
2711 		rle->end = rman_get_end(rle->res);
2712 		rle->count = count;
2713 	}
2714 
2715 	return (rle->res);
2716 }
2717 
2718 /**
2719  * @brief Helper function for implementing BUS_RELEASE_RESOURCE()
2720  *
2721  * Implement BUS_RELEASE_RESOURCE() using a resource list. Normally
2722  * used with resource_list_alloc().
2723  *
2724  * @param rl		the resource list which was allocated from
2725  * @param bus		the parent device of @p child
2726  * @param child		the device which is requesting a release
2727  * @param type		the type of resource to allocate
2728  * @param rid		the resource identifier
2729  * @param res		the resource to release
2730  *
2731  * @retval 0		success
2732  * @retval non-zero	a standard unix error code indicating what
2733  *			error condition prevented the operation
2734  */
2735 int
2736 resource_list_release(struct resource_list *rl, device_t bus, device_t child,
2737     int type, int rid, struct resource *res)
2738 {
2739 	struct resource_list_entry *rle = 0;
2740 	int passthrough = (device_get_parent(child) != bus);
2741 	int error;
2742 
2743 	if (passthrough) {
2744 		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2745 		    type, rid, res));
2746 	}
2747 
2748 	rle = resource_list_find(rl, type, rid);
2749 
2750 	if (!rle)
2751 		panic("resource_list_release: can't find resource");
2752 	if (!rle->res)
2753 		panic("resource_list_release: resource entry is not busy");
2754 
2755 	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2756 	    type, rid, res);
2757 	if (error)
2758 		return (error);
2759 
2760 	rle->res = NULL;
2761 	return (0);
2762 }
2763 
2764 /**
2765  * @brief Print a description of resources in a resource list
2766  *
2767  * Print all resources of a specified type, for use in BUS_PRINT_CHILD().
2768  * The name is printed if at least one resource of the given type is available.
2769  * The format is used to print resource start and end.
2770  *
2771  * @param rl		the resource list to print
2772  * @param name		the name of @p type, e.g. @c "memory"
2773  * @param type		type type of resource entry to print
2774  * @param format	printf(9) format string to print resource
2775  *			start and end values
2776  *
2777  * @returns		the number of characters printed
2778  */
2779 int
2780 resource_list_print_type(struct resource_list *rl, const char *name, int type,
2781     const char *format)
2782 {
2783 	struct resource_list_entry *rle;
2784 	int printed, retval;
2785 
2786 	printed = 0;
2787 	retval = 0;
2788 	/* Yes, this is kinda cheating */
2789 	STAILQ_FOREACH(rle, rl, link) {
2790 		if (rle->type == type) {
2791 			if (printed == 0)
2792 				retval += printf(" %s ", name);
2793 			else
2794 				retval += printf(",");
2795 			printed++;
2796 			retval += printf(format, rle->start);
2797 			if (rle->count > 1) {
2798 				retval += printf("-");
2799 				retval += printf(format, rle->start +
2800 						 rle->count - 1);
2801 			}
2802 		}
2803 	}
2804 	return (retval);
2805 }
2806 
2807 /**
2808  * @brief Releases all the resources in a list.
2809  *
2810  * @param rl		The resource list to purge.
2811  *
2812  * @returns		nothing
2813  */
2814 void
2815 resource_list_purge(struct resource_list *rl)
2816 {
2817 	struct resource_list_entry *rle;
2818 
2819 	STAILQ_FOREACH(rle, rl, link) {
2820 		if (rle->res)
2821 			bus_release_resource(rman_get_device(rle->res),
2822 			    rle->type, rle->rid, rle->res);
2823 		STAILQ_REMOVE_HEAD(rl, link);
2824 		free(rle, M_BUS);
2825 	}
2826 }
2827 
2828 /**
2829  * @brief Helper function for implementing DEVICE_PROBE()
2830  *
2831  * This function can be used to help implement the DEVICE_PROBE() for
2832  * a bus (i.e. a device which has other devices attached to it). It
2833  * calls the DEVICE_IDENTIFY() method of each driver in the device's
2834  * devclass.
2835  */
2836 int
2837 bus_generic_probe(device_t dev)
2838 {
2839 	devclass_t dc = dev->devclass;
2840 	driverlink_t dl;
2841 
2842 	TAILQ_FOREACH(dl, &dc->drivers, link) {
2843 		DEVICE_IDENTIFY(dl->driver, dev);
2844 	}
2845 
2846 	return (0);
2847 }
2848 
2849 /**
2850  * @brief Helper function for implementing DEVICE_ATTACH()
2851  *
2852  * This function can be used to help implement the DEVICE_ATTACH() for
2853  * a bus. It calls device_probe_and_attach() for each of the device's
2854  * children.
2855  */
2856 int
2857 bus_generic_attach(device_t dev)
2858 {
2859 	device_t child;
2860 
2861 	TAILQ_FOREACH(child, &dev->children, link) {
2862 		device_probe_and_attach(child);
2863 	}
2864 
2865 	return (0);
2866 }
2867 
2868 /**
2869  * @brief Helper function for implementing DEVICE_DETACH()
2870  *
2871  * This function can be used to help implement the DEVICE_DETACH() for
2872  * a bus. It calls device_detach() for each of the device's
2873  * children.
2874  */
2875 int
2876 bus_generic_detach(device_t dev)
2877 {
2878 	device_t child;
2879 	int error;
2880 
2881 	if (dev->state != DS_ATTACHED)
2882 		return (EBUSY);
2883 
2884 	TAILQ_FOREACH(child, &dev->children, link) {
2885 		if ((error = device_detach(child)) != 0)
2886 			return (error);
2887 	}
2888 
2889 	return (0);
2890 }
2891 
2892 /**
2893  * @brief Helper function for implementing DEVICE_SHUTDOWN()
2894  *
2895  * This function can be used to help implement the DEVICE_SHUTDOWN()
2896  * for a bus. It calls device_shutdown() for each of the device's
2897  * children.
2898  */
2899 int
2900 bus_generic_shutdown(device_t dev)
2901 {
2902 	device_t child;
2903 
2904 	TAILQ_FOREACH(child, &dev->children, link) {
2905 		device_shutdown(child);
2906 	}
2907 
2908 	return (0);
2909 }
2910 
2911 /**
2912  * @brief Helper function for implementing DEVICE_SUSPEND()
2913  *
2914  * This function can be used to help implement the DEVICE_SUSPEND()
2915  * for a bus. It calls DEVICE_SUSPEND() for each of the device's
2916  * children. If any call to DEVICE_SUSPEND() fails, the suspend
2917  * operation is aborted and any devices which were suspended are
2918  * resumed immediately by calling their DEVICE_RESUME() methods.
2919  */
2920 int
2921 bus_generic_suspend(device_t dev)
2922 {
2923 	int		error;
2924 	device_t	child, child2;
2925 
2926 	TAILQ_FOREACH(child, &dev->children, link) {
2927 		error = DEVICE_SUSPEND(child);
2928 		if (error) {
2929 			for (child2 = TAILQ_FIRST(&dev->children);
2930 			     child2 && child2 != child;
2931 			     child2 = TAILQ_NEXT(child2, link))
2932 				DEVICE_RESUME(child2);
2933 			return (error);
2934 		}
2935 	}
2936 	return (0);
2937 }
2938 
2939 /**
2940  * @brief Helper function for implementing DEVICE_RESUME()
2941  *
2942  * This function can be used to help implement the DEVICE_RESUME() for
2943  * a bus. It calls DEVICE_RESUME() on each of the device's children.
2944  */
2945 int
2946 bus_generic_resume(device_t dev)
2947 {
2948 	device_t	child;
2949 
2950 	TAILQ_FOREACH(child, &dev->children, link) {
2951 		DEVICE_RESUME(child);
2952 		/* if resume fails, there's nothing we can usefully do... */
2953 	}
2954 	return (0);
2955 }
2956 
2957 /**
2958  * @brief Helper function for implementing BUS_PRINT_CHILD().
2959  *
2960  * This function prints the first part of the ascii representation of
2961  * @p child, including its name, unit and description (if any - see
2962  * device_set_desc()).
2963  *
2964  * @returns the number of characters printed
2965  */
2966 int
2967 bus_print_child_header(device_t dev, device_t child)
2968 {
2969 	int	retval = 0;
2970 
2971 	if (device_get_desc(child)) {
2972 		retval += device_printf(child, "<%s>", device_get_desc(child));
2973 	} else {
2974 		retval += printf("%s", device_get_nameunit(child));
2975 	}
2976 
2977 	return (retval);
2978 }
2979 
2980 /**
2981  * @brief Helper function for implementing BUS_PRINT_CHILD().
2982  *
2983  * This function prints the last part of the ascii representation of
2984  * @p child, which consists of the string @c " on " followed by the
2985  * name and unit of the @p dev.
2986  *
2987  * @returns the number of characters printed
2988  */
2989 int
2990 bus_print_child_footer(device_t dev, device_t child)
2991 {
2992 	return (printf(" on %s\n", device_get_nameunit(dev)));
2993 }
2994 
2995 /**
2996  * @brief Helper function for implementing BUS_PRINT_CHILD().
2997  *
2998  * This function simply calls bus_print_child_header() followed by
2999  * bus_print_child_footer().
3000  *
3001  * @returns the number of characters printed
3002  */
3003 int
3004 bus_generic_print_child(device_t dev, device_t child)
3005 {
3006 	int	retval = 0;
3007 
3008 	retval += bus_print_child_header(dev, child);
3009 	retval += bus_print_child_footer(dev, child);
3010 
3011 	return (retval);
3012 }
3013 
3014 /**
3015  * @brief Stub function for implementing BUS_READ_IVAR().
3016  *
3017  * @returns ENOENT
3018  */
3019 int
3020 bus_generic_read_ivar(device_t dev, device_t child, int index,
3021     uintptr_t * result)
3022 {
3023 	return (ENOENT);
3024 }
3025 
3026 /**
3027  * @brief Stub function for implementing BUS_WRITE_IVAR().
3028  *
3029  * @returns ENOENT
3030  */
3031 int
3032 bus_generic_write_ivar(device_t dev, device_t child, int index,
3033     uintptr_t value)
3034 {
3035 	return (ENOENT);
3036 }
3037 
3038 /**
3039  * @brief Stub function for implementing BUS_GET_RESOURCE_LIST().
3040  *
3041  * @returns NULL
3042  */
3043 struct resource_list *
3044 bus_generic_get_resource_list(device_t dev, device_t child)
3045 {
3046 	return (NULL);
3047 }
3048 
3049 /**
3050  * @brief Helper function for implementing BUS_DRIVER_ADDED().
3051  *
3052  * This implementation of BUS_DRIVER_ADDED() simply calls the driver's
3053  * DEVICE_IDENTIFY() method to allow it to add new children to the bus
3054  * and then calls device_probe_and_attach() for each unattached child.
3055  */
3056 void
3057 bus_generic_driver_added(device_t dev, driver_t *driver)
3058 {
3059 	device_t child;
3060 
3061 	DEVICE_IDENTIFY(driver, dev);
3062 	TAILQ_FOREACH(child, &dev->children, link) {
3063 		if (child->state == DS_NOTPRESENT ||
3064 		    (child->flags & DF_REBID))
3065 			device_probe_and_attach(child);
3066 	}
3067 }
3068 
3069 /**
3070  * @brief Helper function for implementing BUS_SETUP_INTR().
3071  *
3072  * This simple implementation of BUS_SETUP_INTR() simply calls the
3073  * BUS_SETUP_INTR() method of the parent of @p dev.
3074  */
3075 int
3076 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
3077     int flags, driver_intr_t *intr, void *arg, void **cookiep)
3078 {
3079 	/* Propagate up the bus hierarchy until someone handles it. */
3080 	if (dev->parent)
3081 		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
3082 		    intr, arg, cookiep));
3083 	return (EINVAL);
3084 }
3085 
3086 /**
3087  * @brief Helper function for implementing BUS_TEARDOWN_INTR().
3088  *
3089  * This simple implementation of BUS_TEARDOWN_INTR() simply calls the
3090  * BUS_TEARDOWN_INTR() method of the parent of @p dev.
3091  */
3092 int
3093 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
3094     void *cookie)
3095 {
3096 	/* Propagate up the bus hierarchy until someone handles it. */
3097 	if (dev->parent)
3098 		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
3099 	return (EINVAL);
3100 }
3101 
3102 /**
3103  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3104  *
3105  * This simple implementation of BUS_ALLOC_RESOURCE() simply calls the
3106  * BUS_ALLOC_RESOURCE() method of the parent of @p dev.
3107  */
3108 struct resource *
3109 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
3110     u_long start, u_long end, u_long count, u_int flags)
3111 {
3112 	/* Propagate up the bus hierarchy until someone handles it. */
3113 	if (dev->parent)
3114 		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
3115 		    start, end, count, flags));
3116 	return (NULL);
3117 }
3118 
3119 /**
3120  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3121  *
3122  * This simple implementation of BUS_RELEASE_RESOURCE() simply calls the
3123  * BUS_RELEASE_RESOURCE() method of the parent of @p dev.
3124  */
3125 int
3126 bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
3127     struct resource *r)
3128 {
3129 	/* Propagate up the bus hierarchy until someone handles it. */
3130 	if (dev->parent)
3131 		return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
3132 		    r));
3133 	return (EINVAL);
3134 }
3135 
3136 /**
3137  * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
3138  *
3139  * This simple implementation of BUS_ACTIVATE_RESOURCE() simply calls the
3140  * BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
3141  */
3142 int
3143 bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
3144     struct resource *r)
3145 {
3146 	/* Propagate up the bus hierarchy until someone handles it. */
3147 	if (dev->parent)
3148 		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
3149 		    r));
3150 	return (EINVAL);
3151 }
3152 
3153 /**
3154  * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
3155  *
3156  * This simple implementation of BUS_DEACTIVATE_RESOURCE() simply calls the
3157  * BUS_DEACTIVATE_RESOURCE() method of the parent of @p dev.
3158  */
3159 int
3160 bus_generic_deactivate_resource(device_t dev, device_t child, int type,
3161     int rid, struct resource *r)
3162 {
3163 	/* Propagate up the bus hierarchy until someone handles it. */
3164 	if (dev->parent)
3165 		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
3166 		    r));
3167 	return (EINVAL);
3168 }
3169 
3170 /**
3171  * @brief Helper function for implementing BUS_CONFIG_INTR().
3172  *
3173  * This simple implementation of BUS_CONFIG_INTR() simply calls the
3174  * BUS_CONFIG_INTR() method of the parent of @p dev.
3175  */
3176 int
3177 bus_generic_config_intr(device_t dev, int irq, enum intr_trigger trig,
3178     enum intr_polarity pol)
3179 {
3180 
3181 	/* Propagate up the bus hierarchy until someone handles it. */
3182 	if (dev->parent)
3183 		return (BUS_CONFIG_INTR(dev->parent, irq, trig, pol));
3184 	return (EINVAL);
3185 }
3186 
3187 /**
3188  * @brief Helper function for implementing BUS_GET_RESOURCE().
3189  *
3190  * This implementation of BUS_GET_RESOURCE() uses the
3191  * resource_list_find() function to do most of the work. It calls
3192  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3193  * search.
3194  */
3195 int
3196 bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
3197     u_long *startp, u_long *countp)
3198 {
3199 	struct resource_list *		rl = NULL;
3200 	struct resource_list_entry *	rle = NULL;
3201 
3202 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3203 	if (!rl)
3204 		return (EINVAL);
3205 
3206 	rle = resource_list_find(rl, type, rid);
3207 	if (!rle)
3208 		return (ENOENT);
3209 
3210 	if (startp)
3211 		*startp = rle->start;
3212 	if (countp)
3213 		*countp = rle->count;
3214 
3215 	return (0);
3216 }
3217 
3218 /**
3219  * @brief Helper function for implementing BUS_SET_RESOURCE().
3220  *
3221  * This implementation of BUS_SET_RESOURCE() uses the
3222  * resource_list_add() function to do most of the work. It calls
3223  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3224  * edit.
3225  */
3226 int
3227 bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
3228     u_long start, u_long count)
3229 {
3230 	struct resource_list *		rl = NULL;
3231 
3232 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3233 	if (!rl)
3234 		return (EINVAL);
3235 
3236 	resource_list_add(rl, type, rid, start, (start + count - 1), count);
3237 
3238 	return (0);
3239 }
3240 
3241 /**
3242  * @brief Helper function for implementing BUS_DELETE_RESOURCE().
3243  *
3244  * This implementation of BUS_DELETE_RESOURCE() uses the
3245  * resource_list_delete() function to do most of the work. It calls
3246  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3247  * edit.
3248  */
3249 void
3250 bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
3251 {
3252 	struct resource_list *		rl = NULL;
3253 
3254 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3255 	if (!rl)
3256 		return;
3257 
3258 	resource_list_delete(rl, type, rid);
3259 
3260 	return;
3261 }
3262 
3263 /**
3264  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3265  *
3266  * This implementation of BUS_RELEASE_RESOURCE() uses the
3267  * resource_list_release() function to do most of the work. It calls
3268  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3269  */
3270 int
3271 bus_generic_rl_release_resource(device_t dev, device_t child, int type,
3272     int rid, struct resource *r)
3273 {
3274 	struct resource_list *		rl = NULL;
3275 
3276 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3277 	if (!rl)
3278 		return (EINVAL);
3279 
3280 	return (resource_list_release(rl, dev, child, type, rid, r));
3281 }
3282 
3283 /**
3284  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3285  *
3286  * This implementation of BUS_ALLOC_RESOURCE() uses the
3287  * resource_list_alloc() function to do most of the work. It calls
3288  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3289  */
3290 struct resource *
3291 bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
3292     int *rid, u_long start, u_long end, u_long count, u_int flags)
3293 {
3294 	struct resource_list *		rl = NULL;
3295 
3296 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3297 	if (!rl)
3298 		return (NULL);
3299 
3300 	return (resource_list_alloc(rl, dev, child, type, rid,
3301 	    start, end, count, flags));
3302 }
3303 
3304 /**
3305  * @brief Helper function for implementing BUS_CHILD_PRESENT().
3306  *
3307  * This simple implementation of BUS_CHILD_PRESENT() simply calls the
3308  * BUS_CHILD_PRESENT() method of the parent of @p dev.
3309  */
3310 int
3311 bus_generic_child_present(device_t dev, device_t child)
3312 {
3313 	return (BUS_CHILD_PRESENT(device_get_parent(dev), dev));
3314 }
3315 
3316 /*
3317  * Some convenience functions to make it easier for drivers to use the
3318  * resource-management functions.  All these really do is hide the
3319  * indirection through the parent's method table, making for slightly
3320  * less-wordy code.  In the future, it might make sense for this code
3321  * to maintain some sort of a list of resources allocated by each device.
3322  */
3323 
3324 int
3325 bus_alloc_resources(device_t dev, struct resource_spec *rs,
3326     struct resource **res)
3327 {
3328 	int i;
3329 
3330 	for (i = 0; rs[i].type != -1; i++)
3331 		res[i] = NULL;
3332 	for (i = 0; rs[i].type != -1; i++) {
3333 		res[i] = bus_alloc_resource_any(dev,
3334 		    rs[i].type, &rs[i].rid, rs[i].flags);
3335 		if (res[i] == NULL && !(rs[i].flags & RF_OPTIONAL)) {
3336 			bus_release_resources(dev, rs, res);
3337 			return (ENXIO);
3338 		}
3339 	}
3340 	return (0);
3341 }
3342 
3343 void
3344 bus_release_resources(device_t dev, struct resource_spec *rs,
3345     struct resource **res)
3346 {
3347 	int i;
3348 
3349 	for (i = 0; rs[i].type != -1; i++)
3350 		if (res[i] != NULL)
3351 			bus_release_resource(
3352 			    dev, rs[i].type, rs[i].rid, res[i]);
3353 }
3354 
3355 /**
3356  * @brief Wrapper function for BUS_ALLOC_RESOURCE().
3357  *
3358  * This function simply calls the BUS_ALLOC_RESOURCE() method of the
3359  * parent of @p dev.
3360  */
3361 struct resource *
3362 bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
3363     u_long count, u_int flags)
3364 {
3365 	if (dev->parent == 0)
3366 		return (0);
3367 	return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
3368 	    count, flags));
3369 }
3370 
3371 /**
3372  * @brief Wrapper function for BUS_ACTIVATE_RESOURCE().
3373  *
3374  * This function simply calls the BUS_ACTIVATE_RESOURCE() method of the
3375  * parent of @p dev.
3376  */
3377 int
3378 bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
3379 {
3380 	if (dev->parent == 0)
3381 		return (EINVAL);
3382 	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
3383 }
3384 
3385 /**
3386  * @brief Wrapper function for BUS_DEACTIVATE_RESOURCE().
3387  *
3388  * This function simply calls the BUS_DEACTIVATE_RESOURCE() method of the
3389  * parent of @p dev.
3390  */
3391 int
3392 bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
3393 {
3394 	if (dev->parent == 0)
3395 		return (EINVAL);
3396 	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
3397 }
3398 
3399 /**
3400  * @brief Wrapper function for BUS_RELEASE_RESOURCE().
3401  *
3402  * This function simply calls the BUS_RELEASE_RESOURCE() method of the
3403  * parent of @p dev.
3404  */
3405 int
3406 bus_release_resource(device_t dev, int type, int rid, struct resource *r)
3407 {
3408 	if (dev->parent == 0)
3409 		return (EINVAL);
3410 	return (BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
3411 }
3412 
3413 /**
3414  * @brief Wrapper function for BUS_SETUP_INTR().
3415  *
3416  * This function simply calls the BUS_SETUP_INTR() method of the
3417  * parent of @p dev.
3418  */
3419 int
3420 bus_setup_intr(device_t dev, struct resource *r, int flags,
3421     driver_intr_t handler, void *arg, void **cookiep)
3422 {
3423 	int error;
3424 
3425 	if (dev->parent != 0) {
3426 		if ((flags &~ INTR_ENTROPY) == (INTR_TYPE_NET | INTR_MPSAFE) &&
3427 		    !debug_mpsafenet)
3428 			flags &= ~INTR_MPSAFE;
3429 		error = BUS_SETUP_INTR(dev->parent, dev, r, flags,
3430 		    handler, arg, cookiep);
3431 		if (error == 0) {
3432 			if (!(flags & (INTR_MPSAFE | INTR_FAST)))
3433 				device_printf(dev, "[GIANT-LOCKED]\n");
3434 			if (bootverbose && (flags & INTR_MPSAFE))
3435 				device_printf(dev, "[MPSAFE]\n");
3436 			if (flags & INTR_FAST)
3437 				device_printf(dev, "[FAST]\n");
3438 		}
3439 	} else
3440 		error = EINVAL;
3441 	return (error);
3442 }
3443 
3444 /**
3445  * @brief Wrapper function for BUS_TEARDOWN_INTR().
3446  *
3447  * This function simply calls the BUS_TEARDOWN_INTR() method of the
3448  * parent of @p dev.
3449  */
3450 int
3451 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
3452 {
3453 	if (dev->parent == 0)
3454 		return (EINVAL);
3455 	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
3456 }
3457 
3458 /**
3459  * @brief Wrapper function for BUS_SET_RESOURCE().
3460  *
3461  * This function simply calls the BUS_SET_RESOURCE() method of the
3462  * parent of @p dev.
3463  */
3464 int
3465 bus_set_resource(device_t dev, int type, int rid,
3466     u_long start, u_long count)
3467 {
3468 	return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
3469 	    start, count));
3470 }
3471 
3472 /**
3473  * @brief Wrapper function for BUS_GET_RESOURCE().
3474  *
3475  * This function simply calls the BUS_GET_RESOURCE() method of the
3476  * parent of @p dev.
3477  */
3478 int
3479 bus_get_resource(device_t dev, int type, int rid,
3480     u_long *startp, u_long *countp)
3481 {
3482 	return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3483 	    startp, countp));
3484 }
3485 
3486 /**
3487  * @brief Wrapper function for BUS_GET_RESOURCE().
3488  *
3489  * This function simply calls the BUS_GET_RESOURCE() method of the
3490  * parent of @p dev and returns the start value.
3491  */
3492 u_long
3493 bus_get_resource_start(device_t dev, int type, int rid)
3494 {
3495 	u_long start, count;
3496 	int error;
3497 
3498 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3499 	    &start, &count);
3500 	if (error)
3501 		return (0);
3502 	return (start);
3503 }
3504 
3505 /**
3506  * @brief Wrapper function for BUS_GET_RESOURCE().
3507  *
3508  * This function simply calls the BUS_GET_RESOURCE() method of the
3509  * parent of @p dev and returns the count value.
3510  */
3511 u_long
3512 bus_get_resource_count(device_t dev, int type, int rid)
3513 {
3514 	u_long start, count;
3515 	int error;
3516 
3517 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3518 	    &start, &count);
3519 	if (error)
3520 		return (0);
3521 	return (count);
3522 }
3523 
3524 /**
3525  * @brief Wrapper function for BUS_DELETE_RESOURCE().
3526  *
3527  * This function simply calls the BUS_DELETE_RESOURCE() method of the
3528  * parent of @p dev.
3529  */
3530 void
3531 bus_delete_resource(device_t dev, int type, int rid)
3532 {
3533 	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
3534 }
3535 
3536 /**
3537  * @brief Wrapper function for BUS_CHILD_PRESENT().
3538  *
3539  * This function simply calls the BUS_CHILD_PRESENT() method of the
3540  * parent of @p dev.
3541  */
3542 int
3543 bus_child_present(device_t child)
3544 {
3545 	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
3546 }
3547 
3548 /**
3549  * @brief Wrapper function for BUS_CHILD_PNPINFO_STR().
3550  *
3551  * This function simply calls the BUS_CHILD_PNPINFO_STR() method of the
3552  * parent of @p dev.
3553  */
3554 int
3555 bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
3556 {
3557 	device_t parent;
3558 
3559 	parent = device_get_parent(child);
3560 	if (parent == NULL) {
3561 		*buf = '\0';
3562 		return (0);
3563 	}
3564 	return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
3565 }
3566 
3567 /**
3568  * @brief Wrapper function for BUS_CHILD_LOCATION_STR().
3569  *
3570  * This function simply calls the BUS_CHILD_LOCATION_STR() method of the
3571  * parent of @p dev.
3572  */
3573 int
3574 bus_child_location_str(device_t child, char *buf, size_t buflen)
3575 {
3576 	device_t parent;
3577 
3578 	parent = device_get_parent(child);
3579 	if (parent == NULL) {
3580 		*buf = '\0';
3581 		return (0);
3582 	}
3583 	return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
3584 }
3585 
3586 static int
3587 root_print_child(device_t dev, device_t child)
3588 {
3589 	int	retval = 0;
3590 
3591 	retval += bus_print_child_header(dev, child);
3592 	retval += printf("\n");
3593 
3594 	return (retval);
3595 }
3596 
3597 static int
3598 root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
3599     void **cookiep)
3600 {
3601 	/*
3602 	 * If an interrupt mapping gets to here something bad has happened.
3603 	 */
3604 	panic("root_setup_intr");
3605 }
3606 
3607 /*
3608  * If we get here, assume that the device is permanant and really is
3609  * present in the system.  Removable bus drivers are expected to intercept
3610  * this call long before it gets here.  We return -1 so that drivers that
3611  * really care can check vs -1 or some ERRNO returned higher in the food
3612  * chain.
3613  */
3614 static int
3615 root_child_present(device_t dev, device_t child)
3616 {
3617 	return (-1);
3618 }
3619 
3620 static kobj_method_t root_methods[] = {
3621 	/* Device interface */
3622 	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
3623 	KOBJMETHOD(device_suspend,	bus_generic_suspend),
3624 	KOBJMETHOD(device_resume,	bus_generic_resume),
3625 
3626 	/* Bus interface */
3627 	KOBJMETHOD(bus_print_child,	root_print_child),
3628 	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
3629 	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
3630 	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
3631 	KOBJMETHOD(bus_child_present,	root_child_present),
3632 
3633 	{ 0, 0 }
3634 };
3635 
3636 static driver_t root_driver = {
3637 	"root",
3638 	root_methods,
3639 	1,			/* no softc */
3640 };
3641 
3642 device_t	root_bus;
3643 devclass_t	root_devclass;
3644 
3645 static int
3646 root_bus_module_handler(module_t mod, int what, void* arg)
3647 {
3648 	switch (what) {
3649 	case MOD_LOAD:
3650 		TAILQ_INIT(&bus_data_devices);
3651 		kobj_class_compile((kobj_class_t) &root_driver);
3652 		root_bus = make_device(NULL, "root", 0);
3653 		root_bus->desc = "System root bus";
3654 		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
3655 		root_bus->driver = &root_driver;
3656 		root_bus->state = DS_ATTACHED;
3657 		root_devclass = devclass_find_internal("root", 0, FALSE);
3658 		devinit();
3659 		return (0);
3660 
3661 	case MOD_SHUTDOWN:
3662 		device_shutdown(root_bus);
3663 		return (0);
3664 	default:
3665 		return (EOPNOTSUPP);
3666 	}
3667 
3668 	return (0);
3669 }
3670 
3671 static moduledata_t root_bus_mod = {
3672 	"rootbus",
3673 	root_bus_module_handler,
3674 	0
3675 };
3676 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
3677 
3678 /**
3679  * @brief Automatically configure devices
3680  *
3681  * This function begins the autoconfiguration process by calling
3682  * device_probe_and_attach() for each child of the @c root0 device.
3683  */
3684 void
3685 root_bus_configure(void)
3686 {
3687 	device_t dev;
3688 
3689 	PDEBUG(("."));
3690 
3691 	TAILQ_FOREACH(dev, &root_bus->children, link) {
3692 		device_probe_and_attach(dev);
3693 	}
3694 }
3695 
3696 /**
3697  * @brief Module handler for registering device drivers
3698  *
3699  * This module handler is used to automatically register device
3700  * drivers when modules are loaded. If @p what is MOD_LOAD, it calls
3701  * devclass_add_driver() for the driver described by the
3702  * driver_module_data structure pointed to by @p arg
3703  */
3704 int
3705 driver_module_handler(module_t mod, int what, void *arg)
3706 {
3707 	int error;
3708 	struct driver_module_data *dmd;
3709 	devclass_t bus_devclass;
3710 	kobj_class_t driver;
3711 
3712 	dmd = (struct driver_module_data *)arg;
3713 	bus_devclass = devclass_find_internal(dmd->dmd_busname, 0, TRUE);
3714 	error = 0;
3715 
3716 	switch (what) {
3717 	case MOD_LOAD:
3718 		if (dmd->dmd_chainevh)
3719 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3720 
3721 		driver = dmd->dmd_driver;
3722 		PDEBUG(("Loading module: driver %s on bus %s",
3723 		    DRIVERNAME(driver), dmd->dmd_busname));
3724 		error = devclass_add_driver(bus_devclass, driver);
3725 		if (error)
3726 			break;
3727 
3728 		/*
3729 		 * If the driver has any base classes, make the
3730 		 * devclass inherit from the devclass of the driver's
3731 		 * first base class. This will allow the system to
3732 		 * search for drivers in both devclasses for children
3733 		 * of a device using this driver.
3734 		 */
3735 		if (driver->baseclasses) {
3736 			const char *parentname;
3737 			parentname = driver->baseclasses[0]->name;
3738 			*dmd->dmd_devclass =
3739 				devclass_find_internal(driver->name,
3740 				    parentname, TRUE);
3741 		} else {
3742 			*dmd->dmd_devclass =
3743 				devclass_find_internal(driver->name, 0, TRUE);
3744 		}
3745 		break;
3746 
3747 	case MOD_UNLOAD:
3748 		PDEBUG(("Unloading module: driver %s from bus %s",
3749 		    DRIVERNAME(dmd->dmd_driver),
3750 		    dmd->dmd_busname));
3751 		error = devclass_delete_driver(bus_devclass,
3752 		    dmd->dmd_driver);
3753 
3754 		if (!error && dmd->dmd_chainevh)
3755 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3756 		break;
3757 	case MOD_QUIESCE:
3758 		PDEBUG(("Quiesce module: driver %s from bus %s",
3759 		    DRIVERNAME(dmd->dmd_driver),
3760 		    dmd->dmd_busname));
3761 		error = devclass_quiesce_driver(bus_devclass,
3762 		    dmd->dmd_driver);
3763 
3764 		if (!error && dmd->dmd_chainevh)
3765 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3766 		break;
3767 	default:
3768 		error = EOPNOTSUPP;
3769 		break;
3770 	}
3771 
3772 	return (error);
3773 }
3774 
3775 #ifdef BUS_DEBUG
3776 
3777 /* the _short versions avoid iteration by not calling anything that prints
3778  * more than oneliners. I love oneliners.
3779  */
3780 
3781 static void
3782 print_device_short(device_t dev, int indent)
3783 {
3784 	if (!dev)
3785 		return;
3786 
3787 	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
3788 	    dev->unit, dev->desc,
3789 	    (dev->parent? "":"no "),
3790 	    (TAILQ_EMPTY(&dev->children)? "no ":""),
3791 	    (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
3792 	    (dev->flags&DF_FIXEDCLASS? "fixed,":""),
3793 	    (dev->flags&DF_WILDCARD? "wildcard,":""),
3794 	    (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
3795 	    (dev->flags&DF_REBID? "rebiddable,":""),
3796 	    (dev->ivars? "":"no "),
3797 	    (dev->softc? "":"no "),
3798 	    dev->busy));
3799 }
3800 
3801 static void
3802 print_device(device_t dev, int indent)
3803 {
3804 	if (!dev)
3805 		return;
3806 
3807 	print_device_short(dev, indent);
3808 
3809 	indentprintf(("Parent:\n"));
3810 	print_device_short(dev->parent, indent+1);
3811 	indentprintf(("Driver:\n"));
3812 	print_driver_short(dev->driver, indent+1);
3813 	indentprintf(("Devclass:\n"));
3814 	print_devclass_short(dev->devclass, indent+1);
3815 }
3816 
3817 void
3818 print_device_tree_short(device_t dev, int indent)
3819 /* print the device and all its children (indented) */
3820 {
3821 	device_t child;
3822 
3823 	if (!dev)
3824 		return;
3825 
3826 	print_device_short(dev, indent);
3827 
3828 	TAILQ_FOREACH(child, &dev->children, link) {
3829 		print_device_tree_short(child, indent+1);
3830 	}
3831 }
3832 
3833 void
3834 print_device_tree(device_t dev, int indent)
3835 /* print the device and all its children (indented) */
3836 {
3837 	device_t child;
3838 
3839 	if (!dev)
3840 		return;
3841 
3842 	print_device(dev, indent);
3843 
3844 	TAILQ_FOREACH(child, &dev->children, link) {
3845 		print_device_tree(child, indent+1);
3846 	}
3847 }
3848 
3849 static void
3850 print_driver_short(driver_t *driver, int indent)
3851 {
3852 	if (!driver)
3853 		return;
3854 
3855 	indentprintf(("driver %s: softc size = %zd\n",
3856 	    driver->name, driver->size));
3857 }
3858 
3859 static void
3860 print_driver(driver_t *driver, int indent)
3861 {
3862 	if (!driver)
3863 		return;
3864 
3865 	print_driver_short(driver, indent);
3866 }
3867 
3868 
3869 static void
3870 print_driver_list(driver_list_t drivers, int indent)
3871 {
3872 	driverlink_t driver;
3873 
3874 	TAILQ_FOREACH(driver, &drivers, link) {
3875 		print_driver(driver->driver, indent);
3876 	}
3877 }
3878 
3879 static void
3880 print_devclass_short(devclass_t dc, int indent)
3881 {
3882 	if ( !dc )
3883 		return;
3884 
3885 	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
3886 }
3887 
3888 static void
3889 print_devclass(devclass_t dc, int indent)
3890 {
3891 	int i;
3892 
3893 	if ( !dc )
3894 		return;
3895 
3896 	print_devclass_short(dc, indent);
3897 	indentprintf(("Drivers:\n"));
3898 	print_driver_list(dc->drivers, indent+1);
3899 
3900 	indentprintf(("Devices:\n"));
3901 	for (i = 0; i < dc->maxunit; i++)
3902 		if (dc->devices[i])
3903 			print_device(dc->devices[i], indent+1);
3904 }
3905 
3906 void
3907 print_devclass_list_short(void)
3908 {
3909 	devclass_t dc;
3910 
3911 	printf("Short listing of devclasses, drivers & devices:\n");
3912 	TAILQ_FOREACH(dc, &devclasses, link) {
3913 		print_devclass_short(dc, 0);
3914 	}
3915 }
3916 
3917 void
3918 print_devclass_list(void)
3919 {
3920 	devclass_t dc;
3921 
3922 	printf("Full listing of devclasses, drivers & devices:\n");
3923 	TAILQ_FOREACH(dc, &devclasses, link) {
3924 		print_devclass(dc, 0);
3925 	}
3926 }
3927 
3928 #endif
3929 
3930 /*
3931  * User-space access to the device tree.
3932  *
3933  * We implement a small set of nodes:
3934  *
3935  * hw.bus			Single integer read method to obtain the
3936  *				current generation count.
3937  * hw.bus.devices		Reads the entire device tree in flat space.
3938  * hw.bus.rman			Resource manager interface
3939  *
3940  * We might like to add the ability to scan devclasses and/or drivers to
3941  * determine what else is currently loaded/available.
3942  */
3943 
3944 static int
3945 sysctl_bus(SYSCTL_HANDLER_ARGS)
3946 {
3947 	struct u_businfo	ubus;
3948 
3949 	ubus.ub_version = BUS_USER_VERSION;
3950 	ubus.ub_generation = bus_data_generation;
3951 
3952 	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
3953 }
3954 SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
3955     "bus-related data");
3956 
3957 static int
3958 sysctl_devices(SYSCTL_HANDLER_ARGS)
3959 {
3960 	int			*name = (int *)arg1;
3961 	u_int			namelen = arg2;
3962 	int			index;
3963 	struct device		*dev;
3964 	struct u_device		udev;	/* XXX this is a bit big */
3965 	int			error;
3966 
3967 	if (namelen != 2)
3968 		return (EINVAL);
3969 
3970 	if (bus_data_generation_check(name[0]))
3971 		return (EINVAL);
3972 
3973 	index = name[1];
3974 
3975 	/*
3976 	 * Scan the list of devices, looking for the requested index.
3977 	 */
3978 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
3979 		if (index-- == 0)
3980 			break;
3981 	}
3982 	if (dev == NULL)
3983 		return (ENOENT);
3984 
3985 	/*
3986 	 * Populate the return array.
3987 	 */
3988 	bzero(&udev, sizeof(udev));
3989 	udev.dv_handle = (uintptr_t)dev;
3990 	udev.dv_parent = (uintptr_t)dev->parent;
3991 	if (dev->nameunit != NULL)
3992 		strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
3993 	if (dev->desc != NULL)
3994 		strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
3995 	if (dev->driver != NULL && dev->driver->name != NULL)
3996 		strlcpy(udev.dv_drivername, dev->driver->name,
3997 		    sizeof(udev.dv_drivername));
3998 	bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
3999 	bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
4000 	udev.dv_devflags = dev->devflags;
4001 	udev.dv_flags = dev->flags;
4002 	udev.dv_state = dev->state;
4003 	error = SYSCTL_OUT(req, &udev, sizeof(udev));
4004 	return (error);
4005 }
4006 
4007 SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
4008     "system device tree");
4009 
4010 int
4011 bus_data_generation_check(int generation)
4012 {
4013 	if (generation != bus_data_generation)
4014 		return (1);
4015 
4016 	/* XXX generate optimised lists here? */
4017 	return (0);
4018 }
4019 
4020 void
4021 bus_data_generation_update(void)
4022 {
4023 	bus_data_generation++;
4024 }
4025 
4026 int
4027 bus_free_resource(device_t dev, int type, struct resource *r)
4028 {
4029 	if (r == NULL)
4030 		return (0);
4031 	return (bus_release_resource(dev, type, rman_get_rid(r), r));
4032 }
4033