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