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