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