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