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