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