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