xref: /freebsd/sys/kern/subr_bus.c (revision 6e0da4f753ed6b5d26395001a6194b4fdea70177)
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
1580  *
1581  * @returns		the device with the given unit number or @c
1582  *			NULL if there is no such device
1583  */
1584 device_t
1585 device_find_child(device_t dev, const char *classname, int unit)
1586 {
1587 	devclass_t dc;
1588 	device_t child;
1589 
1590 	dc = devclass_find(classname);
1591 	if (!dc)
1592 		return (NULL);
1593 
1594 	child = devclass_get_device(dc, unit);
1595 	if (child && child->parent == dev)
1596 		return (child);
1597 	return (NULL);
1598 }
1599 
1600 /**
1601  * @internal
1602  */
1603 static driverlink_t
1604 first_matching_driver(devclass_t dc, device_t dev)
1605 {
1606 	if (dev->devclass)
1607 		return (devclass_find_driver_internal(dc, dev->devclass->name));
1608 	return (TAILQ_FIRST(&dc->drivers));
1609 }
1610 
1611 /**
1612  * @internal
1613  */
1614 static driverlink_t
1615 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1616 {
1617 	if (dev->devclass) {
1618 		driverlink_t dl;
1619 		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1620 			if (!strcmp(dev->devclass->name, dl->driver->name))
1621 				return (dl);
1622 		return (NULL);
1623 	}
1624 	return (TAILQ_NEXT(last, link));
1625 }
1626 
1627 /**
1628  * @internal
1629  */
1630 static int
1631 device_probe_child(device_t dev, device_t child)
1632 {
1633 	devclass_t dc;
1634 	driverlink_t best = 0;
1635 	driverlink_t dl;
1636 	int result, pri = 0;
1637 	int hasclass = (child->devclass != 0);
1638 
1639 	GIANT_REQUIRED;
1640 
1641 	dc = dev->devclass;
1642 	if (!dc)
1643 		panic("device_probe_child: parent device has no devclass");
1644 
1645 	/*
1646 	 * If the state is already probed, then return.  However, don't
1647 	 * return if we can rebid this object.
1648 	 */
1649 	if (child->state == DS_ALIVE && (child->flags & DF_REBID) == 0)
1650 		return (0);
1651 
1652 	for (; dc; dc = dc->parent) {
1653 		for (dl = first_matching_driver(dc, child);
1654 		     dl;
1655 		     dl = next_matching_driver(dc, child, dl)) {
1656 			PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1657 			device_set_driver(child, dl->driver);
1658 			if (!hasclass)
1659 				device_set_devclass(child, dl->driver->name);
1660 
1661 			/* Fetch any flags for the device before probing. */
1662 			resource_int_value(dl->driver->name, child->unit,
1663 			    "flags", &child->devflags);
1664 
1665 			result = DEVICE_PROBE(child);
1666 
1667 			/* Reset flags and devclass before the next probe. */
1668 			child->devflags = 0;
1669 			if (!hasclass)
1670 				device_set_devclass(child, 0);
1671 
1672 			/*
1673 			 * If the driver returns SUCCESS, there can be
1674 			 * no higher match for this device.
1675 			 */
1676 			if (result == 0) {
1677 				best = dl;
1678 				pri = 0;
1679 				break;
1680 			}
1681 
1682 			/*
1683 			 * The driver returned an error so it
1684 			 * certainly doesn't match.
1685 			 */
1686 			if (result > 0) {
1687 				device_set_driver(child, 0);
1688 				continue;
1689 			}
1690 
1691 			/*
1692 			 * A priority lower than SUCCESS, remember the
1693 			 * best matching driver. Initialise the value
1694 			 * of pri for the first match.
1695 			 */
1696 			if (best == 0 || result > pri) {
1697 				best = dl;
1698 				pri = result;
1699 				continue;
1700 			}
1701 		}
1702 		/*
1703 		 * If we have an unambiguous match in this devclass,
1704 		 * don't look in the parent.
1705 		 */
1706 		if (best && pri == 0)
1707 			break;
1708 	}
1709 
1710 	/*
1711 	 * If we found a driver, change state and initialise the devclass.
1712 	 */
1713 	/* XXX What happens if we rebid and got no best? */
1714 	if (best) {
1715 		/*
1716 		 * If this device was atached, and we were asked to
1717 		 * rescan, and it is a different driver, then we have
1718 		 * to detach the old driver and reattach this new one.
1719 		 * Note, we don't have to check for DF_REBID here
1720 		 * because if the state is > DS_ALIVE, we know it must
1721 		 * be.
1722 		 *
1723 		 * This assumes that all DF_REBID drivers can have
1724 		 * their probe routine called at any time and that
1725 		 * they are idempotent as well as completely benign in
1726 		 * normal operations.
1727 		 *
1728 		 * We also have to make sure that the detach
1729 		 * succeeded, otherwise we fail the operation (or
1730 		 * maybe it should just fail silently?  I'm torn).
1731 		 */
1732 		if (child->state > DS_ALIVE && best->driver != child->driver)
1733 			if ((result = device_detach(dev)) != 0)
1734 				return (result);
1735 
1736 		/* Set the winning driver, devclass, and flags. */
1737 		if (!child->devclass)
1738 			device_set_devclass(child, best->driver->name);
1739 		device_set_driver(child, best->driver);
1740 		resource_int_value(best->driver->name, child->unit,
1741 		    "flags", &child->devflags);
1742 
1743 		if (pri < 0) {
1744 			/*
1745 			 * A bit bogus. Call the probe method again to make
1746 			 * sure that we have the right description.
1747 			 */
1748 			DEVICE_PROBE(child);
1749 #if 0
1750 			child->flags |= DF_REBID;
1751 #endif
1752 		} else
1753 			child->flags &= ~DF_REBID;
1754 		child->state = DS_ALIVE;
1755 
1756 		bus_data_generation_update();
1757 		return (0);
1758 	}
1759 
1760 	return (ENXIO);
1761 }
1762 
1763 /**
1764  * @brief Return the parent of a device
1765  */
1766 device_t
1767 device_get_parent(device_t dev)
1768 {
1769 	return (dev->parent);
1770 }
1771 
1772 /**
1773  * @brief Get a list of children of a device
1774  *
1775  * An array containing a list of all the children of the given device
1776  * is allocated and returned in @p *devlistp. The number of devices
1777  * in the array is returned in @p *devcountp. The caller should free
1778  * the array using @c free(p, M_TEMP).
1779  *
1780  * @param dev		the device to examine
1781  * @param devlistp	points at location for array pointer return
1782  *			value
1783  * @param devcountp	points at location for array size return value
1784  *
1785  * @retval 0		success
1786  * @retval ENOMEM	the array allocation failed
1787  */
1788 int
1789 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1790 {
1791 	int count;
1792 	device_t child;
1793 	device_t *list;
1794 
1795 	count = 0;
1796 	TAILQ_FOREACH(child, &dev->children, link) {
1797 		count++;
1798 	}
1799 
1800 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1801 	if (!list)
1802 		return (ENOMEM);
1803 
1804 	count = 0;
1805 	TAILQ_FOREACH(child, &dev->children, link) {
1806 		list[count] = child;
1807 		count++;
1808 	}
1809 
1810 	*devlistp = list;
1811 	*devcountp = count;
1812 
1813 	return (0);
1814 }
1815 
1816 /**
1817  * @brief Return the current driver for the device or @c NULL if there
1818  * is no driver currently attached
1819  */
1820 driver_t *
1821 device_get_driver(device_t dev)
1822 {
1823 	return (dev->driver);
1824 }
1825 
1826 /**
1827  * @brief Return the current devclass for the device or @c NULL if
1828  * there is none.
1829  */
1830 devclass_t
1831 device_get_devclass(device_t dev)
1832 {
1833 	return (dev->devclass);
1834 }
1835 
1836 /**
1837  * @brief Return the name of the device's devclass or @c NULL if there
1838  * is none.
1839  */
1840 const char *
1841 device_get_name(device_t dev)
1842 {
1843 	if (dev != NULL && dev->devclass)
1844 		return (devclass_get_name(dev->devclass));
1845 	return (NULL);
1846 }
1847 
1848 /**
1849  * @brief Return a string containing the device's devclass name
1850  * followed by an ascii representation of the device's unit number
1851  * (e.g. @c "foo2").
1852  */
1853 const char *
1854 device_get_nameunit(device_t dev)
1855 {
1856 	return (dev->nameunit);
1857 }
1858 
1859 /**
1860  * @brief Return the device's unit number.
1861  */
1862 int
1863 device_get_unit(device_t dev)
1864 {
1865 	return (dev->unit);
1866 }
1867 
1868 /**
1869  * @brief Return the device's description string
1870  */
1871 const char *
1872 device_get_desc(device_t dev)
1873 {
1874 	return (dev->desc);
1875 }
1876 
1877 /**
1878  * @brief Return the device's flags
1879  */
1880 u_int32_t
1881 device_get_flags(device_t dev)
1882 {
1883 	return (dev->devflags);
1884 }
1885 
1886 struct sysctl_ctx_list *
1887 device_get_sysctl_ctx(device_t dev)
1888 {
1889 	return (&dev->sysctl_ctx);
1890 }
1891 
1892 struct sysctl_oid *
1893 device_get_sysctl_tree(device_t dev)
1894 {
1895 	return (dev->sysctl_tree);
1896 }
1897 
1898 /**
1899  * @brief Print the name of the device followed by a colon and a space
1900  *
1901  * @returns the number of characters printed
1902  */
1903 int
1904 device_print_prettyname(device_t dev)
1905 {
1906 	const char *name = device_get_name(dev);
1907 
1908 	if (name == 0)
1909 		return (printf("unknown: "));
1910 	return (printf("%s%d: ", name, device_get_unit(dev)));
1911 }
1912 
1913 /**
1914  * @brief Print the name of the device followed by a colon, a space
1915  * and the result of calling vprintf() with the value of @p fmt and
1916  * the following arguments.
1917  *
1918  * @returns the number of characters printed
1919  */
1920 int
1921 device_printf(device_t dev, const char * fmt, ...)
1922 {
1923 	va_list ap;
1924 	int retval;
1925 
1926 	retval = device_print_prettyname(dev);
1927 	va_start(ap, fmt);
1928 	retval += vprintf(fmt, ap);
1929 	va_end(ap);
1930 	return (retval);
1931 }
1932 
1933 /**
1934  * @internal
1935  */
1936 static void
1937 device_set_desc_internal(device_t dev, const char* desc, int copy)
1938 {
1939 	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
1940 		free(dev->desc, M_BUS);
1941 		dev->flags &= ~DF_DESCMALLOCED;
1942 		dev->desc = NULL;
1943 	}
1944 
1945 	if (copy && desc) {
1946 		dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
1947 		if (dev->desc) {
1948 			strcpy(dev->desc, desc);
1949 			dev->flags |= DF_DESCMALLOCED;
1950 		}
1951 	} else {
1952 		/* Avoid a -Wcast-qual warning */
1953 		dev->desc = (char *)(uintptr_t) desc;
1954 	}
1955 
1956 	bus_data_generation_update();
1957 }
1958 
1959 /**
1960  * @brief Set the device's description
1961  *
1962  * The value of @c desc should be a string constant that will not
1963  * change (at least until the description is changed in a subsequent
1964  * call to device_set_desc() or device_set_desc_copy()).
1965  */
1966 void
1967 device_set_desc(device_t dev, const char* desc)
1968 {
1969 	device_set_desc_internal(dev, desc, FALSE);
1970 }
1971 
1972 /**
1973  * @brief Set the device's description
1974  *
1975  * The string pointed to by @c desc is copied. Use this function if
1976  * the device description is generated, (e.g. with sprintf()).
1977  */
1978 void
1979 device_set_desc_copy(device_t dev, const char* desc)
1980 {
1981 	device_set_desc_internal(dev, desc, TRUE);
1982 }
1983 
1984 /**
1985  * @brief Set the device's flags
1986  */
1987 void
1988 device_set_flags(device_t dev, u_int32_t flags)
1989 {
1990 	dev->devflags = flags;
1991 }
1992 
1993 /**
1994  * @brief Return the device's softc field
1995  *
1996  * The softc is allocated and zeroed when a driver is attached, based
1997  * on the size field of the driver.
1998  */
1999 void *
2000 device_get_softc(device_t dev)
2001 {
2002 	return (dev->softc);
2003 }
2004 
2005 /**
2006  * @brief Set the device's softc field
2007  *
2008  * Most drivers do not need to use this since the softc is allocated
2009  * automatically when the driver is attached.
2010  */
2011 void
2012 device_set_softc(device_t dev, void *softc)
2013 {
2014 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
2015 		free(dev->softc, M_BUS_SC);
2016 	dev->softc = softc;
2017 	if (dev->softc)
2018 		dev->flags |= DF_EXTERNALSOFTC;
2019 	else
2020 		dev->flags &= ~DF_EXTERNALSOFTC;
2021 }
2022 
2023 /**
2024  * @brief Get the device's ivars field
2025  *
2026  * The ivars field is used by the parent device to store per-device
2027  * state (e.g. the physical location of the device or a list of
2028  * resources).
2029  */
2030 void *
2031 device_get_ivars(device_t dev)
2032 {
2033 
2034 	KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
2035 	return (dev->ivars);
2036 }
2037 
2038 /**
2039  * @brief Set the device's ivars field
2040  */
2041 void
2042 device_set_ivars(device_t dev, void * ivars)
2043 {
2044 
2045 	KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
2046 	dev->ivars = ivars;
2047 }
2048 
2049 /**
2050  * @brief Return the device's state
2051  */
2052 device_state_t
2053 device_get_state(device_t dev)
2054 {
2055 	return (dev->state);
2056 }
2057 
2058 /**
2059  * @brief Set the DF_ENABLED flag for the device
2060  */
2061 void
2062 device_enable(device_t dev)
2063 {
2064 	dev->flags |= DF_ENABLED;
2065 }
2066 
2067 /**
2068  * @brief Clear the DF_ENABLED flag for the device
2069  */
2070 void
2071 device_disable(device_t dev)
2072 {
2073 	dev->flags &= ~DF_ENABLED;
2074 }
2075 
2076 /**
2077  * @brief Increment the busy counter for the device
2078  */
2079 void
2080 device_busy(device_t dev)
2081 {
2082 	if (dev->state < DS_ATTACHED)
2083 		panic("device_busy: called for unattached device");
2084 	if (dev->busy == 0 && dev->parent)
2085 		device_busy(dev->parent);
2086 	dev->busy++;
2087 	dev->state = DS_BUSY;
2088 }
2089 
2090 /**
2091  * @brief Decrement the busy counter for the device
2092  */
2093 void
2094 device_unbusy(device_t dev)
2095 {
2096 	if (dev->state != DS_BUSY)
2097 		panic("device_unbusy: called for non-busy device %s",
2098 		    device_get_nameunit(dev));
2099 	dev->busy--;
2100 	if (dev->busy == 0) {
2101 		if (dev->parent)
2102 			device_unbusy(dev->parent);
2103 		dev->state = DS_ATTACHED;
2104 	}
2105 }
2106 
2107 /**
2108  * @brief Set the DF_QUIET flag for the device
2109  */
2110 void
2111 device_quiet(device_t dev)
2112 {
2113 	dev->flags |= DF_QUIET;
2114 }
2115 
2116 /**
2117  * @brief Clear the DF_QUIET flag for the device
2118  */
2119 void
2120 device_verbose(device_t dev)
2121 {
2122 	dev->flags &= ~DF_QUIET;
2123 }
2124 
2125 /**
2126  * @brief Return non-zero if the DF_QUIET flag is set on the device
2127  */
2128 int
2129 device_is_quiet(device_t dev)
2130 {
2131 	return ((dev->flags & DF_QUIET) != 0);
2132 }
2133 
2134 /**
2135  * @brief Return non-zero if the DF_ENABLED flag is set on the device
2136  */
2137 int
2138 device_is_enabled(device_t dev)
2139 {
2140 	return ((dev->flags & DF_ENABLED) != 0);
2141 }
2142 
2143 /**
2144  * @brief Return non-zero if the device was successfully probed
2145  */
2146 int
2147 device_is_alive(device_t dev)
2148 {
2149 	return (dev->state >= DS_ALIVE);
2150 }
2151 
2152 /**
2153  * @brief Return non-zero if the device currently has a driver
2154  * attached to it
2155  */
2156 int
2157 device_is_attached(device_t dev)
2158 {
2159 	return (dev->state >= DS_ATTACHED);
2160 }
2161 
2162 /**
2163  * @brief Set the devclass of a device
2164  * @see devclass_add_device().
2165  */
2166 int
2167 device_set_devclass(device_t dev, const char *classname)
2168 {
2169 	devclass_t dc;
2170 	int error;
2171 
2172 	if (!classname) {
2173 		if (dev->devclass)
2174 			devclass_delete_device(dev->devclass, dev);
2175 		return (0);
2176 	}
2177 
2178 	if (dev->devclass) {
2179 		printf("device_set_devclass: device class already set\n");
2180 		return (EINVAL);
2181 	}
2182 
2183 	dc = devclass_find_internal(classname, 0, TRUE);
2184 	if (!dc)
2185 		return (ENOMEM);
2186 
2187 	error = devclass_add_device(dc, dev);
2188 
2189 	bus_data_generation_update();
2190 	return (error);
2191 }
2192 
2193 /**
2194  * @brief Set the driver of a device
2195  *
2196  * @retval 0		success
2197  * @retval EBUSY	the device already has a driver attached
2198  * @retval ENOMEM	a memory allocation failure occurred
2199  */
2200 int
2201 device_set_driver(device_t dev, driver_t *driver)
2202 {
2203 	if (dev->state >= DS_ATTACHED)
2204 		return (EBUSY);
2205 
2206 	if (dev->driver == driver)
2207 		return (0);
2208 
2209 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
2210 		free(dev->softc, M_BUS_SC);
2211 		dev->softc = NULL;
2212 	}
2213 	kobj_delete((kobj_t) dev, 0);
2214 	dev->driver = driver;
2215 	if (driver) {
2216 		kobj_init((kobj_t) dev, (kobj_class_t) driver);
2217 		if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
2218 			dev->softc = malloc(driver->size, M_BUS_SC,
2219 			    M_NOWAIT | M_ZERO);
2220 			if (!dev->softc) {
2221 				kobj_delete((kobj_t) dev, 0);
2222 				kobj_init((kobj_t) dev, &null_class);
2223 				dev->driver = NULL;
2224 				return (ENOMEM);
2225 			}
2226 		}
2227 	} else {
2228 		kobj_init((kobj_t) dev, &null_class);
2229 	}
2230 
2231 	bus_data_generation_update();
2232 	return (0);
2233 }
2234 
2235 /**
2236  * @brief Probe a device and attach a driver if possible
2237  *
2238  * This function is the core of the device autoconfiguration
2239  * system. Its purpose is to select a suitable driver for a device and
2240  * then call that driver to initialise the hardware appropriately. The
2241  * driver is selected by calling the DEVICE_PROBE() method of a set of
2242  * candidate drivers and then choosing the driver which returned the
2243  * best value. This driver is then attached to the device using
2244  * device_attach().
2245  *
2246  * The set of suitable drivers is taken from the list of drivers in
2247  * the parent device's devclass. If the device was originally created
2248  * with a specific class name (see device_add_child()), only drivers
2249  * with that name are probed, otherwise all drivers in the devclass
2250  * are probed. If no drivers return successful probe values in the
2251  * parent devclass, the search continues in the parent of that
2252  * devclass (see devclass_get_parent()) if any.
2253  *
2254  * @param dev		the device to initialise
2255  *
2256  * @retval 0		success
2257  * @retval ENXIO	no driver was found
2258  * @retval ENOMEM	memory allocation failure
2259  * @retval non-zero	some other unix error code
2260  */
2261 int
2262 device_probe_and_attach(device_t dev)
2263 {
2264 	int error;
2265 
2266 	GIANT_REQUIRED;
2267 
2268 	if (dev->state >= DS_ALIVE && (dev->flags & DF_REBID) == 0)
2269 		return (0);
2270 
2271 	if (!(dev->flags & DF_ENABLED)) {
2272 		if (bootverbose && device_get_name(dev) != NULL) {
2273 			device_print_prettyname(dev);
2274 			printf("not probed (disabled)\n");
2275 		}
2276 		return (0);
2277 	}
2278 	if ((error = device_probe_child(dev->parent, dev)) != 0) {
2279 		if (!(dev->flags & DF_DONENOMATCH)) {
2280 			BUS_PROBE_NOMATCH(dev->parent, dev);
2281 			devnomatch(dev);
2282 			dev->flags |= DF_DONENOMATCH;
2283 		}
2284 		return (error);
2285 	}
2286 	error = device_attach(dev);
2287 
2288 	return (error);
2289 }
2290 
2291 /**
2292  * @brief Attach a device driver to a device
2293  *
2294  * This function is a wrapper around the DEVICE_ATTACH() driver
2295  * method. In addition to calling DEVICE_ATTACH(), it initialises the
2296  * device's sysctl tree, optionally prints a description of the device
2297  * and queues a notification event for user-based device management
2298  * services.
2299  *
2300  * Normally this function is only called internally from
2301  * device_probe_and_attach().
2302  *
2303  * @param dev		the device to initialise
2304  *
2305  * @retval 0		success
2306  * @retval ENXIO	no driver was found
2307  * @retval ENOMEM	memory allocation failure
2308  * @retval non-zero	some other unix error code
2309  */
2310 int
2311 device_attach(device_t dev)
2312 {
2313 	int error;
2314 
2315 	device_sysctl_init(dev);
2316 	if (!device_is_quiet(dev))
2317 		device_print_child(dev->parent, dev);
2318 	if ((error = DEVICE_ATTACH(dev)) != 0) {
2319 		printf("device_attach: %s%d attach returned %d\n",
2320 		    dev->driver->name, dev->unit, error);
2321 		/* Unset the class; set in device_probe_child */
2322 		if (dev->devclass == 0)
2323 			device_set_devclass(dev, 0);
2324 		device_set_driver(dev, NULL);
2325 		device_sysctl_fini(dev);
2326 		dev->state = DS_NOTPRESENT;
2327 		return (error);
2328 	}
2329 	dev->state = DS_ATTACHED;
2330 	devadded(dev);
2331 	return (0);
2332 }
2333 
2334 /**
2335  * @brief Detach a driver from a device
2336  *
2337  * This function is a wrapper around the DEVICE_DETACH() driver
2338  * method. If the call to DEVICE_DETACH() succeeds, it calls
2339  * BUS_CHILD_DETACHED() for the parent of @p dev, queues a
2340  * notification event for user-based device management services and
2341  * cleans up the device's sysctl tree.
2342  *
2343  * @param dev		the device to un-initialise
2344  *
2345  * @retval 0		success
2346  * @retval ENXIO	no driver was found
2347  * @retval ENOMEM	memory allocation failure
2348  * @retval non-zero	some other unix error code
2349  */
2350 int
2351 device_detach(device_t dev)
2352 {
2353 	int error;
2354 
2355 	GIANT_REQUIRED;
2356 
2357 	PDEBUG(("%s", DEVICENAME(dev)));
2358 	if (dev->state == DS_BUSY)
2359 		return (EBUSY);
2360 	if (dev->state != DS_ATTACHED)
2361 		return (0);
2362 
2363 	if ((error = DEVICE_DETACH(dev)) != 0)
2364 		return (error);
2365 	devremoved(dev);
2366 	device_printf(dev, "detached\n");
2367 	if (dev->parent)
2368 		BUS_CHILD_DETACHED(dev->parent, dev);
2369 
2370 	if (!(dev->flags & DF_FIXEDCLASS))
2371 		devclass_delete_device(dev->devclass, dev);
2372 
2373 	dev->state = DS_NOTPRESENT;
2374 	device_set_driver(dev, NULL);
2375 	device_set_desc(dev, NULL);
2376 	device_sysctl_fini(dev);
2377 
2378 	return (0);
2379 }
2380 
2381 /**
2382  * @brief Tells a driver to quiesce itself.
2383  *
2384  * This function is a wrapper around the DEVICE_QUIESCE() driver
2385  * method. If the call to DEVICE_QUIESCE() succeeds.
2386  *
2387  * @param dev		the device to quiesce
2388  *
2389  * @retval 0		success
2390  * @retval ENXIO	no driver was found
2391  * @retval ENOMEM	memory allocation failure
2392  * @retval non-zero	some other unix error code
2393  */
2394 int
2395 device_quiesce(device_t dev)
2396 {
2397 
2398 	PDEBUG(("%s", DEVICENAME(dev)));
2399 	if (dev->state == DS_BUSY)
2400 		return (EBUSY);
2401 	if (dev->state != DS_ATTACHED)
2402 		return (0);
2403 
2404 	return (DEVICE_QUIESCE(dev));
2405 }
2406 
2407 /**
2408  * @brief Notify a device of system shutdown
2409  *
2410  * This function calls the DEVICE_SHUTDOWN() driver method if the
2411  * device currently has an attached driver.
2412  *
2413  * @returns the value returned by DEVICE_SHUTDOWN()
2414  */
2415 int
2416 device_shutdown(device_t dev)
2417 {
2418 	if (dev->state < DS_ATTACHED)
2419 		return (0);
2420 	return (DEVICE_SHUTDOWN(dev));
2421 }
2422 
2423 /**
2424  * @brief Set the unit number of a device
2425  *
2426  * This function can be used to override the unit number used for a
2427  * device (e.g. to wire a device to a pre-configured unit number).
2428  */
2429 int
2430 device_set_unit(device_t dev, int unit)
2431 {
2432 	devclass_t dc;
2433 	int err;
2434 
2435 	dc = device_get_devclass(dev);
2436 	if (unit < dc->maxunit && dc->devices[unit])
2437 		return (EBUSY);
2438 	err = devclass_delete_device(dc, dev);
2439 	if (err)
2440 		return (err);
2441 	dev->unit = unit;
2442 	err = devclass_add_device(dc, dev);
2443 	if (err)
2444 		return (err);
2445 
2446 	bus_data_generation_update();
2447 	return (0);
2448 }
2449 
2450 /*======================================*/
2451 /*
2452  * Some useful method implementations to make life easier for bus drivers.
2453  */
2454 
2455 /**
2456  * @brief Initialise a resource list.
2457  *
2458  * @param rl		the resource list to initialise
2459  */
2460 void
2461 resource_list_init(struct resource_list *rl)
2462 {
2463 	SLIST_INIT(rl);
2464 }
2465 
2466 /**
2467  * @brief Reclaim memory used by a resource list.
2468  *
2469  * This function frees the memory for all resource entries on the list
2470  * (if any).
2471  *
2472  * @param rl		the resource list to free
2473  */
2474 void
2475 resource_list_free(struct resource_list *rl)
2476 {
2477 	struct resource_list_entry *rle;
2478 
2479 	while ((rle = SLIST_FIRST(rl)) != NULL) {
2480 		if (rle->res)
2481 			panic("resource_list_free: resource entry is busy");
2482 		SLIST_REMOVE_HEAD(rl, link);
2483 		free(rle, M_BUS);
2484 	}
2485 }
2486 
2487 /**
2488  * @brief Add a resource entry.
2489  *
2490  * This function adds a resource entry using the given @p type, @p
2491  * start, @p end and @p count values. A rid value is chosen by
2492  * searching sequentially for the first unused rid starting at zero.
2493  *
2494  * @param rl		the resource list to edit
2495  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2496  * @param start		the start address of the resource
2497  * @param end		the end address of the resource
2498  * @param count		XXX end-start+1
2499  */
2500 int
2501 resource_list_add_next(struct resource_list *rl, int type, u_long start,
2502     u_long end, u_long count)
2503 {
2504 	int rid;
2505 
2506 	rid = 0;
2507 	while (resource_list_find(rl, type, rid) != NULL)
2508 		rid++;
2509 	resource_list_add(rl, type, rid, start, end, count);
2510 	return (rid);
2511 }
2512 
2513 /**
2514  * @brief Add or modify a resource entry.
2515  *
2516  * If an existing entry exists with the same type and rid, it will be
2517  * modified using the given values of @p start, @p end and @p
2518  * count. If no entry exists, a new one will be created using the
2519  * given values.
2520  *
2521  * @param rl		the resource list to edit
2522  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2523  * @param rid		the resource identifier
2524  * @param start		the start address of the resource
2525  * @param end		the end address of the resource
2526  * @param count		XXX end-start+1
2527  */
2528 void
2529 resource_list_add(struct resource_list *rl, int type, int rid,
2530     u_long start, u_long end, u_long count)
2531 {
2532 	struct resource_list_entry *rle;
2533 
2534 	rle = resource_list_find(rl, type, rid);
2535 	if (!rle) {
2536 		rle = malloc(sizeof(struct resource_list_entry), M_BUS,
2537 		    M_NOWAIT);
2538 		if (!rle)
2539 			panic("resource_list_add: can't record entry");
2540 		SLIST_INSERT_HEAD(rl, rle, link);
2541 		rle->type = type;
2542 		rle->rid = rid;
2543 		rle->res = NULL;
2544 	}
2545 
2546 	if (rle->res)
2547 		panic("resource_list_add: resource entry is busy");
2548 
2549 	rle->start = start;
2550 	rle->end = end;
2551 	rle->count = count;
2552 }
2553 
2554 /**
2555  * @brief Find a resource entry by type and rid.
2556  *
2557  * @param rl		the resource list to search
2558  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2559  * @param rid		the resource identifier
2560  *
2561  * @returns the resource entry pointer or NULL if there is no such
2562  * entry.
2563  */
2564 struct resource_list_entry *
2565 resource_list_find(struct resource_list *rl, int type, int rid)
2566 {
2567 	struct resource_list_entry *rle;
2568 
2569 	SLIST_FOREACH(rle, rl, link) {
2570 		if (rle->type == type && rle->rid == rid)
2571 			return (rle);
2572 	}
2573 	return (NULL);
2574 }
2575 
2576 /**
2577  * @brief Delete a resource entry.
2578  *
2579  * @param rl		the resource list to edit
2580  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2581  * @param rid		the resource identifier
2582  */
2583 void
2584 resource_list_delete(struct resource_list *rl, int type, int rid)
2585 {
2586 	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
2587 
2588 	if (rle) {
2589 		if (rle->res != NULL)
2590 			panic("resource_list_delete: resource has not been released");
2591 		SLIST_REMOVE(rl, rle, resource_list_entry, link);
2592 		free(rle, M_BUS);
2593 	}
2594 }
2595 
2596 /**
2597  * @brief Helper function for implementing BUS_ALLOC_RESOURCE()
2598  *
2599  * Implement BUS_ALLOC_RESOURCE() by looking up a resource from the list
2600  * and passing the allocation up to the parent of @p bus. This assumes
2601  * that the first entry of @c device_get_ivars(child) is a struct
2602  * resource_list. This also handles 'passthrough' allocations where a
2603  * child is a remote descendant of bus by passing the allocation up to
2604  * the parent of bus.
2605  *
2606  * Typically, a bus driver would store a list of child resources
2607  * somewhere in the child device's ivars (see device_get_ivars()) and
2608  * its implementation of BUS_ALLOC_RESOURCE() would find that list and
2609  * then call resource_list_alloc() to perform the allocation.
2610  *
2611  * @param rl		the resource list to allocate from
2612  * @param bus		the parent device of @p child
2613  * @param child		the device which is requesting an allocation
2614  * @param type		the type of resource to allocate
2615  * @param rid		a pointer to the resource identifier
2616  * @param start		hint at the start of the resource range - pass
2617  *			@c 0UL for any start address
2618  * @param end		hint at the end of the resource range - pass
2619  *			@c ~0UL for any end address
2620  * @param count		hint at the size of range required - pass @c 1
2621  *			for any size
2622  * @param flags		any extra flags to control the resource
2623  *			allocation - see @c RF_XXX flags in
2624  *			<sys/rman.h> for details
2625  *
2626  * @returns		the resource which was allocated or @c NULL if no
2627  *			resource could be allocated
2628  */
2629 struct resource *
2630 resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
2631     int type, int *rid, u_long start, u_long end, u_long count, u_int flags)
2632 {
2633 	struct resource_list_entry *rle = 0;
2634 	int passthrough = (device_get_parent(child) != bus);
2635 	int isdefault = (start == 0UL && end == ~0UL);
2636 
2637 	if (passthrough) {
2638 		return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2639 		    type, rid, start, end, count, flags));
2640 	}
2641 
2642 	rle = resource_list_find(rl, type, *rid);
2643 
2644 	if (!rle)
2645 		return (NULL);		/* no resource of that type/rid */
2646 
2647 	if (rle->res)
2648 		panic("resource_list_alloc: resource entry is busy");
2649 
2650 	if (isdefault) {
2651 		start = rle->start;
2652 		count = ulmax(count, rle->count);
2653 		end = ulmax(rle->end, start + count - 1);
2654 	}
2655 
2656 	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2657 	    type, rid, start, end, count, flags);
2658 
2659 	/*
2660 	 * Record the new range.
2661 	 */
2662 	if (rle->res) {
2663 		rle->start = rman_get_start(rle->res);
2664 		rle->end = rman_get_end(rle->res);
2665 		rle->count = count;
2666 	}
2667 
2668 	return (rle->res);
2669 }
2670 
2671 /**
2672  * @brief Helper function for implementing BUS_RELEASE_RESOURCE()
2673  *
2674  * Implement BUS_RELEASE_RESOURCE() using a resource list. Normally
2675  * used with resource_list_alloc().
2676  *
2677  * @param rl		the resource list which was allocated from
2678  * @param bus		the parent device of @p child
2679  * @param child		the device which is requesting a release
2680  * @param type		the type of resource to allocate
2681  * @param rid		the resource identifier
2682  * @param res		the resource to release
2683  *
2684  * @retval 0		success
2685  * @retval non-zero	a standard unix error code indicating what
2686  *			error condition prevented the operation
2687  */
2688 int
2689 resource_list_release(struct resource_list *rl, device_t bus, device_t child,
2690     int type, int rid, struct resource *res)
2691 {
2692 	struct resource_list_entry *rle = 0;
2693 	int passthrough = (device_get_parent(child) != bus);
2694 	int error;
2695 
2696 	if (passthrough) {
2697 		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2698 		    type, rid, res));
2699 	}
2700 
2701 	rle = resource_list_find(rl, type, rid);
2702 
2703 	if (!rle)
2704 		panic("resource_list_release: can't find resource");
2705 	if (!rle->res)
2706 		panic("resource_list_release: resource entry is not busy");
2707 
2708 	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2709 	    type, rid, res);
2710 	if (error)
2711 		return (error);
2712 
2713 	rle->res = NULL;
2714 	return (0);
2715 }
2716 
2717 /**
2718  * @brief Print a description of resources in a resource list
2719  *
2720  * Print all resources of a specified type, for use in BUS_PRINT_CHILD().
2721  * The name is printed if at least one resource of the given type is available.
2722  * The format is used to print resource start and end.
2723  *
2724  * @param rl		the resource list to print
2725  * @param name		the name of @p type, e.g. @c "memory"
2726  * @param type		type type of resource entry to print
2727  * @param format	printf(9) format string to print resource
2728  *			start and end values
2729  *
2730  * @returns		the number of characters printed
2731  */
2732 int
2733 resource_list_print_type(struct resource_list *rl, const char *name, int type,
2734     const char *format)
2735 {
2736 	struct resource_list_entry *rle;
2737 	int printed, retval;
2738 
2739 	printed = 0;
2740 	retval = 0;
2741 	/* Yes, this is kinda cheating */
2742 	SLIST_FOREACH(rle, rl, link) {
2743 		if (rle->type == type) {
2744 			if (printed == 0)
2745 				retval += printf(" %s ", name);
2746 			else
2747 				retval += printf(",");
2748 			printed++;
2749 			retval += printf(format, rle->start);
2750 			if (rle->count > 1) {
2751 				retval += printf("-");
2752 				retval += printf(format, rle->start +
2753 						 rle->count - 1);
2754 			}
2755 		}
2756 	}
2757 	return (retval);
2758 }
2759 
2760 /**
2761  * @brief Helper function for implementing DEVICE_PROBE()
2762  *
2763  * This function can be used to help implement the DEVICE_PROBE() for
2764  * a bus (i.e. a device which has other devices attached to it). It
2765  * calls the DEVICE_IDENTIFY() method of each driver in the device's
2766  * devclass.
2767  */
2768 int
2769 bus_generic_probe(device_t dev)
2770 {
2771 	devclass_t dc = dev->devclass;
2772 	driverlink_t dl;
2773 
2774 	TAILQ_FOREACH(dl, &dc->drivers, link) {
2775 		DEVICE_IDENTIFY(dl->driver, dev);
2776 	}
2777 
2778 	return (0);
2779 }
2780 
2781 /**
2782  * @brief Helper function for implementing DEVICE_ATTACH()
2783  *
2784  * This function can be used to help implement the DEVICE_ATTACH() for
2785  * a bus. It calls device_probe_and_attach() for each of the device's
2786  * children.
2787  */
2788 int
2789 bus_generic_attach(device_t dev)
2790 {
2791 	device_t child;
2792 
2793 	TAILQ_FOREACH(child, &dev->children, link) {
2794 		device_probe_and_attach(child);
2795 	}
2796 
2797 	return (0);
2798 }
2799 
2800 /**
2801  * @brief Helper function for implementing DEVICE_DETACH()
2802  *
2803  * This function can be used to help implement the DEVICE_DETACH() for
2804  * a bus. It calls device_detach() for each of the device's
2805  * children.
2806  */
2807 int
2808 bus_generic_detach(device_t dev)
2809 {
2810 	device_t child;
2811 	int error;
2812 
2813 	if (dev->state != DS_ATTACHED)
2814 		return (EBUSY);
2815 
2816 	TAILQ_FOREACH(child, &dev->children, link) {
2817 		if ((error = device_detach(child)) != 0)
2818 			return (error);
2819 	}
2820 
2821 	return (0);
2822 }
2823 
2824 /**
2825  * @brief Helper function for implementing DEVICE_SHUTDOWN()
2826  *
2827  * This function can be used to help implement the DEVICE_SHUTDOWN()
2828  * for a bus. It calls device_shutdown() for each of the device's
2829  * children.
2830  */
2831 int
2832 bus_generic_shutdown(device_t dev)
2833 {
2834 	device_t child;
2835 
2836 	TAILQ_FOREACH(child, &dev->children, link) {
2837 		device_shutdown(child);
2838 	}
2839 
2840 	return (0);
2841 }
2842 
2843 /**
2844  * @brief Helper function for implementing DEVICE_SUSPEND()
2845  *
2846  * This function can be used to help implement the DEVICE_SUSPEND()
2847  * for a bus. It calls DEVICE_SUSPEND() for each of the device's
2848  * children. If any call to DEVICE_SUSPEND() fails, the suspend
2849  * operation is aborted and any devices which were suspended are
2850  * resumed immediately by calling their DEVICE_RESUME() methods.
2851  */
2852 int
2853 bus_generic_suspend(device_t dev)
2854 {
2855 	int		error;
2856 	device_t	child, child2;
2857 
2858 	TAILQ_FOREACH(child, &dev->children, link) {
2859 		error = DEVICE_SUSPEND(child);
2860 		if (error) {
2861 			for (child2 = TAILQ_FIRST(&dev->children);
2862 			     child2 && child2 != child;
2863 			     child2 = TAILQ_NEXT(child2, link))
2864 				DEVICE_RESUME(child2);
2865 			return (error);
2866 		}
2867 	}
2868 	return (0);
2869 }
2870 
2871 /**
2872  * @brief Helper function for implementing DEVICE_RESUME()
2873  *
2874  * This function can be used to help implement the DEVICE_RESUME() for
2875  * a bus. It calls DEVICE_RESUME() on each of the device's children.
2876  */
2877 int
2878 bus_generic_resume(device_t dev)
2879 {
2880 	device_t	child;
2881 
2882 	TAILQ_FOREACH(child, &dev->children, link) {
2883 		DEVICE_RESUME(child);
2884 		/* if resume fails, there's nothing we can usefully do... */
2885 	}
2886 	return (0);
2887 }
2888 
2889 /**
2890  * @brief Helper function for implementing BUS_PRINT_CHILD().
2891  *
2892  * This function prints the first part of the ascii representation of
2893  * @p child, including its name, unit and description (if any - see
2894  * device_set_desc()).
2895  *
2896  * @returns the number of characters printed
2897  */
2898 int
2899 bus_print_child_header(device_t dev, device_t child)
2900 {
2901 	int	retval = 0;
2902 
2903 	if (device_get_desc(child)) {
2904 		retval += device_printf(child, "<%s>", device_get_desc(child));
2905 	} else {
2906 		retval += printf("%s", device_get_nameunit(child));
2907 	}
2908 
2909 	return (retval);
2910 }
2911 
2912 /**
2913  * @brief Helper function for implementing BUS_PRINT_CHILD().
2914  *
2915  * This function prints the last part of the ascii representation of
2916  * @p child, which consists of the string @c " on " followed by the
2917  * name and unit of the @p dev.
2918  *
2919  * @returns the number of characters printed
2920  */
2921 int
2922 bus_print_child_footer(device_t dev, device_t child)
2923 {
2924 	return (printf(" on %s\n", device_get_nameunit(dev)));
2925 }
2926 
2927 /**
2928  * @brief Helper function for implementing BUS_PRINT_CHILD().
2929  *
2930  * This function simply calls bus_print_child_header() followed by
2931  * bus_print_child_footer().
2932  *
2933  * @returns the number of characters printed
2934  */
2935 int
2936 bus_generic_print_child(device_t dev, device_t child)
2937 {
2938 	int	retval = 0;
2939 
2940 	retval += bus_print_child_header(dev, child);
2941 	retval += bus_print_child_footer(dev, child);
2942 
2943 	return (retval);
2944 }
2945 
2946 /**
2947  * @brief Stub function for implementing BUS_READ_IVAR().
2948  *
2949  * @returns ENOENT
2950  */
2951 int
2952 bus_generic_read_ivar(device_t dev, device_t child, int index,
2953     uintptr_t * result)
2954 {
2955 	return (ENOENT);
2956 }
2957 
2958 /**
2959  * @brief Stub function for implementing BUS_WRITE_IVAR().
2960  *
2961  * @returns ENOENT
2962  */
2963 int
2964 bus_generic_write_ivar(device_t dev, device_t child, int index,
2965     uintptr_t value)
2966 {
2967 	return (ENOENT);
2968 }
2969 
2970 /**
2971  * @brief Stub function for implementing BUS_GET_RESOURCE_LIST().
2972  *
2973  * @returns NULL
2974  */
2975 struct resource_list *
2976 bus_generic_get_resource_list(device_t dev, device_t child)
2977 {
2978 	return (NULL);
2979 }
2980 
2981 /**
2982  * @brief Helper function for implementing BUS_DRIVER_ADDED().
2983  *
2984  * This implementation of BUS_DRIVER_ADDED() simply calls the driver's
2985  * DEVICE_IDENTIFY() method to allow it to add new children to the bus
2986  * and then calls device_probe_and_attach() for each unattached child.
2987  */
2988 void
2989 bus_generic_driver_added(device_t dev, driver_t *driver)
2990 {
2991 	device_t child;
2992 
2993 	DEVICE_IDENTIFY(driver, dev);
2994 	TAILQ_FOREACH(child, &dev->children, link) {
2995 		if (child->state == DS_NOTPRESENT ||
2996 		    (child->flags & DF_REBID))
2997 			device_probe_and_attach(child);
2998 	}
2999 }
3000 
3001 /**
3002  * @brief Helper function for implementing BUS_SETUP_INTR().
3003  *
3004  * This simple implementation of BUS_SETUP_INTR() simply calls the
3005  * BUS_SETUP_INTR() method of the parent of @p dev.
3006  */
3007 int
3008 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
3009     int flags, driver_intr_t *intr, void *arg, void **cookiep)
3010 {
3011 	/* Propagate up the bus hierarchy until someone handles it. */
3012 	if (dev->parent)
3013 		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
3014 		    intr, arg, cookiep));
3015 	return (EINVAL);
3016 }
3017 
3018 /**
3019  * @brief Helper function for implementing BUS_TEARDOWN_INTR().
3020  *
3021  * This simple implementation of BUS_TEARDOWN_INTR() simply calls the
3022  * BUS_TEARDOWN_INTR() method of the parent of @p dev.
3023  */
3024 int
3025 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
3026     void *cookie)
3027 {
3028 	/* Propagate up the bus hierarchy until someone handles it. */
3029 	if (dev->parent)
3030 		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
3031 	return (EINVAL);
3032 }
3033 
3034 /**
3035  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3036  *
3037  * This simple implementation of BUS_ALLOC_RESOURCE() simply calls the
3038  * BUS_ALLOC_RESOURCE() method of the parent of @p dev.
3039  */
3040 struct resource *
3041 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
3042     u_long start, u_long end, u_long count, u_int flags)
3043 {
3044 	/* Propagate up the bus hierarchy until someone handles it. */
3045 	if (dev->parent)
3046 		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
3047 		    start, end, count, flags));
3048 	return (NULL);
3049 }
3050 
3051 /**
3052  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3053  *
3054  * This simple implementation of BUS_RELEASE_RESOURCE() simply calls the
3055  * BUS_RELEASE_RESOURCE() method of the parent of @p dev.
3056  */
3057 int
3058 bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
3059     struct resource *r)
3060 {
3061 	/* Propagate up the bus hierarchy until someone handles it. */
3062 	if (dev->parent)
3063 		return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
3064 		    r));
3065 	return (EINVAL);
3066 }
3067 
3068 /**
3069  * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
3070  *
3071  * This simple implementation of BUS_ACTIVATE_RESOURCE() simply calls the
3072  * BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
3073  */
3074 int
3075 bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
3076     struct resource *r)
3077 {
3078 	/* Propagate up the bus hierarchy until someone handles it. */
3079 	if (dev->parent)
3080 		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
3081 		    r));
3082 	return (EINVAL);
3083 }
3084 
3085 /**
3086  * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
3087  *
3088  * This simple implementation of BUS_DEACTIVATE_RESOURCE() simply calls the
3089  * BUS_DEACTIVATE_RESOURCE() method of the parent of @p dev.
3090  */
3091 int
3092 bus_generic_deactivate_resource(device_t dev, device_t child, int type,
3093     int rid, struct resource *r)
3094 {
3095 	/* Propagate up the bus hierarchy until someone handles it. */
3096 	if (dev->parent)
3097 		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
3098 		    r));
3099 	return (EINVAL);
3100 }
3101 
3102 /**
3103  * @brief Helper function for implementing BUS_CONFIG_INTR().
3104  *
3105  * This simple implementation of BUS_CONFIG_INTR() simply calls the
3106  * BUS_CONFIG_INTR() method of the parent of @p dev.
3107  */
3108 int
3109 bus_generic_config_intr(device_t dev, int irq, enum intr_trigger trig,
3110     enum intr_polarity pol)
3111 {
3112 
3113 	/* Propagate up the bus hierarchy until someone handles it. */
3114 	if (dev->parent)
3115 		return (BUS_CONFIG_INTR(dev->parent, irq, trig, pol));
3116 	return (EINVAL);
3117 }
3118 
3119 /**
3120  * @brief Helper function for implementing BUS_GET_RESOURCE().
3121  *
3122  * This implementation of BUS_GET_RESOURCE() uses the
3123  * resource_list_find() function to do most of the work. It calls
3124  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3125  * search.
3126  */
3127 int
3128 bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
3129     u_long *startp, u_long *countp)
3130 {
3131 	struct resource_list *		rl = NULL;
3132 	struct resource_list_entry *	rle = NULL;
3133 
3134 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3135 	if (!rl)
3136 		return (EINVAL);
3137 
3138 	rle = resource_list_find(rl, type, rid);
3139 	if (!rle)
3140 		return (ENOENT);
3141 
3142 	if (startp)
3143 		*startp = rle->start;
3144 	if (countp)
3145 		*countp = rle->count;
3146 
3147 	return (0);
3148 }
3149 
3150 /**
3151  * @brief Helper function for implementing BUS_SET_RESOURCE().
3152  *
3153  * This implementation of BUS_SET_RESOURCE() uses the
3154  * resource_list_add() function to do most of the work. It calls
3155  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3156  * edit.
3157  */
3158 int
3159 bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
3160     u_long start, u_long count)
3161 {
3162 	struct resource_list *		rl = NULL;
3163 
3164 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3165 	if (!rl)
3166 		return (EINVAL);
3167 
3168 	resource_list_add(rl, type, rid, start, (start + count - 1), count);
3169 
3170 	return (0);
3171 }
3172 
3173 /**
3174  * @brief Helper function for implementing BUS_DELETE_RESOURCE().
3175  *
3176  * This implementation of BUS_DELETE_RESOURCE() uses the
3177  * resource_list_delete() function to do most of the work. It calls
3178  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3179  * edit.
3180  */
3181 void
3182 bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
3183 {
3184 	struct resource_list *		rl = NULL;
3185 
3186 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3187 	if (!rl)
3188 		return;
3189 
3190 	resource_list_delete(rl, type, rid);
3191 
3192 	return;
3193 }
3194 
3195 /**
3196  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3197  *
3198  * This implementation of BUS_RELEASE_RESOURCE() uses the
3199  * resource_list_release() function to do most of the work. It calls
3200  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3201  */
3202 int
3203 bus_generic_rl_release_resource(device_t dev, device_t child, int type,
3204     int rid, struct resource *r)
3205 {
3206 	struct resource_list *		rl = NULL;
3207 
3208 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3209 	if (!rl)
3210 		return (EINVAL);
3211 
3212 	return (resource_list_release(rl, dev, child, type, rid, r));
3213 }
3214 
3215 /**
3216  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3217  *
3218  * This implementation of BUS_ALLOC_RESOURCE() uses the
3219  * resource_list_alloc() function to do most of the work. It calls
3220  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3221  */
3222 struct resource *
3223 bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
3224     int *rid, u_long start, u_long end, u_long count, u_int flags)
3225 {
3226 	struct resource_list *		rl = NULL;
3227 
3228 	rl = BUS_GET_RESOURCE_LIST(dev, child);
3229 	if (!rl)
3230 		return (NULL);
3231 
3232 	return (resource_list_alloc(rl, dev, child, type, rid,
3233 	    start, end, count, flags));
3234 }
3235 
3236 /**
3237  * @brief Helper function for implementing BUS_CHILD_PRESENT().
3238  *
3239  * This simple implementation of BUS_CHILD_PRESENT() simply calls the
3240  * BUS_CHILD_PRESENT() method of the parent of @p dev.
3241  */
3242 int
3243 bus_generic_child_present(device_t dev, device_t child)
3244 {
3245 	return (BUS_CHILD_PRESENT(device_get_parent(dev), dev));
3246 }
3247 
3248 /*
3249  * Some convenience functions to make it easier for drivers to use the
3250  * resource-management functions.  All these really do is hide the
3251  * indirection through the parent's method table, making for slightly
3252  * less-wordy code.  In the future, it might make sense for this code
3253  * to maintain some sort of a list of resources allocated by each device.
3254  */
3255 
3256 /**
3257  * @brief Wrapper function for BUS_ALLOC_RESOURCE().
3258  *
3259  * This function simply calls the BUS_ALLOC_RESOURCE() method of the
3260  * parent of @p dev.
3261  */
3262 struct resource *
3263 bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
3264     u_long count, u_int flags)
3265 {
3266 	if (dev->parent == 0)
3267 		return (0);
3268 	return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
3269 	    count, flags));
3270 }
3271 
3272 /**
3273  * @brief Wrapper function for BUS_ACTIVATE_RESOURCE().
3274  *
3275  * This function simply calls the BUS_ACTIVATE_RESOURCE() method of the
3276  * parent of @p dev.
3277  */
3278 int
3279 bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
3280 {
3281 	if (dev->parent == 0)
3282 		return (EINVAL);
3283 	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
3284 }
3285 
3286 /**
3287  * @brief Wrapper function for BUS_DEACTIVATE_RESOURCE().
3288  *
3289  * This function simply calls the BUS_DEACTIVATE_RESOURCE() method of the
3290  * parent of @p dev.
3291  */
3292 int
3293 bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
3294 {
3295 	if (dev->parent == 0)
3296 		return (EINVAL);
3297 	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
3298 }
3299 
3300 /**
3301  * @brief Wrapper function for BUS_RELEASE_RESOURCE().
3302  *
3303  * This function simply calls the BUS_RELEASE_RESOURCE() method of the
3304  * parent of @p dev.
3305  */
3306 int
3307 bus_release_resource(device_t dev, int type, int rid, struct resource *r)
3308 {
3309 	if (dev->parent == 0)
3310 		return (EINVAL);
3311 	return (BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
3312 }
3313 
3314 /**
3315  * @brief Wrapper function for BUS_SETUP_INTR().
3316  *
3317  * This function simply calls the BUS_SETUP_INTR() method of the
3318  * parent of @p dev.
3319  */
3320 int
3321 bus_setup_intr(device_t dev, struct resource *r, int flags,
3322     driver_intr_t handler, void *arg, void **cookiep)
3323 {
3324 	int error;
3325 
3326 	if (dev->parent != 0) {
3327 		if ((flags &~ INTR_ENTROPY) == (INTR_TYPE_NET | INTR_MPSAFE) &&
3328 		    !debug_mpsafenet)
3329 			flags &= ~INTR_MPSAFE;
3330 		error = BUS_SETUP_INTR(dev->parent, dev, r, flags,
3331 		    handler, arg, cookiep);
3332 		if (error == 0) {
3333 			if (!(flags & (INTR_MPSAFE | INTR_FAST)))
3334 				device_printf(dev, "[GIANT-LOCKED]\n");
3335 			if (bootverbose && (flags & INTR_MPSAFE))
3336 				device_printf(dev, "[MPSAFE]\n");
3337 			if (flags & INTR_FAST)
3338 				device_printf(dev, "[FAST]\n");
3339 		}
3340 	} else
3341 		error = EINVAL;
3342 	return (error);
3343 }
3344 
3345 /**
3346  * @brief Wrapper function for BUS_TEARDOWN_INTR().
3347  *
3348  * This function simply calls the BUS_TEARDOWN_INTR() method of the
3349  * parent of @p dev.
3350  */
3351 int
3352 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
3353 {
3354 	if (dev->parent == 0)
3355 		return (EINVAL);
3356 	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
3357 }
3358 
3359 /**
3360  * @brief Wrapper function for BUS_SET_RESOURCE().
3361  *
3362  * This function simply calls the BUS_SET_RESOURCE() method of the
3363  * parent of @p dev.
3364  */
3365 int
3366 bus_set_resource(device_t dev, int type, int rid,
3367     u_long start, u_long count)
3368 {
3369 	return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
3370 	    start, count));
3371 }
3372 
3373 /**
3374  * @brief Wrapper function for BUS_GET_RESOURCE().
3375  *
3376  * This function simply calls the BUS_GET_RESOURCE() method of the
3377  * parent of @p dev.
3378  */
3379 int
3380 bus_get_resource(device_t dev, int type, int rid,
3381     u_long *startp, u_long *countp)
3382 {
3383 	return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3384 	    startp, countp));
3385 }
3386 
3387 /**
3388  * @brief Wrapper function for BUS_GET_RESOURCE().
3389  *
3390  * This function simply calls the BUS_GET_RESOURCE() method of the
3391  * parent of @p dev and returns the start value.
3392  */
3393 u_long
3394 bus_get_resource_start(device_t dev, int type, int rid)
3395 {
3396 	u_long start, count;
3397 	int error;
3398 
3399 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3400 	    &start, &count);
3401 	if (error)
3402 		return (0);
3403 	return (start);
3404 }
3405 
3406 /**
3407  * @brief Wrapper function for BUS_GET_RESOURCE().
3408  *
3409  * This function simply calls the BUS_GET_RESOURCE() method of the
3410  * parent of @p dev and returns the count value.
3411  */
3412 u_long
3413 bus_get_resource_count(device_t dev, int type, int rid)
3414 {
3415 	u_long start, count;
3416 	int error;
3417 
3418 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3419 	    &start, &count);
3420 	if (error)
3421 		return (0);
3422 	return (count);
3423 }
3424 
3425 /**
3426  * @brief Wrapper function for BUS_DELETE_RESOURCE().
3427  *
3428  * This function simply calls the BUS_DELETE_RESOURCE() method of the
3429  * parent of @p dev.
3430  */
3431 void
3432 bus_delete_resource(device_t dev, int type, int rid)
3433 {
3434 	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
3435 }
3436 
3437 /**
3438  * @brief Wrapper function for BUS_CHILD_PRESENT().
3439  *
3440  * This function simply calls the BUS_CHILD_PRESENT() method of the
3441  * parent of @p dev.
3442  */
3443 int
3444 bus_child_present(device_t child)
3445 {
3446 	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
3447 }
3448 
3449 /**
3450  * @brief Wrapper function for BUS_CHILD_PNPINFO_STR().
3451  *
3452  * This function simply calls the BUS_CHILD_PNPINFO_STR() method of the
3453  * parent of @p dev.
3454  */
3455 int
3456 bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
3457 {
3458 	device_t parent;
3459 
3460 	parent = device_get_parent(child);
3461 	if (parent == NULL) {
3462 		*buf = '\0';
3463 		return (0);
3464 	}
3465 	return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
3466 }
3467 
3468 /**
3469  * @brief Wrapper function for BUS_CHILD_LOCATION_STR().
3470  *
3471  * This function simply calls the BUS_CHILD_LOCATION_STR() method of the
3472  * parent of @p dev.
3473  */
3474 int
3475 bus_child_location_str(device_t child, char *buf, size_t buflen)
3476 {
3477 	device_t parent;
3478 
3479 	parent = device_get_parent(child);
3480 	if (parent == NULL) {
3481 		*buf = '\0';
3482 		return (0);
3483 	}
3484 	return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
3485 }
3486 
3487 static int
3488 root_print_child(device_t dev, device_t child)
3489 {
3490 	int	retval = 0;
3491 
3492 	retval += bus_print_child_header(dev, child);
3493 	retval += printf("\n");
3494 
3495 	return (retval);
3496 }
3497 
3498 static int
3499 root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
3500     void **cookiep)
3501 {
3502 	/*
3503 	 * If an interrupt mapping gets to here something bad has happened.
3504 	 */
3505 	panic("root_setup_intr");
3506 }
3507 
3508 /*
3509  * If we get here, assume that the device is permanant and really is
3510  * present in the system.  Removable bus drivers are expected to intercept
3511  * this call long before it gets here.  We return -1 so that drivers that
3512  * really care can check vs -1 or some ERRNO returned higher in the food
3513  * chain.
3514  */
3515 static int
3516 root_child_present(device_t dev, device_t child)
3517 {
3518 	return (-1);
3519 }
3520 
3521 static kobj_method_t root_methods[] = {
3522 	/* Device interface */
3523 	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
3524 	KOBJMETHOD(device_suspend,	bus_generic_suspend),
3525 	KOBJMETHOD(device_resume,	bus_generic_resume),
3526 
3527 	/* Bus interface */
3528 	KOBJMETHOD(bus_print_child,	root_print_child),
3529 	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
3530 	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
3531 	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
3532 	KOBJMETHOD(bus_child_present,	root_child_present),
3533 
3534 	{ 0, 0 }
3535 };
3536 
3537 static driver_t root_driver = {
3538 	"root",
3539 	root_methods,
3540 	1,			/* no softc */
3541 };
3542 
3543 device_t	root_bus;
3544 devclass_t	root_devclass;
3545 
3546 static int
3547 root_bus_module_handler(module_t mod, int what, void* arg)
3548 {
3549 	switch (what) {
3550 	case MOD_LOAD:
3551 		TAILQ_INIT(&bus_data_devices);
3552 		kobj_class_compile((kobj_class_t) &root_driver);
3553 		root_bus = make_device(NULL, "root", 0);
3554 		root_bus->desc = "System root bus";
3555 		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
3556 		root_bus->driver = &root_driver;
3557 		root_bus->state = DS_ATTACHED;
3558 		root_devclass = devclass_find_internal("root", 0, FALSE);
3559 		devinit();
3560 		return (0);
3561 
3562 	case MOD_SHUTDOWN:
3563 		device_shutdown(root_bus);
3564 		return (0);
3565 	default:
3566 		return (EOPNOTSUPP);
3567 	}
3568 
3569 	return (0);
3570 }
3571 
3572 static moduledata_t root_bus_mod = {
3573 	"rootbus",
3574 	root_bus_module_handler,
3575 	0
3576 };
3577 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
3578 
3579 /**
3580  * @brief Automatically configure devices
3581  *
3582  * This function begins the autoconfiguration process by calling
3583  * device_probe_and_attach() for each child of the @c root0 device.
3584  */
3585 void
3586 root_bus_configure(void)
3587 {
3588 	device_t dev;
3589 
3590 	PDEBUG(("."));
3591 
3592 	TAILQ_FOREACH(dev, &root_bus->children, link) {
3593 		device_probe_and_attach(dev);
3594 	}
3595 }
3596 
3597 /**
3598  * @brief Module handler for registering device drivers
3599  *
3600  * This module handler is used to automatically register device
3601  * drivers when modules are loaded. If @p what is MOD_LOAD, it calls
3602  * devclass_add_driver() for the driver described by the
3603  * driver_module_data structure pointed to by @p arg
3604  */
3605 int
3606 driver_module_handler(module_t mod, int what, void *arg)
3607 {
3608 	int error;
3609 	struct driver_module_data *dmd;
3610 	devclass_t bus_devclass;
3611 	kobj_class_t driver;
3612 
3613 	dmd = (struct driver_module_data *)arg;
3614 	bus_devclass = devclass_find_internal(dmd->dmd_busname, 0, TRUE);
3615 	error = 0;
3616 
3617 	switch (what) {
3618 	case MOD_LOAD:
3619 		if (dmd->dmd_chainevh)
3620 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3621 
3622 		driver = dmd->dmd_driver;
3623 		PDEBUG(("Loading module: driver %s on bus %s",
3624 		    DRIVERNAME(driver), dmd->dmd_busname));
3625 		error = devclass_add_driver(bus_devclass, driver);
3626 		if (error)
3627 			break;
3628 
3629 		/*
3630 		 * If the driver has any base classes, make the
3631 		 * devclass inherit from the devclass of the driver's
3632 		 * first base class. This will allow the system to
3633 		 * search for drivers in both devclasses for children
3634 		 * of a device using this driver.
3635 		 */
3636 		if (driver->baseclasses) {
3637 			const char *parentname;
3638 			parentname = driver->baseclasses[0]->name;
3639 			*dmd->dmd_devclass =
3640 				devclass_find_internal(driver->name,
3641 				    parentname, TRUE);
3642 		} else {
3643 			*dmd->dmd_devclass =
3644 				devclass_find_internal(driver->name, 0, TRUE);
3645 		}
3646 		break;
3647 
3648 	case MOD_UNLOAD:
3649 		PDEBUG(("Unloading module: driver %s from bus %s",
3650 		    DRIVERNAME(dmd->dmd_driver),
3651 		    dmd->dmd_busname));
3652 		error = devclass_delete_driver(bus_devclass,
3653 		    dmd->dmd_driver);
3654 
3655 		if (!error && dmd->dmd_chainevh)
3656 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3657 		break;
3658 	case MOD_QUIESCE:
3659 		PDEBUG(("Quiesce module: driver %s from bus %s",
3660 		    DRIVERNAME(dmd->dmd_driver),
3661 		    dmd->dmd_busname));
3662 		error = devclass_quiesce_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 	default:
3669 		error = EOPNOTSUPP;
3670 		break;
3671 	}
3672 
3673 	return (error);
3674 }
3675 
3676 #ifdef BUS_DEBUG
3677 
3678 /* the _short versions avoid iteration by not calling anything that prints
3679  * more than oneliners. I love oneliners.
3680  */
3681 
3682 static void
3683 print_device_short(device_t dev, int indent)
3684 {
3685 	if (!dev)
3686 		return;
3687 
3688 	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
3689 	    dev->unit, dev->desc,
3690 	    (dev->parent? "":"no "),
3691 	    (TAILQ_EMPTY(&dev->children)? "no ":""),
3692 	    (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
3693 	    (dev->flags&DF_FIXEDCLASS? "fixed,":""),
3694 	    (dev->flags&DF_WILDCARD? "wildcard,":""),
3695 	    (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
3696 	    (dev->flags&DF_REBID? "rebiddable,":""),
3697 	    (dev->ivars? "":"no "),
3698 	    (dev->softc? "":"no "),
3699 	    dev->busy));
3700 }
3701 
3702 static void
3703 print_device(device_t dev, int indent)
3704 {
3705 	if (!dev)
3706 		return;
3707 
3708 	print_device_short(dev, indent);
3709 
3710 	indentprintf(("Parent:\n"));
3711 	print_device_short(dev->parent, indent+1);
3712 	indentprintf(("Driver:\n"));
3713 	print_driver_short(dev->driver, indent+1);
3714 	indentprintf(("Devclass:\n"));
3715 	print_devclass_short(dev->devclass, indent+1);
3716 }
3717 
3718 void
3719 print_device_tree_short(device_t dev, int indent)
3720 /* print the device and all its children (indented) */
3721 {
3722 	device_t child;
3723 
3724 	if (!dev)
3725 		return;
3726 
3727 	print_device_short(dev, indent);
3728 
3729 	TAILQ_FOREACH(child, &dev->children, link) {
3730 		print_device_tree_short(child, indent+1);
3731 	}
3732 }
3733 
3734 void
3735 print_device_tree(device_t dev, int indent)
3736 /* print the device and all its children (indented) */
3737 {
3738 	device_t child;
3739 
3740 	if (!dev)
3741 		return;
3742 
3743 	print_device(dev, indent);
3744 
3745 	TAILQ_FOREACH(child, &dev->children, link) {
3746 		print_device_tree(child, indent+1);
3747 	}
3748 }
3749 
3750 static void
3751 print_driver_short(driver_t *driver, int indent)
3752 {
3753 	if (!driver)
3754 		return;
3755 
3756 	indentprintf(("driver %s: softc size = %zd\n",
3757 	    driver->name, driver->size));
3758 }
3759 
3760 static void
3761 print_driver(driver_t *driver, int indent)
3762 {
3763 	if (!driver)
3764 		return;
3765 
3766 	print_driver_short(driver, indent);
3767 }
3768 
3769 
3770 static void
3771 print_driver_list(driver_list_t drivers, int indent)
3772 {
3773 	driverlink_t driver;
3774 
3775 	TAILQ_FOREACH(driver, &drivers, link) {
3776 		print_driver(driver->driver, indent);
3777 	}
3778 }
3779 
3780 static void
3781 print_devclass_short(devclass_t dc, int indent)
3782 {
3783 	if ( !dc )
3784 		return;
3785 
3786 	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
3787 }
3788 
3789 static void
3790 print_devclass(devclass_t dc, int indent)
3791 {
3792 	int i;
3793 
3794 	if ( !dc )
3795 		return;
3796 
3797 	print_devclass_short(dc, indent);
3798 	indentprintf(("Drivers:\n"));
3799 	print_driver_list(dc->drivers, indent+1);
3800 
3801 	indentprintf(("Devices:\n"));
3802 	for (i = 0; i < dc->maxunit; i++)
3803 		if (dc->devices[i])
3804 			print_device(dc->devices[i], indent+1);
3805 }
3806 
3807 void
3808 print_devclass_list_short(void)
3809 {
3810 	devclass_t dc;
3811 
3812 	printf("Short listing of devclasses, drivers & devices:\n");
3813 	TAILQ_FOREACH(dc, &devclasses, link) {
3814 		print_devclass_short(dc, 0);
3815 	}
3816 }
3817 
3818 void
3819 print_devclass_list(void)
3820 {
3821 	devclass_t dc;
3822 
3823 	printf("Full listing of devclasses, drivers & devices:\n");
3824 	TAILQ_FOREACH(dc, &devclasses, link) {
3825 		print_devclass(dc, 0);
3826 	}
3827 }
3828 
3829 #endif
3830 
3831 /*
3832  * User-space access to the device tree.
3833  *
3834  * We implement a small set of nodes:
3835  *
3836  * hw.bus			Single integer read method to obtain the
3837  *				current generation count.
3838  * hw.bus.devices		Reads the entire device tree in flat space.
3839  * hw.bus.rman			Resource manager interface
3840  *
3841  * We might like to add the ability to scan devclasses and/or drivers to
3842  * determine what else is currently loaded/available.
3843  */
3844 
3845 static int
3846 sysctl_bus(SYSCTL_HANDLER_ARGS)
3847 {
3848 	struct u_businfo	ubus;
3849 
3850 	ubus.ub_version = BUS_USER_VERSION;
3851 	ubus.ub_generation = bus_data_generation;
3852 
3853 	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
3854 }
3855 SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
3856     "bus-related data");
3857 
3858 static int
3859 sysctl_devices(SYSCTL_HANDLER_ARGS)
3860 {
3861 	int			*name = (int *)arg1;
3862 	u_int			namelen = arg2;
3863 	int			index;
3864 	struct device		*dev;
3865 	struct u_device		udev;	/* XXX this is a bit big */
3866 	int			error;
3867 
3868 	if (namelen != 2)
3869 		return (EINVAL);
3870 
3871 	if (bus_data_generation_check(name[0]))
3872 		return (EINVAL);
3873 
3874 	index = name[1];
3875 
3876 	/*
3877 	 * Scan the list of devices, looking for the requested index.
3878 	 */
3879 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
3880 		if (index-- == 0)
3881 			break;
3882 	}
3883 	if (dev == NULL)
3884 		return (ENOENT);
3885 
3886 	/*
3887 	 * Populate the return array.
3888 	 */
3889 	udev.dv_handle = (uintptr_t)dev;
3890 	udev.dv_parent = (uintptr_t)dev->parent;
3891 	if (dev->nameunit == NULL)
3892 		udev.dv_name[0] = '\0';
3893 	else
3894 		strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
3895 
3896 	if (dev->desc == NULL)
3897 		udev.dv_desc[0] = '\0';
3898 	else
3899 		strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
3900 	if (dev->driver == NULL || dev->driver->name == NULL)
3901 		udev.dv_drivername[0] = '\0';
3902 	else
3903 		strlcpy(udev.dv_drivername, dev->driver->name,
3904 		    sizeof(udev.dv_drivername));
3905 	udev.dv_pnpinfo[0] = '\0';
3906 	udev.dv_location[0] = '\0';
3907 	bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
3908 	bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
3909 	udev.dv_devflags = dev->devflags;
3910 	udev.dv_flags = dev->flags;
3911 	udev.dv_state = dev->state;
3912 	error = SYSCTL_OUT(req, &udev, sizeof(udev));
3913 	return (error);
3914 }
3915 
3916 SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
3917     "system device tree");
3918 
3919 /*
3920  * Sysctl interface for scanning the resource lists.
3921  *
3922  * We take two input parameters; the index into the list of resource
3923  * managers, and the resource offset into the list.
3924  */
3925 static int
3926 sysctl_rman(SYSCTL_HANDLER_ARGS)
3927 {
3928 	int			*name = (int *)arg1;
3929 	u_int			namelen = arg2;
3930 	int			rman_idx, res_idx;
3931 	struct rman		*rm;
3932 	struct resource		*res;
3933 	struct u_rman		urm;
3934 	struct u_resource	ures;
3935 	int			error;
3936 
3937 	if (namelen != 3)
3938 		return (EINVAL);
3939 
3940 	if (bus_data_generation_check(name[0]))
3941 		return (EINVAL);
3942 	rman_idx = name[1];
3943 	res_idx = name[2];
3944 
3945 	/*
3946 	 * Find the indexed resource manager
3947 	 */
3948 	TAILQ_FOREACH(rm, &rman_head, rm_link) {
3949 		if (rman_idx-- == 0)
3950 			break;
3951 	}
3952 	if (rm == NULL)
3953 		return (ENOENT);
3954 
3955 	/*
3956 	 * If the resource index is -1, we want details on the
3957 	 * resource manager.
3958 	 */
3959 	if (res_idx == -1) {
3960 		urm.rm_handle = (uintptr_t)rm;
3961 		strlcpy(urm.rm_descr, rm->rm_descr, RM_TEXTLEN);
3962 		urm.rm_start = rm->rm_start;
3963 		urm.rm_size = rm->rm_end - rm->rm_start + 1;
3964 		urm.rm_type = rm->rm_type;
3965 
3966 		error = SYSCTL_OUT(req, &urm, sizeof(urm));
3967 		return (error);
3968 	}
3969 
3970 	/*
3971 	 * Find the indexed resource and return it.
3972 	 */
3973 	TAILQ_FOREACH(res, &rm->rm_list, r_link) {
3974 		if (res_idx-- == 0) {
3975 			ures.r_handle = (uintptr_t)res;
3976 			ures.r_parent = (uintptr_t)res->r_rm;
3977 			ures.r_device = (uintptr_t)res->r_dev;
3978 			if (res->r_dev != NULL) {
3979 				if (device_get_name(res->r_dev) != NULL) {
3980 					snprintf(ures.r_devname, RM_TEXTLEN,
3981 					    "%s%d",
3982 					    device_get_name(res->r_dev),
3983 					    device_get_unit(res->r_dev));
3984 				} else {
3985 					strlcpy(ures.r_devname, "nomatch",
3986 					    RM_TEXTLEN);
3987 				}
3988 			} else {
3989 				ures.r_devname[0] = '\0';
3990 			}
3991 			ures.r_start = res->r_start;
3992 			ures.r_size = res->r_end - res->r_start + 1;
3993 			ures.r_flags = res->r_flags;
3994 
3995 			error = SYSCTL_OUT(req, &ures, sizeof(ures));
3996 			return (error);
3997 		}
3998 	}
3999 	return (ENOENT);
4000 }
4001 
4002 SYSCTL_NODE(_hw_bus, OID_AUTO, rman, CTLFLAG_RD, sysctl_rman,
4003     "kernel resource manager");
4004 
4005 int
4006 bus_data_generation_check(int generation)
4007 {
4008 	if (generation != bus_data_generation)
4009 		return (1);
4010 
4011 	/* XXX generate optimised lists here? */
4012 	return (0);
4013 }
4014 
4015 void
4016 bus_data_generation_update(void)
4017 {
4018 	bus_data_generation++;
4019 }
4020