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