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