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