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