xref: /freebsd/sys/kern/subr_bus.c (revision d9f0ce31900a48d1a2bfc1c8c86f79d1e831451a)
1 /*-
2  * Copyright (c) 1997,1998,2003 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_bus.h"
31 
32 #include <sys/param.h>
33 #include <sys/conf.h>
34 #include <sys/filio.h>
35 #include <sys/lock.h>
36 #include <sys/kernel.h>
37 #include <sys/kobj.h>
38 #include <sys/limits.h>
39 #include <sys/malloc.h>
40 #include <sys/module.h>
41 #include <sys/mutex.h>
42 #include <sys/poll.h>
43 #include <sys/priv.h>
44 #include <sys/proc.h>
45 #include <sys/condvar.h>
46 #include <sys/queue.h>
47 #include <machine/bus.h>
48 #include <sys/random.h>
49 #include <sys/rman.h>
50 #include <sys/selinfo.h>
51 #include <sys/signalvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/systm.h>
54 #include <sys/uio.h>
55 #include <sys/bus.h>
56 #include <sys/interrupt.h>
57 #include <sys/cpuset.h>
58 
59 #include <net/vnet.h>
60 
61 #include <machine/cpu.h>
62 #include <machine/stdarg.h>
63 
64 #include <vm/uma.h>
65 
66 SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW, NULL, NULL);
67 SYSCTL_ROOT_NODE(OID_AUTO, dev, CTLFLAG_RW, NULL, NULL);
68 
69 /*
70  * Used to attach drivers to devclasses.
71  */
72 typedef struct driverlink *driverlink_t;
73 struct driverlink {
74 	kobj_class_t	driver;
75 	TAILQ_ENTRY(driverlink) link;	/* list of drivers in devclass */
76 	int		pass;
77 	TAILQ_ENTRY(driverlink) passlink;
78 };
79 
80 /*
81  * Forward declarations
82  */
83 typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
84 typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
85 typedef TAILQ_HEAD(device_list, device) device_list_t;
86 
87 struct devclass {
88 	TAILQ_ENTRY(devclass) link;
89 	devclass_t	parent;		/* parent in devclass hierarchy */
90 	driver_list_t	drivers;     /* bus devclasses store drivers for bus */
91 	char		*name;
92 	device_t	*devices;	/* array of devices indexed by unit */
93 	int		maxunit;	/* size of devices array */
94 	int		flags;
95 #define DC_HAS_CHILDREN		1
96 
97 	struct sysctl_ctx_list sysctl_ctx;
98 	struct sysctl_oid *sysctl_tree;
99 };
100 
101 /**
102  * @brief Implementation of device.
103  */
104 struct device {
105 	/*
106 	 * A device is a kernel object. The first field must be the
107 	 * current ops table for the object.
108 	 */
109 	KOBJ_FIELDS;
110 
111 	/*
112 	 * Device hierarchy.
113 	 */
114 	TAILQ_ENTRY(device)	link;	/**< list of devices in parent */
115 	TAILQ_ENTRY(device)	devlink; /**< global device list membership */
116 	device_t	parent;		/**< parent of this device  */
117 	device_list_t	children;	/**< list of child devices */
118 
119 	/*
120 	 * Details of this device.
121 	 */
122 	driver_t	*driver;	/**< current driver */
123 	devclass_t	devclass;	/**< current device class */
124 	int		unit;		/**< current unit number */
125 	char*		nameunit;	/**< name+unit e.g. foodev0 */
126 	char*		desc;		/**< driver specific description */
127 	int		busy;		/**< count of calls to device_busy() */
128 	device_state_t	state;		/**< current device state  */
129 	uint32_t	devflags;	/**< api level flags for device_get_flags() */
130 	u_int		flags;		/**< internal device flags  */
131 	u_int	order;			/**< order from device_add_child_ordered() */
132 	void	*ivars;			/**< instance variables  */
133 	void	*softc;			/**< current driver's variables  */
134 
135 	struct sysctl_ctx_list sysctl_ctx; /**< state for sysctl variables  */
136 	struct sysctl_oid *sysctl_tree;	/**< state for sysctl variables */
137 };
138 
139 static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
140 static MALLOC_DEFINE(M_BUS_SC, "bus-sc", "Bus data structures, softc");
141 
142 static void devctl2_init(void);
143 
144 #ifdef BUS_DEBUG
145 
146 static int bus_debug = 1;
147 SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RWTUN, &bus_debug, 0,
148     "Bus debug level");
149 
150 #define PDEBUG(a)	if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
151 #define DEVICENAME(d)	((d)? device_get_name(d): "no device")
152 #define DRIVERNAME(d)	((d)? d->name : "no driver")
153 #define DEVCLANAME(d)	((d)? d->name : "no devclass")
154 
155 /**
156  * Produce the indenting, indent*2 spaces plus a '.' ahead of that to
157  * prevent syslog from deleting initial spaces
158  */
159 #define indentprintf(p)	do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
160 
161 static void print_device_short(device_t dev, int indent);
162 static void print_device(device_t dev, int indent);
163 void print_device_tree_short(device_t dev, int indent);
164 void print_device_tree(device_t dev, int indent);
165 static void print_driver_short(driver_t *driver, int indent);
166 static void print_driver(driver_t *driver, int indent);
167 static void print_driver_list(driver_list_t drivers, int indent);
168 static void print_devclass_short(devclass_t dc, int indent);
169 static void print_devclass(devclass_t dc, int indent);
170 void print_devclass_list_short(void);
171 void print_devclass_list(void);
172 
173 #else
174 /* Make the compiler ignore the function calls */
175 #define PDEBUG(a)			/* nop */
176 #define DEVICENAME(d)			/* nop */
177 #define DRIVERNAME(d)			/* nop */
178 #define DEVCLANAME(d)			/* nop */
179 
180 #define print_device_short(d,i)		/* nop */
181 #define print_device(d,i)		/* nop */
182 #define print_device_tree_short(d,i)	/* nop */
183 #define print_device_tree(d,i)		/* nop */
184 #define print_driver_short(d,i)		/* nop */
185 #define print_driver(d,i)		/* nop */
186 #define print_driver_list(d,i)		/* nop */
187 #define print_devclass_short(d,i)	/* nop */
188 #define print_devclass(d,i)		/* nop */
189 #define print_devclass_list_short()	/* nop */
190 #define print_devclass_list()		/* nop */
191 #endif
192 
193 /*
194  * dev sysctl tree
195  */
196 
197 enum {
198 	DEVCLASS_SYSCTL_PARENT,
199 };
200 
201 static int
202 devclass_sysctl_handler(SYSCTL_HANDLER_ARGS)
203 {
204 	devclass_t dc = (devclass_t)arg1;
205 	const char *value;
206 
207 	switch (arg2) {
208 	case DEVCLASS_SYSCTL_PARENT:
209 		value = dc->parent ? dc->parent->name : "";
210 		break;
211 	default:
212 		return (EINVAL);
213 	}
214 	return (SYSCTL_OUT_STR(req, value));
215 }
216 
217 static void
218 devclass_sysctl_init(devclass_t dc)
219 {
220 
221 	if (dc->sysctl_tree != NULL)
222 		return;
223 	sysctl_ctx_init(&dc->sysctl_ctx);
224 	dc->sysctl_tree = SYSCTL_ADD_NODE(&dc->sysctl_ctx,
225 	    SYSCTL_STATIC_CHILDREN(_dev), OID_AUTO, dc->name,
226 	    CTLFLAG_RD, NULL, "");
227 	SYSCTL_ADD_PROC(&dc->sysctl_ctx, SYSCTL_CHILDREN(dc->sysctl_tree),
228 	    OID_AUTO, "%parent", CTLTYPE_STRING | CTLFLAG_RD,
229 	    dc, DEVCLASS_SYSCTL_PARENT, devclass_sysctl_handler, "A",
230 	    "parent class");
231 }
232 
233 enum {
234 	DEVICE_SYSCTL_DESC,
235 	DEVICE_SYSCTL_DRIVER,
236 	DEVICE_SYSCTL_LOCATION,
237 	DEVICE_SYSCTL_PNPINFO,
238 	DEVICE_SYSCTL_PARENT,
239 };
240 
241 static int
242 device_sysctl_handler(SYSCTL_HANDLER_ARGS)
243 {
244 	device_t dev = (device_t)arg1;
245 	const char *value;
246 	char *buf;
247 	int error;
248 
249 	buf = NULL;
250 	switch (arg2) {
251 	case DEVICE_SYSCTL_DESC:
252 		value = dev->desc ? dev->desc : "";
253 		break;
254 	case DEVICE_SYSCTL_DRIVER:
255 		value = dev->driver ? dev->driver->name : "";
256 		break;
257 	case DEVICE_SYSCTL_LOCATION:
258 		value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
259 		bus_child_location_str(dev, buf, 1024);
260 		break;
261 	case DEVICE_SYSCTL_PNPINFO:
262 		value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
263 		bus_child_pnpinfo_str(dev, buf, 1024);
264 		break;
265 	case DEVICE_SYSCTL_PARENT:
266 		value = dev->parent ? dev->parent->nameunit : "";
267 		break;
268 	default:
269 		return (EINVAL);
270 	}
271 	error = SYSCTL_OUT_STR(req, value);
272 	if (buf != NULL)
273 		free(buf, M_BUS);
274 	return (error);
275 }
276 
277 static void
278 device_sysctl_init(device_t dev)
279 {
280 	devclass_t dc = dev->devclass;
281 	int domain;
282 
283 	if (dev->sysctl_tree != NULL)
284 		return;
285 	devclass_sysctl_init(dc);
286 	sysctl_ctx_init(&dev->sysctl_ctx);
287 	dev->sysctl_tree = SYSCTL_ADD_NODE(&dev->sysctl_ctx,
288 	    SYSCTL_CHILDREN(dc->sysctl_tree), OID_AUTO,
289 	    dev->nameunit + strlen(dc->name),
290 	    CTLFLAG_RD, NULL, "");
291 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
292 	    OID_AUTO, "%desc", CTLTYPE_STRING | CTLFLAG_RD,
293 	    dev, DEVICE_SYSCTL_DESC, device_sysctl_handler, "A",
294 	    "device description");
295 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
296 	    OID_AUTO, "%driver", CTLTYPE_STRING | CTLFLAG_RD,
297 	    dev, DEVICE_SYSCTL_DRIVER, device_sysctl_handler, "A",
298 	    "device driver name");
299 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
300 	    OID_AUTO, "%location", CTLTYPE_STRING | CTLFLAG_RD,
301 	    dev, DEVICE_SYSCTL_LOCATION, device_sysctl_handler, "A",
302 	    "device location relative to parent");
303 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
304 	    OID_AUTO, "%pnpinfo", CTLTYPE_STRING | CTLFLAG_RD,
305 	    dev, DEVICE_SYSCTL_PNPINFO, device_sysctl_handler, "A",
306 	    "device identification");
307 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
308 	    OID_AUTO, "%parent", CTLTYPE_STRING | CTLFLAG_RD,
309 	    dev, DEVICE_SYSCTL_PARENT, device_sysctl_handler, "A",
310 	    "parent device");
311 	if (bus_get_domain(dev, &domain) == 0)
312 		SYSCTL_ADD_INT(&dev->sysctl_ctx,
313 		    SYSCTL_CHILDREN(dev->sysctl_tree), OID_AUTO, "%domain",
314 		    CTLFLAG_RD, NULL, domain, "NUMA domain");
315 }
316 
317 static void
318 device_sysctl_update(device_t dev)
319 {
320 	devclass_t dc = dev->devclass;
321 
322 	if (dev->sysctl_tree == NULL)
323 		return;
324 	sysctl_rename_oid(dev->sysctl_tree, dev->nameunit + strlen(dc->name));
325 }
326 
327 static void
328 device_sysctl_fini(device_t dev)
329 {
330 	if (dev->sysctl_tree == NULL)
331 		return;
332 	sysctl_ctx_free(&dev->sysctl_ctx);
333 	dev->sysctl_tree = NULL;
334 }
335 
336 /*
337  * /dev/devctl implementation
338  */
339 
340 /*
341  * This design allows only one reader for /dev/devctl.  This is not desirable
342  * in the long run, but will get a lot of hair out of this implementation.
343  * Maybe we should make this device a clonable device.
344  *
345  * Also note: we specifically do not attach a device to the device_t tree
346  * to avoid potential chicken and egg problems.  One could argue that all
347  * of this belongs to the root node.  One could also further argue that the
348  * sysctl interface that we have not might more properly be an ioctl
349  * interface, but at this stage of the game, I'm not inclined to rock that
350  * boat.
351  *
352  * I'm also not sure that the SIGIO support is done correctly or not, as
353  * I copied it from a driver that had SIGIO support that likely hasn't been
354  * tested since 3.4 or 2.2.8!
355  */
356 
357 /* Deprecated way to adjust queue length */
358 static int sysctl_devctl_disable(SYSCTL_HANDLER_ARGS);
359 SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_disable, CTLTYPE_INT | CTLFLAG_RWTUN |
360     CTLFLAG_MPSAFE, NULL, 0, sysctl_devctl_disable, "I",
361     "devctl disable -- deprecated");
362 
363 #define DEVCTL_DEFAULT_QUEUE_LEN 1000
364 static int sysctl_devctl_queue(SYSCTL_HANDLER_ARGS);
365 static int devctl_queue_length = DEVCTL_DEFAULT_QUEUE_LEN;
366 SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_queue, CTLTYPE_INT | CTLFLAG_RWTUN |
367     CTLFLAG_MPSAFE, NULL, 0, sysctl_devctl_queue, "I", "devctl queue length");
368 
369 static d_open_t		devopen;
370 static d_close_t	devclose;
371 static d_read_t		devread;
372 static d_ioctl_t	devioctl;
373 static d_poll_t		devpoll;
374 static d_kqfilter_t	devkqfilter;
375 
376 static struct cdevsw dev_cdevsw = {
377 	.d_version =	D_VERSION,
378 	.d_open =	devopen,
379 	.d_close =	devclose,
380 	.d_read =	devread,
381 	.d_ioctl =	devioctl,
382 	.d_poll =	devpoll,
383 	.d_kqfilter =	devkqfilter,
384 	.d_name =	"devctl",
385 };
386 
387 struct dev_event_info
388 {
389 	char *dei_data;
390 	TAILQ_ENTRY(dev_event_info) dei_link;
391 };
392 
393 TAILQ_HEAD(devq, dev_event_info);
394 
395 static struct dev_softc
396 {
397 	int	inuse;
398 	int	nonblock;
399 	int	queued;
400 	int	async;
401 	struct mtx mtx;
402 	struct cv cv;
403 	struct selinfo sel;
404 	struct devq devq;
405 	struct sigio *sigio;
406 } devsoftc;
407 
408 static void	filt_devctl_detach(struct knote *kn);
409 static int	filt_devctl_read(struct knote *kn, long hint);
410 
411 struct filterops devctl_rfiltops = {
412 	.f_isfd = 1,
413 	.f_detach = filt_devctl_detach,
414 	.f_event = filt_devctl_read,
415 };
416 
417 static struct cdev *devctl_dev;
418 
419 static void
420 devinit(void)
421 {
422 	devctl_dev = make_dev_credf(MAKEDEV_ETERNAL, &dev_cdevsw, 0, NULL,
423 	    UID_ROOT, GID_WHEEL, 0600, "devctl");
424 	mtx_init(&devsoftc.mtx, "dev mtx", "devd", MTX_DEF);
425 	cv_init(&devsoftc.cv, "dev cv");
426 	TAILQ_INIT(&devsoftc.devq);
427 	knlist_init_mtx(&devsoftc.sel.si_note, &devsoftc.mtx);
428 	devctl2_init();
429 }
430 
431 static int
432 devopen(struct cdev *dev, int oflags, int devtype, struct thread *td)
433 {
434 
435 	mtx_lock(&devsoftc.mtx);
436 	if (devsoftc.inuse) {
437 		mtx_unlock(&devsoftc.mtx);
438 		return (EBUSY);
439 	}
440 	/* move to init */
441 	devsoftc.inuse = 1;
442 	mtx_unlock(&devsoftc.mtx);
443 	return (0);
444 }
445 
446 static int
447 devclose(struct cdev *dev, int fflag, int devtype, struct thread *td)
448 {
449 
450 	mtx_lock(&devsoftc.mtx);
451 	devsoftc.inuse = 0;
452 	devsoftc.nonblock = 0;
453 	devsoftc.async = 0;
454 	cv_broadcast(&devsoftc.cv);
455 	funsetown(&devsoftc.sigio);
456 	mtx_unlock(&devsoftc.mtx);
457 	return (0);
458 }
459 
460 /*
461  * The read channel for this device is used to report changes to
462  * userland in realtime.  We are required to free the data as well as
463  * the n1 object because we allocate them separately.  Also note that
464  * we return one record at a time.  If you try to read this device a
465  * character at a time, you will lose the rest of the data.  Listening
466  * programs are expected to cope.
467  */
468 static int
469 devread(struct cdev *dev, struct uio *uio, int ioflag)
470 {
471 	struct dev_event_info *n1;
472 	int rv;
473 
474 	mtx_lock(&devsoftc.mtx);
475 	while (TAILQ_EMPTY(&devsoftc.devq)) {
476 		if (devsoftc.nonblock) {
477 			mtx_unlock(&devsoftc.mtx);
478 			return (EAGAIN);
479 		}
480 		rv = cv_wait_sig(&devsoftc.cv, &devsoftc.mtx);
481 		if (rv) {
482 			/*
483 			 * Need to translate ERESTART to EINTR here? -- jake
484 			 */
485 			mtx_unlock(&devsoftc.mtx);
486 			return (rv);
487 		}
488 	}
489 	n1 = TAILQ_FIRST(&devsoftc.devq);
490 	TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
491 	devsoftc.queued--;
492 	mtx_unlock(&devsoftc.mtx);
493 	rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
494 	free(n1->dei_data, M_BUS);
495 	free(n1, M_BUS);
496 	return (rv);
497 }
498 
499 static	int
500 devioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
501 {
502 	switch (cmd) {
503 
504 	case FIONBIO:
505 		if (*(int*)data)
506 			devsoftc.nonblock = 1;
507 		else
508 			devsoftc.nonblock = 0;
509 		return (0);
510 	case FIOASYNC:
511 		if (*(int*)data)
512 			devsoftc.async = 1;
513 		else
514 			devsoftc.async = 0;
515 		return (0);
516 	case FIOSETOWN:
517 		return fsetown(*(int *)data, &devsoftc.sigio);
518 	case FIOGETOWN:
519 		*(int *)data = fgetown(&devsoftc.sigio);
520 		return (0);
521 
522 		/* (un)Support for other fcntl() calls. */
523 	case FIOCLEX:
524 	case FIONCLEX:
525 	case FIONREAD:
526 	default:
527 		break;
528 	}
529 	return (ENOTTY);
530 }
531 
532 static	int
533 devpoll(struct cdev *dev, int events, struct thread *td)
534 {
535 	int	revents = 0;
536 
537 	mtx_lock(&devsoftc.mtx);
538 	if (events & (POLLIN | POLLRDNORM)) {
539 		if (!TAILQ_EMPTY(&devsoftc.devq))
540 			revents = events & (POLLIN | POLLRDNORM);
541 		else
542 			selrecord(td, &devsoftc.sel);
543 	}
544 	mtx_unlock(&devsoftc.mtx);
545 
546 	return (revents);
547 }
548 
549 static int
550 devkqfilter(struct cdev *dev, struct knote *kn)
551 {
552 	int error;
553 
554 	if (kn->kn_filter == EVFILT_READ) {
555 		kn->kn_fop = &devctl_rfiltops;
556 		knlist_add(&devsoftc.sel.si_note, kn, 0);
557 		error = 0;
558 	} else
559 		error = EINVAL;
560 	return (error);
561 }
562 
563 static void
564 filt_devctl_detach(struct knote *kn)
565 {
566 
567 	knlist_remove(&devsoftc.sel.si_note, kn, 0);
568 }
569 
570 static int
571 filt_devctl_read(struct knote *kn, long hint)
572 {
573 	kn->kn_data = devsoftc.queued;
574 	return (kn->kn_data != 0);
575 }
576 
577 /**
578  * @brief Return whether the userland process is running
579  */
580 boolean_t
581 devctl_process_running(void)
582 {
583 	return (devsoftc.inuse == 1);
584 }
585 
586 /**
587  * @brief Queue data to be read from the devctl device
588  *
589  * Generic interface to queue data to the devctl device.  It is
590  * assumed that @p data is properly formatted.  It is further assumed
591  * that @p data is allocated using the M_BUS malloc type.
592  */
593 void
594 devctl_queue_data_f(char *data, int flags)
595 {
596 	struct dev_event_info *n1 = NULL, *n2 = NULL;
597 
598 	if (strlen(data) == 0)
599 		goto out;
600 	if (devctl_queue_length == 0)
601 		goto out;
602 	n1 = malloc(sizeof(*n1), M_BUS, flags);
603 	if (n1 == NULL)
604 		goto out;
605 	n1->dei_data = data;
606 	mtx_lock(&devsoftc.mtx);
607 	if (devctl_queue_length == 0) {
608 		mtx_unlock(&devsoftc.mtx);
609 		free(n1->dei_data, M_BUS);
610 		free(n1, M_BUS);
611 		return;
612 	}
613 	/* Leave at least one spot in the queue... */
614 	while (devsoftc.queued > devctl_queue_length - 1) {
615 		n2 = TAILQ_FIRST(&devsoftc.devq);
616 		TAILQ_REMOVE(&devsoftc.devq, n2, dei_link);
617 		free(n2->dei_data, M_BUS);
618 		free(n2, M_BUS);
619 		devsoftc.queued--;
620 	}
621 	TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
622 	devsoftc.queued++;
623 	cv_broadcast(&devsoftc.cv);
624 	KNOTE_LOCKED(&devsoftc.sel.si_note, 0);
625 	mtx_unlock(&devsoftc.mtx);
626 	selwakeup(&devsoftc.sel);
627 	if (devsoftc.async && devsoftc.sigio != NULL)
628 		pgsigio(&devsoftc.sigio, SIGIO, 0);
629 	return;
630 out:
631 	/*
632 	 * We have to free data on all error paths since the caller
633 	 * assumes it will be free'd when this item is dequeued.
634 	 */
635 	free(data, M_BUS);
636 	return;
637 }
638 
639 void
640 devctl_queue_data(char *data)
641 {
642 
643 	devctl_queue_data_f(data, M_NOWAIT);
644 }
645 
646 /**
647  * @brief Send a 'notification' to userland, using standard ways
648  */
649 void
650 devctl_notify_f(const char *system, const char *subsystem, const char *type,
651     const char *data, int flags)
652 {
653 	int len = 0;
654 	char *msg;
655 
656 	if (system == NULL)
657 		return;		/* BOGUS!  Must specify system. */
658 	if (subsystem == NULL)
659 		return;		/* BOGUS!  Must specify subsystem. */
660 	if (type == NULL)
661 		return;		/* BOGUS!  Must specify type. */
662 	len += strlen(" system=") + strlen(system);
663 	len += strlen(" subsystem=") + strlen(subsystem);
664 	len += strlen(" type=") + strlen(type);
665 	/* add in the data message plus newline. */
666 	if (data != NULL)
667 		len += strlen(data);
668 	len += 3;	/* '!', '\n', and NUL */
669 	msg = malloc(len, M_BUS, flags);
670 	if (msg == NULL)
671 		return;		/* Drop it on the floor */
672 	if (data != NULL)
673 		snprintf(msg, len, "!system=%s subsystem=%s type=%s %s\n",
674 		    system, subsystem, type, data);
675 	else
676 		snprintf(msg, len, "!system=%s subsystem=%s type=%s\n",
677 		    system, subsystem, type);
678 	devctl_queue_data_f(msg, flags);
679 }
680 
681 void
682 devctl_notify(const char *system, const char *subsystem, const char *type,
683     const char *data)
684 {
685 
686 	devctl_notify_f(system, subsystem, type, data, M_NOWAIT);
687 }
688 
689 /*
690  * Common routine that tries to make sending messages as easy as possible.
691  * We allocate memory for the data, copy strings into that, but do not
692  * free it unless there's an error.  The dequeue part of the driver should
693  * free the data.  We don't send data when the device is disabled.  We do
694  * send data, even when we have no listeners, because we wish to avoid
695  * races relating to startup and restart of listening applications.
696  *
697  * devaddq is designed to string together the type of event, with the
698  * object of that event, plus the plug and play info and location info
699  * for that event.  This is likely most useful for devices, but less
700  * useful for other consumers of this interface.  Those should use
701  * the devctl_queue_data() interface instead.
702  */
703 static void
704 devaddq(const char *type, const char *what, device_t dev)
705 {
706 	char *data = NULL;
707 	char *loc = NULL;
708 	char *pnp = NULL;
709 	const char *parstr;
710 
711 	if (!devctl_queue_length)/* Rare race, but lost races safely discard */
712 		return;
713 	data = malloc(1024, M_BUS, M_NOWAIT);
714 	if (data == NULL)
715 		goto bad;
716 
717 	/* get the bus specific location of this device */
718 	loc = malloc(1024, M_BUS, M_NOWAIT);
719 	if (loc == NULL)
720 		goto bad;
721 	*loc = '\0';
722 	bus_child_location_str(dev, loc, 1024);
723 
724 	/* Get the bus specific pnp info of this device */
725 	pnp = malloc(1024, M_BUS, M_NOWAIT);
726 	if (pnp == NULL)
727 		goto bad;
728 	*pnp = '\0';
729 	bus_child_pnpinfo_str(dev, pnp, 1024);
730 
731 	/* Get the parent of this device, or / if high enough in the tree. */
732 	if (device_get_parent(dev) == NULL)
733 		parstr = ".";	/* Or '/' ? */
734 	else
735 		parstr = device_get_nameunit(device_get_parent(dev));
736 	/* String it all together. */
737 	snprintf(data, 1024, "%s%s at %s %s on %s\n", type, what, loc, pnp,
738 	  parstr);
739 	free(loc, M_BUS);
740 	free(pnp, M_BUS);
741 	devctl_queue_data(data);
742 	return;
743 bad:
744 	free(pnp, M_BUS);
745 	free(loc, M_BUS);
746 	free(data, M_BUS);
747 	return;
748 }
749 
750 /*
751  * A device was added to the tree.  We are called just after it successfully
752  * attaches (that is, probe and attach success for this device).  No call
753  * is made if a device is merely parented into the tree.  See devnomatch
754  * if probe fails.  If attach fails, no notification is sent (but maybe
755  * we should have a different message for this).
756  */
757 static void
758 devadded(device_t dev)
759 {
760 	devaddq("+", device_get_nameunit(dev), dev);
761 }
762 
763 /*
764  * A device was removed from the tree.  We are called just before this
765  * happens.
766  */
767 static void
768 devremoved(device_t dev)
769 {
770 	devaddq("-", device_get_nameunit(dev), dev);
771 }
772 
773 /*
774  * Called when there's no match for this device.  This is only called
775  * the first time that no match happens, so we don't keep getting this
776  * message.  Should that prove to be undesirable, we can change it.
777  * This is called when all drivers that can attach to a given bus
778  * decline to accept this device.  Other errors may not be detected.
779  */
780 static void
781 devnomatch(device_t dev)
782 {
783 	devaddq("?", "", dev);
784 }
785 
786 static int
787 sysctl_devctl_disable(SYSCTL_HANDLER_ARGS)
788 {
789 	struct dev_event_info *n1;
790 	int dis, error;
791 
792 	dis = (devctl_queue_length == 0);
793 	error = sysctl_handle_int(oidp, &dis, 0, req);
794 	if (error || !req->newptr)
795 		return (error);
796 	if (mtx_initialized(&devsoftc.mtx))
797 		mtx_lock(&devsoftc.mtx);
798 	if (dis) {
799 		while (!TAILQ_EMPTY(&devsoftc.devq)) {
800 			n1 = TAILQ_FIRST(&devsoftc.devq);
801 			TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
802 			free(n1->dei_data, M_BUS);
803 			free(n1, M_BUS);
804 		}
805 		devsoftc.queued = 0;
806 		devctl_queue_length = 0;
807 	} else {
808 		devctl_queue_length = DEVCTL_DEFAULT_QUEUE_LEN;
809 	}
810 	if (mtx_initialized(&devsoftc.mtx))
811 		mtx_unlock(&devsoftc.mtx);
812 	return (0);
813 }
814 
815 static int
816 sysctl_devctl_queue(SYSCTL_HANDLER_ARGS)
817 {
818 	struct dev_event_info *n1;
819 	int q, error;
820 
821 	q = devctl_queue_length;
822 	error = sysctl_handle_int(oidp, &q, 0, req);
823 	if (error || !req->newptr)
824 		return (error);
825 	if (q < 0)
826 		return (EINVAL);
827 	if (mtx_initialized(&devsoftc.mtx))
828 		mtx_lock(&devsoftc.mtx);
829 	devctl_queue_length = q;
830 	while (devsoftc.queued > devctl_queue_length) {
831 		n1 = TAILQ_FIRST(&devsoftc.devq);
832 		TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
833 		free(n1->dei_data, M_BUS);
834 		free(n1, M_BUS);
835 		devsoftc.queued--;
836 	}
837 	if (mtx_initialized(&devsoftc.mtx))
838 		mtx_unlock(&devsoftc.mtx);
839 	return (0);
840 }
841 
842 /**
843  * @brief safely quotes strings that might have double quotes in them.
844  *
845  * The devctl protocol relies on quoted strings having matching quotes.
846  * This routine quotes any internal quotes so the resulting string
847  * is safe to pass to snprintf to construct, for example pnp info strings.
848  * Strings are always terminated with a NUL, but may be truncated if longer
849  * than @p len bytes after quotes.
850  *
851  * @param dst	Buffer to hold the string. Must be at least @p len bytes long
852  * @param src	Original buffer.
853  * @param len	Length of buffer pointed to by @dst, including trailing NUL
854  */
855 void
856 devctl_safe_quote(char *dst, const char *src, size_t len)
857 {
858 	char *walker = dst, *ep = dst + len - 1;
859 
860 	if (len == 0)
861 		return;
862 	while (src != NULL && walker < ep)
863 	{
864 		if (*src == '"') {
865 			if (ep - walker < 2)
866 				break;
867 			*walker++ = '\\';
868 		}
869 		*walker++ = *src++;
870 	}
871 	*walker = '\0';
872 }
873 
874 /* End of /dev/devctl code */
875 
876 static TAILQ_HEAD(,device)	bus_data_devices;
877 static int bus_data_generation = 1;
878 
879 static kobj_method_t null_methods[] = {
880 	KOBJMETHOD_END
881 };
882 
883 DEFINE_CLASS(null, null_methods, 0);
884 
885 /*
886  * Bus pass implementation
887  */
888 
889 static driver_list_t passes = TAILQ_HEAD_INITIALIZER(passes);
890 int bus_current_pass = BUS_PASS_ROOT;
891 
892 /**
893  * @internal
894  * @brief Register the pass level of a new driver attachment
895  *
896  * Register a new driver attachment's pass level.  If no driver
897  * attachment with the same pass level has been added, then @p new
898  * will be added to the global passes list.
899  *
900  * @param new		the new driver attachment
901  */
902 static void
903 driver_register_pass(struct driverlink *new)
904 {
905 	struct driverlink *dl;
906 
907 	/* We only consider pass numbers during boot. */
908 	if (bus_current_pass == BUS_PASS_DEFAULT)
909 		return;
910 
911 	/*
912 	 * Walk the passes list.  If we already know about this pass
913 	 * then there is nothing to do.  If we don't, then insert this
914 	 * driver link into the list.
915 	 */
916 	TAILQ_FOREACH(dl, &passes, passlink) {
917 		if (dl->pass < new->pass)
918 			continue;
919 		if (dl->pass == new->pass)
920 			return;
921 		TAILQ_INSERT_BEFORE(dl, new, passlink);
922 		return;
923 	}
924 	TAILQ_INSERT_TAIL(&passes, new, passlink);
925 }
926 
927 /**
928  * @brief Raise the current bus pass
929  *
930  * Raise the current bus pass level to @p pass.  Call the BUS_NEW_PASS()
931  * method on the root bus to kick off a new device tree scan for each
932  * new pass level that has at least one driver.
933  */
934 void
935 bus_set_pass(int pass)
936 {
937 	struct driverlink *dl;
938 
939 	if (bus_current_pass > pass)
940 		panic("Attempt to lower bus pass level");
941 
942 	TAILQ_FOREACH(dl, &passes, passlink) {
943 		/* Skip pass values below the current pass level. */
944 		if (dl->pass <= bus_current_pass)
945 			continue;
946 
947 		/*
948 		 * Bail once we hit a driver with a pass level that is
949 		 * too high.
950 		 */
951 		if (dl->pass > pass)
952 			break;
953 
954 		/*
955 		 * Raise the pass level to the next level and rescan
956 		 * the tree.
957 		 */
958 		bus_current_pass = dl->pass;
959 		BUS_NEW_PASS(root_bus);
960 	}
961 
962 	/*
963 	 * If there isn't a driver registered for the requested pass,
964 	 * then bus_current_pass might still be less than 'pass'.  Set
965 	 * it to 'pass' in that case.
966 	 */
967 	if (bus_current_pass < pass)
968 		bus_current_pass = pass;
969 	KASSERT(bus_current_pass == pass, ("Failed to update bus pass level"));
970 }
971 
972 /*
973  * Devclass implementation
974  */
975 
976 static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
977 
978 /**
979  * @internal
980  * @brief Find or create a device class
981  *
982  * If a device class with the name @p classname exists, return it,
983  * otherwise if @p create is non-zero create and return a new device
984  * class.
985  *
986  * If @p parentname is non-NULL, the parent of the devclass is set to
987  * the devclass of that name.
988  *
989  * @param classname	the devclass name to find or create
990  * @param parentname	the parent devclass name or @c NULL
991  * @param create	non-zero to create a devclass
992  */
993 static devclass_t
994 devclass_find_internal(const char *classname, const char *parentname,
995 		       int create)
996 {
997 	devclass_t dc;
998 
999 	PDEBUG(("looking for %s", classname));
1000 	if (!classname)
1001 		return (NULL);
1002 
1003 	TAILQ_FOREACH(dc, &devclasses, link) {
1004 		if (!strcmp(dc->name, classname))
1005 			break;
1006 	}
1007 
1008 	if (create && !dc) {
1009 		PDEBUG(("creating %s", classname));
1010 		dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
1011 		    M_BUS, M_NOWAIT | M_ZERO);
1012 		if (!dc)
1013 			return (NULL);
1014 		dc->parent = NULL;
1015 		dc->name = (char*) (dc + 1);
1016 		strcpy(dc->name, classname);
1017 		TAILQ_INIT(&dc->drivers);
1018 		TAILQ_INSERT_TAIL(&devclasses, dc, link);
1019 
1020 		bus_data_generation_update();
1021 	}
1022 
1023 	/*
1024 	 * If a parent class is specified, then set that as our parent so
1025 	 * that this devclass will support drivers for the parent class as
1026 	 * well.  If the parent class has the same name don't do this though
1027 	 * as it creates a cycle that can trigger an infinite loop in
1028 	 * device_probe_child() if a device exists for which there is no
1029 	 * suitable driver.
1030 	 */
1031 	if (parentname && dc && !dc->parent &&
1032 	    strcmp(classname, parentname) != 0) {
1033 		dc->parent = devclass_find_internal(parentname, NULL, TRUE);
1034 		dc->parent->flags |= DC_HAS_CHILDREN;
1035 	}
1036 
1037 	return (dc);
1038 }
1039 
1040 /**
1041  * @brief Create a device class
1042  *
1043  * If a device class with the name @p classname exists, return it,
1044  * otherwise create and return a new device class.
1045  *
1046  * @param classname	the devclass name to find or create
1047  */
1048 devclass_t
1049 devclass_create(const char *classname)
1050 {
1051 	return (devclass_find_internal(classname, NULL, TRUE));
1052 }
1053 
1054 /**
1055  * @brief Find a device class
1056  *
1057  * If a device class with the name @p classname exists, return it,
1058  * otherwise return @c NULL.
1059  *
1060  * @param classname	the devclass name to find
1061  */
1062 devclass_t
1063 devclass_find(const char *classname)
1064 {
1065 	return (devclass_find_internal(classname, NULL, FALSE));
1066 }
1067 
1068 /**
1069  * @brief Register that a device driver has been added to a devclass
1070  *
1071  * Register that a device driver has been added to a devclass.  This
1072  * is called by devclass_add_driver to accomplish the recursive
1073  * notification of all the children classes of dc, as well as dc.
1074  * Each layer will have BUS_DRIVER_ADDED() called for all instances of
1075  * the devclass.
1076  *
1077  * We do a full search here of the devclass list at each iteration
1078  * level to save storing children-lists in the devclass structure.  If
1079  * we ever move beyond a few dozen devices doing this, we may need to
1080  * reevaluate...
1081  *
1082  * @param dc		the devclass to edit
1083  * @param driver	the driver that was just added
1084  */
1085 static void
1086 devclass_driver_added(devclass_t dc, driver_t *driver)
1087 {
1088 	devclass_t parent;
1089 	int i;
1090 
1091 	/*
1092 	 * Call BUS_DRIVER_ADDED for any existing busses in this class.
1093 	 */
1094 	for (i = 0; i < dc->maxunit; i++)
1095 		if (dc->devices[i] && device_is_attached(dc->devices[i]))
1096 			BUS_DRIVER_ADDED(dc->devices[i], driver);
1097 
1098 	/*
1099 	 * Walk through the children classes.  Since we only keep a
1100 	 * single parent pointer around, we walk the entire list of
1101 	 * devclasses looking for children.  We set the
1102 	 * DC_HAS_CHILDREN flag when a child devclass is created on
1103 	 * the parent, so we only walk the list for those devclasses
1104 	 * that have children.
1105 	 */
1106 	if (!(dc->flags & DC_HAS_CHILDREN))
1107 		return;
1108 	parent = dc;
1109 	TAILQ_FOREACH(dc, &devclasses, link) {
1110 		if (dc->parent == parent)
1111 			devclass_driver_added(dc, driver);
1112 	}
1113 }
1114 
1115 /**
1116  * @brief Add a device driver to a device class
1117  *
1118  * Add a device driver to a devclass. This is normally called
1119  * automatically by DRIVER_MODULE(). The BUS_DRIVER_ADDED() method of
1120  * all devices in the devclass will be called to allow them to attempt
1121  * to re-probe any unmatched children.
1122  *
1123  * @param dc		the devclass to edit
1124  * @param driver	the driver to register
1125  */
1126 int
1127 devclass_add_driver(devclass_t dc, driver_t *driver, int pass, devclass_t *dcp)
1128 {
1129 	driverlink_t dl;
1130 	const char *parentname;
1131 
1132 	PDEBUG(("%s", DRIVERNAME(driver)));
1133 
1134 	/* Don't allow invalid pass values. */
1135 	if (pass <= BUS_PASS_ROOT)
1136 		return (EINVAL);
1137 
1138 	dl = malloc(sizeof *dl, M_BUS, M_NOWAIT|M_ZERO);
1139 	if (!dl)
1140 		return (ENOMEM);
1141 
1142 	/*
1143 	 * Compile the driver's methods. Also increase the reference count
1144 	 * so that the class doesn't get freed when the last instance
1145 	 * goes. This means we can safely use static methods and avoids a
1146 	 * double-free in devclass_delete_driver.
1147 	 */
1148 	kobj_class_compile((kobj_class_t) driver);
1149 
1150 	/*
1151 	 * If the driver has any base classes, make the
1152 	 * devclass inherit from the devclass of the driver's
1153 	 * first base class. This will allow the system to
1154 	 * search for drivers in both devclasses for children
1155 	 * of a device using this driver.
1156 	 */
1157 	if (driver->baseclasses)
1158 		parentname = driver->baseclasses[0]->name;
1159 	else
1160 		parentname = NULL;
1161 	*dcp = devclass_find_internal(driver->name, parentname, TRUE);
1162 
1163 	dl->driver = driver;
1164 	TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
1165 	driver->refs++;		/* XXX: kobj_mtx */
1166 	dl->pass = pass;
1167 	driver_register_pass(dl);
1168 
1169 	devclass_driver_added(dc, driver);
1170 	bus_data_generation_update();
1171 	return (0);
1172 }
1173 
1174 /**
1175  * @brief Register that a device driver has been deleted from a devclass
1176  *
1177  * Register that a device driver has been removed from a devclass.
1178  * This is called by devclass_delete_driver to accomplish the
1179  * recursive notification of all the children classes of busclass, as
1180  * well as busclass.  Each layer will attempt to detach the driver
1181  * from any devices that are children of the bus's devclass.  The function
1182  * will return an error if a device fails to detach.
1183  *
1184  * We do a full search here of the devclass list at each iteration
1185  * level to save storing children-lists in the devclass structure.  If
1186  * we ever move beyond a few dozen devices doing this, we may need to
1187  * reevaluate...
1188  *
1189  * @param busclass	the devclass of the parent bus
1190  * @param dc		the devclass of the driver being deleted
1191  * @param driver	the driver being deleted
1192  */
1193 static int
1194 devclass_driver_deleted(devclass_t busclass, devclass_t dc, driver_t *driver)
1195 {
1196 	devclass_t parent;
1197 	device_t dev;
1198 	int error, i;
1199 
1200 	/*
1201 	 * Disassociate from any devices.  We iterate through all the
1202 	 * devices in the devclass of the driver and detach any which are
1203 	 * using the driver and which have a parent in the devclass which
1204 	 * we are deleting from.
1205 	 *
1206 	 * Note that since a driver can be in multiple devclasses, we
1207 	 * should not detach devices which are not children of devices in
1208 	 * the affected devclass.
1209 	 */
1210 	for (i = 0; i < dc->maxunit; i++) {
1211 		if (dc->devices[i]) {
1212 			dev = dc->devices[i];
1213 			if (dev->driver == driver && dev->parent &&
1214 			    dev->parent->devclass == busclass) {
1215 				if ((error = device_detach(dev)) != 0)
1216 					return (error);
1217 				BUS_PROBE_NOMATCH(dev->parent, dev);
1218 				devnomatch(dev);
1219 				dev->flags |= DF_DONENOMATCH;
1220 			}
1221 		}
1222 	}
1223 
1224 	/*
1225 	 * Walk through the children classes.  Since we only keep a
1226 	 * single parent pointer around, we walk the entire list of
1227 	 * devclasses looking for children.  We set the
1228 	 * DC_HAS_CHILDREN flag when a child devclass is created on
1229 	 * the parent, so we only walk the list for those devclasses
1230 	 * that have children.
1231 	 */
1232 	if (!(busclass->flags & DC_HAS_CHILDREN))
1233 		return (0);
1234 	parent = busclass;
1235 	TAILQ_FOREACH(busclass, &devclasses, link) {
1236 		if (busclass->parent == parent) {
1237 			error = devclass_driver_deleted(busclass, dc, driver);
1238 			if (error)
1239 				return (error);
1240 		}
1241 	}
1242 	return (0);
1243 }
1244 
1245 /**
1246  * @brief Delete a device driver from a device class
1247  *
1248  * Delete a device driver from a devclass. This is normally called
1249  * automatically by DRIVER_MODULE().
1250  *
1251  * If the driver is currently attached to any devices,
1252  * devclass_delete_driver() will first attempt to detach from each
1253  * device. If one of the detach calls fails, the driver will not be
1254  * deleted.
1255  *
1256  * @param dc		the devclass to edit
1257  * @param driver	the driver to unregister
1258  */
1259 int
1260 devclass_delete_driver(devclass_t busclass, driver_t *driver)
1261 {
1262 	devclass_t dc = devclass_find(driver->name);
1263 	driverlink_t dl;
1264 	int error;
1265 
1266 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
1267 
1268 	if (!dc)
1269 		return (0);
1270 
1271 	/*
1272 	 * Find the link structure in the bus' list of drivers.
1273 	 */
1274 	TAILQ_FOREACH(dl, &busclass->drivers, link) {
1275 		if (dl->driver == driver)
1276 			break;
1277 	}
1278 
1279 	if (!dl) {
1280 		PDEBUG(("%s not found in %s list", driver->name,
1281 		    busclass->name));
1282 		return (ENOENT);
1283 	}
1284 
1285 	error = devclass_driver_deleted(busclass, dc, driver);
1286 	if (error != 0)
1287 		return (error);
1288 
1289 	TAILQ_REMOVE(&busclass->drivers, dl, link);
1290 	free(dl, M_BUS);
1291 
1292 	/* XXX: kobj_mtx */
1293 	driver->refs--;
1294 	if (driver->refs == 0)
1295 		kobj_class_free((kobj_class_t) driver);
1296 
1297 	bus_data_generation_update();
1298 	return (0);
1299 }
1300 
1301 /**
1302  * @brief Quiesces a set of device drivers from a device class
1303  *
1304  * Quiesce a device driver from a devclass. This is normally called
1305  * automatically by DRIVER_MODULE().
1306  *
1307  * If the driver is currently attached to any devices,
1308  * devclass_quiesece_driver() will first attempt to quiesce each
1309  * device.
1310  *
1311  * @param dc		the devclass to edit
1312  * @param driver	the driver to unregister
1313  */
1314 static int
1315 devclass_quiesce_driver(devclass_t busclass, driver_t *driver)
1316 {
1317 	devclass_t dc = devclass_find(driver->name);
1318 	driverlink_t dl;
1319 	device_t dev;
1320 	int i;
1321 	int error;
1322 
1323 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
1324 
1325 	if (!dc)
1326 		return (0);
1327 
1328 	/*
1329 	 * Find the link structure in the bus' list of drivers.
1330 	 */
1331 	TAILQ_FOREACH(dl, &busclass->drivers, link) {
1332 		if (dl->driver == driver)
1333 			break;
1334 	}
1335 
1336 	if (!dl) {
1337 		PDEBUG(("%s not found in %s list", driver->name,
1338 		    busclass->name));
1339 		return (ENOENT);
1340 	}
1341 
1342 	/*
1343 	 * Quiesce all devices.  We iterate through all the devices in
1344 	 * the devclass of the driver and quiesce any which are using
1345 	 * the driver and which have a parent in the devclass which we
1346 	 * are quiescing.
1347 	 *
1348 	 * Note that since a driver can be in multiple devclasses, we
1349 	 * should not quiesce devices which are not children of
1350 	 * devices in the affected devclass.
1351 	 */
1352 	for (i = 0; i < dc->maxunit; i++) {
1353 		if (dc->devices[i]) {
1354 			dev = dc->devices[i];
1355 			if (dev->driver == driver && dev->parent &&
1356 			    dev->parent->devclass == busclass) {
1357 				if ((error = device_quiesce(dev)) != 0)
1358 					return (error);
1359 			}
1360 		}
1361 	}
1362 
1363 	return (0);
1364 }
1365 
1366 /**
1367  * @internal
1368  */
1369 static driverlink_t
1370 devclass_find_driver_internal(devclass_t dc, const char *classname)
1371 {
1372 	driverlink_t dl;
1373 
1374 	PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
1375 
1376 	TAILQ_FOREACH(dl, &dc->drivers, link) {
1377 		if (!strcmp(dl->driver->name, classname))
1378 			return (dl);
1379 	}
1380 
1381 	PDEBUG(("not found"));
1382 	return (NULL);
1383 }
1384 
1385 /**
1386  * @brief Return the name of the devclass
1387  */
1388 const char *
1389 devclass_get_name(devclass_t dc)
1390 {
1391 	return (dc->name);
1392 }
1393 
1394 /**
1395  * @brief Find a device given a unit number
1396  *
1397  * @param dc		the devclass to search
1398  * @param unit		the unit number to search for
1399  *
1400  * @returns		the device with the given unit number or @c
1401  *			NULL if there is no such device
1402  */
1403 device_t
1404 devclass_get_device(devclass_t dc, int unit)
1405 {
1406 	if (dc == NULL || unit < 0 || unit >= dc->maxunit)
1407 		return (NULL);
1408 	return (dc->devices[unit]);
1409 }
1410 
1411 /**
1412  * @brief Find the softc field of a device given a unit number
1413  *
1414  * @param dc		the devclass to search
1415  * @param unit		the unit number to search for
1416  *
1417  * @returns		the softc field of the device with the given
1418  *			unit number or @c NULL if there is no such
1419  *			device
1420  */
1421 void *
1422 devclass_get_softc(devclass_t dc, int unit)
1423 {
1424 	device_t dev;
1425 
1426 	dev = devclass_get_device(dc, unit);
1427 	if (!dev)
1428 		return (NULL);
1429 
1430 	return (device_get_softc(dev));
1431 }
1432 
1433 /**
1434  * @brief Get a list of devices in the devclass
1435  *
1436  * An array containing a list of all the devices in the given devclass
1437  * is allocated and returned in @p *devlistp. The number of devices
1438  * in the array is returned in @p *devcountp. The caller should free
1439  * the array using @c free(p, M_TEMP), even if @p *devcountp is 0.
1440  *
1441  * @param dc		the devclass to examine
1442  * @param devlistp	points at location for array pointer return
1443  *			value
1444  * @param devcountp	points at location for array size return value
1445  *
1446  * @retval 0		success
1447  * @retval ENOMEM	the array allocation failed
1448  */
1449 int
1450 devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
1451 {
1452 	int count, i;
1453 	device_t *list;
1454 
1455 	count = devclass_get_count(dc);
1456 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1457 	if (!list)
1458 		return (ENOMEM);
1459 
1460 	count = 0;
1461 	for (i = 0; i < dc->maxunit; i++) {
1462 		if (dc->devices[i]) {
1463 			list[count] = dc->devices[i];
1464 			count++;
1465 		}
1466 	}
1467 
1468 	*devlistp = list;
1469 	*devcountp = count;
1470 
1471 	return (0);
1472 }
1473 
1474 /**
1475  * @brief Get a list of drivers in the devclass
1476  *
1477  * An array containing a list of pointers to all the drivers in the
1478  * given devclass is allocated and returned in @p *listp.  The number
1479  * of drivers in the array is returned in @p *countp. The caller should
1480  * free the array using @c free(p, M_TEMP).
1481  *
1482  * @param dc		the devclass to examine
1483  * @param listp		gives location for array pointer return value
1484  * @param countp	gives location for number of array elements
1485  *			return value
1486  *
1487  * @retval 0		success
1488  * @retval ENOMEM	the array allocation failed
1489  */
1490 int
1491 devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
1492 {
1493 	driverlink_t dl;
1494 	driver_t **list;
1495 	int count;
1496 
1497 	count = 0;
1498 	TAILQ_FOREACH(dl, &dc->drivers, link)
1499 		count++;
1500 	list = malloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
1501 	if (list == NULL)
1502 		return (ENOMEM);
1503 
1504 	count = 0;
1505 	TAILQ_FOREACH(dl, &dc->drivers, link) {
1506 		list[count] = dl->driver;
1507 		count++;
1508 	}
1509 	*listp = list;
1510 	*countp = count;
1511 
1512 	return (0);
1513 }
1514 
1515 /**
1516  * @brief Get the number of devices in a devclass
1517  *
1518  * @param dc		the devclass to examine
1519  */
1520 int
1521 devclass_get_count(devclass_t dc)
1522 {
1523 	int count, i;
1524 
1525 	count = 0;
1526 	for (i = 0; i < dc->maxunit; i++)
1527 		if (dc->devices[i])
1528 			count++;
1529 	return (count);
1530 }
1531 
1532 /**
1533  * @brief Get the maximum unit number used in a devclass
1534  *
1535  * Note that this is one greater than the highest currently-allocated
1536  * unit.  If a null devclass_t is passed in, -1 is returned to indicate
1537  * that not even the devclass has been allocated yet.
1538  *
1539  * @param dc		the devclass to examine
1540  */
1541 int
1542 devclass_get_maxunit(devclass_t dc)
1543 {
1544 	if (dc == NULL)
1545 		return (-1);
1546 	return (dc->maxunit);
1547 }
1548 
1549 /**
1550  * @brief Find a free unit number in a devclass
1551  *
1552  * This function searches for the first unused unit number greater
1553  * that or equal to @p unit.
1554  *
1555  * @param dc		the devclass to examine
1556  * @param unit		the first unit number to check
1557  */
1558 int
1559 devclass_find_free_unit(devclass_t dc, int unit)
1560 {
1561 	if (dc == NULL)
1562 		return (unit);
1563 	while (unit < dc->maxunit && dc->devices[unit] != NULL)
1564 		unit++;
1565 	return (unit);
1566 }
1567 
1568 /**
1569  * @brief Set the parent of a devclass
1570  *
1571  * The parent class is normally initialised automatically by
1572  * DRIVER_MODULE().
1573  *
1574  * @param dc		the devclass to edit
1575  * @param pdc		the new parent devclass
1576  */
1577 void
1578 devclass_set_parent(devclass_t dc, devclass_t pdc)
1579 {
1580 	dc->parent = pdc;
1581 }
1582 
1583 /**
1584  * @brief Get the parent of a devclass
1585  *
1586  * @param dc		the devclass to examine
1587  */
1588 devclass_t
1589 devclass_get_parent(devclass_t dc)
1590 {
1591 	return (dc->parent);
1592 }
1593 
1594 struct sysctl_ctx_list *
1595 devclass_get_sysctl_ctx(devclass_t dc)
1596 {
1597 	return (&dc->sysctl_ctx);
1598 }
1599 
1600 struct sysctl_oid *
1601 devclass_get_sysctl_tree(devclass_t dc)
1602 {
1603 	return (dc->sysctl_tree);
1604 }
1605 
1606 /**
1607  * @internal
1608  * @brief Allocate a unit number
1609  *
1610  * On entry, @p *unitp is the desired unit number (or @c -1 if any
1611  * will do). The allocated unit number is returned in @p *unitp.
1612 
1613  * @param dc		the devclass to allocate from
1614  * @param unitp		points at the location for the allocated unit
1615  *			number
1616  *
1617  * @retval 0		success
1618  * @retval EEXIST	the requested unit number is already allocated
1619  * @retval ENOMEM	memory allocation failure
1620  */
1621 static int
1622 devclass_alloc_unit(devclass_t dc, device_t dev, int *unitp)
1623 {
1624 	const char *s;
1625 	int unit = *unitp;
1626 
1627 	PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
1628 
1629 	/* Ask the parent bus if it wants to wire this device. */
1630 	if (unit == -1)
1631 		BUS_HINT_DEVICE_UNIT(device_get_parent(dev), dev, dc->name,
1632 		    &unit);
1633 
1634 	/* If we were given a wired unit number, check for existing device */
1635 	/* XXX imp XXX */
1636 	if (unit != -1) {
1637 		if (unit >= 0 && unit < dc->maxunit &&
1638 		    dc->devices[unit] != NULL) {
1639 			if (bootverbose)
1640 				printf("%s: %s%d already exists; skipping it\n",
1641 				    dc->name, dc->name, *unitp);
1642 			return (EEXIST);
1643 		}
1644 	} else {
1645 		/* Unwired device, find the next available slot for it */
1646 		unit = 0;
1647 		for (unit = 0;; unit++) {
1648 			/* If there is an "at" hint for a unit then skip it. */
1649 			if (resource_string_value(dc->name, unit, "at", &s) ==
1650 			    0)
1651 				continue;
1652 
1653 			/* If this device slot is already in use, skip it. */
1654 			if (unit < dc->maxunit && dc->devices[unit] != NULL)
1655 				continue;
1656 
1657 			break;
1658 		}
1659 	}
1660 
1661 	/*
1662 	 * We've selected a unit beyond the length of the table, so let's
1663 	 * extend the table to make room for all units up to and including
1664 	 * this one.
1665 	 */
1666 	if (unit >= dc->maxunit) {
1667 		device_t *newlist, *oldlist;
1668 		int newsize;
1669 
1670 		oldlist = dc->devices;
1671 		newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
1672 		newlist = malloc(sizeof(device_t) * newsize, M_BUS, M_NOWAIT);
1673 		if (!newlist)
1674 			return (ENOMEM);
1675 		if (oldlist != NULL)
1676 			bcopy(oldlist, newlist, sizeof(device_t) * dc->maxunit);
1677 		bzero(newlist + dc->maxunit,
1678 		    sizeof(device_t) * (newsize - dc->maxunit));
1679 		dc->devices = newlist;
1680 		dc->maxunit = newsize;
1681 		if (oldlist != NULL)
1682 			free(oldlist, M_BUS);
1683 	}
1684 	PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
1685 
1686 	*unitp = unit;
1687 	return (0);
1688 }
1689 
1690 /**
1691  * @internal
1692  * @brief Add a device to a devclass
1693  *
1694  * A unit number is allocated for the device (using the device's
1695  * preferred unit number if any) and the device is registered in the
1696  * devclass. This allows the device to be looked up by its unit
1697  * number, e.g. by decoding a dev_t minor number.
1698  *
1699  * @param dc		the devclass to add to
1700  * @param dev		the device to add
1701  *
1702  * @retval 0		success
1703  * @retval EEXIST	the requested unit number is already allocated
1704  * @retval ENOMEM	memory allocation failure
1705  */
1706 static int
1707 devclass_add_device(devclass_t dc, device_t dev)
1708 {
1709 	int buflen, error;
1710 
1711 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1712 
1713 	buflen = snprintf(NULL, 0, "%s%d$", dc->name, INT_MAX);
1714 	if (buflen < 0)
1715 		return (ENOMEM);
1716 	dev->nameunit = malloc(buflen, M_BUS, M_NOWAIT|M_ZERO);
1717 	if (!dev->nameunit)
1718 		return (ENOMEM);
1719 
1720 	if ((error = devclass_alloc_unit(dc, dev, &dev->unit)) != 0) {
1721 		free(dev->nameunit, M_BUS);
1722 		dev->nameunit = NULL;
1723 		return (error);
1724 	}
1725 	dc->devices[dev->unit] = dev;
1726 	dev->devclass = dc;
1727 	snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
1728 
1729 	return (0);
1730 }
1731 
1732 /**
1733  * @internal
1734  * @brief Delete a device from a devclass
1735  *
1736  * The device is removed from the devclass's device list and its unit
1737  * number is freed.
1738 
1739  * @param dc		the devclass to delete from
1740  * @param dev		the device to delete
1741  *
1742  * @retval 0		success
1743  */
1744 static int
1745 devclass_delete_device(devclass_t dc, device_t dev)
1746 {
1747 	if (!dc || !dev)
1748 		return (0);
1749 
1750 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1751 
1752 	if (dev->devclass != dc || dc->devices[dev->unit] != dev)
1753 		panic("devclass_delete_device: inconsistent device class");
1754 	dc->devices[dev->unit] = NULL;
1755 	if (dev->flags & DF_WILDCARD)
1756 		dev->unit = -1;
1757 	dev->devclass = NULL;
1758 	free(dev->nameunit, M_BUS);
1759 	dev->nameunit = NULL;
1760 
1761 	return (0);
1762 }
1763 
1764 /**
1765  * @internal
1766  * @brief Make a new device and add it as a child of @p parent
1767  *
1768  * @param parent	the parent of the new device
1769  * @param name		the devclass name of the new device or @c NULL
1770  *			to leave the devclass unspecified
1771  * @parem unit		the unit number of the new device of @c -1 to
1772  *			leave the unit number unspecified
1773  *
1774  * @returns the new device
1775  */
1776 static device_t
1777 make_device(device_t parent, const char *name, int unit)
1778 {
1779 	device_t dev;
1780 	devclass_t dc;
1781 
1782 	PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1783 
1784 	if (name) {
1785 		dc = devclass_find_internal(name, NULL, TRUE);
1786 		if (!dc) {
1787 			printf("make_device: can't find device class %s\n",
1788 			    name);
1789 			return (NULL);
1790 		}
1791 	} else {
1792 		dc = NULL;
1793 	}
1794 
1795 	dev = malloc(sizeof(struct device), M_BUS, M_NOWAIT|M_ZERO);
1796 	if (!dev)
1797 		return (NULL);
1798 
1799 	dev->parent = parent;
1800 	TAILQ_INIT(&dev->children);
1801 	kobj_init((kobj_t) dev, &null_class);
1802 	dev->driver = NULL;
1803 	dev->devclass = NULL;
1804 	dev->unit = unit;
1805 	dev->nameunit = NULL;
1806 	dev->desc = NULL;
1807 	dev->busy = 0;
1808 	dev->devflags = 0;
1809 	dev->flags = DF_ENABLED;
1810 	dev->order = 0;
1811 	if (unit == -1)
1812 		dev->flags |= DF_WILDCARD;
1813 	if (name) {
1814 		dev->flags |= DF_FIXEDCLASS;
1815 		if (devclass_add_device(dc, dev)) {
1816 			kobj_delete((kobj_t) dev, M_BUS);
1817 			return (NULL);
1818 		}
1819 	}
1820 	dev->ivars = NULL;
1821 	dev->softc = NULL;
1822 
1823 	dev->state = DS_NOTPRESENT;
1824 
1825 	TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1826 	bus_data_generation_update();
1827 
1828 	return (dev);
1829 }
1830 
1831 /**
1832  * @internal
1833  * @brief Print a description of a device.
1834  */
1835 static int
1836 device_print_child(device_t dev, device_t child)
1837 {
1838 	int retval = 0;
1839 
1840 	if (device_is_alive(child))
1841 		retval += BUS_PRINT_CHILD(dev, child);
1842 	else
1843 		retval += device_printf(child, " not found\n");
1844 
1845 	return (retval);
1846 }
1847 
1848 /**
1849  * @brief Create a new device
1850  *
1851  * This creates a new device and adds it as a child of an existing
1852  * parent device. The new device will be added after the last existing
1853  * child with order zero.
1854  *
1855  * @param dev		the device which will be the parent of the
1856  *			new child device
1857  * @param name		devclass name for new device or @c NULL if not
1858  *			specified
1859  * @param unit		unit number for new device or @c -1 if not
1860  *			specified
1861  *
1862  * @returns		the new device
1863  */
1864 device_t
1865 device_add_child(device_t dev, const char *name, int unit)
1866 {
1867 	return (device_add_child_ordered(dev, 0, name, unit));
1868 }
1869 
1870 /**
1871  * @brief Create a new device
1872  *
1873  * This creates a new device and adds it as a child of an existing
1874  * parent device. The new device will be added after the last existing
1875  * child with the same order.
1876  *
1877  * @param dev		the device which will be the parent of the
1878  *			new child device
1879  * @param order		a value which is used to partially sort the
1880  *			children of @p dev - devices created using
1881  *			lower values of @p order appear first in @p
1882  *			dev's list of children
1883  * @param name		devclass name for new device or @c NULL if not
1884  *			specified
1885  * @param unit		unit number for new device or @c -1 if not
1886  *			specified
1887  *
1888  * @returns		the new device
1889  */
1890 device_t
1891 device_add_child_ordered(device_t dev, u_int order, const char *name, int unit)
1892 {
1893 	device_t child;
1894 	device_t place;
1895 
1896 	PDEBUG(("%s at %s with order %u as unit %d",
1897 	    name, DEVICENAME(dev), order, unit));
1898 	KASSERT(name != NULL || unit == -1,
1899 	    ("child device with wildcard name and specific unit number"));
1900 
1901 	child = make_device(dev, name, unit);
1902 	if (child == NULL)
1903 		return (child);
1904 	child->order = order;
1905 
1906 	TAILQ_FOREACH(place, &dev->children, link) {
1907 		if (place->order > order)
1908 			break;
1909 	}
1910 
1911 	if (place) {
1912 		/*
1913 		 * The device 'place' is the first device whose order is
1914 		 * greater than the new child.
1915 		 */
1916 		TAILQ_INSERT_BEFORE(place, child, link);
1917 	} else {
1918 		/*
1919 		 * The new child's order is greater or equal to the order of
1920 		 * any existing device. Add the child to the tail of the list.
1921 		 */
1922 		TAILQ_INSERT_TAIL(&dev->children, child, link);
1923 	}
1924 
1925 	bus_data_generation_update();
1926 	return (child);
1927 }
1928 
1929 /**
1930  * @brief Delete a device
1931  *
1932  * This function deletes a device along with all of its children. If
1933  * the device currently has a driver attached to it, the device is
1934  * detached first using device_detach().
1935  *
1936  * @param dev		the parent device
1937  * @param child		the device to delete
1938  *
1939  * @retval 0		success
1940  * @retval non-zero	a unit error code describing the error
1941  */
1942 int
1943 device_delete_child(device_t dev, device_t child)
1944 {
1945 	int error;
1946 	device_t grandchild;
1947 
1948 	PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1949 
1950 	/* remove children first */
1951 	while ((grandchild = TAILQ_FIRST(&child->children)) != NULL) {
1952 		error = device_delete_child(child, grandchild);
1953 		if (error)
1954 			return (error);
1955 	}
1956 
1957 	if ((error = device_detach(child)) != 0)
1958 		return (error);
1959 	if (child->devclass)
1960 		devclass_delete_device(child->devclass, child);
1961 	if (child->parent)
1962 		BUS_CHILD_DELETED(dev, child);
1963 	TAILQ_REMOVE(&dev->children, child, link);
1964 	TAILQ_REMOVE(&bus_data_devices, child, devlink);
1965 	kobj_delete((kobj_t) child, M_BUS);
1966 
1967 	bus_data_generation_update();
1968 	return (0);
1969 }
1970 
1971 /**
1972  * @brief Delete all children devices of the given device, if any.
1973  *
1974  * This function deletes all children devices of the given device, if
1975  * any, using the device_delete_child() function for each device it
1976  * finds. If a child device cannot be deleted, this function will
1977  * return an error code.
1978  *
1979  * @param dev		the parent device
1980  *
1981  * @retval 0		success
1982  * @retval non-zero	a device would not detach
1983  */
1984 int
1985 device_delete_children(device_t dev)
1986 {
1987 	device_t child;
1988 	int error;
1989 
1990 	PDEBUG(("Deleting all children of %s", DEVICENAME(dev)));
1991 
1992 	error = 0;
1993 
1994 	while ((child = TAILQ_FIRST(&dev->children)) != NULL) {
1995 		error = device_delete_child(dev, child);
1996 		if (error) {
1997 			PDEBUG(("Failed deleting %s", DEVICENAME(child)));
1998 			break;
1999 		}
2000 	}
2001 	return (error);
2002 }
2003 
2004 /**
2005  * @brief Find a device given a unit number
2006  *
2007  * This is similar to devclass_get_devices() but only searches for
2008  * devices which have @p dev as a parent.
2009  *
2010  * @param dev		the parent device to search
2011  * @param unit		the unit number to search for.  If the unit is -1,
2012  *			return the first child of @p dev which has name
2013  *			@p classname (that is, the one with the lowest unit.)
2014  *
2015  * @returns		the device with the given unit number or @c
2016  *			NULL if there is no such device
2017  */
2018 device_t
2019 device_find_child(device_t dev, const char *classname, int unit)
2020 {
2021 	devclass_t dc;
2022 	device_t child;
2023 
2024 	dc = devclass_find(classname);
2025 	if (!dc)
2026 		return (NULL);
2027 
2028 	if (unit != -1) {
2029 		child = devclass_get_device(dc, unit);
2030 		if (child && child->parent == dev)
2031 			return (child);
2032 	} else {
2033 		for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
2034 			child = devclass_get_device(dc, unit);
2035 			if (child && child->parent == dev)
2036 				return (child);
2037 		}
2038 	}
2039 	return (NULL);
2040 }
2041 
2042 /**
2043  * @internal
2044  */
2045 static driverlink_t
2046 first_matching_driver(devclass_t dc, device_t dev)
2047 {
2048 	if (dev->devclass)
2049 		return (devclass_find_driver_internal(dc, dev->devclass->name));
2050 	return (TAILQ_FIRST(&dc->drivers));
2051 }
2052 
2053 /**
2054  * @internal
2055  */
2056 static driverlink_t
2057 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
2058 {
2059 	if (dev->devclass) {
2060 		driverlink_t dl;
2061 		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
2062 			if (!strcmp(dev->devclass->name, dl->driver->name))
2063 				return (dl);
2064 		return (NULL);
2065 	}
2066 	return (TAILQ_NEXT(last, link));
2067 }
2068 
2069 /**
2070  * @internal
2071  */
2072 int
2073 device_probe_child(device_t dev, device_t child)
2074 {
2075 	devclass_t dc;
2076 	driverlink_t best = NULL;
2077 	driverlink_t dl;
2078 	int result, pri = 0;
2079 	int hasclass = (child->devclass != NULL);
2080 
2081 	GIANT_REQUIRED;
2082 
2083 	dc = dev->devclass;
2084 	if (!dc)
2085 		panic("device_probe_child: parent device has no devclass");
2086 
2087 	/*
2088 	 * If the state is already probed, then return.  However, don't
2089 	 * return if we can rebid this object.
2090 	 */
2091 	if (child->state == DS_ALIVE && (child->flags & DF_REBID) == 0)
2092 		return (0);
2093 
2094 	for (; dc; dc = dc->parent) {
2095 		for (dl = first_matching_driver(dc, child);
2096 		     dl;
2097 		     dl = next_matching_driver(dc, child, dl)) {
2098 			/* If this driver's pass is too high, then ignore it. */
2099 			if (dl->pass > bus_current_pass)
2100 				continue;
2101 
2102 			PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
2103 			result = device_set_driver(child, dl->driver);
2104 			if (result == ENOMEM)
2105 				return (result);
2106 			else if (result != 0)
2107 				continue;
2108 			if (!hasclass) {
2109 				if (device_set_devclass(child,
2110 				    dl->driver->name) != 0) {
2111 					char const * devname =
2112 					    device_get_name(child);
2113 					if (devname == NULL)
2114 						devname = "(unknown)";
2115 					printf("driver bug: Unable to set "
2116 					    "devclass (class: %s "
2117 					    "devname: %s)\n",
2118 					    dl->driver->name,
2119 					    devname);
2120 					(void)device_set_driver(child, NULL);
2121 					continue;
2122 				}
2123 			}
2124 
2125 			/* Fetch any flags for the device before probing. */
2126 			resource_int_value(dl->driver->name, child->unit,
2127 			    "flags", &child->devflags);
2128 
2129 			result = DEVICE_PROBE(child);
2130 
2131 			/* Reset flags and devclass before the next probe. */
2132 			child->devflags = 0;
2133 			if (!hasclass)
2134 				(void)device_set_devclass(child, NULL);
2135 
2136 			/*
2137 			 * If the driver returns SUCCESS, there can be
2138 			 * no higher match for this device.
2139 			 */
2140 			if (result == 0) {
2141 				best = dl;
2142 				pri = 0;
2143 				break;
2144 			}
2145 
2146 			/*
2147 			 * Probes that return BUS_PROBE_NOWILDCARD or lower
2148 			 * only match on devices whose driver was explicitly
2149 			 * specified.
2150 			 */
2151 			if (result <= BUS_PROBE_NOWILDCARD &&
2152 			    !(child->flags & DF_FIXEDCLASS)) {
2153 				result = ENXIO;
2154 			}
2155 
2156 			/*
2157 			 * The driver returned an error so it
2158 			 * certainly doesn't match.
2159 			 */
2160 			if (result > 0) {
2161 				(void)device_set_driver(child, NULL);
2162 				continue;
2163 			}
2164 
2165 			/*
2166 			 * A priority lower than SUCCESS, remember the
2167 			 * best matching driver. Initialise the value
2168 			 * of pri for the first match.
2169 			 */
2170 			if (best == NULL || result > pri) {
2171 				best = dl;
2172 				pri = result;
2173 				continue;
2174 			}
2175 		}
2176 		/*
2177 		 * If we have an unambiguous match in this devclass,
2178 		 * don't look in the parent.
2179 		 */
2180 		if (best && pri == 0)
2181 			break;
2182 	}
2183 
2184 	/*
2185 	 * If we found a driver, change state and initialise the devclass.
2186 	 */
2187 	/* XXX What happens if we rebid and got no best? */
2188 	if (best) {
2189 		/*
2190 		 * If this device was attached, and we were asked to
2191 		 * rescan, and it is a different driver, then we have
2192 		 * to detach the old driver and reattach this new one.
2193 		 * Note, we don't have to check for DF_REBID here
2194 		 * because if the state is > DS_ALIVE, we know it must
2195 		 * be.
2196 		 *
2197 		 * This assumes that all DF_REBID drivers can have
2198 		 * their probe routine called at any time and that
2199 		 * they are idempotent as well as completely benign in
2200 		 * normal operations.
2201 		 *
2202 		 * We also have to make sure that the detach
2203 		 * succeeded, otherwise we fail the operation (or
2204 		 * maybe it should just fail silently?  I'm torn).
2205 		 */
2206 		if (child->state > DS_ALIVE && best->driver != child->driver)
2207 			if ((result = device_detach(dev)) != 0)
2208 				return (result);
2209 
2210 		/* Set the winning driver, devclass, and flags. */
2211 		if (!child->devclass) {
2212 			result = device_set_devclass(child, best->driver->name);
2213 			if (result != 0)
2214 				return (result);
2215 		}
2216 		result = device_set_driver(child, best->driver);
2217 		if (result != 0)
2218 			return (result);
2219 		resource_int_value(best->driver->name, child->unit,
2220 		    "flags", &child->devflags);
2221 
2222 		if (pri < 0) {
2223 			/*
2224 			 * A bit bogus. Call the probe method again to make
2225 			 * sure that we have the right description.
2226 			 */
2227 			DEVICE_PROBE(child);
2228 #if 0
2229 			child->flags |= DF_REBID;
2230 #endif
2231 		} else
2232 			child->flags &= ~DF_REBID;
2233 		child->state = DS_ALIVE;
2234 
2235 		bus_data_generation_update();
2236 		return (0);
2237 	}
2238 
2239 	return (ENXIO);
2240 }
2241 
2242 /**
2243  * @brief Return the parent of a device
2244  */
2245 device_t
2246 device_get_parent(device_t dev)
2247 {
2248 	return (dev->parent);
2249 }
2250 
2251 /**
2252  * @brief Get a list of children of a device
2253  *
2254  * An array containing a list of all the children of the given device
2255  * is allocated and returned in @p *devlistp. The number of devices
2256  * in the array is returned in @p *devcountp. The caller should free
2257  * the array using @c free(p, M_TEMP).
2258  *
2259  * @param dev		the device to examine
2260  * @param devlistp	points at location for array pointer return
2261  *			value
2262  * @param devcountp	points at location for array size return value
2263  *
2264  * @retval 0		success
2265  * @retval ENOMEM	the array allocation failed
2266  */
2267 int
2268 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
2269 {
2270 	int count;
2271 	device_t child;
2272 	device_t *list;
2273 
2274 	count = 0;
2275 	TAILQ_FOREACH(child, &dev->children, link) {
2276 		count++;
2277 	}
2278 	if (count == 0) {
2279 		*devlistp = NULL;
2280 		*devcountp = 0;
2281 		return (0);
2282 	}
2283 
2284 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
2285 	if (!list)
2286 		return (ENOMEM);
2287 
2288 	count = 0;
2289 	TAILQ_FOREACH(child, &dev->children, link) {
2290 		list[count] = child;
2291 		count++;
2292 	}
2293 
2294 	*devlistp = list;
2295 	*devcountp = count;
2296 
2297 	return (0);
2298 }
2299 
2300 /**
2301  * @brief Return the current driver for the device or @c NULL if there
2302  * is no driver currently attached
2303  */
2304 driver_t *
2305 device_get_driver(device_t dev)
2306 {
2307 	return (dev->driver);
2308 }
2309 
2310 /**
2311  * @brief Return the current devclass for the device or @c NULL if
2312  * there is none.
2313  */
2314 devclass_t
2315 device_get_devclass(device_t dev)
2316 {
2317 	return (dev->devclass);
2318 }
2319 
2320 /**
2321  * @brief Return the name of the device's devclass or @c NULL if there
2322  * is none.
2323  */
2324 const char *
2325 device_get_name(device_t dev)
2326 {
2327 	if (dev != NULL && dev->devclass)
2328 		return (devclass_get_name(dev->devclass));
2329 	return (NULL);
2330 }
2331 
2332 /**
2333  * @brief Return a string containing the device's devclass name
2334  * followed by an ascii representation of the device's unit number
2335  * (e.g. @c "foo2").
2336  */
2337 const char *
2338 device_get_nameunit(device_t dev)
2339 {
2340 	return (dev->nameunit);
2341 }
2342 
2343 /**
2344  * @brief Return the device's unit number.
2345  */
2346 int
2347 device_get_unit(device_t dev)
2348 {
2349 	return (dev->unit);
2350 }
2351 
2352 /**
2353  * @brief Return the device's description string
2354  */
2355 const char *
2356 device_get_desc(device_t dev)
2357 {
2358 	return (dev->desc);
2359 }
2360 
2361 /**
2362  * @brief Return the device's flags
2363  */
2364 uint32_t
2365 device_get_flags(device_t dev)
2366 {
2367 	return (dev->devflags);
2368 }
2369 
2370 struct sysctl_ctx_list *
2371 device_get_sysctl_ctx(device_t dev)
2372 {
2373 	return (&dev->sysctl_ctx);
2374 }
2375 
2376 struct sysctl_oid *
2377 device_get_sysctl_tree(device_t dev)
2378 {
2379 	return (dev->sysctl_tree);
2380 }
2381 
2382 /**
2383  * @brief Print the name of the device followed by a colon and a space
2384  *
2385  * @returns the number of characters printed
2386  */
2387 int
2388 device_print_prettyname(device_t dev)
2389 {
2390 	const char *name = device_get_name(dev);
2391 
2392 	if (name == NULL)
2393 		return (printf("unknown: "));
2394 	return (printf("%s%d: ", name, device_get_unit(dev)));
2395 }
2396 
2397 /**
2398  * @brief Print the name of the device followed by a colon, a space
2399  * and the result of calling vprintf() with the value of @p fmt and
2400  * the following arguments.
2401  *
2402  * @returns the number of characters printed
2403  */
2404 int
2405 device_printf(device_t dev, const char * fmt, ...)
2406 {
2407 	va_list ap;
2408 	int retval;
2409 
2410 	retval = device_print_prettyname(dev);
2411 	va_start(ap, fmt);
2412 	retval += vprintf(fmt, ap);
2413 	va_end(ap);
2414 	return (retval);
2415 }
2416 
2417 /**
2418  * @internal
2419  */
2420 static void
2421 device_set_desc_internal(device_t dev, const char* desc, int copy)
2422 {
2423 	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
2424 		free(dev->desc, M_BUS);
2425 		dev->flags &= ~DF_DESCMALLOCED;
2426 		dev->desc = NULL;
2427 	}
2428 
2429 	if (copy && desc) {
2430 		dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
2431 		if (dev->desc) {
2432 			strcpy(dev->desc, desc);
2433 			dev->flags |= DF_DESCMALLOCED;
2434 		}
2435 	} else {
2436 		/* Avoid a -Wcast-qual warning */
2437 		dev->desc = (char *)(uintptr_t) desc;
2438 	}
2439 
2440 	bus_data_generation_update();
2441 }
2442 
2443 /**
2444  * @brief Set the device's description
2445  *
2446  * The value of @c desc should be a string constant that will not
2447  * change (at least until the description is changed in a subsequent
2448  * call to device_set_desc() or device_set_desc_copy()).
2449  */
2450 void
2451 device_set_desc(device_t dev, const char* desc)
2452 {
2453 	device_set_desc_internal(dev, desc, FALSE);
2454 }
2455 
2456 /**
2457  * @brief Set the device's description
2458  *
2459  * The string pointed to by @c desc is copied. Use this function if
2460  * the device description is generated, (e.g. with sprintf()).
2461  */
2462 void
2463 device_set_desc_copy(device_t dev, const char* desc)
2464 {
2465 	device_set_desc_internal(dev, desc, TRUE);
2466 }
2467 
2468 /**
2469  * @brief Set the device's flags
2470  */
2471 void
2472 device_set_flags(device_t dev, uint32_t flags)
2473 {
2474 	dev->devflags = flags;
2475 }
2476 
2477 /**
2478  * @brief Return the device's softc field
2479  *
2480  * The softc is allocated and zeroed when a driver is attached, based
2481  * on the size field of the driver.
2482  */
2483 void *
2484 device_get_softc(device_t dev)
2485 {
2486 	return (dev->softc);
2487 }
2488 
2489 /**
2490  * @brief Set the device's softc field
2491  *
2492  * Most drivers do not need to use this since the softc is allocated
2493  * automatically when the driver is attached.
2494  */
2495 void
2496 device_set_softc(device_t dev, void *softc)
2497 {
2498 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
2499 		free(dev->softc, M_BUS_SC);
2500 	dev->softc = softc;
2501 	if (dev->softc)
2502 		dev->flags |= DF_EXTERNALSOFTC;
2503 	else
2504 		dev->flags &= ~DF_EXTERNALSOFTC;
2505 }
2506 
2507 /**
2508  * @brief Free claimed softc
2509  *
2510  * Most drivers do not need to use this since the softc is freed
2511  * automatically when the driver is detached.
2512  */
2513 void
2514 device_free_softc(void *softc)
2515 {
2516 	free(softc, M_BUS_SC);
2517 }
2518 
2519 /**
2520  * @brief Claim softc
2521  *
2522  * This function can be used to let the driver free the automatically
2523  * allocated softc using "device_free_softc()". This function is
2524  * useful when the driver is refcounting the softc and the softc
2525  * cannot be freed when the "device_detach" method is called.
2526  */
2527 void
2528 device_claim_softc(device_t dev)
2529 {
2530 	if (dev->softc)
2531 		dev->flags |= DF_EXTERNALSOFTC;
2532 	else
2533 		dev->flags &= ~DF_EXTERNALSOFTC;
2534 }
2535 
2536 /**
2537  * @brief Get the device's ivars field
2538  *
2539  * The ivars field is used by the parent device to store per-device
2540  * state (e.g. the physical location of the device or a list of
2541  * resources).
2542  */
2543 void *
2544 device_get_ivars(device_t dev)
2545 {
2546 
2547 	KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
2548 	return (dev->ivars);
2549 }
2550 
2551 /**
2552  * @brief Set the device's ivars field
2553  */
2554 void
2555 device_set_ivars(device_t dev, void * ivars)
2556 {
2557 
2558 	KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
2559 	dev->ivars = ivars;
2560 }
2561 
2562 /**
2563  * @brief Return the device's state
2564  */
2565 device_state_t
2566 device_get_state(device_t dev)
2567 {
2568 	return (dev->state);
2569 }
2570 
2571 /**
2572  * @brief Set the DF_ENABLED flag for the device
2573  */
2574 void
2575 device_enable(device_t dev)
2576 {
2577 	dev->flags |= DF_ENABLED;
2578 }
2579 
2580 /**
2581  * @brief Clear the DF_ENABLED flag for the device
2582  */
2583 void
2584 device_disable(device_t dev)
2585 {
2586 	dev->flags &= ~DF_ENABLED;
2587 }
2588 
2589 /**
2590  * @brief Increment the busy counter for the device
2591  */
2592 void
2593 device_busy(device_t dev)
2594 {
2595 	if (dev->state < DS_ATTACHING)
2596 		panic("device_busy: called for unattached device");
2597 	if (dev->busy == 0 && dev->parent)
2598 		device_busy(dev->parent);
2599 	dev->busy++;
2600 	if (dev->state == DS_ATTACHED)
2601 		dev->state = DS_BUSY;
2602 }
2603 
2604 /**
2605  * @brief Decrement the busy counter for the device
2606  */
2607 void
2608 device_unbusy(device_t dev)
2609 {
2610 	if (dev->busy != 0 && dev->state != DS_BUSY &&
2611 	    dev->state != DS_ATTACHING)
2612 		panic("device_unbusy: called for non-busy device %s",
2613 		    device_get_nameunit(dev));
2614 	dev->busy--;
2615 	if (dev->busy == 0) {
2616 		if (dev->parent)
2617 			device_unbusy(dev->parent);
2618 		if (dev->state == DS_BUSY)
2619 			dev->state = DS_ATTACHED;
2620 	}
2621 }
2622 
2623 /**
2624  * @brief Set the DF_QUIET flag for the device
2625  */
2626 void
2627 device_quiet(device_t dev)
2628 {
2629 	dev->flags |= DF_QUIET;
2630 }
2631 
2632 /**
2633  * @brief Clear the DF_QUIET flag for the device
2634  */
2635 void
2636 device_verbose(device_t dev)
2637 {
2638 	dev->flags &= ~DF_QUIET;
2639 }
2640 
2641 /**
2642  * @brief Return non-zero if the DF_QUIET flag is set on the device
2643  */
2644 int
2645 device_is_quiet(device_t dev)
2646 {
2647 	return ((dev->flags & DF_QUIET) != 0);
2648 }
2649 
2650 /**
2651  * @brief Return non-zero if the DF_ENABLED flag is set on the device
2652  */
2653 int
2654 device_is_enabled(device_t dev)
2655 {
2656 	return ((dev->flags & DF_ENABLED) != 0);
2657 }
2658 
2659 /**
2660  * @brief Return non-zero if the device was successfully probed
2661  */
2662 int
2663 device_is_alive(device_t dev)
2664 {
2665 	return (dev->state >= DS_ALIVE);
2666 }
2667 
2668 /**
2669  * @brief Return non-zero if the device currently has a driver
2670  * attached to it
2671  */
2672 int
2673 device_is_attached(device_t dev)
2674 {
2675 	return (dev->state >= DS_ATTACHED);
2676 }
2677 
2678 /**
2679  * @brief Return non-zero if the device is currently suspended.
2680  */
2681 int
2682 device_is_suspended(device_t dev)
2683 {
2684 	return ((dev->flags & DF_SUSPENDED) != 0);
2685 }
2686 
2687 /**
2688  * @brief Set the devclass of a device
2689  * @see devclass_add_device().
2690  */
2691 int
2692 device_set_devclass(device_t dev, const char *classname)
2693 {
2694 	devclass_t dc;
2695 	int error;
2696 
2697 	if (!classname) {
2698 		if (dev->devclass)
2699 			devclass_delete_device(dev->devclass, dev);
2700 		return (0);
2701 	}
2702 
2703 	if (dev->devclass) {
2704 		printf("device_set_devclass: device class already set\n");
2705 		return (EINVAL);
2706 	}
2707 
2708 	dc = devclass_find_internal(classname, NULL, TRUE);
2709 	if (!dc)
2710 		return (ENOMEM);
2711 
2712 	error = devclass_add_device(dc, dev);
2713 
2714 	bus_data_generation_update();
2715 	return (error);
2716 }
2717 
2718 /**
2719  * @brief Set the devclass of a device and mark the devclass fixed.
2720  * @see device_set_devclass()
2721  */
2722 int
2723 device_set_devclass_fixed(device_t dev, const char *classname)
2724 {
2725 	int error;
2726 
2727 	if (classname == NULL)
2728 		return (EINVAL);
2729 
2730 	error = device_set_devclass(dev, classname);
2731 	if (error)
2732 		return (error);
2733 	dev->flags |= DF_FIXEDCLASS;
2734 	return (0);
2735 }
2736 
2737 /**
2738  * @brief Set the driver of a device
2739  *
2740  * @retval 0		success
2741  * @retval EBUSY	the device already has a driver attached
2742  * @retval ENOMEM	a memory allocation failure occurred
2743  */
2744 int
2745 device_set_driver(device_t dev, driver_t *driver)
2746 {
2747 	if (dev->state >= DS_ATTACHED)
2748 		return (EBUSY);
2749 
2750 	if (dev->driver == driver)
2751 		return (0);
2752 
2753 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
2754 		free(dev->softc, M_BUS_SC);
2755 		dev->softc = NULL;
2756 	}
2757 	device_set_desc(dev, NULL);
2758 	kobj_delete((kobj_t) dev, NULL);
2759 	dev->driver = driver;
2760 	if (driver) {
2761 		kobj_init((kobj_t) dev, (kobj_class_t) driver);
2762 		if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
2763 			dev->softc = malloc(driver->size, M_BUS_SC,
2764 			    M_NOWAIT | M_ZERO);
2765 			if (!dev->softc) {
2766 				kobj_delete((kobj_t) dev, NULL);
2767 				kobj_init((kobj_t) dev, &null_class);
2768 				dev->driver = NULL;
2769 				return (ENOMEM);
2770 			}
2771 		}
2772 	} else {
2773 		kobj_init((kobj_t) dev, &null_class);
2774 	}
2775 
2776 	bus_data_generation_update();
2777 	return (0);
2778 }
2779 
2780 /**
2781  * @brief Probe a device, and return this status.
2782  *
2783  * This function is the core of the device autoconfiguration
2784  * system. Its purpose is to select a suitable driver for a device and
2785  * then call that driver to initialise the hardware appropriately. The
2786  * driver is selected by calling the DEVICE_PROBE() method of a set of
2787  * candidate drivers and then choosing the driver which returned the
2788  * best value. This driver is then attached to the device using
2789  * device_attach().
2790  *
2791  * The set of suitable drivers is taken from the list of drivers in
2792  * the parent device's devclass. If the device was originally created
2793  * with a specific class name (see device_add_child()), only drivers
2794  * with that name are probed, otherwise all drivers in the devclass
2795  * are probed. If no drivers return successful probe values in the
2796  * parent devclass, the search continues in the parent of that
2797  * devclass (see devclass_get_parent()) if any.
2798  *
2799  * @param dev		the device to initialise
2800  *
2801  * @retval 0		success
2802  * @retval ENXIO	no driver was found
2803  * @retval ENOMEM	memory allocation failure
2804  * @retval non-zero	some other unix error code
2805  * @retval -1		Device already attached
2806  */
2807 int
2808 device_probe(device_t dev)
2809 {
2810 	int error;
2811 
2812 	GIANT_REQUIRED;
2813 
2814 	if (dev->state >= DS_ALIVE && (dev->flags & DF_REBID) == 0)
2815 		return (-1);
2816 
2817 	if (!(dev->flags & DF_ENABLED)) {
2818 		if (bootverbose && device_get_name(dev) != NULL) {
2819 			device_print_prettyname(dev);
2820 			printf("not probed (disabled)\n");
2821 		}
2822 		return (-1);
2823 	}
2824 	if ((error = device_probe_child(dev->parent, dev)) != 0) {
2825 		if (bus_current_pass == BUS_PASS_DEFAULT &&
2826 		    !(dev->flags & DF_DONENOMATCH)) {
2827 			BUS_PROBE_NOMATCH(dev->parent, dev);
2828 			devnomatch(dev);
2829 			dev->flags |= DF_DONENOMATCH;
2830 		}
2831 		return (error);
2832 	}
2833 	return (0);
2834 }
2835 
2836 /**
2837  * @brief Probe a device and attach a driver if possible
2838  *
2839  * calls device_probe() and attaches if that was successful.
2840  */
2841 int
2842 device_probe_and_attach(device_t dev)
2843 {
2844 	int error;
2845 
2846 	GIANT_REQUIRED;
2847 
2848 	error = device_probe(dev);
2849 	if (error == -1)
2850 		return (0);
2851 	else if (error != 0)
2852 		return (error);
2853 
2854 	CURVNET_SET_QUIET(vnet0);
2855 	error = device_attach(dev);
2856 	CURVNET_RESTORE();
2857 	return error;
2858 }
2859 
2860 /**
2861  * @brief Attach a device driver to a device
2862  *
2863  * This function is a wrapper around the DEVICE_ATTACH() driver
2864  * method. In addition to calling DEVICE_ATTACH(), it initialises the
2865  * device's sysctl tree, optionally prints a description of the device
2866  * and queues a notification event for user-based device management
2867  * services.
2868  *
2869  * Normally this function is only called internally from
2870  * device_probe_and_attach().
2871  *
2872  * @param dev		the device to initialise
2873  *
2874  * @retval 0		success
2875  * @retval ENXIO	no driver was found
2876  * @retval ENOMEM	memory allocation failure
2877  * @retval non-zero	some other unix error code
2878  */
2879 int
2880 device_attach(device_t dev)
2881 {
2882 	uint64_t attachtime;
2883 	int error;
2884 
2885 	if (resource_disabled(dev->driver->name, dev->unit)) {
2886 		device_disable(dev);
2887 		if (bootverbose)
2888 			 device_printf(dev, "disabled via hints entry\n");
2889 		return (ENXIO);
2890 	}
2891 
2892 	device_sysctl_init(dev);
2893 	if (!device_is_quiet(dev))
2894 		device_print_child(dev->parent, dev);
2895 	attachtime = get_cyclecount();
2896 	dev->state = DS_ATTACHING;
2897 	if ((error = DEVICE_ATTACH(dev)) != 0) {
2898 		printf("device_attach: %s%d attach returned %d\n",
2899 		    dev->driver->name, dev->unit, error);
2900 		if (!(dev->flags & DF_FIXEDCLASS))
2901 			devclass_delete_device(dev->devclass, dev);
2902 		(void)device_set_driver(dev, NULL);
2903 		device_sysctl_fini(dev);
2904 		KASSERT(dev->busy == 0, ("attach failed but busy"));
2905 		dev->state = DS_NOTPRESENT;
2906 		return (error);
2907 	}
2908 	attachtime = get_cyclecount() - attachtime;
2909 	/*
2910 	 * 4 bits per device is a reasonable value for desktop and server
2911 	 * hardware with good get_cyclecount() implementations, but WILL
2912 	 * need to be adjusted on other platforms.
2913 	 */
2914 #define	RANDOM_PROBE_BIT_GUESS	4
2915 	if (bootverbose)
2916 		printf("random: harvesting attach, %zu bytes (%d bits) from %s%d\n",
2917 		    sizeof(attachtime), RANDOM_PROBE_BIT_GUESS,
2918 		    dev->driver->name, dev->unit);
2919 	random_harvest_direct(&attachtime, sizeof(attachtime),
2920 	    RANDOM_PROBE_BIT_GUESS, RANDOM_ATTACH);
2921 	device_sysctl_update(dev);
2922 	if (dev->busy)
2923 		dev->state = DS_BUSY;
2924 	else
2925 		dev->state = DS_ATTACHED;
2926 	dev->flags &= ~DF_DONENOMATCH;
2927 	devadded(dev);
2928 	return (0);
2929 }
2930 
2931 /**
2932  * @brief Detach a driver from a device
2933  *
2934  * This function is a wrapper around the DEVICE_DETACH() driver
2935  * method. If the call to DEVICE_DETACH() succeeds, it calls
2936  * BUS_CHILD_DETACHED() for the parent of @p dev, queues a
2937  * notification event for user-based device management services and
2938  * cleans up the device's sysctl tree.
2939  *
2940  * @param dev		the device to un-initialise
2941  *
2942  * @retval 0		success
2943  * @retval ENXIO	no driver was found
2944  * @retval ENOMEM	memory allocation failure
2945  * @retval non-zero	some other unix error code
2946  */
2947 int
2948 device_detach(device_t dev)
2949 {
2950 	int error;
2951 
2952 	GIANT_REQUIRED;
2953 
2954 	PDEBUG(("%s", DEVICENAME(dev)));
2955 	if (dev->state == DS_BUSY)
2956 		return (EBUSY);
2957 	if (dev->state != DS_ATTACHED)
2958 		return (0);
2959 
2960 	if ((error = DEVICE_DETACH(dev)) != 0)
2961 		return (error);
2962 	devremoved(dev);
2963 	if (!device_is_quiet(dev))
2964 		device_printf(dev, "detached\n");
2965 	if (dev->parent)
2966 		BUS_CHILD_DETACHED(dev->parent, dev);
2967 
2968 	if (!(dev->flags & DF_FIXEDCLASS))
2969 		devclass_delete_device(dev->devclass, dev);
2970 
2971 	dev->state = DS_NOTPRESENT;
2972 	(void)device_set_driver(dev, NULL);
2973 	device_sysctl_fini(dev);
2974 
2975 	return (0);
2976 }
2977 
2978 /**
2979  * @brief Tells a driver to quiesce itself.
2980  *
2981  * This function is a wrapper around the DEVICE_QUIESCE() driver
2982  * method. If the call to DEVICE_QUIESCE() succeeds.
2983  *
2984  * @param dev		the device to quiesce
2985  *
2986  * @retval 0		success
2987  * @retval ENXIO	no driver was found
2988  * @retval ENOMEM	memory allocation failure
2989  * @retval non-zero	some other unix error code
2990  */
2991 int
2992 device_quiesce(device_t dev)
2993 {
2994 
2995 	PDEBUG(("%s", DEVICENAME(dev)));
2996 	if (dev->state == DS_BUSY)
2997 		return (EBUSY);
2998 	if (dev->state != DS_ATTACHED)
2999 		return (0);
3000 
3001 	return (DEVICE_QUIESCE(dev));
3002 }
3003 
3004 /**
3005  * @brief Notify a device of system shutdown
3006  *
3007  * This function calls the DEVICE_SHUTDOWN() driver method if the
3008  * device currently has an attached driver.
3009  *
3010  * @returns the value returned by DEVICE_SHUTDOWN()
3011  */
3012 int
3013 device_shutdown(device_t dev)
3014 {
3015 	if (dev->state < DS_ATTACHED)
3016 		return (0);
3017 	return (DEVICE_SHUTDOWN(dev));
3018 }
3019 
3020 /**
3021  * @brief Set the unit number of a device
3022  *
3023  * This function can be used to override the unit number used for a
3024  * device (e.g. to wire a device to a pre-configured unit number).
3025  */
3026 int
3027 device_set_unit(device_t dev, int unit)
3028 {
3029 	devclass_t dc;
3030 	int err;
3031 
3032 	dc = device_get_devclass(dev);
3033 	if (unit < dc->maxunit && dc->devices[unit])
3034 		return (EBUSY);
3035 	err = devclass_delete_device(dc, dev);
3036 	if (err)
3037 		return (err);
3038 	dev->unit = unit;
3039 	err = devclass_add_device(dc, dev);
3040 	if (err)
3041 		return (err);
3042 
3043 	bus_data_generation_update();
3044 	return (0);
3045 }
3046 
3047 /*======================================*/
3048 /*
3049  * Some useful method implementations to make life easier for bus drivers.
3050  */
3051 
3052 /**
3053  * @brief Initialise a resource list.
3054  *
3055  * @param rl		the resource list to initialise
3056  */
3057 void
3058 resource_list_init(struct resource_list *rl)
3059 {
3060 	STAILQ_INIT(rl);
3061 }
3062 
3063 /**
3064  * @brief Reclaim memory used by a resource list.
3065  *
3066  * This function frees the memory for all resource entries on the list
3067  * (if any).
3068  *
3069  * @param rl		the resource list to free
3070  */
3071 void
3072 resource_list_free(struct resource_list *rl)
3073 {
3074 	struct resource_list_entry *rle;
3075 
3076 	while ((rle = STAILQ_FIRST(rl)) != NULL) {
3077 		if (rle->res)
3078 			panic("resource_list_free: resource entry is busy");
3079 		STAILQ_REMOVE_HEAD(rl, link);
3080 		free(rle, M_BUS);
3081 	}
3082 }
3083 
3084 /**
3085  * @brief Add a resource entry.
3086  *
3087  * This function adds a resource entry using the given @p type, @p
3088  * start, @p end and @p count values. A rid value is chosen by
3089  * searching sequentially for the first unused rid starting at zero.
3090  *
3091  * @param rl		the resource list to edit
3092  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
3093  * @param start		the start address of the resource
3094  * @param end		the end address of the resource
3095  * @param count		XXX end-start+1
3096  */
3097 int
3098 resource_list_add_next(struct resource_list *rl, int type, rman_res_t start,
3099     rman_res_t end, rman_res_t count)
3100 {
3101 	int rid;
3102 
3103 	rid = 0;
3104 	while (resource_list_find(rl, type, rid) != NULL)
3105 		rid++;
3106 	resource_list_add(rl, type, rid, start, end, count);
3107 	return (rid);
3108 }
3109 
3110 /**
3111  * @brief Add or modify a resource entry.
3112  *
3113  * If an existing entry exists with the same type and rid, it will be
3114  * modified using the given values of @p start, @p end and @p
3115  * count. If no entry exists, a new one will be created using the
3116  * given values.  The resource list entry that matches is then returned.
3117  *
3118  * @param rl		the resource list to edit
3119  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
3120  * @param rid		the resource identifier
3121  * @param start		the start address of the resource
3122  * @param end		the end address of the resource
3123  * @param count		XXX end-start+1
3124  */
3125 struct resource_list_entry *
3126 resource_list_add(struct resource_list *rl, int type, int rid,
3127     rman_res_t start, rman_res_t end, rman_res_t count)
3128 {
3129 	struct resource_list_entry *rle;
3130 
3131 	rle = resource_list_find(rl, type, rid);
3132 	if (!rle) {
3133 		rle = malloc(sizeof(struct resource_list_entry), M_BUS,
3134 		    M_NOWAIT);
3135 		if (!rle)
3136 			panic("resource_list_add: can't record entry");
3137 		STAILQ_INSERT_TAIL(rl, rle, link);
3138 		rle->type = type;
3139 		rle->rid = rid;
3140 		rle->res = NULL;
3141 		rle->flags = 0;
3142 	}
3143 
3144 	if (rle->res)
3145 		panic("resource_list_add: resource entry is busy");
3146 
3147 	rle->start = start;
3148 	rle->end = end;
3149 	rle->count = count;
3150 	return (rle);
3151 }
3152 
3153 /**
3154  * @brief Determine if a resource entry is busy.
3155  *
3156  * Returns true if a resource entry is busy meaning that it has an
3157  * associated resource that is not an unallocated "reserved" resource.
3158  *
3159  * @param rl		the resource list to search
3160  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
3161  * @param rid		the resource identifier
3162  *
3163  * @returns Non-zero if the entry is busy, zero otherwise.
3164  */
3165 int
3166 resource_list_busy(struct resource_list *rl, int type, int rid)
3167 {
3168 	struct resource_list_entry *rle;
3169 
3170 	rle = resource_list_find(rl, type, rid);
3171 	if (rle == NULL || rle->res == NULL)
3172 		return (0);
3173 	if ((rle->flags & (RLE_RESERVED | RLE_ALLOCATED)) == RLE_RESERVED) {
3174 		KASSERT(!(rman_get_flags(rle->res) & RF_ACTIVE),
3175 		    ("reserved resource is active"));
3176 		return (0);
3177 	}
3178 	return (1);
3179 }
3180 
3181 /**
3182  * @brief Determine if a resource entry is reserved.
3183  *
3184  * Returns true if a resource entry is reserved meaning that it has an
3185  * associated "reserved" resource.  The resource can either be
3186  * allocated or unallocated.
3187  *
3188  * @param rl		the resource list to search
3189  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
3190  * @param rid		the resource identifier
3191  *
3192  * @returns Non-zero if the entry is reserved, zero otherwise.
3193  */
3194 int
3195 resource_list_reserved(struct resource_list *rl, int type, int rid)
3196 {
3197 	struct resource_list_entry *rle;
3198 
3199 	rle = resource_list_find(rl, type, rid);
3200 	if (rle != NULL && rle->flags & RLE_RESERVED)
3201 		return (1);
3202 	return (0);
3203 }
3204 
3205 /**
3206  * @brief Find a resource entry by type and rid.
3207  *
3208  * @param rl		the resource list to search
3209  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
3210  * @param rid		the resource identifier
3211  *
3212  * @returns the resource entry pointer or NULL if there is no such
3213  * entry.
3214  */
3215 struct resource_list_entry *
3216 resource_list_find(struct resource_list *rl, int type, int rid)
3217 {
3218 	struct resource_list_entry *rle;
3219 
3220 	STAILQ_FOREACH(rle, rl, link) {
3221 		if (rle->type == type && rle->rid == rid)
3222 			return (rle);
3223 	}
3224 	return (NULL);
3225 }
3226 
3227 /**
3228  * @brief Delete a resource entry.
3229  *
3230  * @param rl		the resource list to edit
3231  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
3232  * @param rid		the resource identifier
3233  */
3234 void
3235 resource_list_delete(struct resource_list *rl, int type, int rid)
3236 {
3237 	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
3238 
3239 	if (rle) {
3240 		if (rle->res != NULL)
3241 			panic("resource_list_delete: resource has not been released");
3242 		STAILQ_REMOVE(rl, rle, resource_list_entry, link);
3243 		free(rle, M_BUS);
3244 	}
3245 }
3246 
3247 /**
3248  * @brief Allocate a reserved resource
3249  *
3250  * This can be used by busses to force the allocation of resources
3251  * that are always active in the system even if they are not allocated
3252  * by a driver (e.g. PCI BARs).  This function is usually called when
3253  * adding a new child to the bus.  The resource is allocated from the
3254  * parent bus when it is reserved.  The resource list entry is marked
3255  * with RLE_RESERVED to note that it is a reserved resource.
3256  *
3257  * Subsequent attempts to allocate the resource with
3258  * resource_list_alloc() will succeed the first time and will set
3259  * RLE_ALLOCATED to note that it has been allocated.  When a reserved
3260  * resource that has been allocated is released with
3261  * resource_list_release() the resource RLE_ALLOCATED is cleared, but
3262  * the actual resource remains allocated.  The resource can be released to
3263  * the parent bus by calling resource_list_unreserve().
3264  *
3265  * @param rl		the resource list to allocate from
3266  * @param bus		the parent device of @p child
3267  * @param child		the device for which the resource is being reserved
3268  * @param type		the type of resource to allocate
3269  * @param rid		a pointer to the resource identifier
3270  * @param start		hint at the start of the resource range - pass
3271  *			@c 0 for any start address
3272  * @param end		hint at the end of the resource range - pass
3273  *			@c ~0 for any end address
3274  * @param count		hint at the size of range required - pass @c 1
3275  *			for any size
3276  * @param flags		any extra flags to control the resource
3277  *			allocation - see @c RF_XXX flags in
3278  *			<sys/rman.h> for details
3279  *
3280  * @returns		the resource which was allocated or @c NULL if no
3281  *			resource could be allocated
3282  */
3283 struct resource *
3284 resource_list_reserve(struct resource_list *rl, device_t bus, device_t child,
3285     int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
3286 {
3287 	struct resource_list_entry *rle = NULL;
3288 	int passthrough = (device_get_parent(child) != bus);
3289 	struct resource *r;
3290 
3291 	if (passthrough)
3292 		panic(
3293     "resource_list_reserve() should only be called for direct children");
3294 	if (flags & RF_ACTIVE)
3295 		panic(
3296     "resource_list_reserve() should only reserve inactive resources");
3297 
3298 	r = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
3299 	    flags);
3300 	if (r != NULL) {
3301 		rle = resource_list_find(rl, type, *rid);
3302 		rle->flags |= RLE_RESERVED;
3303 	}
3304 	return (r);
3305 }
3306 
3307 /**
3308  * @brief Helper function for implementing BUS_ALLOC_RESOURCE()
3309  *
3310  * Implement BUS_ALLOC_RESOURCE() by looking up a resource from the list
3311  * and passing the allocation up to the parent of @p bus. This assumes
3312  * that the first entry of @c device_get_ivars(child) is a struct
3313  * resource_list. This also handles 'passthrough' allocations where a
3314  * child is a remote descendant of bus by passing the allocation up to
3315  * the parent of bus.
3316  *
3317  * Typically, a bus driver would store a list of child resources
3318  * somewhere in the child device's ivars (see device_get_ivars()) and
3319  * its implementation of BUS_ALLOC_RESOURCE() would find that list and
3320  * then call resource_list_alloc() to perform the allocation.
3321  *
3322  * @param rl		the resource list to allocate from
3323  * @param bus		the parent device of @p child
3324  * @param child		the device which is requesting an allocation
3325  * @param type		the type of resource to allocate
3326  * @param rid		a pointer to the resource identifier
3327  * @param start		hint at the start of the resource range - pass
3328  *			@c 0 for any start address
3329  * @param end		hint at the end of the resource range - pass
3330  *			@c ~0 for any end address
3331  * @param count		hint at the size of range required - pass @c 1
3332  *			for any size
3333  * @param flags		any extra flags to control the resource
3334  *			allocation - see @c RF_XXX flags in
3335  *			<sys/rman.h> for details
3336  *
3337  * @returns		the resource which was allocated or @c NULL if no
3338  *			resource could be allocated
3339  */
3340 struct resource *
3341 resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
3342     int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
3343 {
3344 	struct resource_list_entry *rle = NULL;
3345 	int passthrough = (device_get_parent(child) != bus);
3346 	int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
3347 
3348 	if (passthrough) {
3349 		return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3350 		    type, rid, start, end, count, flags));
3351 	}
3352 
3353 	rle = resource_list_find(rl, type, *rid);
3354 
3355 	if (!rle)
3356 		return (NULL);		/* no resource of that type/rid */
3357 
3358 	if (rle->res) {
3359 		if (rle->flags & RLE_RESERVED) {
3360 			if (rle->flags & RLE_ALLOCATED)
3361 				return (NULL);
3362 			if ((flags & RF_ACTIVE) &&
3363 			    bus_activate_resource(child, type, *rid,
3364 			    rle->res) != 0)
3365 				return (NULL);
3366 			rle->flags |= RLE_ALLOCATED;
3367 			return (rle->res);
3368 		}
3369 		device_printf(bus,
3370 		    "resource entry %#x type %d for child %s is busy\n", *rid,
3371 		    type, device_get_nameunit(child));
3372 		return (NULL);
3373 	}
3374 
3375 	if (isdefault) {
3376 		start = rle->start;
3377 		count = ulmax(count, rle->count);
3378 		end = ulmax(rle->end, start + count - 1);
3379 	}
3380 
3381 	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3382 	    type, rid, start, end, count, flags);
3383 
3384 	/*
3385 	 * Record the new range.
3386 	 */
3387 	if (rle->res) {
3388 		rle->start = rman_get_start(rle->res);
3389 		rle->end = rman_get_end(rle->res);
3390 		rle->count = count;
3391 	}
3392 
3393 	return (rle->res);
3394 }
3395 
3396 /**
3397  * @brief Helper function for implementing BUS_RELEASE_RESOURCE()
3398  *
3399  * Implement BUS_RELEASE_RESOURCE() using a resource list. Normally
3400  * used with resource_list_alloc().
3401  *
3402  * @param rl		the resource list which was allocated from
3403  * @param bus		the parent device of @p child
3404  * @param child		the device which is requesting a release
3405  * @param type		the type of resource to release
3406  * @param rid		the resource identifier
3407  * @param res		the resource to release
3408  *
3409  * @retval 0		success
3410  * @retval non-zero	a standard unix error code indicating what
3411  *			error condition prevented the operation
3412  */
3413 int
3414 resource_list_release(struct resource_list *rl, device_t bus, device_t child,
3415     int type, int rid, struct resource *res)
3416 {
3417 	struct resource_list_entry *rle = NULL;
3418 	int passthrough = (device_get_parent(child) != bus);
3419 	int error;
3420 
3421 	if (passthrough) {
3422 		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
3423 		    type, rid, res));
3424 	}
3425 
3426 	rle = resource_list_find(rl, type, rid);
3427 
3428 	if (!rle)
3429 		panic("resource_list_release: can't find resource");
3430 	if (!rle->res)
3431 		panic("resource_list_release: resource entry is not busy");
3432 	if (rle->flags & RLE_RESERVED) {
3433 		if (rle->flags & RLE_ALLOCATED) {
3434 			if (rman_get_flags(res) & RF_ACTIVE) {
3435 				error = bus_deactivate_resource(child, type,
3436 				    rid, res);
3437 				if (error)
3438 					return (error);
3439 			}
3440 			rle->flags &= ~RLE_ALLOCATED;
3441 			return (0);
3442 		}
3443 		return (EINVAL);
3444 	}
3445 
3446 	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
3447 	    type, rid, res);
3448 	if (error)
3449 		return (error);
3450 
3451 	rle->res = NULL;
3452 	return (0);
3453 }
3454 
3455 /**
3456  * @brief Release all active resources of a given type
3457  *
3458  * Release all active resources of a specified type.  This is intended
3459  * to be used to cleanup resources leaked by a driver after detach or
3460  * a failed attach.
3461  *
3462  * @param rl		the resource list which was allocated from
3463  * @param bus		the parent device of @p child
3464  * @param child		the device whose active resources are being released
3465  * @param type		the type of resources to release
3466  *
3467  * @retval 0		success
3468  * @retval EBUSY	at least one resource was active
3469  */
3470 int
3471 resource_list_release_active(struct resource_list *rl, device_t bus,
3472     device_t child, int type)
3473 {
3474 	struct resource_list_entry *rle;
3475 	int error, retval;
3476 
3477 	retval = 0;
3478 	STAILQ_FOREACH(rle, rl, link) {
3479 		if (rle->type != type)
3480 			continue;
3481 		if (rle->res == NULL)
3482 			continue;
3483 		if ((rle->flags & (RLE_RESERVED | RLE_ALLOCATED)) ==
3484 		    RLE_RESERVED)
3485 			continue;
3486 		retval = EBUSY;
3487 		error = resource_list_release(rl, bus, child, type,
3488 		    rman_get_rid(rle->res), rle->res);
3489 		if (error != 0)
3490 			device_printf(bus,
3491 			    "Failed to release active resource: %d\n", error);
3492 	}
3493 	return (retval);
3494 }
3495 
3496 
3497 /**
3498  * @brief Fully release a reserved resource
3499  *
3500  * Fully releases a resource reserved via resource_list_reserve().
3501  *
3502  * @param rl		the resource list which was allocated from
3503  * @param bus		the parent device of @p child
3504  * @param child		the device whose reserved resource is being released
3505  * @param type		the type of resource to release
3506  * @param rid		the resource identifier
3507  * @param res		the resource to release
3508  *
3509  * @retval 0		success
3510  * @retval non-zero	a standard unix error code indicating what
3511  *			error condition prevented the operation
3512  */
3513 int
3514 resource_list_unreserve(struct resource_list *rl, device_t bus, device_t child,
3515     int type, int rid)
3516 {
3517 	struct resource_list_entry *rle = NULL;
3518 	int passthrough = (device_get_parent(child) != bus);
3519 
3520 	if (passthrough)
3521 		panic(
3522     "resource_list_unreserve() should only be called for direct children");
3523 
3524 	rle = resource_list_find(rl, type, rid);
3525 
3526 	if (!rle)
3527 		panic("resource_list_unreserve: can't find resource");
3528 	if (!(rle->flags & RLE_RESERVED))
3529 		return (EINVAL);
3530 	if (rle->flags & RLE_ALLOCATED)
3531 		return (EBUSY);
3532 	rle->flags &= ~RLE_RESERVED;
3533 	return (resource_list_release(rl, bus, child, type, rid, rle->res));
3534 }
3535 
3536 /**
3537  * @brief Print a description of resources in a resource list
3538  *
3539  * Print all resources of a specified type, for use in BUS_PRINT_CHILD().
3540  * The name is printed if at least one resource of the given type is available.
3541  * The format is used to print resource start and end.
3542  *
3543  * @param rl		the resource list to print
3544  * @param name		the name of @p type, e.g. @c "memory"
3545  * @param type		type type of resource entry to print
3546  * @param format	printf(9) format string to print resource
3547  *			start and end values
3548  *
3549  * @returns		the number of characters printed
3550  */
3551 int
3552 resource_list_print_type(struct resource_list *rl, const char *name, int type,
3553     const char *format)
3554 {
3555 	struct resource_list_entry *rle;
3556 	int printed, retval;
3557 
3558 	printed = 0;
3559 	retval = 0;
3560 	/* Yes, this is kinda cheating */
3561 	STAILQ_FOREACH(rle, rl, link) {
3562 		if (rle->type == type) {
3563 			if (printed == 0)
3564 				retval += printf(" %s ", name);
3565 			else
3566 				retval += printf(",");
3567 			printed++;
3568 			retval += printf(format, rle->start);
3569 			if (rle->count > 1) {
3570 				retval += printf("-");
3571 				retval += printf(format, rle->start +
3572 						 rle->count - 1);
3573 			}
3574 		}
3575 	}
3576 	return (retval);
3577 }
3578 
3579 /**
3580  * @brief Releases all the resources in a list.
3581  *
3582  * @param rl		The resource list to purge.
3583  *
3584  * @returns		nothing
3585  */
3586 void
3587 resource_list_purge(struct resource_list *rl)
3588 {
3589 	struct resource_list_entry *rle;
3590 
3591 	while ((rle = STAILQ_FIRST(rl)) != NULL) {
3592 		if (rle->res)
3593 			bus_release_resource(rman_get_device(rle->res),
3594 			    rle->type, rle->rid, rle->res);
3595 		STAILQ_REMOVE_HEAD(rl, link);
3596 		free(rle, M_BUS);
3597 	}
3598 }
3599 
3600 device_t
3601 bus_generic_add_child(device_t dev, u_int order, const char *name, int unit)
3602 {
3603 
3604 	return (device_add_child_ordered(dev, order, name, unit));
3605 }
3606 
3607 /**
3608  * @brief Helper function for implementing DEVICE_PROBE()
3609  *
3610  * This function can be used to help implement the DEVICE_PROBE() for
3611  * a bus (i.e. a device which has other devices attached to it). It
3612  * calls the DEVICE_IDENTIFY() method of each driver in the device's
3613  * devclass.
3614  */
3615 int
3616 bus_generic_probe(device_t dev)
3617 {
3618 	devclass_t dc = dev->devclass;
3619 	driverlink_t dl;
3620 
3621 	TAILQ_FOREACH(dl, &dc->drivers, link) {
3622 		/*
3623 		 * If this driver's pass is too high, then ignore it.
3624 		 * For most drivers in the default pass, this will
3625 		 * never be true.  For early-pass drivers they will
3626 		 * only call the identify routines of eligible drivers
3627 		 * when this routine is called.  Drivers for later
3628 		 * passes should have their identify routines called
3629 		 * on early-pass busses during BUS_NEW_PASS().
3630 		 */
3631 		if (dl->pass > bus_current_pass)
3632 			continue;
3633 		DEVICE_IDENTIFY(dl->driver, dev);
3634 	}
3635 
3636 	return (0);
3637 }
3638 
3639 /**
3640  * @brief Helper function for implementing DEVICE_ATTACH()
3641  *
3642  * This function can be used to help implement the DEVICE_ATTACH() for
3643  * a bus. It calls device_probe_and_attach() for each of the device's
3644  * children.
3645  */
3646 int
3647 bus_generic_attach(device_t dev)
3648 {
3649 	device_t child;
3650 
3651 	TAILQ_FOREACH(child, &dev->children, link) {
3652 		device_probe_and_attach(child);
3653 	}
3654 
3655 	return (0);
3656 }
3657 
3658 /**
3659  * @brief Helper function for implementing DEVICE_DETACH()
3660  *
3661  * This function can be used to help implement the DEVICE_DETACH() for
3662  * a bus. It calls device_detach() for each of the device's
3663  * children.
3664  */
3665 int
3666 bus_generic_detach(device_t dev)
3667 {
3668 	device_t child;
3669 	int error;
3670 
3671 	if (dev->state != DS_ATTACHED)
3672 		return (EBUSY);
3673 
3674 	TAILQ_FOREACH(child, &dev->children, link) {
3675 		if ((error = device_detach(child)) != 0)
3676 			return (error);
3677 	}
3678 
3679 	return (0);
3680 }
3681 
3682 /**
3683  * @brief Helper function for implementing DEVICE_SHUTDOWN()
3684  *
3685  * This function can be used to help implement the DEVICE_SHUTDOWN()
3686  * for a bus. It calls device_shutdown() for each of the device's
3687  * children.
3688  */
3689 int
3690 bus_generic_shutdown(device_t dev)
3691 {
3692 	device_t child;
3693 
3694 	TAILQ_FOREACH(child, &dev->children, link) {
3695 		device_shutdown(child);
3696 	}
3697 
3698 	return (0);
3699 }
3700 
3701 /**
3702  * @brief Default function for suspending a child device.
3703  *
3704  * This function is to be used by a bus's DEVICE_SUSPEND_CHILD().
3705  */
3706 int
3707 bus_generic_suspend_child(device_t dev, device_t child)
3708 {
3709 	int	error;
3710 
3711 	error = DEVICE_SUSPEND(child);
3712 
3713 	if (error == 0)
3714 		child->flags |= DF_SUSPENDED;
3715 
3716 	return (error);
3717 }
3718 
3719 /**
3720  * @brief Default function for resuming a child device.
3721  *
3722  * This function is to be used by a bus's DEVICE_RESUME_CHILD().
3723  */
3724 int
3725 bus_generic_resume_child(device_t dev, device_t child)
3726 {
3727 
3728 	DEVICE_RESUME(child);
3729 	child->flags &= ~DF_SUSPENDED;
3730 
3731 	return (0);
3732 }
3733 
3734 /**
3735  * @brief Helper function for implementing DEVICE_SUSPEND()
3736  *
3737  * This function can be used to help implement the DEVICE_SUSPEND()
3738  * for a bus. It calls DEVICE_SUSPEND() for each of the device's
3739  * children. If any call to DEVICE_SUSPEND() fails, the suspend
3740  * operation is aborted and any devices which were suspended are
3741  * resumed immediately by calling their DEVICE_RESUME() methods.
3742  */
3743 int
3744 bus_generic_suspend(device_t dev)
3745 {
3746 	int		error;
3747 	device_t	child, child2;
3748 
3749 	TAILQ_FOREACH(child, &dev->children, link) {
3750 		error = BUS_SUSPEND_CHILD(dev, child);
3751 		if (error) {
3752 			for (child2 = TAILQ_FIRST(&dev->children);
3753 			     child2 && child2 != child;
3754 			     child2 = TAILQ_NEXT(child2, link))
3755 				BUS_RESUME_CHILD(dev, child2);
3756 			return (error);
3757 		}
3758 	}
3759 	return (0);
3760 }
3761 
3762 /**
3763  * @brief Helper function for implementing DEVICE_RESUME()
3764  *
3765  * This function can be used to help implement the DEVICE_RESUME() for
3766  * a bus. It calls DEVICE_RESUME() on each of the device's children.
3767  */
3768 int
3769 bus_generic_resume(device_t dev)
3770 {
3771 	device_t	child;
3772 
3773 	TAILQ_FOREACH(child, &dev->children, link) {
3774 		BUS_RESUME_CHILD(dev, child);
3775 		/* if resume fails, there's nothing we can usefully do... */
3776 	}
3777 	return (0);
3778 }
3779 
3780 /**
3781  * @brief Helper function for implementing BUS_PRINT_CHILD().
3782  *
3783  * This function prints the first part of the ascii representation of
3784  * @p child, including its name, unit and description (if any - see
3785  * device_set_desc()).
3786  *
3787  * @returns the number of characters printed
3788  */
3789 int
3790 bus_print_child_header(device_t dev, device_t child)
3791 {
3792 	int	retval = 0;
3793 
3794 	if (device_get_desc(child)) {
3795 		retval += device_printf(child, "<%s>", device_get_desc(child));
3796 	} else {
3797 		retval += printf("%s", device_get_nameunit(child));
3798 	}
3799 
3800 	return (retval);
3801 }
3802 
3803 /**
3804  * @brief Helper function for implementing BUS_PRINT_CHILD().
3805  *
3806  * This function prints the last part of the ascii representation of
3807  * @p child, which consists of the string @c " on " followed by the
3808  * name and unit of the @p dev.
3809  *
3810  * @returns the number of characters printed
3811  */
3812 int
3813 bus_print_child_footer(device_t dev, device_t child)
3814 {
3815 	return (printf(" on %s\n", device_get_nameunit(dev)));
3816 }
3817 
3818 /**
3819  * @brief Helper function for implementing BUS_PRINT_CHILD().
3820  *
3821  * This function prints out the VM domain for the given device.
3822  *
3823  * @returns the number of characters printed
3824  */
3825 int
3826 bus_print_child_domain(device_t dev, device_t child)
3827 {
3828 	int domain;
3829 
3830 	/* No domain? Don't print anything */
3831 	if (BUS_GET_DOMAIN(dev, child, &domain) != 0)
3832 		return (0);
3833 
3834 	return (printf(" numa-domain %d", domain));
3835 }
3836 
3837 /**
3838  * @brief Helper function for implementing BUS_PRINT_CHILD().
3839  *
3840  * This function simply calls bus_print_child_header() followed by
3841  * bus_print_child_footer().
3842  *
3843  * @returns the number of characters printed
3844  */
3845 int
3846 bus_generic_print_child(device_t dev, device_t child)
3847 {
3848 	int	retval = 0;
3849 
3850 	retval += bus_print_child_header(dev, child);
3851 	retval += bus_print_child_domain(dev, child);
3852 	retval += bus_print_child_footer(dev, child);
3853 
3854 	return (retval);
3855 }
3856 
3857 /**
3858  * @brief Stub function for implementing BUS_READ_IVAR().
3859  *
3860  * @returns ENOENT
3861  */
3862 int
3863 bus_generic_read_ivar(device_t dev, device_t child, int index,
3864     uintptr_t * result)
3865 {
3866 	return (ENOENT);
3867 }
3868 
3869 /**
3870  * @brief Stub function for implementing BUS_WRITE_IVAR().
3871  *
3872  * @returns ENOENT
3873  */
3874 int
3875 bus_generic_write_ivar(device_t dev, device_t child, int index,
3876     uintptr_t value)
3877 {
3878 	return (ENOENT);
3879 }
3880 
3881 /**
3882  * @brief Stub function for implementing BUS_GET_RESOURCE_LIST().
3883  *
3884  * @returns NULL
3885  */
3886 struct resource_list *
3887 bus_generic_get_resource_list(device_t dev, device_t child)
3888 {
3889 	return (NULL);
3890 }
3891 
3892 /**
3893  * @brief Helper function for implementing BUS_DRIVER_ADDED().
3894  *
3895  * This implementation of BUS_DRIVER_ADDED() simply calls the driver's
3896  * DEVICE_IDENTIFY() method to allow it to add new children to the bus
3897  * and then calls device_probe_and_attach() for each unattached child.
3898  */
3899 void
3900 bus_generic_driver_added(device_t dev, driver_t *driver)
3901 {
3902 	device_t child;
3903 
3904 	DEVICE_IDENTIFY(driver, dev);
3905 	TAILQ_FOREACH(child, &dev->children, link) {
3906 		if (child->state == DS_NOTPRESENT ||
3907 		    (child->flags & DF_REBID))
3908 			device_probe_and_attach(child);
3909 	}
3910 }
3911 
3912 /**
3913  * @brief Helper function for implementing BUS_NEW_PASS().
3914  *
3915  * This implementing of BUS_NEW_PASS() first calls the identify
3916  * routines for any drivers that probe at the current pass.  Then it
3917  * walks the list of devices for this bus.  If a device is already
3918  * attached, then it calls BUS_NEW_PASS() on that device.  If the
3919  * device is not already attached, it attempts to attach a driver to
3920  * it.
3921  */
3922 void
3923 bus_generic_new_pass(device_t dev)
3924 {
3925 	driverlink_t dl;
3926 	devclass_t dc;
3927 	device_t child;
3928 
3929 	dc = dev->devclass;
3930 	TAILQ_FOREACH(dl, &dc->drivers, link) {
3931 		if (dl->pass == bus_current_pass)
3932 			DEVICE_IDENTIFY(dl->driver, dev);
3933 	}
3934 	TAILQ_FOREACH(child, &dev->children, link) {
3935 		if (child->state >= DS_ATTACHED)
3936 			BUS_NEW_PASS(child);
3937 		else if (child->state == DS_NOTPRESENT)
3938 			device_probe_and_attach(child);
3939 	}
3940 }
3941 
3942 /**
3943  * @brief Helper function for implementing BUS_SETUP_INTR().
3944  *
3945  * This simple implementation of BUS_SETUP_INTR() simply calls the
3946  * BUS_SETUP_INTR() method of the parent of @p dev.
3947  */
3948 int
3949 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
3950     int flags, driver_filter_t *filter, driver_intr_t *intr, void *arg,
3951     void **cookiep)
3952 {
3953 	/* Propagate up the bus hierarchy until someone handles it. */
3954 	if (dev->parent)
3955 		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
3956 		    filter, intr, arg, cookiep));
3957 	return (EINVAL);
3958 }
3959 
3960 /**
3961  * @brief Helper function for implementing BUS_TEARDOWN_INTR().
3962  *
3963  * This simple implementation of BUS_TEARDOWN_INTR() simply calls the
3964  * BUS_TEARDOWN_INTR() method of the parent of @p dev.
3965  */
3966 int
3967 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
3968     void *cookie)
3969 {
3970 	/* Propagate up the bus hierarchy until someone handles it. */
3971 	if (dev->parent)
3972 		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
3973 	return (EINVAL);
3974 }
3975 
3976 /**
3977  * @brief Helper function for implementing BUS_ADJUST_RESOURCE().
3978  *
3979  * This simple implementation of BUS_ADJUST_RESOURCE() simply calls the
3980  * BUS_ADJUST_RESOURCE() method of the parent of @p dev.
3981  */
3982 int
3983 bus_generic_adjust_resource(device_t dev, device_t child, int type,
3984     struct resource *r, rman_res_t start, rman_res_t end)
3985 {
3986 	/* Propagate up the bus hierarchy until someone handles it. */
3987 	if (dev->parent)
3988 		return (BUS_ADJUST_RESOURCE(dev->parent, child, type, r, start,
3989 		    end));
3990 	return (EINVAL);
3991 }
3992 
3993 /**
3994  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3995  *
3996  * This simple implementation of BUS_ALLOC_RESOURCE() simply calls the
3997  * BUS_ALLOC_RESOURCE() method of the parent of @p dev.
3998  */
3999 struct resource *
4000 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
4001     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
4002 {
4003 	/* Propagate up the bus hierarchy until someone handles it. */
4004 	if (dev->parent)
4005 		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
4006 		    start, end, count, flags));
4007 	return (NULL);
4008 }
4009 
4010 /**
4011  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
4012  *
4013  * This simple implementation of BUS_RELEASE_RESOURCE() simply calls the
4014  * BUS_RELEASE_RESOURCE() method of the parent of @p dev.
4015  */
4016 int
4017 bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
4018     struct resource *r)
4019 {
4020 	/* Propagate up the bus hierarchy until someone handles it. */
4021 	if (dev->parent)
4022 		return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
4023 		    r));
4024 	return (EINVAL);
4025 }
4026 
4027 /**
4028  * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
4029  *
4030  * This simple implementation of BUS_ACTIVATE_RESOURCE() simply calls the
4031  * BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
4032  */
4033 int
4034 bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
4035     struct resource *r)
4036 {
4037 	/* Propagate up the bus hierarchy until someone handles it. */
4038 	if (dev->parent)
4039 		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
4040 		    r));
4041 	return (EINVAL);
4042 }
4043 
4044 /**
4045  * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
4046  *
4047  * This simple implementation of BUS_DEACTIVATE_RESOURCE() simply calls the
4048  * BUS_DEACTIVATE_RESOURCE() method of the parent of @p dev.
4049  */
4050 int
4051 bus_generic_deactivate_resource(device_t dev, device_t child, int type,
4052     int rid, struct resource *r)
4053 {
4054 	/* Propagate up the bus hierarchy until someone handles it. */
4055 	if (dev->parent)
4056 		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
4057 		    r));
4058 	return (EINVAL);
4059 }
4060 
4061 /**
4062  * @brief Helper function for implementing BUS_BIND_INTR().
4063  *
4064  * This simple implementation of BUS_BIND_INTR() simply calls the
4065  * BUS_BIND_INTR() method of the parent of @p dev.
4066  */
4067 int
4068 bus_generic_bind_intr(device_t dev, device_t child, struct resource *irq,
4069     int cpu)
4070 {
4071 
4072 	/* Propagate up the bus hierarchy until someone handles it. */
4073 	if (dev->parent)
4074 		return (BUS_BIND_INTR(dev->parent, child, irq, cpu));
4075 	return (EINVAL);
4076 }
4077 
4078 /**
4079  * @brief Helper function for implementing BUS_CONFIG_INTR().
4080  *
4081  * This simple implementation of BUS_CONFIG_INTR() simply calls the
4082  * BUS_CONFIG_INTR() method of the parent of @p dev.
4083  */
4084 int
4085 bus_generic_config_intr(device_t dev, int irq, enum intr_trigger trig,
4086     enum intr_polarity pol)
4087 {
4088 
4089 	/* Propagate up the bus hierarchy until someone handles it. */
4090 	if (dev->parent)
4091 		return (BUS_CONFIG_INTR(dev->parent, irq, trig, pol));
4092 	return (EINVAL);
4093 }
4094 
4095 /**
4096  * @brief Helper function for implementing BUS_DESCRIBE_INTR().
4097  *
4098  * This simple implementation of BUS_DESCRIBE_INTR() simply calls the
4099  * BUS_DESCRIBE_INTR() method of the parent of @p dev.
4100  */
4101 int
4102 bus_generic_describe_intr(device_t dev, device_t child, struct resource *irq,
4103     void *cookie, const char *descr)
4104 {
4105 
4106 	/* Propagate up the bus hierarchy until someone handles it. */
4107 	if (dev->parent)
4108 		return (BUS_DESCRIBE_INTR(dev->parent, child, irq, cookie,
4109 		    descr));
4110 	return (EINVAL);
4111 }
4112 
4113 /**
4114  * @brief Helper function for implementing BUS_GET_DMA_TAG().
4115  *
4116  * This simple implementation of BUS_GET_DMA_TAG() simply calls the
4117  * BUS_GET_DMA_TAG() method of the parent of @p dev.
4118  */
4119 bus_dma_tag_t
4120 bus_generic_get_dma_tag(device_t dev, device_t child)
4121 {
4122 
4123 	/* Propagate up the bus hierarchy until someone handles it. */
4124 	if (dev->parent != NULL)
4125 		return (BUS_GET_DMA_TAG(dev->parent, child));
4126 	return (NULL);
4127 }
4128 
4129 /**
4130  * @brief Helper function for implementing BUS_GET_BUS_TAG().
4131  *
4132  * This simple implementation of BUS_GET_BUS_TAG() simply calls the
4133  * BUS_GET_BUS_TAG() method of the parent of @p dev.
4134  */
4135 bus_space_tag_t
4136 bus_generic_get_bus_tag(device_t dev, device_t child)
4137 {
4138 
4139 	/* Propagate up the bus hierarchy until someone handles it. */
4140 	if (dev->parent != NULL)
4141 		return (BUS_GET_BUS_TAG(dev->parent, child));
4142 	return ((bus_space_tag_t)0);
4143 }
4144 
4145 /**
4146  * @brief Helper function for implementing BUS_GET_RESOURCE().
4147  *
4148  * This implementation of BUS_GET_RESOURCE() uses the
4149  * resource_list_find() function to do most of the work. It calls
4150  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4151  * search.
4152  */
4153 int
4154 bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
4155     rman_res_t *startp, rman_res_t *countp)
4156 {
4157 	struct resource_list *		rl = NULL;
4158 	struct resource_list_entry *	rle = NULL;
4159 
4160 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4161 	if (!rl)
4162 		return (EINVAL);
4163 
4164 	rle = resource_list_find(rl, type, rid);
4165 	if (!rle)
4166 		return (ENOENT);
4167 
4168 	if (startp)
4169 		*startp = rle->start;
4170 	if (countp)
4171 		*countp = rle->count;
4172 
4173 	return (0);
4174 }
4175 
4176 /**
4177  * @brief Helper function for implementing BUS_SET_RESOURCE().
4178  *
4179  * This implementation of BUS_SET_RESOURCE() uses the
4180  * resource_list_add() function to do most of the work. It calls
4181  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4182  * edit.
4183  */
4184 int
4185 bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
4186     rman_res_t start, rman_res_t count)
4187 {
4188 	struct resource_list *		rl = NULL;
4189 
4190 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4191 	if (!rl)
4192 		return (EINVAL);
4193 
4194 	resource_list_add(rl, type, rid, start, (start + count - 1), count);
4195 
4196 	return (0);
4197 }
4198 
4199 /**
4200  * @brief Helper function for implementing BUS_DELETE_RESOURCE().
4201  *
4202  * This implementation of BUS_DELETE_RESOURCE() uses the
4203  * resource_list_delete() function to do most of the work. It calls
4204  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4205  * edit.
4206  */
4207 void
4208 bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
4209 {
4210 	struct resource_list *		rl = NULL;
4211 
4212 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4213 	if (!rl)
4214 		return;
4215 
4216 	resource_list_delete(rl, type, rid);
4217 
4218 	return;
4219 }
4220 
4221 /**
4222  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
4223  *
4224  * This implementation of BUS_RELEASE_RESOURCE() uses the
4225  * resource_list_release() function to do most of the work. It calls
4226  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
4227  */
4228 int
4229 bus_generic_rl_release_resource(device_t dev, device_t child, int type,
4230     int rid, struct resource *r)
4231 {
4232 	struct resource_list *		rl = NULL;
4233 
4234 	if (device_get_parent(child) != dev)
4235 		return (BUS_RELEASE_RESOURCE(device_get_parent(dev), child,
4236 		    type, rid, r));
4237 
4238 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4239 	if (!rl)
4240 		return (EINVAL);
4241 
4242 	return (resource_list_release(rl, dev, child, type, rid, r));
4243 }
4244 
4245 /**
4246  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
4247  *
4248  * This implementation of BUS_ALLOC_RESOURCE() uses the
4249  * resource_list_alloc() function to do most of the work. It calls
4250  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
4251  */
4252 struct resource *
4253 bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
4254     int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
4255 {
4256 	struct resource_list *		rl = NULL;
4257 
4258 	if (device_get_parent(child) != dev)
4259 		return (BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
4260 		    type, rid, start, end, count, flags));
4261 
4262 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4263 	if (!rl)
4264 		return (NULL);
4265 
4266 	return (resource_list_alloc(rl, dev, child, type, rid,
4267 	    start, end, count, flags));
4268 }
4269 
4270 /**
4271  * @brief Helper function for implementing BUS_CHILD_PRESENT().
4272  *
4273  * This simple implementation of BUS_CHILD_PRESENT() simply calls the
4274  * BUS_CHILD_PRESENT() method of the parent of @p dev.
4275  */
4276 int
4277 bus_generic_child_present(device_t dev, device_t child)
4278 {
4279 	return (BUS_CHILD_PRESENT(device_get_parent(dev), dev));
4280 }
4281 
4282 int
4283 bus_generic_get_domain(device_t dev, device_t child, int *domain)
4284 {
4285 
4286 	if (dev->parent)
4287 		return (BUS_GET_DOMAIN(dev->parent, dev, domain));
4288 
4289 	return (ENOENT);
4290 }
4291 
4292 /*
4293  * Some convenience functions to make it easier for drivers to use the
4294  * resource-management functions.  All these really do is hide the
4295  * indirection through the parent's method table, making for slightly
4296  * less-wordy code.  In the future, it might make sense for this code
4297  * to maintain some sort of a list of resources allocated by each device.
4298  */
4299 
4300 int
4301 bus_alloc_resources(device_t dev, struct resource_spec *rs,
4302     struct resource **res)
4303 {
4304 	int i;
4305 
4306 	for (i = 0; rs[i].type != -1; i++)
4307 		res[i] = NULL;
4308 	for (i = 0; rs[i].type != -1; i++) {
4309 		res[i] = bus_alloc_resource_any(dev,
4310 		    rs[i].type, &rs[i].rid, rs[i].flags);
4311 		if (res[i] == NULL && !(rs[i].flags & RF_OPTIONAL)) {
4312 			bus_release_resources(dev, rs, res);
4313 			return (ENXIO);
4314 		}
4315 	}
4316 	return (0);
4317 }
4318 
4319 void
4320 bus_release_resources(device_t dev, const struct resource_spec *rs,
4321     struct resource **res)
4322 {
4323 	int i;
4324 
4325 	for (i = 0; rs[i].type != -1; i++)
4326 		if (res[i] != NULL) {
4327 			bus_release_resource(
4328 			    dev, rs[i].type, rs[i].rid, res[i]);
4329 			res[i] = NULL;
4330 		}
4331 }
4332 
4333 /**
4334  * @brief Wrapper function for BUS_ALLOC_RESOURCE().
4335  *
4336  * This function simply calls the BUS_ALLOC_RESOURCE() method of the
4337  * parent of @p dev.
4338  */
4339 struct resource *
4340 bus_alloc_resource(device_t dev, int type, int *rid, rman_res_t start, rman_res_t end,
4341     rman_res_t count, u_int flags)
4342 {
4343 	if (dev->parent == NULL)
4344 		return (NULL);
4345 	return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
4346 	    count, flags));
4347 }
4348 
4349 /**
4350  * @brief Wrapper function for BUS_ADJUST_RESOURCE().
4351  *
4352  * This function simply calls the BUS_ADJUST_RESOURCE() method of the
4353  * parent of @p dev.
4354  */
4355 int
4356 bus_adjust_resource(device_t dev, int type, struct resource *r, rman_res_t start,
4357     rman_res_t end)
4358 {
4359 	if (dev->parent == NULL)
4360 		return (EINVAL);
4361 	return (BUS_ADJUST_RESOURCE(dev->parent, dev, type, r, start, end));
4362 }
4363 
4364 /**
4365  * @brief Wrapper function for BUS_ACTIVATE_RESOURCE().
4366  *
4367  * This function simply calls the BUS_ACTIVATE_RESOURCE() method of the
4368  * parent of @p dev.
4369  */
4370 int
4371 bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
4372 {
4373 	if (dev->parent == NULL)
4374 		return (EINVAL);
4375 	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
4376 }
4377 
4378 /**
4379  * @brief Wrapper function for BUS_DEACTIVATE_RESOURCE().
4380  *
4381  * This function simply calls the BUS_DEACTIVATE_RESOURCE() method of the
4382  * parent of @p dev.
4383  */
4384 int
4385 bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
4386 {
4387 	if (dev->parent == NULL)
4388 		return (EINVAL);
4389 	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
4390 }
4391 
4392 /**
4393  * @brief Wrapper function for BUS_RELEASE_RESOURCE().
4394  *
4395  * This function simply calls the BUS_RELEASE_RESOURCE() method of the
4396  * parent of @p dev.
4397  */
4398 int
4399 bus_release_resource(device_t dev, int type, int rid, struct resource *r)
4400 {
4401 	if (dev->parent == NULL)
4402 		return (EINVAL);
4403 	return (BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
4404 }
4405 
4406 /**
4407  * @brief Wrapper function for BUS_SETUP_INTR().
4408  *
4409  * This function simply calls the BUS_SETUP_INTR() method of the
4410  * parent of @p dev.
4411  */
4412 int
4413 bus_setup_intr(device_t dev, struct resource *r, int flags,
4414     driver_filter_t filter, driver_intr_t handler, void *arg, void **cookiep)
4415 {
4416 	int error;
4417 
4418 	if (dev->parent == NULL)
4419 		return (EINVAL);
4420 	error = BUS_SETUP_INTR(dev->parent, dev, r, flags, filter, handler,
4421 	    arg, cookiep);
4422 	if (error != 0)
4423 		return (error);
4424 	if (handler != NULL && !(flags & INTR_MPSAFE))
4425 		device_printf(dev, "[GIANT-LOCKED]\n");
4426 	return (0);
4427 }
4428 
4429 /**
4430  * @brief Wrapper function for BUS_TEARDOWN_INTR().
4431  *
4432  * This function simply calls the BUS_TEARDOWN_INTR() method of the
4433  * parent of @p dev.
4434  */
4435 int
4436 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
4437 {
4438 	if (dev->parent == NULL)
4439 		return (EINVAL);
4440 	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
4441 }
4442 
4443 /**
4444  * @brief Wrapper function for BUS_BIND_INTR().
4445  *
4446  * This function simply calls the BUS_BIND_INTR() method of the
4447  * parent of @p dev.
4448  */
4449 int
4450 bus_bind_intr(device_t dev, struct resource *r, int cpu)
4451 {
4452 	if (dev->parent == NULL)
4453 		return (EINVAL);
4454 	return (BUS_BIND_INTR(dev->parent, dev, r, cpu));
4455 }
4456 
4457 /**
4458  * @brief Wrapper function for BUS_DESCRIBE_INTR().
4459  *
4460  * This function first formats the requested description into a
4461  * temporary buffer and then calls the BUS_DESCRIBE_INTR() method of
4462  * the parent of @p dev.
4463  */
4464 int
4465 bus_describe_intr(device_t dev, struct resource *irq, void *cookie,
4466     const char *fmt, ...)
4467 {
4468 	va_list ap;
4469 	char descr[MAXCOMLEN + 1];
4470 
4471 	if (dev->parent == NULL)
4472 		return (EINVAL);
4473 	va_start(ap, fmt);
4474 	vsnprintf(descr, sizeof(descr), fmt, ap);
4475 	va_end(ap);
4476 	return (BUS_DESCRIBE_INTR(dev->parent, dev, irq, cookie, descr));
4477 }
4478 
4479 /**
4480  * @brief Wrapper function for BUS_SET_RESOURCE().
4481  *
4482  * This function simply calls the BUS_SET_RESOURCE() method of the
4483  * parent of @p dev.
4484  */
4485 int
4486 bus_set_resource(device_t dev, int type, int rid,
4487     rman_res_t start, rman_res_t count)
4488 {
4489 	return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
4490 	    start, count));
4491 }
4492 
4493 /**
4494  * @brief Wrapper function for BUS_GET_RESOURCE().
4495  *
4496  * This function simply calls the BUS_GET_RESOURCE() method of the
4497  * parent of @p dev.
4498  */
4499 int
4500 bus_get_resource(device_t dev, int type, int rid,
4501     rman_res_t *startp, rman_res_t *countp)
4502 {
4503 	return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4504 	    startp, countp));
4505 }
4506 
4507 /**
4508  * @brief Wrapper function for BUS_GET_RESOURCE().
4509  *
4510  * This function simply calls the BUS_GET_RESOURCE() method of the
4511  * parent of @p dev and returns the start value.
4512  */
4513 rman_res_t
4514 bus_get_resource_start(device_t dev, int type, int rid)
4515 {
4516 	rman_res_t start;
4517 	rman_res_t count;
4518 	int error;
4519 
4520 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4521 	    &start, &count);
4522 	if (error)
4523 		return (0);
4524 	return (start);
4525 }
4526 
4527 /**
4528  * @brief Wrapper function for BUS_GET_RESOURCE().
4529  *
4530  * This function simply calls the BUS_GET_RESOURCE() method of the
4531  * parent of @p dev and returns the count value.
4532  */
4533 rman_res_t
4534 bus_get_resource_count(device_t dev, int type, int rid)
4535 {
4536 	rman_res_t start;
4537 	rman_res_t count;
4538 	int error;
4539 
4540 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4541 	    &start, &count);
4542 	if (error)
4543 		return (0);
4544 	return (count);
4545 }
4546 
4547 /**
4548  * @brief Wrapper function for BUS_DELETE_RESOURCE().
4549  *
4550  * This function simply calls the BUS_DELETE_RESOURCE() method of the
4551  * parent of @p dev.
4552  */
4553 void
4554 bus_delete_resource(device_t dev, int type, int rid)
4555 {
4556 	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
4557 }
4558 
4559 /**
4560  * @brief Wrapper function for BUS_CHILD_PRESENT().
4561  *
4562  * This function simply calls the BUS_CHILD_PRESENT() method of the
4563  * parent of @p dev.
4564  */
4565 int
4566 bus_child_present(device_t child)
4567 {
4568 	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
4569 }
4570 
4571 /**
4572  * @brief Wrapper function for BUS_CHILD_PNPINFO_STR().
4573  *
4574  * This function simply calls the BUS_CHILD_PNPINFO_STR() method of the
4575  * parent of @p dev.
4576  */
4577 int
4578 bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
4579 {
4580 	device_t parent;
4581 
4582 	parent = device_get_parent(child);
4583 	if (parent == NULL) {
4584 		*buf = '\0';
4585 		return (0);
4586 	}
4587 	return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
4588 }
4589 
4590 /**
4591  * @brief Wrapper function for BUS_CHILD_LOCATION_STR().
4592  *
4593  * This function simply calls the BUS_CHILD_LOCATION_STR() method of the
4594  * parent of @p dev.
4595  */
4596 int
4597 bus_child_location_str(device_t child, char *buf, size_t buflen)
4598 {
4599 	device_t parent;
4600 
4601 	parent = device_get_parent(child);
4602 	if (parent == NULL) {
4603 		*buf = '\0';
4604 		return (0);
4605 	}
4606 	return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
4607 }
4608 
4609 /**
4610  * @brief Wrapper function for BUS_GET_DMA_TAG().
4611  *
4612  * This function simply calls the BUS_GET_DMA_TAG() method of the
4613  * parent of @p dev.
4614  */
4615 bus_dma_tag_t
4616 bus_get_dma_tag(device_t dev)
4617 {
4618 	device_t parent;
4619 
4620 	parent = device_get_parent(dev);
4621 	if (parent == NULL)
4622 		return (NULL);
4623 	return (BUS_GET_DMA_TAG(parent, dev));
4624 }
4625 
4626 /**
4627  * @brief Wrapper function for BUS_GET_BUS_TAG().
4628  *
4629  * This function simply calls the BUS_GET_BUS_TAG() method of the
4630  * parent of @p dev.
4631  */
4632 bus_space_tag_t
4633 bus_get_bus_tag(device_t dev)
4634 {
4635 	device_t parent;
4636 
4637 	parent = device_get_parent(dev);
4638 	if (parent == NULL)
4639 		return ((bus_space_tag_t)0);
4640 	return (BUS_GET_BUS_TAG(parent, dev));
4641 }
4642 
4643 /**
4644  * @brief Wrapper function for BUS_GET_DOMAIN().
4645  *
4646  * This function simply calls the BUS_GET_DOMAIN() method of the
4647  * parent of @p dev.
4648  */
4649 int
4650 bus_get_domain(device_t dev, int *domain)
4651 {
4652 	return (BUS_GET_DOMAIN(device_get_parent(dev), dev, domain));
4653 }
4654 
4655 /* Resume all devices and then notify userland that we're up again. */
4656 static int
4657 root_resume(device_t dev)
4658 {
4659 	int error;
4660 
4661 	error = bus_generic_resume(dev);
4662 	if (error == 0)
4663 		devctl_notify("kern", "power", "resume", NULL);
4664 	return (error);
4665 }
4666 
4667 static int
4668 root_print_child(device_t dev, device_t child)
4669 {
4670 	int	retval = 0;
4671 
4672 	retval += bus_print_child_header(dev, child);
4673 	retval += printf("\n");
4674 
4675 	return (retval);
4676 }
4677 
4678 static int
4679 root_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
4680     driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
4681 {
4682 	/*
4683 	 * If an interrupt mapping gets to here something bad has happened.
4684 	 */
4685 	panic("root_setup_intr");
4686 }
4687 
4688 /*
4689  * If we get here, assume that the device is permanant and really is
4690  * present in the system.  Removable bus drivers are expected to intercept
4691  * this call long before it gets here.  We return -1 so that drivers that
4692  * really care can check vs -1 or some ERRNO returned higher in the food
4693  * chain.
4694  */
4695 static int
4696 root_child_present(device_t dev, device_t child)
4697 {
4698 	return (-1);
4699 }
4700 
4701 static kobj_method_t root_methods[] = {
4702 	/* Device interface */
4703 	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
4704 	KOBJMETHOD(device_suspend,	bus_generic_suspend),
4705 	KOBJMETHOD(device_resume,	root_resume),
4706 
4707 	/* Bus interface */
4708 	KOBJMETHOD(bus_print_child,	root_print_child),
4709 	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
4710 	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
4711 	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
4712 	KOBJMETHOD(bus_child_present,	root_child_present),
4713 
4714 	KOBJMETHOD_END
4715 };
4716 
4717 static driver_t root_driver = {
4718 	"root",
4719 	root_methods,
4720 	1,			/* no softc */
4721 };
4722 
4723 device_t	root_bus;
4724 devclass_t	root_devclass;
4725 
4726 static int
4727 root_bus_module_handler(module_t mod, int what, void* arg)
4728 {
4729 	switch (what) {
4730 	case MOD_LOAD:
4731 		TAILQ_INIT(&bus_data_devices);
4732 		kobj_class_compile((kobj_class_t) &root_driver);
4733 		root_bus = make_device(NULL, "root", 0);
4734 		root_bus->desc = "System root bus";
4735 		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
4736 		root_bus->driver = &root_driver;
4737 		root_bus->state = DS_ATTACHED;
4738 		root_devclass = devclass_find_internal("root", NULL, FALSE);
4739 		devinit();
4740 		return (0);
4741 
4742 	case MOD_SHUTDOWN:
4743 		device_shutdown(root_bus);
4744 		return (0);
4745 	default:
4746 		return (EOPNOTSUPP);
4747 	}
4748 
4749 	return (0);
4750 }
4751 
4752 static moduledata_t root_bus_mod = {
4753 	"rootbus",
4754 	root_bus_module_handler,
4755 	NULL
4756 };
4757 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
4758 
4759 /**
4760  * @brief Automatically configure devices
4761  *
4762  * This function begins the autoconfiguration process by calling
4763  * device_probe_and_attach() for each child of the @c root0 device.
4764  */
4765 void
4766 root_bus_configure(void)
4767 {
4768 
4769 	PDEBUG(("."));
4770 
4771 	/* Eventually this will be split up, but this is sufficient for now. */
4772 	bus_set_pass(BUS_PASS_DEFAULT);
4773 }
4774 
4775 /**
4776  * @brief Module handler for registering device drivers
4777  *
4778  * This module handler is used to automatically register device
4779  * drivers when modules are loaded. If @p what is MOD_LOAD, it calls
4780  * devclass_add_driver() for the driver described by the
4781  * driver_module_data structure pointed to by @p arg
4782  */
4783 int
4784 driver_module_handler(module_t mod, int what, void *arg)
4785 {
4786 	struct driver_module_data *dmd;
4787 	devclass_t bus_devclass;
4788 	kobj_class_t driver;
4789 	int error, pass;
4790 
4791 	dmd = (struct driver_module_data *)arg;
4792 	bus_devclass = devclass_find_internal(dmd->dmd_busname, NULL, TRUE);
4793 	error = 0;
4794 
4795 	switch (what) {
4796 	case MOD_LOAD:
4797 		if (dmd->dmd_chainevh)
4798 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
4799 
4800 		pass = dmd->dmd_pass;
4801 		driver = dmd->dmd_driver;
4802 		PDEBUG(("Loading module: driver %s on bus %s (pass %d)",
4803 		    DRIVERNAME(driver), dmd->dmd_busname, pass));
4804 		error = devclass_add_driver(bus_devclass, driver, pass,
4805 		    dmd->dmd_devclass);
4806 		break;
4807 
4808 	case MOD_UNLOAD:
4809 		PDEBUG(("Unloading module: driver %s from bus %s",
4810 		    DRIVERNAME(dmd->dmd_driver),
4811 		    dmd->dmd_busname));
4812 		error = devclass_delete_driver(bus_devclass,
4813 		    dmd->dmd_driver);
4814 
4815 		if (!error && dmd->dmd_chainevh)
4816 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
4817 		break;
4818 	case MOD_QUIESCE:
4819 		PDEBUG(("Quiesce module: driver %s from bus %s",
4820 		    DRIVERNAME(dmd->dmd_driver),
4821 		    dmd->dmd_busname));
4822 		error = devclass_quiesce_driver(bus_devclass,
4823 		    dmd->dmd_driver);
4824 
4825 		if (!error && dmd->dmd_chainevh)
4826 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
4827 		break;
4828 	default:
4829 		error = EOPNOTSUPP;
4830 		break;
4831 	}
4832 
4833 	return (error);
4834 }
4835 
4836 /**
4837  * @brief Enumerate all hinted devices for this bus.
4838  *
4839  * Walks through the hints for this bus and calls the bus_hinted_child
4840  * routine for each one it fines.  It searches first for the specific
4841  * bus that's being probed for hinted children (eg isa0), and then for
4842  * generic children (eg isa).
4843  *
4844  * @param	dev	bus device to enumerate
4845  */
4846 void
4847 bus_enumerate_hinted_children(device_t bus)
4848 {
4849 	int i;
4850 	const char *dname, *busname;
4851 	int dunit;
4852 
4853 	/*
4854 	 * enumerate all devices on the specific bus
4855 	 */
4856 	busname = device_get_nameunit(bus);
4857 	i = 0;
4858 	while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
4859 		BUS_HINTED_CHILD(bus, dname, dunit);
4860 
4861 	/*
4862 	 * and all the generic ones.
4863 	 */
4864 	busname = device_get_name(bus);
4865 	i = 0;
4866 	while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
4867 		BUS_HINTED_CHILD(bus, dname, dunit);
4868 }
4869 
4870 #ifdef BUS_DEBUG
4871 
4872 /* the _short versions avoid iteration by not calling anything that prints
4873  * more than oneliners. I love oneliners.
4874  */
4875 
4876 static void
4877 print_device_short(device_t dev, int indent)
4878 {
4879 	if (!dev)
4880 		return;
4881 
4882 	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
4883 	    dev->unit, dev->desc,
4884 	    (dev->parent? "":"no "),
4885 	    (TAILQ_EMPTY(&dev->children)? "no ":""),
4886 	    (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
4887 	    (dev->flags&DF_FIXEDCLASS? "fixed,":""),
4888 	    (dev->flags&DF_WILDCARD? "wildcard,":""),
4889 	    (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
4890 	    (dev->flags&DF_REBID? "rebiddable,":""),
4891 	    (dev->ivars? "":"no "),
4892 	    (dev->softc? "":"no "),
4893 	    dev->busy));
4894 }
4895 
4896 static void
4897 print_device(device_t dev, int indent)
4898 {
4899 	if (!dev)
4900 		return;
4901 
4902 	print_device_short(dev, indent);
4903 
4904 	indentprintf(("Parent:\n"));
4905 	print_device_short(dev->parent, indent+1);
4906 	indentprintf(("Driver:\n"));
4907 	print_driver_short(dev->driver, indent+1);
4908 	indentprintf(("Devclass:\n"));
4909 	print_devclass_short(dev->devclass, indent+1);
4910 }
4911 
4912 void
4913 print_device_tree_short(device_t dev, int indent)
4914 /* print the device and all its children (indented) */
4915 {
4916 	device_t child;
4917 
4918 	if (!dev)
4919 		return;
4920 
4921 	print_device_short(dev, indent);
4922 
4923 	TAILQ_FOREACH(child, &dev->children, link) {
4924 		print_device_tree_short(child, indent+1);
4925 	}
4926 }
4927 
4928 void
4929 print_device_tree(device_t dev, int indent)
4930 /* print the device and all its children (indented) */
4931 {
4932 	device_t child;
4933 
4934 	if (!dev)
4935 		return;
4936 
4937 	print_device(dev, indent);
4938 
4939 	TAILQ_FOREACH(child, &dev->children, link) {
4940 		print_device_tree(child, indent+1);
4941 	}
4942 }
4943 
4944 static void
4945 print_driver_short(driver_t *driver, int indent)
4946 {
4947 	if (!driver)
4948 		return;
4949 
4950 	indentprintf(("driver %s: softc size = %zd\n",
4951 	    driver->name, driver->size));
4952 }
4953 
4954 static void
4955 print_driver(driver_t *driver, int indent)
4956 {
4957 	if (!driver)
4958 		return;
4959 
4960 	print_driver_short(driver, indent);
4961 }
4962 
4963 static void
4964 print_driver_list(driver_list_t drivers, int indent)
4965 {
4966 	driverlink_t driver;
4967 
4968 	TAILQ_FOREACH(driver, &drivers, link) {
4969 		print_driver(driver->driver, indent);
4970 	}
4971 }
4972 
4973 static void
4974 print_devclass_short(devclass_t dc, int indent)
4975 {
4976 	if ( !dc )
4977 		return;
4978 
4979 	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
4980 }
4981 
4982 static void
4983 print_devclass(devclass_t dc, int indent)
4984 {
4985 	int i;
4986 
4987 	if ( !dc )
4988 		return;
4989 
4990 	print_devclass_short(dc, indent);
4991 	indentprintf(("Drivers:\n"));
4992 	print_driver_list(dc->drivers, indent+1);
4993 
4994 	indentprintf(("Devices:\n"));
4995 	for (i = 0; i < dc->maxunit; i++)
4996 		if (dc->devices[i])
4997 			print_device(dc->devices[i], indent+1);
4998 }
4999 
5000 void
5001 print_devclass_list_short(void)
5002 {
5003 	devclass_t dc;
5004 
5005 	printf("Short listing of devclasses, drivers & devices:\n");
5006 	TAILQ_FOREACH(dc, &devclasses, link) {
5007 		print_devclass_short(dc, 0);
5008 	}
5009 }
5010 
5011 void
5012 print_devclass_list(void)
5013 {
5014 	devclass_t dc;
5015 
5016 	printf("Full listing of devclasses, drivers & devices:\n");
5017 	TAILQ_FOREACH(dc, &devclasses, link) {
5018 		print_devclass(dc, 0);
5019 	}
5020 }
5021 
5022 #endif
5023 
5024 /*
5025  * User-space access to the device tree.
5026  *
5027  * We implement a small set of nodes:
5028  *
5029  * hw.bus			Single integer read method to obtain the
5030  *				current generation count.
5031  * hw.bus.devices		Reads the entire device tree in flat space.
5032  * hw.bus.rman			Resource manager interface
5033  *
5034  * We might like to add the ability to scan devclasses and/or drivers to
5035  * determine what else is currently loaded/available.
5036  */
5037 
5038 static int
5039 sysctl_bus(SYSCTL_HANDLER_ARGS)
5040 {
5041 	struct u_businfo	ubus;
5042 
5043 	ubus.ub_version = BUS_USER_VERSION;
5044 	ubus.ub_generation = bus_data_generation;
5045 
5046 	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
5047 }
5048 SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
5049     "bus-related data");
5050 
5051 static int
5052 sysctl_devices(SYSCTL_HANDLER_ARGS)
5053 {
5054 	int			*name = (int *)arg1;
5055 	u_int			namelen = arg2;
5056 	int			index;
5057 	struct device		*dev;
5058 	struct u_device		udev;	/* XXX this is a bit big */
5059 	int			error;
5060 
5061 	if (namelen != 2)
5062 		return (EINVAL);
5063 
5064 	if (bus_data_generation_check(name[0]))
5065 		return (EINVAL);
5066 
5067 	index = name[1];
5068 
5069 	/*
5070 	 * Scan the list of devices, looking for the requested index.
5071 	 */
5072 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
5073 		if (index-- == 0)
5074 			break;
5075 	}
5076 	if (dev == NULL)
5077 		return (ENOENT);
5078 
5079 	/*
5080 	 * Populate the return array.
5081 	 */
5082 	bzero(&udev, sizeof(udev));
5083 	udev.dv_handle = (uintptr_t)dev;
5084 	udev.dv_parent = (uintptr_t)dev->parent;
5085 	if (dev->nameunit != NULL)
5086 		strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
5087 	if (dev->desc != NULL)
5088 		strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
5089 	if (dev->driver != NULL && dev->driver->name != NULL)
5090 		strlcpy(udev.dv_drivername, dev->driver->name,
5091 		    sizeof(udev.dv_drivername));
5092 	bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
5093 	bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
5094 	udev.dv_devflags = dev->devflags;
5095 	udev.dv_flags = dev->flags;
5096 	udev.dv_state = dev->state;
5097 	error = SYSCTL_OUT(req, &udev, sizeof(udev));
5098 	return (error);
5099 }
5100 
5101 SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
5102     "system device tree");
5103 
5104 int
5105 bus_data_generation_check(int generation)
5106 {
5107 	if (generation != bus_data_generation)
5108 		return (1);
5109 
5110 	/* XXX generate optimised lists here? */
5111 	return (0);
5112 }
5113 
5114 void
5115 bus_data_generation_update(void)
5116 {
5117 	bus_data_generation++;
5118 }
5119 
5120 int
5121 bus_free_resource(device_t dev, int type, struct resource *r)
5122 {
5123 	if (r == NULL)
5124 		return (0);
5125 	return (bus_release_resource(dev, type, rman_get_rid(r), r));
5126 }
5127 
5128 device_t
5129 device_lookup_by_name(const char *name)
5130 {
5131 	device_t dev;
5132 
5133 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
5134 		if (dev->nameunit != NULL && strcmp(dev->nameunit, name) == 0)
5135 			return (dev);
5136 	}
5137 	return (NULL);
5138 }
5139 
5140 /*
5141  * /dev/devctl2 implementation.  The existing /dev/devctl device has
5142  * implicit semantics on open, so it could not be reused for this.
5143  * Another option would be to call this /dev/bus?
5144  */
5145 static int
5146 find_device(struct devreq *req, device_t *devp)
5147 {
5148 	device_t dev;
5149 
5150 	/*
5151 	 * First, ensure that the name is nul terminated.
5152 	 */
5153 	if (memchr(req->dr_name, '\0', sizeof(req->dr_name)) == NULL)
5154 		return (EINVAL);
5155 
5156 	/*
5157 	 * Second, try to find an attached device whose name matches
5158 	 * 'name'.
5159 	 */
5160 	dev = device_lookup_by_name(req->dr_name);
5161 	if (dev != NULL) {
5162 		*devp = dev;
5163 		return (0);
5164 	}
5165 
5166 	/* Finally, give device enumerators a chance. */
5167 	dev = NULL;
5168 	EVENTHANDLER_INVOKE(dev_lookup, req->dr_name, &dev);
5169 	if (dev == NULL)
5170 		return (ENOENT);
5171 	*devp = dev;
5172 	return (0);
5173 }
5174 
5175 static bool
5176 driver_exists(struct device *bus, const char *driver)
5177 {
5178 	devclass_t dc;
5179 
5180 	for (dc = bus->devclass; dc != NULL; dc = dc->parent) {
5181 		if (devclass_find_driver_internal(dc, driver) != NULL)
5182 			return (true);
5183 	}
5184 	return (false);
5185 }
5186 
5187 static int
5188 devctl2_ioctl(struct cdev *cdev, u_long cmd, caddr_t data, int fflag,
5189     struct thread *td)
5190 {
5191 	struct devreq *req;
5192 	device_t dev;
5193 	int error, old;
5194 
5195 	/* Locate the device to control. */
5196 	mtx_lock(&Giant);
5197 	req = (struct devreq *)data;
5198 	switch (cmd) {
5199 	case DEV_ATTACH:
5200 	case DEV_DETACH:
5201 	case DEV_ENABLE:
5202 	case DEV_DISABLE:
5203 	case DEV_SUSPEND:
5204 	case DEV_RESUME:
5205 	case DEV_SET_DRIVER:
5206 		error = priv_check(td, PRIV_DRIVER);
5207 		if (error == 0)
5208 			error = find_device(req, &dev);
5209 		break;
5210 	default:
5211 		error = ENOTTY;
5212 		break;
5213 	}
5214 	if (error) {
5215 		mtx_unlock(&Giant);
5216 		return (error);
5217 	}
5218 
5219 	/* Perform the requested operation. */
5220 	switch (cmd) {
5221 	case DEV_ATTACH:
5222 		if (device_is_attached(dev) && (dev->flags & DF_REBID) == 0)
5223 			error = EBUSY;
5224 		else if (!device_is_enabled(dev))
5225 			error = ENXIO;
5226 		else
5227 			error = device_probe_and_attach(dev);
5228 		break;
5229 	case DEV_DETACH:
5230 		if (!device_is_attached(dev)) {
5231 			error = ENXIO;
5232 			break;
5233 		}
5234 		if (!(req->dr_flags & DEVF_FORCE_DETACH)) {
5235 			error = device_quiesce(dev);
5236 			if (error)
5237 				break;
5238 		}
5239 		error = device_detach(dev);
5240 		break;
5241 	case DEV_ENABLE:
5242 		if (device_is_enabled(dev)) {
5243 			error = EBUSY;
5244 			break;
5245 		}
5246 
5247 		/*
5248 		 * If the device has been probed but not attached (e.g.
5249 		 * when it has been disabled by a loader hint), just
5250 		 * attach the device rather than doing a full probe.
5251 		 */
5252 		device_enable(dev);
5253 		if (device_is_alive(dev)) {
5254 			/*
5255 			 * If the device was disabled via a hint, clear
5256 			 * the hint.
5257 			 */
5258 			if (resource_disabled(dev->driver->name, dev->unit))
5259 				resource_unset_value(dev->driver->name,
5260 				    dev->unit, "disabled");
5261 			error = device_attach(dev);
5262 		} else
5263 			error = device_probe_and_attach(dev);
5264 		break;
5265 	case DEV_DISABLE:
5266 		if (!device_is_enabled(dev)) {
5267 			error = ENXIO;
5268 			break;
5269 		}
5270 
5271 		if (!(req->dr_flags & DEVF_FORCE_DETACH)) {
5272 			error = device_quiesce(dev);
5273 			if (error)
5274 				break;
5275 		}
5276 
5277 		/*
5278 		 * Force DF_FIXEDCLASS on around detach to preserve
5279 		 * the existing name.
5280 		 */
5281 		old = dev->flags;
5282 		dev->flags |= DF_FIXEDCLASS;
5283 		error = device_detach(dev);
5284 		if (!(old & DF_FIXEDCLASS))
5285 			dev->flags &= ~DF_FIXEDCLASS;
5286 		if (error == 0)
5287 			device_disable(dev);
5288 		break;
5289 	case DEV_SUSPEND:
5290 		if (device_is_suspended(dev)) {
5291 			error = EBUSY;
5292 			break;
5293 		}
5294 		if (device_get_parent(dev) == NULL) {
5295 			error = EINVAL;
5296 			break;
5297 		}
5298 		error = BUS_SUSPEND_CHILD(device_get_parent(dev), dev);
5299 		break;
5300 	case DEV_RESUME:
5301 		if (!device_is_suspended(dev)) {
5302 			error = EINVAL;
5303 			break;
5304 		}
5305 		if (device_get_parent(dev) == NULL) {
5306 			error = EINVAL;
5307 			break;
5308 		}
5309 		error = BUS_RESUME_CHILD(device_get_parent(dev), dev);
5310 		break;
5311 	case DEV_SET_DRIVER: {
5312 		devclass_t dc;
5313 		char driver[128];
5314 
5315 		error = copyinstr(req->dr_data, driver, sizeof(driver), NULL);
5316 		if (error)
5317 			break;
5318 		if (driver[0] == '\0') {
5319 			error = EINVAL;
5320 			break;
5321 		}
5322 		if (dev->devclass != NULL &&
5323 		    strcmp(driver, dev->devclass->name) == 0)
5324 			/* XXX: Could possibly force DF_FIXEDCLASS on? */
5325 			break;
5326 
5327 		/*
5328 		 * Scan drivers for this device's bus looking for at
5329 		 * least one matching driver.
5330 		 */
5331 		if (dev->parent == NULL) {
5332 			error = EINVAL;
5333 			break;
5334 		}
5335 		if (!driver_exists(dev->parent, driver)) {
5336 			error = ENOENT;
5337 			break;
5338 		}
5339 		dc = devclass_create(driver);
5340 		if (dc == NULL) {
5341 			error = ENOMEM;
5342 			break;
5343 		}
5344 
5345 		/* Detach device if necessary. */
5346 		if (device_is_attached(dev)) {
5347 			if (req->dr_flags & DEVF_SET_DRIVER_DETACH)
5348 				error = device_detach(dev);
5349 			else
5350 				error = EBUSY;
5351 			if (error)
5352 				break;
5353 		}
5354 
5355 		/* Clear any previously-fixed device class and unit. */
5356 		if (dev->flags & DF_FIXEDCLASS)
5357 			devclass_delete_device(dev->devclass, dev);
5358 		dev->flags |= DF_WILDCARD;
5359 		dev->unit = -1;
5360 
5361 		/* Force the new device class. */
5362 		error = devclass_add_device(dc, dev);
5363 		if (error)
5364 			break;
5365 		dev->flags |= DF_FIXEDCLASS;
5366 		error = device_probe_and_attach(dev);
5367 		break;
5368 	}
5369 	}
5370 	mtx_unlock(&Giant);
5371 	return (error);
5372 }
5373 
5374 static struct cdevsw devctl2_cdevsw = {
5375 	.d_version =	D_VERSION,
5376 	.d_ioctl =	devctl2_ioctl,
5377 	.d_name =	"devctl2",
5378 };
5379 
5380 static void
5381 devctl2_init(void)
5382 {
5383 
5384 	make_dev_credf(MAKEDEV_ETERNAL, &devctl2_cdevsw, 0, NULL,
5385 	    UID_ROOT, GID_WHEEL, 0600, "devctl2");
5386 }
5387