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