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