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