3453b71f9ded49eac5b79edecdda11eb0c30bdfc
[dragonfly.git] / sys / kern / subr_bus.c
1 /*
2  * Copyright (c) 1997,1998 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/kern/subr_bus.c,v 1.54.2.9 2002/10/10 15:13:32 jhb Exp $
27  * $DragonFly: src/sys/kern/subr_bus.c,v 1.46 2008/10/03 00:26:21 hasso Exp $
28  */
29
30 #include "opt_bus.h"
31
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 #include <sys/malloc.h>
35 #include <sys/kernel.h>
36 #include <sys/module.h>
37 #include <sys/kobj.h>
38 #include <sys/bus_private.h>
39 #include <sys/sysctl.h>
40 #include <sys/systm.h>
41 #include <sys/bus.h>
42 #include <sys/rman.h>
43 #include <sys/device.h>
44 #include <sys/lock.h>
45 #include <sys/conf.h>
46 #include <sys/selinfo.h>
47 #include <sys/uio.h>
48 #include <sys/filio.h>
49 #include <sys/poll.h>
50 #include <sys/event.h>
51 #include <sys/signalvar.h>
52
53 #include <machine/stdarg.h>     /* for device_printf() */
54
55 #include <sys/thread2.h>
56 #include <sys/mplock2.h>
57
58 SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW, NULL, NULL);
59
60 MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
61
62 #ifdef BUS_DEBUG
63 #define PDEBUG(a)       (kprintf("%s:%d: ", __func__, __LINE__), kprintf a, kprintf("\n"))
64 #define DEVICENAME(d)   ((d)? device_get_name(d): "no device")
65 #define DRIVERNAME(d)   ((d)? d->name : "no driver")
66 #define DEVCLANAME(d)   ((d)? d->name : "no devclass")
67
68 /* Produce the indenting, indent*2 spaces plus a '.' ahead of that to 
69  * prevent syslog from deleting initial spaces
70  */
71 #define indentprintf(p) do { int iJ; kprintf("."); for (iJ=0; iJ<indent; iJ++) kprintf("  "); kprintf p ; } while(0)
72
73 static void     print_device_short(device_t dev, int indent);
74 static void     print_device(device_t dev, int indent);
75 void            print_device_tree_short(device_t dev, int indent);
76 void            print_device_tree(device_t dev, int indent);
77 static void     print_driver_short(driver_t *driver, int indent);
78 static void     print_driver(driver_t *driver, int indent);
79 static void     print_driver_list(driver_list_t drivers, int indent);
80 static void     print_devclass_short(devclass_t dc, int indent);
81 static void     print_devclass(devclass_t dc, int indent);
82 void            print_devclass_list_short(void);
83 void            print_devclass_list(void);
84
85 #else
86 /* Make the compiler ignore the function calls */
87 #define PDEBUG(a)                       /* nop */
88 #define DEVICENAME(d)                   /* nop */
89 #define DRIVERNAME(d)                   /* nop */
90 #define DEVCLANAME(d)                   /* nop */
91
92 #define print_device_short(d,i)         /* nop */
93 #define print_device(d,i)               /* nop */
94 #define print_device_tree_short(d,i)    /* nop */
95 #define print_device_tree(d,i)          /* nop */
96 #define print_driver_short(d,i)         /* nop */
97 #define print_driver(d,i)               /* nop */
98 #define print_driver_list(d,i)          /* nop */
99 #define print_devclass_short(d,i)       /* nop */
100 #define print_devclass(d,i)             /* nop */
101 #define print_devclass_list_short()     /* nop */
102 #define print_devclass_list()           /* nop */
103 #endif
104
105 static void     device_attach_async(device_t dev);
106 static void     device_attach_thread(void *arg);
107 static int      device_doattach(device_t dev);
108
109 static int do_async_attach = 0;
110 static int numasyncthreads;
111 TUNABLE_INT("kern.do_async_attach", &do_async_attach);
112
113 /*
114  * /dev/devctl implementation
115  */
116
117 /*
118  * This design allows only one reader for /dev/devctl.  This is not desirable
119  * in the long run, but will get a lot of hair out of this implementation.
120  * Maybe we should make this device a clonable device.
121  *
122  * Also note: we specifically do not attach a device to the device_t tree
123  * to avoid potential chicken and egg problems.  One could argue that all
124  * of this belongs to the root node.  One could also further argue that the
125  * sysctl interface that we have not might more properly be an ioctl
126  * interface, but at this stage of the game, I'm not inclined to rock that
127  * boat.
128  *
129  * I'm also not sure that the SIGIO support is done correctly or not, as
130  * I copied it from a driver that had SIGIO support that likely hasn't been
131  * tested since 3.4 or 2.2.8!
132  */
133
134 static int sysctl_devctl_disable(SYSCTL_HANDLER_ARGS);
135 static int devctl_disable = 0;
136 TUNABLE_INT("hw.bus.devctl_disable", &devctl_disable);
137 SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_disable, CTLTYPE_INT | CTLFLAG_RW, 0, 0,
138     sysctl_devctl_disable, "I", "devctl disable");
139
140 #define CDEV_MAJOR      188
141
142 static d_open_t         devopen;
143 static d_close_t        devclose;
144 static d_read_t         devread;
145 static d_ioctl_t        devioctl;
146 static d_poll_t         devpoll;
147 static d_kqfilter_t     devkqfilter;
148
149 static struct dev_ops devctl_ops = {
150         { "devctl", CDEV_MAJOR, 0 },
151         .d_open =       devopen,
152         .d_close =      devclose,
153         .d_read =       devread,
154         .d_ioctl =      devioctl,
155         .d_poll =       devpoll,
156         .d_kqfilter =   devkqfilter
157 };
158
159 struct dev_event_info
160 {
161         char *dei_data;
162         TAILQ_ENTRY(dev_event_info) dei_link;
163 };
164
165 TAILQ_HEAD(devq, dev_event_info);
166
167 static struct dev_softc
168 {
169         int     inuse;
170         int     nonblock;
171         struct lock lock;
172         struct selinfo sel;
173         struct devq devq;
174         struct proc *async_proc;
175 } devsoftc;
176
177 static void
178 devinit(void)
179 {
180         make_dev(&devctl_ops, 0, UID_ROOT, GID_WHEEL, 0600, "devctl");
181         lockinit(&devsoftc.lock, "dev mtx", 0, 0);
182         TAILQ_INIT(&devsoftc.devq);
183 }
184
185 static int
186 devopen(struct dev_open_args *ap)
187 {
188         if (devsoftc.inuse)
189                 return (EBUSY);
190         /* move to init */
191         devsoftc.inuse = 1;
192         devsoftc.nonblock = 0;
193         devsoftc.async_proc = NULL;
194         return (0);
195 }
196
197 static int
198 devclose(struct dev_close_args *ap)
199 {
200         devsoftc.inuse = 0;
201         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
202         wakeup(&devsoftc);
203         lockmgr(&devsoftc.lock, LK_RELEASE);
204
205         return (0);
206 }
207
208 /*
209  * The read channel for this device is used to report changes to
210  * userland in realtime.  We are required to free the data as well as
211  * the n1 object because we allocate them separately.  Also note that
212  * we return one record at a time.  If you try to read this device a
213  * character at a time, you will lose the rest of the data.  Listening
214  * programs are expected to cope.
215  */
216 static int
217 devread(struct dev_read_args *ap)
218 {
219         struct uio *uio = ap->a_uio;
220         struct dev_event_info *n1;
221         int rv;
222
223         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
224         while (TAILQ_EMPTY(&devsoftc.devq)) {
225                 if (devsoftc.nonblock) {
226                         lockmgr(&devsoftc.lock, LK_RELEASE);
227                         return (EAGAIN);
228                 }
229                 tsleep_interlock(&devsoftc, PCATCH);
230                 lockmgr(&devsoftc.lock, LK_RELEASE);
231                 rv = tsleep(&devsoftc, PCATCH | PINTERLOCKED, "devctl", 0);
232                 lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
233                 if (rv) {
234                         /*
235                          * Need to translate ERESTART to EINTR here? -- jake
236                          */
237                         lockmgr(&devsoftc.lock, LK_RELEASE);
238                         return (rv);
239                 }
240         }
241         n1 = TAILQ_FIRST(&devsoftc.devq);
242         TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
243         lockmgr(&devsoftc.lock, LK_RELEASE);
244         rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
245         kfree(n1->dei_data, M_BUS);
246         kfree(n1, M_BUS);
247         return (rv);
248 }
249
250 static  int
251 devioctl(struct dev_ioctl_args *ap)
252 {
253         switch (ap->a_cmd) {
254
255         case FIONBIO:
256                 if (*(int*)ap->a_data)
257                         devsoftc.nonblock = 1;
258                 else
259                         devsoftc.nonblock = 0;
260                 return (0);
261         case FIOASYNC:
262                 if (*(int*)ap->a_data)
263                         devsoftc.async_proc = curproc;
264                 else
265                         devsoftc.async_proc = NULL;
266                 return (0);
267
268                 /* (un)Support for other fcntl() calls. */
269         case FIOCLEX:
270         case FIONCLEX:
271         case FIONREAD:
272         case FIOSETOWN:
273         case FIOGETOWN:
274         default:
275                 break;
276         }
277         return (ENOTTY);
278 }
279
280 static  int
281 devpoll(struct dev_poll_args *ap)
282 {
283         int     revents = 0;
284
285         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
286         if (ap->a_events & (POLLIN | POLLRDNORM)) {
287                 if (!TAILQ_EMPTY(&devsoftc.devq))
288                         revents = ap->a_events & (POLLIN | POLLRDNORM);
289                 else
290                         selrecord(curthread, &devsoftc.sel);
291         }
292         lockmgr(&devsoftc.lock, LK_RELEASE);
293
294         ap->a_events = revents;
295         return (0);
296 }
297
298 static void dev_filter_detach(struct knote *);
299 static int dev_filter_read(struct knote *, long);
300
301 static struct filterops dev_filtops =
302         { 1, NULL, dev_filter_detach, dev_filter_read };
303
304 static int
305 devkqfilter(struct dev_kqfilter_args *ap)
306 {
307         struct knote *kn = ap->a_kn;
308         struct klist *klist;
309
310         ap->a_result = 0;
311         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
312
313         switch (kn->kn_filter) {
314         case EVFILT_READ:
315                 kn->kn_fop = &dev_filtops;
316                 break;
317         default:
318                 ap->a_result = EOPNOTSUPP;
319                 lockmgr(&devsoftc.lock, LK_RELEASE);
320                 return (0);
321         }
322
323         crit_enter();
324         klist = &devsoftc.sel.si_note;
325         SLIST_INSERT_HEAD(klist, kn, kn_selnext);
326         crit_exit();
327
328         lockmgr(&devsoftc.lock, LK_RELEASE);
329
330         return (0);
331 }
332
333 static void
334 dev_filter_detach(struct knote *kn)
335 {
336         struct klist *klist;
337
338         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
339         crit_enter();
340         klist = &devsoftc.sel.si_note;
341         SLIST_INSERT_HEAD(klist, kn, kn_selnext);
342         crit_exit();
343         lockmgr(&devsoftc.lock, LK_RELEASE);
344 }
345
346 static int
347 dev_filter_read(struct knote *kn, long hint)
348 {
349         int ready = 0;
350
351         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
352         if (!TAILQ_EMPTY(&devsoftc.devq))
353                 ready = 1;
354         lockmgr(&devsoftc.lock, LK_RELEASE);
355
356         return (ready);
357 }
358
359
360 /**
361  * @brief Return whether the userland process is running
362  */
363 boolean_t
364 devctl_process_running(void)
365 {
366         return (devsoftc.inuse == 1);
367 }
368
369 /**
370  * @brief Queue data to be read from the devctl device
371  *
372  * Generic interface to queue data to the devctl device.  It is
373  * assumed that @p data is properly formatted.  It is further assumed
374  * that @p data is allocated using the M_BUS malloc type.
375  */
376 void
377 devctl_queue_data(char *data)
378 {
379         struct dev_event_info *n1 = NULL;
380         struct proc *p;
381
382         n1 = kmalloc(sizeof(*n1), M_BUS, M_NOWAIT);
383         if (n1 == NULL)
384                 return;
385         n1->dei_data = data;
386         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
387         TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
388         wakeup(&devsoftc);
389         lockmgr(&devsoftc.lock, LK_RELEASE);
390         get_mplock();   /* XXX */
391         selwakeup(&devsoftc.sel);
392         rel_mplock();   /* XXX */
393         p = devsoftc.async_proc;
394         if (p != NULL)
395                 ksignal(p, SIGIO);
396 }
397
398 /**
399  * @brief Send a 'notification' to userland, using standard ways
400  */
401 void
402 devctl_notify(const char *system, const char *subsystem, const char *type,
403     const char *data)
404 {
405         int len = 0;
406         char *msg;
407
408         if (system == NULL)
409                 return;         /* BOGUS!  Must specify system. */
410         if (subsystem == NULL)
411                 return;         /* BOGUS!  Must specify subsystem. */
412         if (type == NULL)
413                 return;         /* BOGUS!  Must specify type. */
414         len += strlen(" system=") + strlen(system);
415         len += strlen(" subsystem=") + strlen(subsystem);
416         len += strlen(" type=") + strlen(type);
417         /* add in the data message plus newline. */
418         if (data != NULL)
419                 len += strlen(data);
420         len += 3;       /* '!', '\n', and NUL */
421         msg = kmalloc(len, M_BUS, M_NOWAIT);
422         if (msg == NULL)
423                 return;         /* Drop it on the floor */
424         if (data != NULL)
425                 ksnprintf(msg, len, "!system=%s subsystem=%s type=%s %s\n",
426                     system, subsystem, type, data);
427         else
428                 ksnprintf(msg, len, "!system=%s subsystem=%s type=%s\n",
429                     system, subsystem, type);
430         devctl_queue_data(msg);
431 }
432
433 /*
434  * Common routine that tries to make sending messages as easy as possible.
435  * We allocate memory for the data, copy strings into that, but do not
436  * free it unless there's an error.  The dequeue part of the driver should
437  * free the data.  We don't send data when the device is disabled.  We do
438  * send data, even when we have no listeners, because we wish to avoid
439  * races relating to startup and restart of listening applications.
440  *
441  * devaddq is designed to string together the type of event, with the
442  * object of that event, plus the plug and play info and location info
443  * for that event.  This is likely most useful for devices, but less
444  * useful for other consumers of this interface.  Those should use
445  * the devctl_queue_data() interface instead.
446  */
447 static void
448 devaddq(const char *type, const char *what, device_t dev)
449 {
450         char *data = NULL;
451         char *loc = NULL;
452         char *pnp = NULL;
453         const char *parstr;
454
455         if (devctl_disable)
456                 return;
457         data = kmalloc(1024, M_BUS, M_NOWAIT);
458         if (data == NULL)
459                 goto bad;
460
461         /* get the bus specific location of this device */
462         loc = kmalloc(1024, M_BUS, M_NOWAIT);
463         if (loc == NULL)
464                 goto bad;
465         *loc = '\0';
466         bus_child_location_str(dev, loc, 1024);
467
468         /* Get the bus specific pnp info of this device */
469         pnp = kmalloc(1024, M_BUS, M_NOWAIT);
470         if (pnp == NULL)
471                 goto bad;
472         *pnp = '\0';
473         bus_child_pnpinfo_str(dev, pnp, 1024);
474
475         /* Get the parent of this device, or / if high enough in the tree. */
476         if (device_get_parent(dev) == NULL)
477                 parstr = ".";   /* Or '/' ? */
478         else
479                 parstr = device_get_nameunit(device_get_parent(dev));
480         /* String it all together. */
481         ksnprintf(data, 1024, "%s%s at %s %s on %s\n", type, what, loc, pnp,
482           parstr);
483         kfree(loc, M_BUS);
484         kfree(pnp, M_BUS);
485         devctl_queue_data(data);
486         return;
487 bad:
488         kfree(pnp, M_BUS);
489         kfree(loc, M_BUS);
490         kfree(data, M_BUS);
491         return;
492 }
493
494 /*
495  * A device was added to the tree.  We are called just after it successfully
496  * attaches (that is, probe and attach success for this device).  No call
497  * is made if a device is merely parented into the tree.  See devnomatch
498  * if probe fails.  If attach fails, no notification is sent (but maybe
499  * we should have a different message for this).
500  */
501 static void
502 devadded(device_t dev)
503 {
504         char *pnp = NULL;
505         char *tmp = NULL;
506
507         pnp = kmalloc(1024, M_BUS, M_NOWAIT);
508         if (pnp == NULL)
509                 goto fail;
510         tmp = kmalloc(1024, M_BUS, M_NOWAIT);
511         if (tmp == NULL)
512                 goto fail;
513         *pnp = '\0';
514         bus_child_pnpinfo_str(dev, pnp, 1024);
515         ksnprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
516         devaddq("+", tmp, dev);
517 fail:
518         if (pnp != NULL)
519                 kfree(pnp, M_BUS);
520         if (tmp != NULL)
521                 kfree(tmp, M_BUS);
522         return;
523 }
524
525 /*
526  * A device was removed from the tree.  We are called just before this
527  * happens.
528  */
529 static void
530 devremoved(device_t dev)
531 {
532         char *pnp = NULL;
533         char *tmp = NULL;
534
535         pnp = kmalloc(1024, M_BUS, M_NOWAIT);
536         if (pnp == NULL)
537                 goto fail;
538         tmp = kmalloc(1024, M_BUS, M_NOWAIT);
539         if (tmp == NULL)
540                 goto fail;
541         *pnp = '\0';
542         bus_child_pnpinfo_str(dev, pnp, 1024);
543         ksnprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
544         devaddq("-", tmp, dev);
545 fail:
546         if (pnp != NULL)
547                 kfree(pnp, M_BUS);
548         if (tmp != NULL)
549                 kfree(tmp, M_BUS);
550         return;
551 }
552
553 /*
554  * Called when there's no match for this device.  This is only called
555  * the first time that no match happens, so we don't keep getitng this
556  * message.  Should that prove to be undesirable, we can change it.
557  * This is called when all drivers that can attach to a given bus
558  * decline to accept this device.  Other errrors may not be detected.
559  */
560 static void
561 devnomatch(device_t dev)
562 {
563         devaddq("?", "", dev);
564 }
565
566 static int
567 sysctl_devctl_disable(SYSCTL_HANDLER_ARGS)
568 {
569         struct dev_event_info *n1;
570         int dis, error;
571
572         dis = devctl_disable;
573         error = sysctl_handle_int(oidp, &dis, 0, req);
574         if (error || !req->newptr)
575                 return (error);
576         lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
577         devctl_disable = dis;
578         if (dis) {
579                 while (!TAILQ_EMPTY(&devsoftc.devq)) {
580                         n1 = TAILQ_FIRST(&devsoftc.devq);
581                         TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
582                         kfree(n1->dei_data, M_BUS);
583                         kfree(n1, M_BUS);
584                 }
585         }
586         lockmgr(&devsoftc.lock, LK_RELEASE);
587         return (0);
588 }
589
590 /* End of /dev/devctl code */
591
592 TAILQ_HEAD(,device)     bus_data_devices;
593 static int bus_data_generation = 1;
594
595 kobj_method_t null_methods[] = {
596         { 0, 0 }
597 };
598
599 DEFINE_CLASS(null, null_methods, 0);
600
601 /*
602  * Devclass implementation
603  */
604
605 static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
606
607 static devclass_t
608 devclass_find_internal(const char *classname, const char *parentname,
609                        int create)
610 {
611         devclass_t dc;
612
613         PDEBUG(("looking for %s", classname));
614         if (classname == NULL)
615                 return(NULL);
616
617         TAILQ_FOREACH(dc, &devclasses, link)
618                 if (!strcmp(dc->name, classname))
619                         break;
620
621         if (create && !dc) {
622                 PDEBUG(("creating %s", classname));
623                 dc = kmalloc(sizeof(struct devclass) + strlen(classname) + 1,
624                             M_BUS, M_INTWAIT | M_ZERO);
625                 if (!dc)
626                         return(NULL);
627                 dc->parent = NULL;
628                 dc->name = (char*) (dc + 1);
629                 strcpy(dc->name, classname);
630                 dc->devices = NULL;
631                 dc->maxunit = 0;
632                 TAILQ_INIT(&dc->drivers);
633                 TAILQ_INSERT_TAIL(&devclasses, dc, link);
634
635                 bus_data_generation_update();
636
637         }
638         if (parentname && dc && !dc->parent)
639                 dc->parent = devclass_find_internal(parentname, NULL, FALSE);
640
641         return(dc);
642 }
643
644 devclass_t
645 devclass_create(const char *classname)
646 {
647         return(devclass_find_internal(classname, NULL, TRUE));
648 }
649
650 devclass_t
651 devclass_find(const char *classname)
652 {
653         return(devclass_find_internal(classname, NULL, FALSE));
654 }
655
656 device_t
657 devclass_find_unit(const char *classname, int unit)
658 {
659         devclass_t dc;
660
661         if ((dc = devclass_find(classname)) != NULL)
662             return(devclass_get_device(dc, unit));
663         return (NULL);
664 }
665
666 int
667 devclass_add_driver(devclass_t dc, driver_t *driver)
668 {
669         driverlink_t dl;
670         device_t dev;
671         int i;
672
673         PDEBUG(("%s", DRIVERNAME(driver)));
674
675         dl = kmalloc(sizeof *dl, M_BUS, M_INTWAIT | M_ZERO);
676         if (!dl)
677                 return(ENOMEM);
678
679         /*
680          * Compile the driver's methods. Also increase the reference count
681          * so that the class doesn't get freed when the last instance
682          * goes. This means we can safely use static methods and avoids a
683          * double-free in devclass_delete_driver.
684          */
685         kobj_class_instantiate(driver);
686
687         /*
688          * Make sure the devclass which the driver is implementing exists.
689          */
690         devclass_find_internal(driver->name, NULL, TRUE);
691
692         dl->driver = driver;
693         TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
694
695         /*
696          * Call BUS_DRIVER_ADDED for any existing busses in this class,
697          * but only if the bus has already been attached (otherwise we
698          * might probe too early).
699          *
700          * This is what will cause a newly loaded module to be associated
701          * with hardware.  bus_generic_driver_added() is typically what ends
702          * up being called.
703          */
704         for (i = 0; i < dc->maxunit; i++) {
705                 if ((dev = dc->devices[i]) != NULL) {
706                         if (dev->state >= DS_ATTACHED)
707                                 BUS_DRIVER_ADDED(dev, driver);
708                 }
709         }
710
711         bus_data_generation_update();
712         return(0);
713 }
714
715 int
716 devclass_delete_driver(devclass_t busclass, driver_t *driver)
717 {
718         devclass_t dc = devclass_find(driver->name);
719         driverlink_t dl;
720         device_t dev;
721         int i;
722         int error;
723
724         PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
725
726         if (!dc)
727                 return(0);
728
729         /*
730          * Find the link structure in the bus' list of drivers.
731          */
732         TAILQ_FOREACH(dl, &busclass->drivers, link)
733                 if (dl->driver == driver)
734                         break;
735
736         if (!dl) {
737                 PDEBUG(("%s not found in %s list", driver->name, busclass->name));
738                 return(ENOENT);
739         }
740
741         /*
742          * Disassociate from any devices.  We iterate through all the
743          * devices in the devclass of the driver and detach any which are
744          * using the driver and which have a parent in the devclass which
745          * we are deleting from.
746          *
747          * Note that since a driver can be in multiple devclasses, we
748          * should not detach devices which are not children of devices in
749          * the affected devclass.
750          */
751         for (i = 0; i < dc->maxunit; i++)
752                 if (dc->devices[i]) {
753                         dev = dc->devices[i];
754                         if (dev->driver == driver && dev->parent &&
755                             dev->parent->devclass == busclass) {
756                                 if ((error = device_detach(dev)) != 0)
757                                         return(error);
758                                 device_set_driver(dev, NULL);
759                         }
760                 }
761
762         TAILQ_REMOVE(&busclass->drivers, dl, link);
763         kfree(dl, M_BUS);
764
765         kobj_class_uninstantiate(driver);
766
767         bus_data_generation_update();
768         return(0);
769 }
770
771 static driverlink_t
772 devclass_find_driver_internal(devclass_t dc, const char *classname)
773 {
774         driverlink_t dl;
775
776         PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
777
778         TAILQ_FOREACH(dl, &dc->drivers, link)
779                 if (!strcmp(dl->driver->name, classname))
780                         return(dl);
781
782         PDEBUG(("not found"));
783         return(NULL);
784 }
785
786 kobj_class_t
787 devclass_find_driver(devclass_t dc, const char *classname)
788 {
789         driverlink_t dl;
790
791         dl = devclass_find_driver_internal(dc, classname);
792         if (dl)
793                 return(dl->driver);
794         else
795                 return(NULL);
796 }
797
798 const char *
799 devclass_get_name(devclass_t dc)
800 {
801         return(dc->name);
802 }
803
804 device_t
805 devclass_get_device(devclass_t dc, int unit)
806 {
807         if (dc == NULL || unit < 0 || unit >= dc->maxunit)
808                 return(NULL);
809         return(dc->devices[unit]);
810 }
811
812 void *
813 devclass_get_softc(devclass_t dc, int unit)
814 {
815         device_t dev;
816
817         dev = devclass_get_device(dc, unit);
818         if (!dev)
819                 return(NULL);
820
821         return(device_get_softc(dev));
822 }
823
824 int
825 devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
826 {
827         int i;
828         int count;
829         device_t *list;
830     
831         count = 0;
832         for (i = 0; i < dc->maxunit; i++)
833                 if (dc->devices[i])
834                         count++;
835
836         list = kmalloc(count * sizeof(device_t), M_TEMP, M_INTWAIT | M_ZERO);
837         if (list == NULL)
838                 return(ENOMEM);
839
840         count = 0;
841         for (i = 0; i < dc->maxunit; i++)
842                 if (dc->devices[i]) {
843                         list[count] = dc->devices[i];
844                         count++;
845                 }
846
847         *devlistp = list;
848         *devcountp = count;
849
850         return(0);
851 }
852
853 /**
854  * @brief Get a list of drivers in the devclass
855  *
856  * An array containing a list of pointers to all the drivers in the
857  * given devclass is allocated and returned in @p *listp.  The number
858  * of drivers in the array is returned in @p *countp. The caller should
859  * free the array using @c free(p, M_TEMP).
860  *
861  * @param dc            the devclass to examine
862  * @param listp         gives location for array pointer return value
863  * @param countp        gives location for number of array elements
864  *                      return value
865  *
866  * @retval 0            success
867  * @retval ENOMEM       the array allocation failed
868  */
869 int
870 devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
871 {
872         driverlink_t dl;
873         driver_t **list;
874         int count;
875
876         count = 0;
877         TAILQ_FOREACH(dl, &dc->drivers, link)
878                 count++;
879         list = kmalloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
880         if (list == NULL)
881                 return (ENOMEM);
882
883         count = 0;
884         TAILQ_FOREACH(dl, &dc->drivers, link) {
885                 list[count] = dl->driver;
886                 count++;
887         }
888         *listp = list;
889         *countp = count;
890
891         return (0);
892 }
893
894 /**
895  * @brief Get the number of devices in a devclass
896  *
897  * @param dc            the devclass to examine
898  */
899 int
900 devclass_get_count(devclass_t dc)
901 {
902         int count, i;
903
904         count = 0;
905         for (i = 0; i < dc->maxunit; i++)
906                 if (dc->devices[i])
907                         count++;
908         return (count);
909 }
910
911 int
912 devclass_get_maxunit(devclass_t dc)
913 {
914         return(dc->maxunit);
915 }
916
917 void
918 devclass_set_parent(devclass_t dc, devclass_t pdc)
919 {
920         dc->parent = pdc;
921 }
922
923 devclass_t
924 devclass_get_parent(devclass_t dc)
925 {
926         return(dc->parent);
927 }
928
929 static int
930 devclass_alloc_unit(devclass_t dc, int *unitp)
931 {
932         int unit = *unitp;
933
934         PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
935
936         /* If we have been given a wired unit number, check for existing device */
937         if (unit != -1) {
938                 if (unit >= 0 && unit < dc->maxunit &&
939                     dc->devices[unit] != NULL) {
940                         if (bootverbose)
941                                 kprintf("%s-: %s%d exists, using next available unit number\n",
942                                        dc->name, dc->name, unit);
943                         /* find the next available slot */
944                         while (++unit < dc->maxunit && dc->devices[unit] != NULL)
945                                 ;
946                 }
947         } else {
948                 /* Unwired device, find the next available slot for it */
949                 unit = 0;
950                 while (unit < dc->maxunit && dc->devices[unit] != NULL)
951                         unit++;
952         }
953
954         /*
955          * We've selected a unit beyond the length of the table, so let's
956          * extend the table to make room for all units up to and including
957          * this one.
958          */
959         if (unit >= dc->maxunit) {
960                 device_t *newlist;
961                 int newsize;
962
963                 newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
964                 newlist = kmalloc(sizeof(device_t) * newsize, M_BUS,
965                                  M_INTWAIT | M_ZERO);
966                 if (newlist == NULL)
967                         return(ENOMEM);
968                 bcopy(dc->devices, newlist, sizeof(device_t) * dc->maxunit);
969                 if (dc->devices)
970                         kfree(dc->devices, M_BUS);
971                 dc->devices = newlist;
972                 dc->maxunit = newsize;
973         }
974         PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
975
976         *unitp = unit;
977         return(0);
978 }
979
980 static int
981 devclass_add_device(devclass_t dc, device_t dev)
982 {
983         int buflen, error;
984
985         PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
986
987         buflen = strlen(dc->name) + 5;
988         dev->nameunit = kmalloc(buflen, M_BUS, M_INTWAIT | M_ZERO);
989         if (!dev->nameunit)
990                 return(ENOMEM);
991
992         if ((error = devclass_alloc_unit(dc, &dev->unit)) != 0) {
993                 kfree(dev->nameunit, M_BUS);
994                 dev->nameunit = NULL;
995                 return(error);
996         }
997         dc->devices[dev->unit] = dev;
998         dev->devclass = dc;
999         ksnprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
1000
1001         return(0);
1002 }
1003
1004 static int
1005 devclass_delete_device(devclass_t dc, device_t dev)
1006 {
1007         if (!dc || !dev)
1008                 return(0);
1009
1010         PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1011
1012         if (dev->devclass != dc || dc->devices[dev->unit] != dev)
1013                 panic("devclass_delete_device: inconsistent device class");
1014         dc->devices[dev->unit] = NULL;
1015         if (dev->flags & DF_WILDCARD)
1016                 dev->unit = -1;
1017         dev->devclass = NULL;
1018         kfree(dev->nameunit, M_BUS);
1019         dev->nameunit = NULL;
1020
1021         return(0);
1022 }
1023
1024 static device_t
1025 make_device(device_t parent, const char *name, int unit)
1026 {
1027         device_t dev;
1028         devclass_t dc;
1029
1030         PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1031
1032         if (name != NULL) {
1033                 dc = devclass_find_internal(name, NULL, TRUE);
1034                 if (!dc) {
1035                         kprintf("make_device: can't find device class %s\n", name);
1036                         return(NULL);
1037                 }
1038         } else
1039                 dc = NULL;
1040
1041         dev = kmalloc(sizeof(struct device), M_BUS, M_INTWAIT | M_ZERO);
1042         if (!dev)
1043                 return(0);
1044
1045         dev->parent = parent;
1046         TAILQ_INIT(&dev->children);
1047         kobj_init((kobj_t) dev, &null_class);
1048         dev->driver = NULL;
1049         dev->devclass = NULL;
1050         dev->unit = unit;
1051         dev->nameunit = NULL;
1052         dev->desc = NULL;
1053         dev->busy = 0;
1054         dev->devflags = 0;
1055         dev->flags = DF_ENABLED;
1056         dev->order = 0;
1057         if (unit == -1)
1058                 dev->flags |= DF_WILDCARD;
1059         if (name) {
1060                 dev->flags |= DF_FIXEDCLASS;
1061                 if (devclass_add_device(dc, dev) != 0) {
1062                         kobj_delete((kobj_t)dev, M_BUS);
1063                         return(NULL);
1064                 }
1065         }
1066         dev->ivars = NULL;
1067         dev->softc = NULL;
1068
1069         dev->state = DS_NOTPRESENT;
1070
1071         TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1072         bus_data_generation_update();
1073
1074         return(dev);
1075 }
1076
1077 static int
1078 device_print_child(device_t dev, device_t child)
1079 {
1080         int retval = 0;
1081
1082         if (device_is_alive(child))
1083                 retval += BUS_PRINT_CHILD(dev, child);
1084         else
1085                 retval += device_printf(child, " not found\n");
1086
1087         return(retval);
1088 }
1089
1090 device_t
1091 device_add_child(device_t dev, const char *name, int unit)
1092 {
1093         return device_add_child_ordered(dev, 0, name, unit);
1094 }
1095
1096 device_t
1097 device_add_child_ordered(device_t dev, int order, const char *name, int unit)
1098 {
1099         device_t child;
1100         device_t place;
1101
1102         PDEBUG(("%s at %s with order %d as unit %d", name, DEVICENAME(dev),
1103                 order, unit));
1104
1105         child = make_device(dev, name, unit);
1106         if (child == NULL)
1107                 return child;
1108         child->order = order;
1109
1110         TAILQ_FOREACH(place, &dev->children, link)
1111                 if (place->order > order)
1112                         break;
1113
1114         if (place) {
1115                 /*
1116                  * The device 'place' is the first device whose order is
1117                  * greater than the new child.
1118                  */
1119                 TAILQ_INSERT_BEFORE(place, child, link);
1120         } else {
1121                 /*
1122                  * The new child's order is greater or equal to the order of
1123                  * any existing device. Add the child to the tail of the list.
1124                  */
1125                 TAILQ_INSERT_TAIL(&dev->children, child, link);
1126         }
1127
1128         bus_data_generation_update();
1129         return(child);
1130 }
1131
1132 int
1133 device_delete_child(device_t dev, device_t child)
1134 {
1135         int error;
1136         device_t grandchild;
1137
1138         PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1139
1140         /* remove children first */
1141         while ( (grandchild = TAILQ_FIRST(&child->children)) ) {
1142                 error = device_delete_child(child, grandchild);
1143                 if (error)
1144                         return(error);
1145         }
1146
1147         if ((error = device_detach(child)) != 0)
1148                 return(error);
1149         if (child->devclass)
1150                 devclass_delete_device(child->devclass, child);
1151         TAILQ_REMOVE(&dev->children, child, link);
1152         TAILQ_REMOVE(&bus_data_devices, child, devlink);
1153         device_set_desc(child, NULL);
1154         kobj_delete((kobj_t)child, M_BUS);
1155
1156         bus_data_generation_update();
1157         return(0);
1158 }
1159
1160 /**
1161  * @brief Find a device given a unit number
1162  *
1163  * This is similar to devclass_get_devices() but only searches for
1164  * devices which have @p dev as a parent.
1165  *
1166  * @param dev           the parent device to search
1167  * @param unit          the unit number to search for.  If the unit is -1,
1168  *                      return the first child of @p dev which has name
1169  *                      @p classname (that is, the one with the lowest unit.)
1170  *
1171  * @returns             the device with the given unit number or @c
1172  *                      NULL if there is no such device
1173  */
1174 device_t
1175 device_find_child(device_t dev, const char *classname, int unit)
1176 {
1177         devclass_t dc;
1178         device_t child;
1179
1180         dc = devclass_find(classname);
1181         if (!dc)
1182                 return(NULL);
1183
1184         if (unit != -1) {
1185                 child = devclass_get_device(dc, unit);
1186                 if (child && child->parent == dev)
1187                         return (child);
1188         } else {
1189                 for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
1190                         child = devclass_get_device(dc, unit);
1191                         if (child && child->parent == dev)
1192                                 return (child);
1193                 }
1194         }
1195         return(NULL);
1196 }
1197
1198 static driverlink_t
1199 first_matching_driver(devclass_t dc, device_t dev)
1200 {
1201         if (dev->devclass)
1202                 return(devclass_find_driver_internal(dc, dev->devclass->name));
1203         else
1204                 return(TAILQ_FIRST(&dc->drivers));
1205 }
1206
1207 static driverlink_t
1208 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1209 {
1210         if (dev->devclass) {
1211                 driverlink_t dl;
1212                 for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1213                         if (!strcmp(dev->devclass->name, dl->driver->name))
1214                                 return(dl);
1215                 return(NULL);
1216         } else
1217                 return(TAILQ_NEXT(last, link));
1218 }
1219
1220 static int
1221 device_probe_child(device_t dev, device_t child)
1222 {
1223         devclass_t dc;
1224         driverlink_t best = 0;
1225         driverlink_t dl;
1226         int result, pri = 0;
1227         int hasclass = (child->devclass != 0);
1228
1229         dc = dev->devclass;
1230         if (!dc)
1231                 panic("device_probe_child: parent device has no devclass");
1232
1233         if (child->state == DS_ALIVE)
1234                 return(0);
1235
1236         for (; dc; dc = dc->parent) {
1237                 for (dl = first_matching_driver(dc, child); dl;
1238                      dl = next_matching_driver(dc, child, dl)) {
1239                         PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1240                         device_set_driver(child, dl->driver);
1241                         if (!hasclass)
1242                                 device_set_devclass(child, dl->driver->name);
1243                         result = DEVICE_PROBE(child);
1244                         if (!hasclass)
1245                                 device_set_devclass(child, 0);
1246
1247                         /*
1248                          * If the driver returns SUCCESS, there can be
1249                          * no higher match for this device.
1250                          */
1251                         if (result == 0) {
1252                                 best = dl;
1253                                 pri = 0;
1254                                 break;
1255                         }
1256
1257                         /*
1258                          * The driver returned an error so it
1259                          * certainly doesn't match.
1260                          */
1261                         if (result > 0) {
1262                                 device_set_driver(child, 0);
1263                                 continue;
1264                         }
1265
1266                         /*
1267                          * A priority lower than SUCCESS, remember the
1268                          * best matching driver. Initialise the value
1269                          * of pri for the first match.
1270                          */
1271                         if (best == 0 || result > pri) {
1272                                 best = dl;
1273                                 pri = result;
1274                                 continue;
1275                         }
1276                 }
1277                 /*
1278                  * If we have unambiguous match in this devclass,
1279                  * don't look in the parent.
1280                  */
1281                 if (best && pri == 0)
1282                         break;
1283         }
1284
1285         /*
1286          * If we found a driver, change state and initialise the devclass.
1287          */
1288         if (best) {
1289                 if (!child->devclass)
1290                         device_set_devclass(child, best->driver->name);
1291                 device_set_driver(child, best->driver);
1292                 if (pri < 0) {
1293                         /*
1294                          * A bit bogus. Call the probe method again to make
1295                          * sure that we have the right description.
1296                          */
1297                         DEVICE_PROBE(child);
1298                 }
1299
1300                 bus_data_generation_update();
1301                 child->state = DS_ALIVE;
1302                 return(0);
1303         }
1304
1305         return(ENXIO);
1306 }
1307
1308 device_t
1309 device_get_parent(device_t dev)
1310 {
1311         return dev->parent;
1312 }
1313
1314 int
1315 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1316 {
1317         int count;
1318         device_t child;
1319         device_t *list;
1320     
1321         count = 0;
1322         TAILQ_FOREACH(child, &dev->children, link)
1323                 count++;
1324
1325         list = kmalloc(count * sizeof(device_t), M_TEMP, M_INTWAIT | M_ZERO);
1326         if (!list)
1327                 return(ENOMEM);
1328
1329         count = 0;
1330         TAILQ_FOREACH(child, &dev->children, link) {
1331                 list[count] = child;
1332                 count++;
1333         }
1334
1335         *devlistp = list;
1336         *devcountp = count;
1337
1338         return(0);
1339 }
1340
1341 driver_t *
1342 device_get_driver(device_t dev)
1343 {
1344         return(dev->driver);
1345 }
1346
1347 devclass_t
1348 device_get_devclass(device_t dev)
1349 {
1350         return(dev->devclass);
1351 }
1352
1353 const char *
1354 device_get_name(device_t dev)
1355 {
1356         if (dev->devclass)
1357                 return devclass_get_name(dev->devclass);
1358         return(NULL);
1359 }
1360
1361 const char *
1362 device_get_nameunit(device_t dev)
1363 {
1364         return(dev->nameunit);
1365 }
1366
1367 int
1368 device_get_unit(device_t dev)
1369 {
1370         return(dev->unit);
1371 }
1372
1373 const char *
1374 device_get_desc(device_t dev)
1375 {
1376         return(dev->desc);
1377 }
1378
1379 uint32_t
1380 device_get_flags(device_t dev)
1381 {
1382         return(dev->devflags);
1383 }
1384
1385 int
1386 device_print_prettyname(device_t dev)
1387 {
1388         const char *name = device_get_name(dev);
1389
1390         if (name == 0)
1391                 return kprintf("unknown: ");
1392         else
1393                 return kprintf("%s%d: ", name, device_get_unit(dev));
1394 }
1395
1396 int
1397 device_printf(device_t dev, const char * fmt, ...)
1398 {
1399         __va_list ap;
1400         int retval;
1401
1402         retval = device_print_prettyname(dev);
1403         __va_start(ap, fmt);
1404         retval += kvprintf(fmt, ap);
1405         __va_end(ap);
1406         return retval;
1407 }
1408
1409 static void
1410 device_set_desc_internal(device_t dev, const char* desc, int copy)
1411 {
1412         if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
1413                 kfree(dev->desc, M_BUS);
1414                 dev->flags &= ~DF_DESCMALLOCED;
1415                 dev->desc = NULL;
1416         }
1417
1418         if (copy && desc) {
1419                 dev->desc = kmalloc(strlen(desc) + 1, M_BUS, M_INTWAIT);
1420                 if (dev->desc) {
1421                         strcpy(dev->desc, desc);
1422                         dev->flags |= DF_DESCMALLOCED;
1423                 }
1424         } else {
1425                 /* Avoid a -Wcast-qual warning */
1426                 dev->desc = (char *)(uintptr_t) desc;
1427         }
1428
1429         bus_data_generation_update();
1430 }
1431
1432 void
1433 device_set_desc(device_t dev, const char* desc)
1434 {
1435         device_set_desc_internal(dev, desc, FALSE);
1436 }
1437
1438 void
1439 device_set_desc_copy(device_t dev, const char* desc)
1440 {
1441         device_set_desc_internal(dev, desc, TRUE);
1442 }
1443
1444 void
1445 device_set_flags(device_t dev, uint32_t flags)
1446 {
1447         dev->devflags = flags;
1448 }
1449
1450 void *
1451 device_get_softc(device_t dev)
1452 {
1453         return dev->softc;
1454 }
1455
1456 void
1457 device_set_softc(device_t dev, void *softc)
1458 {
1459         if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
1460                 kfree(dev->softc, M_BUS);
1461         dev->softc = softc;
1462         if (dev->softc)
1463                 dev->flags |= DF_EXTERNALSOFTC;
1464         else
1465                 dev->flags &= ~DF_EXTERNALSOFTC;
1466 }
1467
1468 void
1469 device_set_async_attach(device_t dev, int enable)
1470 {
1471         if (enable)
1472                 dev->flags |= DF_ASYNCPROBE;
1473         else
1474                 dev->flags &= ~DF_ASYNCPROBE;
1475 }
1476
1477 void *
1478 device_get_ivars(device_t dev)
1479 {
1480         return dev->ivars;
1481 }
1482
1483 void
1484 device_set_ivars(device_t dev, void * ivars)
1485 {
1486         if (!dev)
1487                 return;
1488
1489         dev->ivars = ivars;
1490 }
1491
1492 device_state_t
1493 device_get_state(device_t dev)
1494 {
1495         return(dev->state);
1496 }
1497
1498 void
1499 device_enable(device_t dev)
1500 {
1501         dev->flags |= DF_ENABLED;
1502 }
1503
1504 void
1505 device_disable(device_t dev)
1506 {
1507         dev->flags &= ~DF_ENABLED;
1508 }
1509
1510 /*
1511  * YYY cannot block
1512  */
1513 void
1514 device_busy(device_t dev)
1515 {
1516         if (dev->state < DS_ATTACHED)
1517                 panic("device_busy: called for unattached device");
1518         if (dev->busy == 0 && dev->parent)
1519                 device_busy(dev->parent);
1520         dev->busy++;
1521         dev->state = DS_BUSY;
1522 }
1523
1524 /*
1525  * YYY cannot block
1526  */
1527 void
1528 device_unbusy(device_t dev)
1529 {
1530         if (dev->state != DS_BUSY)
1531                 panic("device_unbusy: called for non-busy device");
1532         dev->busy--;
1533         if (dev->busy == 0) {
1534                 if (dev->parent)
1535                         device_unbusy(dev->parent);
1536                 dev->state = DS_ATTACHED;
1537         }
1538 }
1539
1540 void
1541 device_quiet(device_t dev)
1542 {
1543         dev->flags |= DF_QUIET;
1544 }
1545
1546 void
1547 device_verbose(device_t dev)
1548 {
1549         dev->flags &= ~DF_QUIET;
1550 }
1551
1552 int
1553 device_is_quiet(device_t dev)
1554 {
1555         return((dev->flags & DF_QUIET) != 0);
1556 }
1557
1558 int
1559 device_is_enabled(device_t dev)
1560 {
1561         return((dev->flags & DF_ENABLED) != 0);
1562 }
1563
1564 int
1565 device_is_alive(device_t dev)
1566 {
1567         return(dev->state >= DS_ALIVE);
1568 }
1569
1570 int
1571 device_is_attached(device_t dev)
1572 {
1573         return(dev->state >= DS_ATTACHED);
1574 }
1575
1576 int
1577 device_set_devclass(device_t dev, const char *classname)
1578 {
1579         devclass_t dc;
1580         int error;
1581
1582         if (!classname) {
1583                 if (dev->devclass)
1584                         devclass_delete_device(dev->devclass, dev);
1585                 return(0);
1586         }
1587
1588         if (dev->devclass) {
1589                 kprintf("device_set_devclass: device class already set\n");
1590                 return(EINVAL);
1591         }
1592
1593         dc = devclass_find_internal(classname, NULL, TRUE);
1594         if (!dc)
1595                 return(ENOMEM);
1596
1597         error = devclass_add_device(dc, dev);
1598
1599         bus_data_generation_update();
1600         return(error);
1601 }
1602
1603 int
1604 device_set_driver(device_t dev, driver_t *driver)
1605 {
1606         if (dev->state >= DS_ATTACHED)
1607                 return(EBUSY);
1608
1609         if (dev->driver == driver)
1610                 return(0);
1611
1612         if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
1613                 kfree(dev->softc, M_BUS);
1614                 dev->softc = NULL;
1615         }
1616         kobj_delete((kobj_t) dev, 0);
1617         dev->driver = driver;
1618         if (driver) {
1619                 kobj_init((kobj_t) dev, (kobj_class_t) driver);
1620                 if (!(dev->flags & DF_EXTERNALSOFTC)) {
1621                         dev->softc = kmalloc(driver->size, M_BUS,
1622                                             M_INTWAIT | M_ZERO);
1623                         if (!dev->softc) {
1624                                 kobj_delete((kobj_t)dev, 0);
1625                                 kobj_init((kobj_t) dev, &null_class);
1626                                 dev->driver = NULL;
1627                                 return(ENOMEM);
1628                         }
1629                 }
1630         } else {
1631                 kobj_init((kobj_t) dev, &null_class);
1632         }
1633
1634         bus_data_generation_update();
1635         return(0);
1636 }
1637
1638 int
1639 device_probe_and_attach(device_t dev)
1640 {
1641         device_t bus = dev->parent;
1642         int error = 0;
1643
1644         if (dev->state >= DS_ALIVE)
1645                 return(0);
1646
1647         if ((dev->flags & DF_ENABLED) == 0) {
1648                 if (bootverbose) {
1649                         device_print_prettyname(dev);
1650                         kprintf("not probed (disabled)\n");
1651                 }
1652                 return(0);
1653         }
1654
1655         error = device_probe_child(bus, dev);
1656         if (error) {
1657                 if (!(dev->flags & DF_DONENOMATCH)) {
1658                         BUS_PROBE_NOMATCH(bus, dev);
1659                         devnomatch(dev);
1660                         dev->flags |= DF_DONENOMATCH;
1661                 }
1662                 return(error);
1663         }
1664
1665         /*
1666          * Output the exact device chain prior to the attach in case the  
1667          * system locks up during attach, and generate the full info after
1668          * the attach so correct irq and other information is displayed.
1669          */
1670         if (bootverbose && !device_is_quiet(dev)) {
1671                 device_t tmp;
1672
1673                 kprintf("%s", device_get_nameunit(dev));
1674                 for (tmp = dev->parent; tmp; tmp = tmp->parent)
1675                         kprintf(".%s", device_get_nameunit(tmp));
1676                 kprintf("\n");
1677         }
1678         if (!device_is_quiet(dev))
1679                 device_print_child(bus, dev);
1680         if ((dev->flags & DF_ASYNCPROBE) && do_async_attach) {
1681                 kprintf("%s: probing asynchronously\n",
1682                         device_get_nameunit(dev));
1683                 dev->state = DS_INPROGRESS;
1684                 device_attach_async(dev);
1685                 error = 0;
1686         } else {
1687                 error = device_doattach(dev);
1688         }
1689         return(error);
1690 }
1691
1692 /*
1693  * Device is known to be alive, do the attach asynchronously.
1694  *
1695  * The MP lock is held by all threads.
1696  */
1697 static void
1698 device_attach_async(device_t dev)
1699 {
1700         thread_t td;
1701
1702         atomic_add_int(&numasyncthreads, 1);
1703         lwkt_create(device_attach_thread, dev, &td, NULL,
1704                     0, 0, (dev->desc ? dev->desc : "devattach"));
1705 }
1706
1707 static void
1708 device_attach_thread(void *arg)
1709 {
1710         device_t dev = arg;
1711
1712         (void)device_doattach(dev);
1713         atomic_subtract_int(&numasyncthreads, 1);
1714         wakeup(&numasyncthreads);
1715 }
1716
1717 /*
1718  * Device is known to be alive, do the attach (synchronous or asynchronous)
1719  */
1720 static int
1721 device_doattach(device_t dev)
1722 {
1723         device_t bus = dev->parent;
1724         int hasclass = (dev->devclass != 0);
1725         int error;
1726
1727         error = DEVICE_ATTACH(dev);
1728         if (error == 0) {
1729                 dev->state = DS_ATTACHED;
1730                 if (bootverbose && !device_is_quiet(dev))
1731                         device_print_child(bus, dev);
1732                 devadded(dev);
1733         } else {
1734                 kprintf("device_probe_and_attach: %s%d attach returned %d\n",
1735                        dev->driver->name, dev->unit, error);
1736                 /* Unset the class that was set in device_probe_child */
1737                 if (!hasclass)
1738                         device_set_devclass(dev, 0);
1739                 device_set_driver(dev, NULL);
1740                 dev->state = DS_NOTPRESENT;
1741         }
1742         return(error);
1743 }
1744
1745 int
1746 device_detach(device_t dev)
1747 {
1748         int error;
1749
1750         PDEBUG(("%s", DEVICENAME(dev)));
1751         if (dev->state == DS_BUSY)
1752                 return(EBUSY);
1753         if (dev->state != DS_ATTACHED)
1754                 return(0);
1755
1756         if ((error = DEVICE_DETACH(dev)) != 0)
1757                 return(error);
1758         devremoved(dev);
1759         device_printf(dev, "detached\n");
1760         if (dev->parent)
1761                 BUS_CHILD_DETACHED(dev->parent, dev);
1762
1763         if (!(dev->flags & DF_FIXEDCLASS))
1764                 devclass_delete_device(dev->devclass, dev);
1765
1766         dev->state = DS_NOTPRESENT;
1767         device_set_driver(dev, NULL);
1768
1769         return(0);
1770 }
1771
1772 int
1773 device_shutdown(device_t dev)
1774 {
1775         if (dev->state < DS_ATTACHED)
1776                 return 0;
1777         PDEBUG(("%s", DEVICENAME(dev)));
1778         return DEVICE_SHUTDOWN(dev);
1779 }
1780
1781 int
1782 device_set_unit(device_t dev, int unit)
1783 {
1784         devclass_t dc;
1785         int err;
1786
1787         dc = device_get_devclass(dev);
1788         if (unit < dc->maxunit && dc->devices[unit])
1789                 return(EBUSY);
1790         err = devclass_delete_device(dc, dev);
1791         if (err)
1792                 return(err);
1793         dev->unit = unit;
1794         err = devclass_add_device(dc, dev);
1795         if (err)
1796                 return(err);
1797
1798         bus_data_generation_update();
1799         return(0);
1800 }
1801
1802 /*======================================*/
1803 /*
1804  * Access functions for device resources.
1805  */
1806
1807 /* Supplied by config(8) in ioconf.c */
1808 extern struct config_device config_devtab[];
1809 extern int devtab_count;
1810
1811 /* Runtime version */
1812 struct config_device *devtab = config_devtab;
1813
1814 static int
1815 resource_new_name(const char *name, int unit)
1816 {
1817         struct config_device *new;
1818
1819         new = kmalloc((devtab_count + 1) * sizeof(*new), M_TEMP,
1820                      M_INTWAIT | M_ZERO);
1821         if (new == NULL)
1822                 return(-1);
1823         if (devtab && devtab_count > 0)
1824                 bcopy(devtab, new, devtab_count * sizeof(*new));
1825         new[devtab_count].name = kmalloc(strlen(name) + 1, M_TEMP, M_INTWAIT);
1826         if (new[devtab_count].name == NULL) {
1827                 kfree(new, M_TEMP);
1828                 return(-1);
1829         }
1830         strcpy(new[devtab_count].name, name);
1831         new[devtab_count].unit = unit;
1832         new[devtab_count].resource_count = 0;
1833         new[devtab_count].resources = NULL;
1834         if (devtab && devtab != config_devtab)
1835                 kfree(devtab, M_TEMP);
1836         devtab = new;
1837         return devtab_count++;
1838 }
1839
1840 static int
1841 resource_new_resname(int j, const char *resname, resource_type type)
1842 {
1843         struct config_resource *new;
1844         int i;
1845
1846         i = devtab[j].resource_count;
1847         new = kmalloc((i + 1) * sizeof(*new), M_TEMP, M_INTWAIT | M_ZERO);
1848         if (new == NULL)
1849                 return(-1);
1850         if (devtab[j].resources && i > 0)
1851                 bcopy(devtab[j].resources, new, i * sizeof(*new));
1852         new[i].name = kmalloc(strlen(resname) + 1, M_TEMP, M_INTWAIT);
1853         if (new[i].name == NULL) {
1854                 kfree(new, M_TEMP);
1855                 return(-1);
1856         }
1857         strcpy(new[i].name, resname);
1858         new[i].type = type;
1859         if (devtab[j].resources)
1860                 kfree(devtab[j].resources, M_TEMP);
1861         devtab[j].resources = new;
1862         devtab[j].resource_count = i + 1;
1863         return(i);
1864 }
1865
1866 static int
1867 resource_match_string(int i, const char *resname, const char *value)
1868 {
1869         int j;
1870         struct config_resource *res;
1871
1872         for (j = 0, res = devtab[i].resources;
1873              j < devtab[i].resource_count; j++, res++)
1874                 if (!strcmp(res->name, resname)
1875                     && res->type == RES_STRING
1876                     && !strcmp(res->u.stringval, value))
1877                         return(j);
1878         return(-1);
1879 }
1880
1881 static int
1882 resource_find(const char *name, int unit, const char *resname, 
1883               struct config_resource **result)
1884 {
1885         int i, j;
1886         struct config_resource *res;
1887
1888         /*
1889          * First check specific instances, then generic.
1890          */
1891         for (i = 0; i < devtab_count; i++) {
1892                 if (devtab[i].unit < 0)
1893                         continue;
1894                 if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1895                         res = devtab[i].resources;
1896                         for (j = 0; j < devtab[i].resource_count; j++, res++)
1897                                 if (!strcmp(res->name, resname)) {
1898                                         *result = res;
1899                                         return(0);
1900                                 }
1901                 }
1902         }
1903         for (i = 0; i < devtab_count; i++) {
1904                 if (devtab[i].unit >= 0)
1905                         continue;
1906                 /* XXX should this `&& devtab[i].unit == unit' be here? */
1907                 /* XXX if so, then the generic match does nothing */
1908                 if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1909                         res = devtab[i].resources;
1910                         for (j = 0; j < devtab[i].resource_count; j++, res++)
1911                                 if (!strcmp(res->name, resname)) {
1912                                         *result = res;
1913                                         return(0);
1914                                 }
1915                 }
1916         }
1917         return(ENOENT);
1918 }
1919
1920 int
1921 resource_int_value(const char *name, int unit, const char *resname, int *result)
1922 {
1923         int error;
1924         struct config_resource *res;
1925
1926         if ((error = resource_find(name, unit, resname, &res)) != 0)
1927                 return(error);
1928         if (res->type != RES_INT)
1929                 return(EFTYPE);
1930         *result = res->u.intval;
1931         return(0);
1932 }
1933
1934 int
1935 resource_long_value(const char *name, int unit, const char *resname,
1936                     long *result)
1937 {
1938         int error;
1939         struct config_resource *res;
1940
1941         if ((error = resource_find(name, unit, resname, &res)) != 0)
1942                 return(error);
1943         if (res->type != RES_LONG)
1944                 return(EFTYPE);
1945         *result = res->u.longval;
1946         return(0);
1947 }
1948
1949 int
1950 resource_string_value(const char *name, int unit, const char *resname,
1951                       char **result)
1952 {
1953         int error;
1954         struct config_resource *res;
1955
1956         if ((error = resource_find(name, unit, resname, &res)) != 0)
1957                 return(error);
1958         if (res->type != RES_STRING)
1959                 return(EFTYPE);
1960         *result = res->u.stringval;
1961         return(0);
1962 }
1963
1964 int
1965 resource_query_string(int i, const char *resname, const char *value)
1966 {
1967         if (i < 0)
1968                 i = 0;
1969         else
1970                 i = i + 1;
1971         for (; i < devtab_count; i++)
1972                 if (resource_match_string(i, resname, value) >= 0)
1973                         return(i);
1974         return(-1);
1975 }
1976
1977 int
1978 resource_locate(int i, const char *resname)
1979 {
1980         if (i < 0)
1981                 i = 0;
1982         else
1983                 i = i + 1;
1984         for (; i < devtab_count; i++)
1985                 if (!strcmp(devtab[i].name, resname))
1986                         return(i);
1987         return(-1);
1988 }
1989
1990 int
1991 resource_count(void)
1992 {
1993         return(devtab_count);
1994 }
1995
1996 char *
1997 resource_query_name(int i)
1998 {
1999         return(devtab[i].name);
2000 }
2001
2002 int
2003 resource_query_unit(int i)
2004 {
2005         return(devtab[i].unit);
2006 }
2007
2008 static int
2009 resource_create(const char *name, int unit, const char *resname,
2010                 resource_type type, struct config_resource **result)
2011 {
2012         int i, j;
2013         struct config_resource *res = NULL;
2014
2015         for (i = 0; i < devtab_count; i++)
2016                 if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
2017                         res = devtab[i].resources;
2018                         break;
2019                 }
2020         if (res == NULL) {
2021                 i = resource_new_name(name, unit);
2022                 if (i < 0)
2023                         return(ENOMEM);
2024                 res = devtab[i].resources;
2025         }
2026         for (j = 0; j < devtab[i].resource_count; j++, res++)
2027                 if (!strcmp(res->name, resname)) {
2028                         *result = res;
2029                         return(0);
2030                 }
2031         j = resource_new_resname(i, resname, type);
2032         if (j < 0)
2033                 return(ENOMEM);
2034         res = &devtab[i].resources[j];
2035         *result = res;
2036         return(0);
2037 }
2038
2039 int
2040 resource_set_int(const char *name, int unit, const char *resname, int value)
2041 {
2042         int error;
2043         struct config_resource *res;
2044
2045         error = resource_create(name, unit, resname, RES_INT, &res);
2046         if (error)
2047                 return(error);
2048         if (res->type != RES_INT)
2049                 return(EFTYPE);
2050         res->u.intval = value;
2051         return(0);
2052 }
2053
2054 int
2055 resource_set_long(const char *name, int unit, const char *resname, long value)
2056 {
2057         int error;
2058         struct config_resource *res;
2059
2060         error = resource_create(name, unit, resname, RES_LONG, &res);
2061         if (error)
2062                 return(error);
2063         if (res->type != RES_LONG)
2064                 return(EFTYPE);
2065         res->u.longval = value;
2066         return(0);
2067 }
2068
2069 int
2070 resource_set_string(const char *name, int unit, const char *resname,
2071                     const char *value)
2072 {
2073         int error;
2074         struct config_resource *res;
2075
2076         error = resource_create(name, unit, resname, RES_STRING, &res);
2077         if (error)
2078                 return(error);
2079         if (res->type != RES_STRING)
2080                 return(EFTYPE);
2081         if (res->u.stringval)
2082                 kfree(res->u.stringval, M_TEMP);
2083         res->u.stringval = kmalloc(strlen(value) + 1, M_TEMP, M_INTWAIT);
2084         if (res->u.stringval == NULL)
2085                 return(ENOMEM);
2086         strcpy(res->u.stringval, value);
2087         return(0);
2088 }
2089
2090 static void
2091 resource_cfgload(void *dummy __unused)
2092 {
2093         struct config_resource *res, *cfgres;
2094         int i, j;
2095         int error;
2096         char *name, *resname;
2097         int unit;
2098         resource_type type;
2099         char *stringval;
2100         int config_devtab_count;
2101
2102         config_devtab_count = devtab_count;
2103         devtab = NULL;
2104         devtab_count = 0;
2105
2106         for (i = 0; i < config_devtab_count; i++) {
2107                 name = config_devtab[i].name;
2108                 unit = config_devtab[i].unit;
2109
2110                 for (j = 0; j < config_devtab[i].resource_count; j++) {
2111                         cfgres = config_devtab[i].resources;
2112                         resname = cfgres[j].name;
2113                         type = cfgres[j].type;
2114                         error = resource_create(name, unit, resname, type,
2115                                                 &res);
2116                         if (error) {
2117                                 kprintf("create resource %s%d: error %d\n",
2118                                         name, unit, error);
2119                                 continue;
2120                         }
2121                         if (res->type != type) {
2122                                 kprintf("type mismatch %s%d: %d != %d\n",
2123                                         name, unit, res->type, type);
2124                                 continue;
2125                         }
2126                         switch (type) {
2127                         case RES_INT:
2128                                 res->u.intval = cfgres[j].u.intval;
2129                                 break;
2130                         case RES_LONG:
2131                                 res->u.longval = cfgres[j].u.longval;
2132                                 break;
2133                         case RES_STRING:
2134                                 if (res->u.stringval)
2135                                         kfree(res->u.stringval, M_TEMP);
2136                                 stringval = cfgres[j].u.stringval;
2137                                 res->u.stringval = kmalloc(strlen(stringval) + 1,
2138                                                           M_TEMP, M_INTWAIT);
2139                                 if (res->u.stringval == NULL)
2140                                         break;
2141                                 strcpy(res->u.stringval, stringval);
2142                                 break;
2143                         default:
2144                                 panic("unknown resource type %d", type);
2145                         }
2146                 }
2147         }
2148 }
2149 SYSINIT(cfgload, SI_BOOT1_POST, SI_ORDER_ANY + 50, resource_cfgload, 0)
2150
2151
2152 /*======================================*/
2153 /*
2154  * Some useful method implementations to make life easier for bus drivers.
2155  */
2156
2157 void
2158 resource_list_init(struct resource_list *rl)
2159 {
2160         SLIST_INIT(rl);
2161 }
2162
2163 void
2164 resource_list_free(struct resource_list *rl)
2165 {
2166         struct resource_list_entry *rle;
2167
2168         while ((rle = SLIST_FIRST(rl)) != NULL) {
2169                 if (rle->res)
2170                         panic("resource_list_free: resource entry is busy");
2171                 SLIST_REMOVE_HEAD(rl, link);
2172                 kfree(rle, M_BUS);
2173         }
2174 }
2175
2176 void
2177 resource_list_add(struct resource_list *rl,
2178                   int type, int rid,
2179                   u_long start, u_long end, u_long count)
2180 {
2181         struct resource_list_entry *rle;
2182
2183         rle = resource_list_find(rl, type, rid);
2184         if (rle == NULL) {
2185                 rle = kmalloc(sizeof(struct resource_list_entry), M_BUS,
2186                              M_INTWAIT);
2187                 if (!rle)
2188                         panic("resource_list_add: can't record entry");
2189                 SLIST_INSERT_HEAD(rl, rle, link);
2190                 rle->type = type;
2191                 rle->rid = rid;
2192                 rle->res = NULL;
2193         }
2194
2195         if (rle->res)
2196                 panic("resource_list_add: resource entry is busy");
2197
2198         rle->start = start;
2199         rle->end = end;
2200         rle->count = count;
2201 }
2202
2203 struct resource_list_entry*
2204 resource_list_find(struct resource_list *rl,
2205                    int type, int rid)
2206 {
2207         struct resource_list_entry *rle;
2208
2209         SLIST_FOREACH(rle, rl, link)
2210                 if (rle->type == type && rle->rid == rid)
2211                         return(rle);
2212         return(NULL);
2213 }
2214
2215 void
2216 resource_list_delete(struct resource_list *rl,
2217                      int type, int rid)
2218 {
2219         struct resource_list_entry *rle = resource_list_find(rl, type, rid);
2220
2221         if (rle) {
2222                 if (rle->res != NULL)
2223                         panic("resource_list_delete: resource has not been released");
2224                 SLIST_REMOVE(rl, rle, resource_list_entry, link);
2225                 kfree(rle, M_BUS);
2226         }
2227 }
2228
2229 struct resource *
2230 resource_list_alloc(struct resource_list *rl,
2231                     device_t bus, device_t child,
2232                     int type, int *rid,
2233                     u_long start, u_long end,
2234                     u_long count, u_int flags)
2235 {
2236         struct resource_list_entry *rle = 0;
2237         int passthrough = (device_get_parent(child) != bus);
2238         int isdefault = (start == 0UL && end == ~0UL);
2239
2240         if (passthrough) {
2241                 return(BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2242                                           type, rid,
2243                                           start, end, count, flags));
2244         }
2245
2246         rle = resource_list_find(rl, type, *rid);
2247
2248         if (!rle)
2249                 return(0);              /* no resource of that type/rid */
2250
2251         if (rle->res)
2252                 panic("resource_list_alloc: resource entry is busy");
2253
2254         if (isdefault) {
2255                 start = rle->start;
2256                 count = max(count, rle->count);
2257                 end = max(rle->end, start + count - 1);
2258         }
2259
2260         rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2261                                       type, rid, start, end, count, flags);
2262
2263         /*
2264          * Record the new range.
2265          */
2266         if (rle->res) {
2267                 rle->start = rman_get_start(rle->res);
2268                 rle->end = rman_get_end(rle->res);
2269                 rle->count = count;
2270         }
2271
2272         return(rle->res);
2273 }
2274
2275 int
2276 resource_list_release(struct resource_list *rl,
2277                       device_t bus, device_t child,
2278                       int type, int rid, struct resource *res)
2279 {
2280         struct resource_list_entry *rle = 0;
2281         int passthrough = (device_get_parent(child) != bus);
2282         int error;
2283
2284         if (passthrough) {
2285                 return(BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2286                                             type, rid, res));
2287         }
2288
2289         rle = resource_list_find(rl, type, rid);
2290
2291         if (!rle)
2292                 panic("resource_list_release: can't find resource");
2293         if (!rle->res)
2294                 panic("resource_list_release: resource entry is not busy");
2295
2296         error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2297                                      type, rid, res);
2298         if (error)
2299                 return(error);
2300
2301         rle->res = NULL;
2302         return(0);
2303 }
2304
2305 int
2306 resource_list_print_type(struct resource_list *rl, const char *name, int type,
2307                          const char *format)
2308 {
2309         struct resource_list_entry *rle;
2310         int printed, retval;
2311
2312         printed = 0;
2313         retval = 0;
2314         /* Yes, this is kinda cheating */
2315         SLIST_FOREACH(rle, rl, link) {
2316                 if (rle->type == type) {
2317                         if (printed == 0)
2318                                 retval += kprintf(" %s ", name);
2319                         else
2320                                 retval += kprintf(",");
2321                         printed++;
2322                         retval += kprintf(format, rle->start);
2323                         if (rle->count > 1) {
2324                                 retval += kprintf("-");
2325                                 retval += kprintf(format, rle->start +
2326                                                  rle->count - 1);
2327                         }
2328                 }
2329         }
2330         return(retval);
2331 }
2332
2333 /*
2334  * Generic driver/device identify functions.  These will install a device
2335  * rendezvous point under the parent using the same name as the driver
2336  * name, which will at a later time be probed and attached.
2337  *
2338  * These functions are used when the parent does not 'scan' its bus for
2339  * matching devices, or for the particular devices using these functions,
2340  * or when the device is a pseudo or synthesized device (such as can be
2341  * found under firewire and ppbus).
2342  */
2343 int
2344 bus_generic_identify(driver_t *driver, device_t parent)
2345 {
2346         if (parent->state == DS_ATTACHED)
2347                 return (0);
2348         BUS_ADD_CHILD(parent, parent, 0, driver->name, -1);
2349         return (0);
2350 }
2351
2352 int
2353 bus_generic_identify_sameunit(driver_t *driver, device_t parent)
2354 {
2355         if (parent->state == DS_ATTACHED)
2356                 return (0);
2357         BUS_ADD_CHILD(parent, parent, 0, driver->name, device_get_unit(parent));
2358         return (0);
2359 }
2360
2361 /*
2362  * Call DEVICE_IDENTIFY for each driver.
2363  */
2364 int
2365 bus_generic_probe(device_t dev)
2366 {
2367         devclass_t dc = dev->devclass;
2368         driverlink_t dl;
2369
2370         TAILQ_FOREACH(dl, &dc->drivers, link) {
2371                 DEVICE_IDENTIFY(dl->driver, dev);
2372         }
2373
2374         return(0);
2375 }
2376
2377 /*
2378  * This is an aweful hack due to the isa bus and autoconf code not
2379  * probing the ISA devices until after everything else has configured.
2380  * The ISA bus did a dummy attach long ago so we have to set it back
2381  * to an earlier state so the probe thinks its the initial probe and
2382  * not a bus rescan.
2383  *
2384  * XXX remove by properly defering the ISA bus scan.
2385  */
2386 int
2387 bus_generic_probe_hack(device_t dev)
2388 {
2389         if (dev->state == DS_ATTACHED) {
2390                 dev->state = DS_ALIVE;
2391                 bus_generic_probe(dev);
2392                 dev->state = DS_ATTACHED;
2393         }
2394         return (0);
2395 }
2396
2397 int
2398 bus_generic_attach(device_t dev)
2399 {
2400         device_t child;
2401
2402         TAILQ_FOREACH(child, &dev->children, link) {
2403                 device_probe_and_attach(child);
2404         }
2405
2406         return(0);
2407 }
2408
2409 int
2410 bus_generic_detach(device_t dev)
2411 {
2412         device_t child;
2413         int error;
2414
2415         if (dev->state != DS_ATTACHED)
2416                 return(EBUSY);
2417
2418         TAILQ_FOREACH(child, &dev->children, link)
2419                 if ((error = device_detach(child)) != 0)
2420                         return(error);
2421
2422         return 0;
2423 }
2424
2425 int
2426 bus_generic_shutdown(device_t dev)
2427 {
2428         device_t child;
2429
2430         TAILQ_FOREACH(child, &dev->children, link)
2431                 device_shutdown(child);
2432
2433         return(0);
2434 }
2435
2436 int
2437 bus_generic_suspend(device_t dev)
2438 {
2439         int error;
2440         device_t child, child2;
2441
2442         TAILQ_FOREACH(child, &dev->children, link) {
2443                 error = DEVICE_SUSPEND(child);
2444                 if (error) {
2445                         for (child2 = TAILQ_FIRST(&dev->children);
2446                              child2 && child2 != child; 
2447                              child2 = TAILQ_NEXT(child2, link))
2448                                 DEVICE_RESUME(child2);
2449                         return(error);
2450                 }
2451         }
2452         return(0);
2453 }
2454
2455 int
2456 bus_generic_resume(device_t dev)
2457 {
2458         device_t child;
2459
2460         TAILQ_FOREACH(child, &dev->children, link)
2461                 DEVICE_RESUME(child);
2462                 /* if resume fails, there's nothing we can usefully do... */
2463
2464         return(0);
2465 }
2466
2467 int
2468 bus_print_child_header(device_t dev, device_t child)
2469 {
2470         int retval = 0;
2471
2472         if (device_get_desc(child))
2473                 retval += device_printf(child, "<%s>", device_get_desc(child));
2474         else
2475                 retval += kprintf("%s", device_get_nameunit(child));
2476         if (bootverbose) {
2477                 if (child->state != DS_ATTACHED)
2478                         kprintf(" [tentative]");
2479                 else
2480                         kprintf(" [attached!]");
2481         }
2482         return(retval);
2483 }
2484
2485 int
2486 bus_print_child_footer(device_t dev, device_t child)
2487 {
2488         return(kprintf(" on %s\n", device_get_nameunit(dev)));
2489 }
2490
2491 device_t
2492 bus_generic_add_child(device_t dev, device_t child, int order,
2493                       const char *name, int unit)
2494 {
2495         if (dev->parent)
2496                 dev = BUS_ADD_CHILD(dev->parent, child, order, name, unit);
2497         else
2498                 dev = device_add_child_ordered(child, order, name, unit);
2499         return(dev);
2500                 
2501 }
2502
2503 int
2504 bus_generic_print_child(device_t dev, device_t child)
2505 {
2506         int retval = 0;
2507
2508         retval += bus_print_child_header(dev, child);
2509         retval += bus_print_child_footer(dev, child);
2510
2511         return(retval);
2512 }
2513
2514 int
2515 bus_generic_read_ivar(device_t dev, device_t child, int index, 
2516                       uintptr_t * result)
2517 {
2518         int error;
2519
2520         if (dev->parent)
2521                 error = BUS_READ_IVAR(dev->parent, child, index, result);
2522         else
2523                 error = ENOENT;
2524         return (error);
2525 }
2526
2527 int
2528 bus_generic_write_ivar(device_t dev, device_t child, int index, 
2529                        uintptr_t value)
2530 {
2531         int error;
2532
2533         if (dev->parent)
2534                 error = BUS_WRITE_IVAR(dev->parent, child, index, value);
2535         else
2536                 error = ENOENT;
2537         return (error);
2538 }
2539
2540 /*
2541  * Resource list are used for iterations, do not recurse.
2542  */
2543 struct resource_list *
2544 bus_generic_get_resource_list(device_t dev, device_t child)
2545 {
2546         return (NULL);
2547 }
2548
2549 void
2550 bus_generic_driver_added(device_t dev, driver_t *driver)
2551 {
2552         device_t child;
2553
2554         DEVICE_IDENTIFY(driver, dev);
2555         TAILQ_FOREACH(child, &dev->children, link) {
2556                 if (child->state == DS_NOTPRESENT)
2557                         device_probe_and_attach(child);
2558         }
2559 }
2560
2561 int
2562 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq, 
2563                        int flags, driver_intr_t *intr, void *arg,
2564                        void **cookiep, lwkt_serialize_t serializer)
2565 {
2566         /* Propagate up the bus hierarchy until someone handles it. */
2567         if (dev->parent)
2568                 return(BUS_SETUP_INTR(dev->parent, child, irq, flags,
2569                                       intr, arg, cookiep, serializer));
2570         else
2571                 return(EINVAL);
2572 }
2573
2574 int
2575 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
2576                           void *cookie)
2577 {
2578         /* Propagate up the bus hierarchy until someone handles it. */
2579         if (dev->parent)
2580                 return(BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
2581         else
2582                 return(EINVAL);
2583 }
2584
2585 int
2586 bus_generic_disable_intr(device_t dev, device_t child, void *cookie)
2587 {
2588         if (dev->parent)
2589                 return(BUS_DISABLE_INTR(dev->parent, child, cookie));
2590         else
2591                 return(0);
2592 }
2593
2594 void
2595 bus_generic_enable_intr(device_t dev, device_t child, void *cookie)
2596 {
2597         if (dev->parent)
2598                 BUS_ENABLE_INTR(dev->parent, child, cookie);
2599 }
2600
2601 int
2602 bus_generic_config_intr(device_t dev, device_t child, int irq, enum intr_trigger trig,
2603     enum intr_polarity pol)
2604 {
2605         /* Propagate up the bus hierarchy until someone handles it. */
2606         if (dev->parent)
2607                 return(BUS_CONFIG_INTR(dev->parent, child, irq, trig, pol));
2608         else
2609                 return(EINVAL);
2610 }
2611
2612 struct resource *
2613 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
2614                            u_long start, u_long end, u_long count, u_int flags)
2615 {
2616         /* Propagate up the bus hierarchy until someone handles it. */
2617         if (dev->parent)
2618                 return(BUS_ALLOC_RESOURCE(dev->parent, child, type, rid, 
2619                                            start, end, count, flags));
2620         else
2621                 return(NULL);
2622 }
2623
2624 int
2625 bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
2626                              struct resource *r)
2627 {
2628         /* Propagate up the bus hierarchy until someone handles it. */
2629         if (dev->parent)
2630                 return(BUS_RELEASE_RESOURCE(dev->parent, child, type, rid, r));
2631         else
2632                 return(EINVAL);
2633 }
2634
2635 int
2636 bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
2637                               struct resource *r)
2638 {
2639         /* Propagate up the bus hierarchy until someone handles it. */
2640         if (dev->parent)
2641                 return(BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid, r));
2642         else
2643                 return(EINVAL);
2644 }
2645
2646 int
2647 bus_generic_deactivate_resource(device_t dev, device_t child, int type,
2648                                 int rid, struct resource *r)
2649 {
2650         /* Propagate up the bus hierarchy until someone handles it. */
2651         if (dev->parent)
2652                 return(BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
2653                                                r));
2654         else
2655                 return(EINVAL);
2656 }
2657
2658 int
2659 bus_generic_get_resource(device_t dev, device_t child, int type, int rid,
2660                          u_long *startp, u_long *countp)
2661 {
2662         int error;
2663
2664         error = ENOENT;
2665         if (dev->parent) {
2666                 error = BUS_GET_RESOURCE(dev->parent, child, type, rid, 
2667                                          startp, countp);
2668         }
2669         return (error);
2670 }
2671
2672 int
2673 bus_generic_set_resource(device_t dev, device_t child, int type, int rid,
2674                         u_long start, u_long count)
2675 {
2676         int error;
2677
2678         error = EINVAL;
2679         if (dev->parent) {
2680                 error = BUS_SET_RESOURCE(dev->parent, child, type, rid, 
2681                                          start, count);
2682         }
2683         return (error);
2684 }
2685
2686 void
2687 bus_generic_delete_resource(device_t dev, device_t child, int type, int rid)
2688 {
2689         if (dev->parent)
2690                 BUS_DELETE_RESOURCE(dev, child, type, rid);
2691 }
2692
2693 int
2694 bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
2695     u_long *startp, u_long *countp)
2696 {
2697         struct resource_list *rl = NULL;
2698         struct resource_list_entry *rle = NULL;
2699
2700         rl = BUS_GET_RESOURCE_LIST(dev, child);
2701         if (!rl)
2702                 return(EINVAL);
2703
2704         rle = resource_list_find(rl, type, rid);
2705         if (!rle)
2706                 return(ENOENT);
2707
2708         if (startp)
2709                 *startp = rle->start;
2710         if (countp)
2711                 *countp = rle->count;
2712
2713         return(0);
2714 }
2715
2716 int
2717 bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
2718     u_long start, u_long count)
2719 {
2720         struct resource_list *rl = NULL;
2721
2722         rl = BUS_GET_RESOURCE_LIST(dev, child);
2723         if (!rl)
2724                 return(EINVAL);
2725
2726         resource_list_add(rl, type, rid, start, (start + count - 1), count);
2727
2728         return(0);
2729 }
2730
2731 void
2732 bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
2733 {
2734         struct resource_list *rl = NULL;
2735
2736         rl = BUS_GET_RESOURCE_LIST(dev, child);
2737         if (!rl)
2738                 return;
2739
2740         resource_list_delete(rl, type, rid);
2741 }
2742
2743 int
2744 bus_generic_rl_release_resource(device_t dev, device_t child, int type,
2745     int rid, struct resource *r)
2746 {
2747         struct resource_list *rl = NULL;
2748
2749         rl = BUS_GET_RESOURCE_LIST(dev, child);
2750         if (!rl)
2751                 return(EINVAL);
2752
2753         return(resource_list_release(rl, dev, child, type, rid, r));
2754 }
2755
2756 struct resource *
2757 bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
2758     int *rid, u_long start, u_long end, u_long count, u_int flags)
2759 {
2760         struct resource_list *rl = NULL;
2761
2762         rl = BUS_GET_RESOURCE_LIST(dev, child);
2763         if (!rl)
2764                 return(NULL);
2765
2766         return(resource_list_alloc(rl, dev, child, type, rid,
2767             start, end, count, flags));
2768 }
2769
2770 int
2771 bus_generic_child_present(device_t bus, device_t child)
2772 {
2773         return(BUS_CHILD_PRESENT(device_get_parent(bus), bus));
2774 }
2775
2776
2777 /*
2778  * Some convenience functions to make it easier for drivers to use the
2779  * resource-management functions.  All these really do is hide the
2780  * indirection through the parent's method table, making for slightly
2781  * less-wordy code.  In the future, it might make sense for this code
2782  * to maintain some sort of a list of resources allocated by each device.
2783  */
2784 int
2785 bus_alloc_resources(device_t dev, struct resource_spec *rs,
2786     struct resource **res)
2787 {
2788         int i;
2789
2790         for (i = 0; rs[i].type != -1; i++)
2791                 res[i] = NULL;
2792         for (i = 0; rs[i].type != -1; i++) {
2793                 res[i] = bus_alloc_resource_any(dev,
2794                     rs[i].type, &rs[i].rid, rs[i].flags);
2795                 if (res[i] == NULL) {
2796                         bus_release_resources(dev, rs, res);
2797                         return (ENXIO);
2798                 }
2799         }
2800         return (0);
2801 }
2802
2803 void
2804 bus_release_resources(device_t dev, const struct resource_spec *rs,
2805     struct resource **res)
2806 {
2807         int i;
2808
2809         for (i = 0; rs[i].type != -1; i++)
2810                 if (res[i] != NULL) {
2811                         bus_release_resource(
2812                             dev, rs[i].type, rs[i].rid, res[i]);
2813                         res[i] = NULL;
2814                 }
2815 }
2816
2817 struct resource *
2818 bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
2819                    u_long count, u_int flags)
2820 {
2821         if (dev->parent == 0)
2822                 return(0);
2823         return(BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
2824                                   count, flags));
2825 }
2826
2827 int
2828 bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
2829 {
2830         if (dev->parent == 0)
2831                 return(EINVAL);
2832         return(BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2833 }
2834
2835 int
2836 bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
2837 {
2838         if (dev->parent == 0)
2839                 return(EINVAL);
2840         return(BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2841 }
2842
2843 int
2844 bus_release_resource(device_t dev, int type, int rid, struct resource *r)
2845 {
2846         if (dev->parent == 0)
2847                 return(EINVAL);
2848         return(BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
2849 }
2850
2851 int
2852 bus_setup_intr(device_t dev, struct resource *r, int flags,
2853                driver_intr_t handler, void *arg,
2854                void **cookiep, lwkt_serialize_t serializer)
2855 {
2856         if (dev->parent == 0)
2857                 return(EINVAL);
2858         return(BUS_SETUP_INTR(dev->parent, dev, r, flags, handler, arg,
2859                               cookiep, serializer));
2860 }
2861
2862 int
2863 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
2864 {
2865         if (dev->parent == 0)
2866                 return(EINVAL);
2867         return(BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
2868 }
2869
2870 void
2871 bus_enable_intr(device_t dev, void *cookie)
2872 {
2873         if (dev->parent)
2874                 BUS_ENABLE_INTR(dev->parent, dev, cookie);
2875 }
2876
2877 int
2878 bus_disable_intr(device_t dev, void *cookie)
2879 {
2880         if (dev->parent)
2881                 return(BUS_DISABLE_INTR(dev->parent, dev, cookie));
2882         else
2883                 return(0);
2884 }
2885
2886 int
2887 bus_set_resource(device_t dev, int type, int rid,
2888                  u_long start, u_long count)
2889 {
2890         return(BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
2891                                 start, count));
2892 }
2893
2894 int
2895 bus_get_resource(device_t dev, int type, int rid,
2896                  u_long *startp, u_long *countp)
2897 {
2898         return(BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2899                                 startp, countp));
2900 }
2901
2902 u_long
2903 bus_get_resource_start(device_t dev, int type, int rid)
2904 {
2905         u_long start, count;
2906         int error;
2907
2908         error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2909                                  &start, &count);
2910         if (error)
2911                 return(0);
2912         return(start);
2913 }
2914
2915 u_long
2916 bus_get_resource_count(device_t dev, int type, int rid)
2917 {
2918         u_long start, count;
2919         int error;
2920
2921         error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2922                                  &start, &count);
2923         if (error)
2924                 return(0);
2925         return(count);
2926 }
2927
2928 void
2929 bus_delete_resource(device_t dev, int type, int rid)
2930 {
2931         BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
2932 }
2933
2934 int
2935 bus_child_present(device_t child)
2936 {
2937         return (BUS_CHILD_PRESENT(device_get_parent(child), child));
2938 }
2939
2940 int
2941 bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
2942 {
2943         device_t parent;
2944
2945         parent = device_get_parent(child);
2946         if (parent == NULL) {
2947                 *buf = '\0';
2948                 return (0);
2949         }
2950         return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
2951 }
2952
2953 int
2954 bus_child_location_str(device_t child, char *buf, size_t buflen)
2955 {
2956         device_t parent;
2957
2958         parent = device_get_parent(child);
2959         if (parent == NULL) {
2960                 *buf = '\0';
2961                 return (0);
2962         }
2963         return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
2964 }
2965
2966 static int
2967 root_print_child(device_t dev, device_t child)
2968 {
2969         return(0);
2970 }
2971
2972 static int
2973 root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
2974                 void **cookiep, lwkt_serialize_t serializer)
2975 {
2976         /*
2977          * If an interrupt mapping gets to here something bad has happened.
2978          */
2979         panic("root_setup_intr");
2980 }
2981
2982 /*
2983  * If we get here, assume that the device is permanant and really is
2984  * present in the system.  Removable bus drivers are expected to intercept
2985  * this call long before it gets here.  We return -1 so that drivers that
2986  * really care can check vs -1 or some ERRNO returned higher in the food
2987  * chain.
2988  */
2989 static int
2990 root_child_present(device_t dev, device_t child)
2991 {
2992         return(-1);
2993 }
2994
2995 /*
2996  * XXX NOTE! other defaults may be set in bus_if.m
2997  */
2998 static kobj_method_t root_methods[] = {
2999         /* Device interface */
3000         KOBJMETHOD(device_shutdown,     bus_generic_shutdown),
3001         KOBJMETHOD(device_suspend,      bus_generic_suspend),
3002         KOBJMETHOD(device_resume,       bus_generic_resume),
3003
3004         /* Bus interface */
3005         KOBJMETHOD(bus_add_child,       bus_generic_add_child),
3006         KOBJMETHOD(bus_print_child,     root_print_child),
3007         KOBJMETHOD(bus_read_ivar,       bus_generic_read_ivar),
3008         KOBJMETHOD(bus_write_ivar,      bus_generic_write_ivar),
3009         KOBJMETHOD(bus_setup_intr,      root_setup_intr),
3010         KOBJMETHOD(bus_child_present,   root_child_present),
3011
3012         { 0, 0 }
3013 };
3014
3015 static driver_t root_driver = {
3016         "root",
3017         root_methods,
3018         1,                      /* no softc */
3019 };
3020
3021 device_t        root_bus;
3022 devclass_t      root_devclass;
3023
3024 static int
3025 root_bus_module_handler(module_t mod, int what, void* arg)
3026 {
3027         switch (what) {
3028         case MOD_LOAD:
3029                 TAILQ_INIT(&bus_data_devices);
3030                 root_bus = make_device(NULL, "root", 0);
3031                 root_bus->desc = "System root bus";
3032                 kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
3033                 root_bus->driver = &root_driver;
3034                 root_bus->state = DS_ALIVE;
3035                 root_devclass = devclass_find_internal("root", NULL, FALSE);
3036                 devinit();
3037                 return(0);
3038
3039         case MOD_SHUTDOWN:
3040                 device_shutdown(root_bus);
3041                 return(0);
3042         default:
3043                 return(0);
3044         }
3045 }
3046
3047 static moduledata_t root_bus_mod = {
3048         "rootbus",
3049         root_bus_module_handler,
3050         0
3051 };
3052 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
3053
3054 void
3055 root_bus_configure(void)
3056 {
3057         int warncount;
3058         device_t dev;
3059
3060         PDEBUG(("."));
3061
3062         /*
3063          * handle device_identify based device attachments to the root_bus
3064          * (typically nexus).
3065          */
3066         bus_generic_probe(root_bus);
3067
3068         /*
3069          * Probe and attach the devices under root_bus.
3070          */
3071         TAILQ_FOREACH(dev, &root_bus->children, link) {
3072                 device_probe_and_attach(dev);
3073         }
3074
3075         /*
3076          * Wait for all asynchronous attaches to complete.  If we don't
3077          * our legacy ISA bus scan could steal device unit numbers or
3078          * even I/O ports.
3079          */
3080         warncount = 10;
3081         if (numasyncthreads)
3082                 kprintf("Waiting for async drivers to attach\n");
3083         while (numasyncthreads > 0) {
3084                 if (tsleep(&numasyncthreads, 0, "rootbus", hz) == EWOULDBLOCK)
3085                         --warncount;
3086                 if (warncount == 0) {
3087                         kprintf("Warning: Still waiting for %d "
3088                                 "drivers to attach\n", numasyncthreads);
3089                 } else if (warncount == -30) {
3090                         kprintf("Giving up on %d drivers\n", numasyncthreads);
3091                         break;
3092                 }
3093         }
3094         root_bus->state = DS_ATTACHED;
3095 }
3096
3097 int
3098 driver_module_handler(module_t mod, int what, void *arg)
3099 {
3100         int error;
3101         struct driver_module_data *dmd;
3102         devclass_t bus_devclass;
3103         kobj_class_t driver;
3104         const char *parentname;
3105
3106         dmd = (struct driver_module_data *)arg;
3107         bus_devclass = devclass_find_internal(dmd->dmd_busname, NULL, TRUE);
3108         error = 0;
3109
3110         switch (what) {
3111         case MOD_LOAD:
3112                 if (dmd->dmd_chainevh)
3113                         error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3114
3115                 driver = dmd->dmd_driver;
3116                 PDEBUG(("Loading module: driver %s on bus %s",
3117                         DRIVERNAME(driver), dmd->dmd_busname));
3118
3119                 /*
3120                  * If the driver has any base classes, make the
3121                  * devclass inherit from the devclass of the driver's
3122                  * first base class. This will allow the system to
3123                  * search for drivers in both devclasses for children
3124                  * of a device using this driver.
3125                  */
3126                 if (driver->baseclasses)
3127                         parentname = driver->baseclasses[0]->name;
3128                 else
3129                         parentname = NULL;
3130                 *dmd->dmd_devclass = devclass_find_internal(driver->name,
3131                                                             parentname, TRUE);
3132
3133                 error = devclass_add_driver(bus_devclass, driver);
3134                 if (error)
3135                         break;
3136                 break;
3137
3138         case MOD_UNLOAD:
3139                 PDEBUG(("Unloading module: driver %s from bus %s",
3140                         DRIVERNAME(dmd->dmd_driver), dmd->dmd_busname));
3141                 error = devclass_delete_driver(bus_devclass, dmd->dmd_driver);
3142
3143                 if (!error && dmd->dmd_chainevh)
3144                         error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3145                 break;
3146         }
3147
3148         return (error);
3149 }
3150
3151 #ifdef BUS_DEBUG
3152
3153 /*
3154  * The _short versions avoid iteration by not calling anything that prints
3155  * more than oneliners. I love oneliners.
3156  */
3157
3158 static void
3159 print_device_short(device_t dev, int indent)
3160 {
3161         if (!dev)
3162                 return;
3163
3164         indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
3165                       dev->unit, dev->desc,
3166                       (dev->parent? "":"no "),
3167                       (TAILQ_EMPTY(&dev->children)? "no ":""),
3168                       (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
3169                       (dev->flags&DF_FIXEDCLASS? "fixed,":""),
3170                       (dev->flags&DF_WILDCARD? "wildcard,":""),
3171                       (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
3172                       (dev->ivars? "":"no "),
3173                       (dev->softc? "":"no "),
3174                       dev->busy));
3175 }
3176
3177 static void
3178 print_device(device_t dev, int indent)
3179 {
3180         if (!dev)
3181                 return;
3182
3183         print_device_short(dev, indent);
3184
3185         indentprintf(("Parent:\n"));
3186         print_device_short(dev->parent, indent+1);
3187         indentprintf(("Driver:\n"));
3188         print_driver_short(dev->driver, indent+1);
3189         indentprintf(("Devclass:\n"));
3190         print_devclass_short(dev->devclass, indent+1);
3191 }
3192
3193 /*
3194  * Print the device and all its children (indented).
3195  */
3196 void
3197 print_device_tree_short(device_t dev, int indent)
3198 {
3199         device_t child;
3200
3201         if (!dev)
3202                 return;
3203
3204         print_device_short(dev, indent);
3205
3206         TAILQ_FOREACH(child, &dev->children, link)
3207                 print_device_tree_short(child, indent+1);
3208 }
3209
3210 /*
3211  * Print the device and all its children (indented).
3212  */
3213 void
3214 print_device_tree(device_t dev, int indent)
3215 {
3216         device_t child;
3217
3218         if (!dev)
3219                 return;
3220
3221         print_device(dev, indent);
3222
3223         TAILQ_FOREACH(child, &dev->children, link)
3224                 print_device_tree(child, indent+1);
3225 }
3226
3227 static void
3228 print_driver_short(driver_t *driver, int indent)
3229 {
3230         if (!driver)
3231                 return;
3232
3233         indentprintf(("driver %s: softc size = %zu\n",
3234                       driver->name, driver->size));
3235 }
3236
3237 static void
3238 print_driver(driver_t *driver, int indent)
3239 {
3240         if (!driver)
3241                 return;
3242
3243         print_driver_short(driver, indent);
3244 }
3245
3246
3247 static void
3248 print_driver_list(driver_list_t drivers, int indent)
3249 {
3250         driverlink_t driver;
3251
3252         TAILQ_FOREACH(driver, &drivers, link)
3253                 print_driver(driver->driver, indent);
3254 }
3255
3256 static void
3257 print_devclass_short(devclass_t dc, int indent)
3258 {
3259         if (!dc)
3260                 return;
3261
3262         indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
3263 }
3264
3265 static void
3266 print_devclass(devclass_t dc, int indent)
3267 {
3268         int i;
3269
3270         if (!dc)
3271                 return;
3272
3273         print_devclass_short(dc, indent);
3274         indentprintf(("Drivers:\n"));
3275         print_driver_list(dc->drivers, indent+1);
3276
3277         indentprintf(("Devices:\n"));
3278         for (i = 0; i < dc->maxunit; i++)
3279                 if (dc->devices[i])
3280                         print_device(dc->devices[i], indent+1);
3281 }
3282
3283 void
3284 print_devclass_list_short(void)
3285 {
3286         devclass_t dc;
3287
3288         kprintf("Short listing of devclasses, drivers & devices:\n");
3289         TAILQ_FOREACH(dc, &devclasses, link) {
3290                 print_devclass_short(dc, 0);
3291         }
3292 }
3293
3294 void
3295 print_devclass_list(void)
3296 {
3297         devclass_t dc;
3298
3299         kprintf("Full listing of devclasses, drivers & devices:\n");
3300         TAILQ_FOREACH(dc, &devclasses, link) {
3301                 print_devclass(dc, 0);
3302         }
3303 }
3304
3305 #endif
3306
3307 /*
3308  * Check to see if a device is disabled via a disabled hint.
3309  */
3310 int
3311 resource_disabled(const char *name, int unit)
3312 {
3313         int error, value;
3314
3315         error = resource_int_value(name, unit, "disabled", &value);
3316         if (error)
3317                return(0);
3318         return(value);
3319 }
3320
3321 /*
3322  * User-space access to the device tree.
3323  *
3324  * We implement a small set of nodes:
3325  *
3326  * hw.bus                       Single integer read method to obtain the
3327  *                              current generation count.
3328  * hw.bus.devices               Reads the entire device tree in flat space.
3329  * hw.bus.rman                  Resource manager interface
3330  *
3331  * We might like to add the ability to scan devclasses and/or drivers to
3332  * determine what else is currently loaded/available.
3333  */
3334
3335 static int
3336 sysctl_bus(SYSCTL_HANDLER_ARGS)
3337 {
3338         struct u_businfo        ubus;
3339
3340         ubus.ub_version = BUS_USER_VERSION;
3341         ubus.ub_generation = bus_data_generation;
3342
3343         return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
3344 }
3345 SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
3346     "bus-related data");
3347
3348 static int
3349 sysctl_devices(SYSCTL_HANDLER_ARGS)
3350 {
3351         int                     *name = (int *)arg1;
3352         u_int                   namelen = arg2;
3353         int                     index;
3354         struct device           *dev;
3355         struct u_device         udev;   /* XXX this is a bit big */
3356         int                     error;
3357
3358         if (namelen != 2)
3359                 return (EINVAL);
3360
3361         if (bus_data_generation_check(name[0]))
3362                 return (EINVAL);
3363
3364         index = name[1];
3365
3366         /*
3367          * Scan the list of devices, looking for the requested index.
3368          */
3369         TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
3370                 if (index-- == 0)
3371                         break;
3372         }
3373         if (dev == NULL)
3374                 return (ENOENT);
3375
3376         /*
3377          * Populate the return array.
3378          */
3379         bzero(&udev, sizeof(udev));
3380         udev.dv_handle = (uintptr_t)dev;
3381         udev.dv_parent = (uintptr_t)dev->parent;
3382         if (dev->nameunit != NULL)
3383                 strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
3384         if (dev->desc != NULL)
3385                 strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
3386         if (dev->driver != NULL && dev->driver->name != NULL)
3387                 strlcpy(udev.dv_drivername, dev->driver->name,
3388                     sizeof(udev.dv_drivername));
3389         bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
3390         bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
3391         udev.dv_devflags = dev->devflags;
3392         udev.dv_flags = dev->flags;
3393         udev.dv_state = dev->state;
3394         error = SYSCTL_OUT(req, &udev, sizeof(udev));
3395         return (error);
3396 }
3397
3398 SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
3399     "system device tree");
3400
3401 int
3402 bus_data_generation_check(int generation)
3403 {
3404         if (generation != bus_data_generation)
3405                 return (1);
3406
3407         /* XXX generate optimised lists here? */
3408         return (0);
3409 }
3410
3411 void
3412 bus_data_generation_update(void)
3413 {
3414         bus_data_generation++;
3415 }