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