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