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