subr_autoconf.c revision 1.186 1 /* $NetBSD: subr_autoconf.c,v 1.186 2009/10/12 23:33:02 yamt Exp $ */
2
3 /*
4 * Copyright (c) 1996, 2000 Christopher G. Demetriou
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed for the
18 * NetBSD Project. See http://www.NetBSD.org/ for
19 * information about NetBSD.
20 * 4. The name of the author may not be used to endorse or promote products
21 * derived from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 *
34 * --(license Id: LICENSE.proto,v 1.1 2000/06/13 21:40:26 cgd Exp )--
35 */
36
37 /*
38 * Copyright (c) 1992, 1993
39 * The Regents of the University of California. All rights reserved.
40 *
41 * This software was developed by the Computer Systems Engineering group
42 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
43 * contributed to Berkeley.
44 *
45 * All advertising materials mentioning features or use of this software
46 * must display the following acknowledgement:
47 * This product includes software developed by the University of
48 * California, Lawrence Berkeley Laboratories.
49 *
50 * Redistribution and use in source and binary forms, with or without
51 * modification, are permitted provided that the following conditions
52 * are met:
53 * 1. Redistributions of source code must retain the above copyright
54 * notice, this list of conditions and the following disclaimer.
55 * 2. Redistributions in binary form must reproduce the above copyright
56 * notice, this list of conditions and the following disclaimer in the
57 * documentation and/or other materials provided with the distribution.
58 * 3. Neither the name of the University nor the names of its contributors
59 * may be used to endorse or promote products derived from this software
60 * without specific prior written permission.
61 *
62 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
63 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
65 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
66 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
67 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
68 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
69 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
70 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
71 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72 * SUCH DAMAGE.
73 *
74 * from: Header: subr_autoconf.c,v 1.12 93/02/01 19:31:48 torek Exp (LBL)
75 *
76 * @(#)subr_autoconf.c 8.3 (Berkeley) 5/17/94
77 */
78
79 #include <sys/cdefs.h>
80 __KERNEL_RCSID(0, "$NetBSD: subr_autoconf.c,v 1.186 2009/10/12 23:33:02 yamt Exp $");
81
82 #ifdef _KERNEL_OPT
83 #include "opt_ddb.h"
84 #endif
85
86 #include <sys/param.h>
87 #include <sys/device.h>
88 #include <sys/disklabel.h>
89 #include <sys/conf.h>
90 #include <sys/kauth.h>
91 #include <sys/malloc.h>
92 #include <sys/kmem.h>
93 #include <sys/systm.h>
94 #include <sys/kernel.h>
95 #include <sys/errno.h>
96 #include <sys/proc.h>
97 #include <sys/reboot.h>
98 #include <sys/kthread.h>
99 #include <sys/buf.h>
100 #include <sys/dirent.h>
101 #include <sys/vnode.h>
102 #include <sys/mount.h>
103 #include <sys/namei.h>
104 #include <sys/unistd.h>
105 #include <sys/fcntl.h>
106 #include <sys/lockf.h>
107 #include <sys/callout.h>
108 #include <sys/devmon.h>
109 #include <sys/cpu.h>
110 #include <sys/sysctl.h>
111
112 #include <sys/disk.h>
113
114 #include <machine/limits.h>
115
116 #if defined(__i386__) && defined(_KERNEL_OPT)
117 #include "opt_splash.h"
118 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
119 #include <dev/splash/splash.h>
120 extern struct splash_progress *splash_progress_state;
121 #endif
122 #endif
123
124 /*
125 * Autoconfiguration subroutines.
126 */
127
128 /*
129 * ioconf.c exports exactly two names: cfdata and cfroots. All system
130 * devices and drivers are found via these tables.
131 */
132 extern struct cfdata cfdata[];
133 extern const short cfroots[];
134
135 /*
136 * List of all cfdriver structures. We use this to detect duplicates
137 * when other cfdrivers are loaded.
138 */
139 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
140 extern struct cfdriver * const cfdriver_list_initial[];
141
142 /*
143 * Initial list of cfattach's.
144 */
145 extern const struct cfattachinit cfattachinit[];
146
147 /*
148 * List of cfdata tables. We always have one such list -- the one
149 * built statically when the kernel was configured.
150 */
151 struct cftablelist allcftables = TAILQ_HEAD_INITIALIZER(allcftables);
152 static struct cftable initcftable;
153
154 #define ROOT ((device_t)NULL)
155
156 struct matchinfo {
157 cfsubmatch_t fn;
158 struct device *parent;
159 const int *locs;
160 void *aux;
161 struct cfdata *match;
162 int pri;
163 };
164
165 static char *number(char *, int);
166 static void mapply(struct matchinfo *, cfdata_t);
167 static device_t config_devalloc(const device_t, const cfdata_t, const int *);
168 static void config_devdealloc(device_t);
169 static void config_makeroom(int, struct cfdriver *);
170 static void config_devlink(device_t);
171 static void config_devunlink(device_t);
172
173 static void pmflock_debug(device_t, const char *, int);
174
175 static device_t deviter_next1(deviter_t *);
176 static void deviter_reinit(deviter_t *);
177
178 struct deferred_config {
179 TAILQ_ENTRY(deferred_config) dc_queue;
180 device_t dc_dev;
181 void (*dc_func)(device_t);
182 };
183
184 TAILQ_HEAD(deferred_config_head, deferred_config);
185
186 struct deferred_config_head deferred_config_queue =
187 TAILQ_HEAD_INITIALIZER(deferred_config_queue);
188 struct deferred_config_head interrupt_config_queue =
189 TAILQ_HEAD_INITIALIZER(interrupt_config_queue);
190 int interrupt_config_threads = 8;
191
192 static void config_process_deferred(struct deferred_config_head *, device_t);
193
194 /* Hooks to finalize configuration once all real devices have been found. */
195 struct finalize_hook {
196 TAILQ_ENTRY(finalize_hook) f_list;
197 int (*f_func)(device_t);
198 device_t f_dev;
199 };
200 static TAILQ_HEAD(, finalize_hook) config_finalize_list =
201 TAILQ_HEAD_INITIALIZER(config_finalize_list);
202 static int config_finalize_done;
203
204 /* list of all devices */
205 struct devicelist alldevs = TAILQ_HEAD_INITIALIZER(alldevs);
206 kcondvar_t alldevs_cv;
207 kmutex_t alldevs_mtx;
208 static int alldevs_nread = 0;
209 static int alldevs_nwrite = 0;
210 static lwp_t *alldevs_writer = NULL;
211
212 static int config_pending; /* semaphore for mountroot */
213 static kmutex_t config_misc_lock;
214 static kcondvar_t config_misc_cv;
215
216 static int detachall = 0;
217
218 #define STREQ(s1, s2) \
219 (*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
220
221 static bool config_initialized = false; /* config_init() has been called. */
222
223 static int config_do_twiddle;
224 static callout_t config_twiddle_ch;
225
226 static void sysctl_detach_setup(struct sysctllog **);
227
228 /*
229 * Initialize the autoconfiguration data structures. Normally this
230 * is done by configure(), but some platforms need to do this very
231 * early (to e.g. initialize the console).
232 */
233 void
234 config_init(void)
235 {
236 const struct cfattachinit *cfai;
237 int i, j;
238
239 KASSERT(config_initialized == false);
240
241 mutex_init(&alldevs_mtx, MUTEX_DEFAULT, IPL_NONE);
242 cv_init(&alldevs_cv, "alldevs");
243
244 mutex_init(&config_misc_lock, MUTEX_DEFAULT, IPL_NONE);
245 cv_init(&config_misc_cv, "cfgmisc");
246
247 callout_init(&config_twiddle_ch, CALLOUT_MPSAFE);
248
249 /* allcfdrivers is statically initialized. */
250 for (i = 0; cfdriver_list_initial[i] != NULL; i++) {
251 if (config_cfdriver_attach(cfdriver_list_initial[i]) != 0)
252 panic("configure: duplicate `%s' drivers",
253 cfdriver_list_initial[i]->cd_name);
254 }
255
256 for (cfai = &cfattachinit[0]; cfai->cfai_name != NULL; cfai++) {
257 for (j = 0; cfai->cfai_list[j] != NULL; j++) {
258 if (config_cfattach_attach(cfai->cfai_name,
259 cfai->cfai_list[j]) != 0)
260 panic("configure: duplicate `%s' attachment "
261 "of `%s' driver",
262 cfai->cfai_list[j]->ca_name,
263 cfai->cfai_name);
264 }
265 }
266
267 initcftable.ct_cfdata = cfdata;
268 TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
269
270 config_initialized = true;
271 }
272
273 void
274 config_init_mi(void)
275 {
276
277 if (!config_initialized)
278 config_init();
279
280 sysctl_detach_setup(NULL);
281 }
282
283 void
284 config_deferred(device_t dev)
285 {
286 config_process_deferred(&deferred_config_queue, dev);
287 config_process_deferred(&interrupt_config_queue, dev);
288 }
289
290 static void
291 config_interrupts_thread(void *cookie)
292 {
293 struct deferred_config *dc;
294
295 while ((dc = TAILQ_FIRST(&interrupt_config_queue)) != NULL) {
296 TAILQ_REMOVE(&interrupt_config_queue, dc, dc_queue);
297 (*dc->dc_func)(dc->dc_dev);
298 kmem_free(dc, sizeof(*dc));
299 config_pending_decr();
300 }
301 kthread_exit(0);
302 }
303
304 void
305 config_create_interruptthreads()
306 {
307 int i;
308
309 for (i = 0; i < interrupt_config_threads; i++) {
310 (void)kthread_create(PRI_NONE, 0, NULL,
311 config_interrupts_thread, NULL, NULL, "config");
312 }
313 }
314
315 /*
316 * Announce device attach/detach to userland listeners.
317 */
318 static void
319 devmon_report_device(device_t dev, bool isattach)
320 {
321 #if NDRVCTL > 0
322 prop_dictionary_t ev;
323 const char *parent;
324 const char *what;
325 device_t pdev = device_parent(dev);
326
327 ev = prop_dictionary_create();
328 if (ev == NULL)
329 return;
330
331 what = (isattach ? "device-attach" : "device-detach");
332 parent = (pdev == NULL ? "root" : device_xname(pdev));
333 if (!prop_dictionary_set_cstring(ev, "device", device_xname(dev)) ||
334 !prop_dictionary_set_cstring(ev, "parent", parent)) {
335 prop_object_release(ev);
336 return;
337 }
338
339 devmon_insert(what, ev);
340 #endif
341 }
342
343 /*
344 * Add a cfdriver to the system.
345 */
346 int
347 config_cfdriver_attach(struct cfdriver *cd)
348 {
349 struct cfdriver *lcd;
350
351 /* Make sure this driver isn't already in the system. */
352 LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
353 if (STREQ(lcd->cd_name, cd->cd_name))
354 return EEXIST;
355 }
356
357 LIST_INIT(&cd->cd_attach);
358 LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
359
360 return 0;
361 }
362
363 /*
364 * Remove a cfdriver from the system.
365 */
366 int
367 config_cfdriver_detach(struct cfdriver *cd)
368 {
369 int i;
370
371 /* Make sure there are no active instances. */
372 for (i = 0; i < cd->cd_ndevs; i++) {
373 if (cd->cd_devs[i] != NULL)
374 return EBUSY;
375 }
376
377 /* ...and no attachments loaded. */
378 if (LIST_EMPTY(&cd->cd_attach) == 0)
379 return EBUSY;
380
381 LIST_REMOVE(cd, cd_list);
382
383 KASSERT(cd->cd_devs == NULL);
384
385 return 0;
386 }
387
388 /*
389 * Look up a cfdriver by name.
390 */
391 struct cfdriver *
392 config_cfdriver_lookup(const char *name)
393 {
394 struct cfdriver *cd;
395
396 LIST_FOREACH(cd, &allcfdrivers, cd_list) {
397 if (STREQ(cd->cd_name, name))
398 return cd;
399 }
400
401 return NULL;
402 }
403
404 /*
405 * Add a cfattach to the specified driver.
406 */
407 int
408 config_cfattach_attach(const char *driver, struct cfattach *ca)
409 {
410 struct cfattach *lca;
411 struct cfdriver *cd;
412
413 cd = config_cfdriver_lookup(driver);
414 if (cd == NULL)
415 return ESRCH;
416
417 /* Make sure this attachment isn't already on this driver. */
418 LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
419 if (STREQ(lca->ca_name, ca->ca_name))
420 return EEXIST;
421 }
422
423 LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
424
425 return 0;
426 }
427
428 /*
429 * Remove a cfattach from the specified driver.
430 */
431 int
432 config_cfattach_detach(const char *driver, struct cfattach *ca)
433 {
434 struct cfdriver *cd;
435 device_t dev;
436 int i;
437
438 cd = config_cfdriver_lookup(driver);
439 if (cd == NULL)
440 return ESRCH;
441
442 /* Make sure there are no active instances. */
443 for (i = 0; i < cd->cd_ndevs; i++) {
444 if ((dev = cd->cd_devs[i]) == NULL)
445 continue;
446 if (dev->dv_cfattach == ca)
447 return EBUSY;
448 }
449
450 LIST_REMOVE(ca, ca_list);
451
452 return 0;
453 }
454
455 /*
456 * Look up a cfattach by name.
457 */
458 static struct cfattach *
459 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
460 {
461 struct cfattach *ca;
462
463 LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
464 if (STREQ(ca->ca_name, atname))
465 return ca;
466 }
467
468 return NULL;
469 }
470
471 /*
472 * Look up a cfattach by driver/attachment name.
473 */
474 struct cfattach *
475 config_cfattach_lookup(const char *name, const char *atname)
476 {
477 struct cfdriver *cd;
478
479 cd = config_cfdriver_lookup(name);
480 if (cd == NULL)
481 return NULL;
482
483 return config_cfattach_lookup_cd(cd, atname);
484 }
485
486 /*
487 * Apply the matching function and choose the best. This is used
488 * a few times and we want to keep the code small.
489 */
490 static void
491 mapply(struct matchinfo *m, cfdata_t cf)
492 {
493 int pri;
494
495 if (m->fn != NULL) {
496 pri = (*m->fn)(m->parent, cf, m->locs, m->aux);
497 } else {
498 pri = config_match(m->parent, cf, m->aux);
499 }
500 if (pri > m->pri) {
501 m->match = cf;
502 m->pri = pri;
503 }
504 }
505
506 int
507 config_stdsubmatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
508 {
509 const struct cfiattrdata *ci;
510 const struct cflocdesc *cl;
511 int nlocs, i;
512
513 ci = cfiattr_lookup(cf->cf_pspec->cfp_iattr, parent->dv_cfdriver);
514 KASSERT(ci);
515 nlocs = ci->ci_loclen;
516 KASSERT(!nlocs || locs);
517 for (i = 0; i < nlocs; i++) {
518 cl = &ci->ci_locdesc[i];
519 /* !cld_defaultstr means no default value */
520 if ((!(cl->cld_defaultstr)
521 || (cf->cf_loc[i] != cl->cld_default))
522 && cf->cf_loc[i] != locs[i])
523 return 0;
524 }
525
526 return config_match(parent, cf, aux);
527 }
528
529 /*
530 * Helper function: check whether the driver supports the interface attribute
531 * and return its descriptor structure.
532 */
533 static const struct cfiattrdata *
534 cfdriver_get_iattr(const struct cfdriver *cd, const char *ia)
535 {
536 const struct cfiattrdata * const *cpp;
537
538 if (cd->cd_attrs == NULL)
539 return 0;
540
541 for (cpp = cd->cd_attrs; *cpp; cpp++) {
542 if (STREQ((*cpp)->ci_name, ia)) {
543 /* Match. */
544 return *cpp;
545 }
546 }
547 return 0;
548 }
549
550 /*
551 * Lookup an interface attribute description by name.
552 * If the driver is given, consider only its supported attributes.
553 */
554 const struct cfiattrdata *
555 cfiattr_lookup(const char *name, const struct cfdriver *cd)
556 {
557 const struct cfdriver *d;
558 const struct cfiattrdata *ia;
559
560 if (cd)
561 return cfdriver_get_iattr(cd, name);
562
563 LIST_FOREACH(d, &allcfdrivers, cd_list) {
564 ia = cfdriver_get_iattr(d, name);
565 if (ia)
566 return ia;
567 }
568 return 0;
569 }
570
571 /*
572 * Determine if `parent' is a potential parent for a device spec based
573 * on `cfp'.
574 */
575 static int
576 cfparent_match(const device_t parent, const struct cfparent *cfp)
577 {
578 struct cfdriver *pcd;
579
580 /* We don't match root nodes here. */
581 if (cfp == NULL)
582 return 0;
583
584 pcd = parent->dv_cfdriver;
585 KASSERT(pcd != NULL);
586
587 /*
588 * First, ensure this parent has the correct interface
589 * attribute.
590 */
591 if (!cfdriver_get_iattr(pcd, cfp->cfp_iattr))
592 return 0;
593
594 /*
595 * If no specific parent device instance was specified (i.e.
596 * we're attaching to the attribute only), we're done!
597 */
598 if (cfp->cfp_parent == NULL)
599 return 1;
600
601 /*
602 * Check the parent device's name.
603 */
604 if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
605 return 0; /* not the same parent */
606
607 /*
608 * Make sure the unit number matches.
609 */
610 if (cfp->cfp_unit == DVUNIT_ANY || /* wildcard */
611 cfp->cfp_unit == parent->dv_unit)
612 return 1;
613
614 /* Unit numbers don't match. */
615 return 0;
616 }
617
618 /*
619 * Helper for config_cfdata_attach(): check all devices whether it could be
620 * parent any attachment in the config data table passed, and rescan.
621 */
622 static void
623 rescan_with_cfdata(const struct cfdata *cf)
624 {
625 device_t d;
626 const struct cfdata *cf1;
627 deviter_t di;
628
629
630 /*
631 * "alldevs" is likely longer than a modules's cfdata, so make it
632 * the outer loop.
633 */
634 for (d = deviter_first(&di, 0); d != NULL; d = deviter_next(&di)) {
635
636 if (!(d->dv_cfattach->ca_rescan))
637 continue;
638
639 for (cf1 = cf; cf1->cf_name; cf1++) {
640
641 if (!cfparent_match(d, cf1->cf_pspec))
642 continue;
643
644 (*d->dv_cfattach->ca_rescan)(d,
645 cf1->cf_pspec->cfp_iattr, cf1->cf_loc);
646 }
647 }
648 deviter_release(&di);
649 }
650
651 /*
652 * Attach a supplemental config data table and rescan potential
653 * parent devices if required.
654 */
655 int
656 config_cfdata_attach(cfdata_t cf, int scannow)
657 {
658 struct cftable *ct;
659
660 ct = kmem_alloc(sizeof(*ct), KM_SLEEP);
661 ct->ct_cfdata = cf;
662 TAILQ_INSERT_TAIL(&allcftables, ct, ct_list);
663
664 if (scannow)
665 rescan_with_cfdata(cf);
666
667 return 0;
668 }
669
670 /*
671 * Helper for config_cfdata_detach: check whether a device is
672 * found through any attachment in the config data table.
673 */
674 static int
675 dev_in_cfdata(const struct device *d, const struct cfdata *cf)
676 {
677 const struct cfdata *cf1;
678
679 for (cf1 = cf; cf1->cf_name; cf1++)
680 if (d->dv_cfdata == cf1)
681 return 1;
682
683 return 0;
684 }
685
686 /*
687 * Detach a supplemental config data table. Detach all devices found
688 * through that table (and thus keeping references to it) before.
689 */
690 int
691 config_cfdata_detach(cfdata_t cf)
692 {
693 device_t d;
694 int error = 0;
695 struct cftable *ct;
696 deviter_t di;
697
698 for (d = deviter_first(&di, DEVITER_F_RW); d != NULL;
699 d = deviter_next(&di)) {
700 if (!dev_in_cfdata(d, cf))
701 continue;
702 if ((error = config_detach(d, 0)) != 0)
703 break;
704 }
705 deviter_release(&di);
706 if (error) {
707 aprint_error_dev(d, "unable to detach instance\n");
708 return error;
709 }
710
711 TAILQ_FOREACH(ct, &allcftables, ct_list) {
712 if (ct->ct_cfdata == cf) {
713 TAILQ_REMOVE(&allcftables, ct, ct_list);
714 kmem_free(ct, sizeof(*ct));
715 return 0;
716 }
717 }
718
719 /* not found -- shouldn't happen */
720 return EINVAL;
721 }
722
723 /*
724 * Invoke the "match" routine for a cfdata entry on behalf of
725 * an external caller, usually a "submatch" routine.
726 */
727 int
728 config_match(device_t parent, cfdata_t cf, void *aux)
729 {
730 struct cfattach *ca;
731
732 ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
733 if (ca == NULL) {
734 /* No attachment for this entry, oh well. */
735 return 0;
736 }
737
738 return (*ca->ca_match)(parent, cf, aux);
739 }
740
741 /*
742 * Iterate over all potential children of some device, calling the given
743 * function (default being the child's match function) for each one.
744 * Nonzero returns are matches; the highest value returned is considered
745 * the best match. Return the `found child' if we got a match, or NULL
746 * otherwise. The `aux' pointer is simply passed on through.
747 *
748 * Note that this function is designed so that it can be used to apply
749 * an arbitrary function to all potential children (its return value
750 * can be ignored).
751 */
752 cfdata_t
753 config_search_loc(cfsubmatch_t fn, device_t parent,
754 const char *ifattr, const int *locs, void *aux)
755 {
756 struct cftable *ct;
757 cfdata_t cf;
758 struct matchinfo m;
759
760 KASSERT(config_initialized);
761 KASSERT(!ifattr || cfdriver_get_iattr(parent->dv_cfdriver, ifattr));
762
763 m.fn = fn;
764 m.parent = parent;
765 m.locs = locs;
766 m.aux = aux;
767 m.match = NULL;
768 m.pri = 0;
769
770 TAILQ_FOREACH(ct, &allcftables, ct_list) {
771 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
772
773 /* We don't match root nodes here. */
774 if (!cf->cf_pspec)
775 continue;
776
777 /*
778 * Skip cf if no longer eligible, otherwise scan
779 * through parents for one matching `parent', and
780 * try match function.
781 */
782 if (cf->cf_fstate == FSTATE_FOUND)
783 continue;
784 if (cf->cf_fstate == FSTATE_DNOTFOUND ||
785 cf->cf_fstate == FSTATE_DSTAR)
786 continue;
787
788 /*
789 * If an interface attribute was specified,
790 * consider only children which attach to
791 * that attribute.
792 */
793 if (ifattr && !STREQ(ifattr, cf->cf_pspec->cfp_iattr))
794 continue;
795
796 if (cfparent_match(parent, cf->cf_pspec))
797 mapply(&m, cf);
798 }
799 }
800 return m.match;
801 }
802
803 cfdata_t
804 config_search_ia(cfsubmatch_t fn, device_t parent, const char *ifattr,
805 void *aux)
806 {
807
808 return config_search_loc(fn, parent, ifattr, NULL, aux);
809 }
810
811 /*
812 * Find the given root device.
813 * This is much like config_search, but there is no parent.
814 * Don't bother with multiple cfdata tables; the root node
815 * must always be in the initial table.
816 */
817 cfdata_t
818 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
819 {
820 cfdata_t cf;
821 const short *p;
822 struct matchinfo m;
823
824 m.fn = fn;
825 m.parent = ROOT;
826 m.aux = aux;
827 m.match = NULL;
828 m.pri = 0;
829 m.locs = 0;
830 /*
831 * Look at root entries for matching name. We do not bother
832 * with found-state here since only one root should ever be
833 * searched (and it must be done first).
834 */
835 for (p = cfroots; *p >= 0; p++) {
836 cf = &cfdata[*p];
837 if (strcmp(cf->cf_name, rootname) == 0)
838 mapply(&m, cf);
839 }
840 return m.match;
841 }
842
843 static const char * const msgs[3] = { "", " not configured\n", " unsupported\n" };
844
845 /*
846 * The given `aux' argument describes a device that has been found
847 * on the given parent, but not necessarily configured. Locate the
848 * configuration data for that device (using the submatch function
849 * provided, or using candidates' cd_match configuration driver
850 * functions) and attach it, and return true. If the device was
851 * not configured, call the given `print' function and return 0.
852 */
853 device_t
854 config_found_sm_loc(device_t parent,
855 const char *ifattr, const int *locs, void *aux,
856 cfprint_t print, cfsubmatch_t submatch)
857 {
858 cfdata_t cf;
859
860 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
861 if (splash_progress_state)
862 splash_progress_update(splash_progress_state);
863 #endif
864
865 if ((cf = config_search_loc(submatch, parent, ifattr, locs, aux)))
866 return(config_attach_loc(parent, cf, locs, aux, print));
867 if (print) {
868 if (config_do_twiddle && cold)
869 twiddle();
870 aprint_normal("%s", msgs[(*print)(aux, device_xname(parent))]);
871 }
872
873 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
874 if (splash_progress_state)
875 splash_progress_update(splash_progress_state);
876 #endif
877
878 return NULL;
879 }
880
881 device_t
882 config_found_ia(device_t parent, const char *ifattr, void *aux,
883 cfprint_t print)
884 {
885
886 return config_found_sm_loc(parent, ifattr, NULL, aux, print, NULL);
887 }
888
889 device_t
890 config_found(device_t parent, void *aux, cfprint_t print)
891 {
892
893 return config_found_sm_loc(parent, NULL, NULL, aux, print, NULL);
894 }
895
896 /*
897 * As above, but for root devices.
898 */
899 device_t
900 config_rootfound(const char *rootname, void *aux)
901 {
902 cfdata_t cf;
903
904 if ((cf = config_rootsearch((cfsubmatch_t)NULL, rootname, aux)) != NULL)
905 return config_attach(ROOT, cf, aux, (cfprint_t)NULL);
906 aprint_error("root device %s not configured\n", rootname);
907 return NULL;
908 }
909
910 /* just like sprintf(buf, "%d") except that it works from the end */
911 static char *
912 number(char *ep, int n)
913 {
914
915 *--ep = 0;
916 while (n >= 10) {
917 *--ep = (n % 10) + '0';
918 n /= 10;
919 }
920 *--ep = n + '0';
921 return ep;
922 }
923
924 /*
925 * Expand the size of the cd_devs array if necessary.
926 */
927 static void
928 config_makeroom(int n, struct cfdriver *cd)
929 {
930 int old, new;
931 device_t *nsp;
932
933 if (n < cd->cd_ndevs)
934 return;
935
936 /*
937 * Need to expand the array.
938 */
939 old = cd->cd_ndevs;
940 if (old == 0)
941 new = 4;
942 else
943 new = old * 2;
944 while (new <= n)
945 new *= 2;
946 cd->cd_ndevs = new;
947 nsp = kmem_alloc(sizeof(device_t [new]), KM_SLEEP);
948 if (nsp == NULL)
949 panic("config_attach: %sing dev array",
950 old != 0 ? "expand" : "creat");
951 memset(nsp + old, 0, sizeof(device_t [new - old]));
952 if (old != 0) {
953 memcpy(nsp, cd->cd_devs, sizeof(device_t [old]));
954 kmem_free(cd->cd_devs, sizeof(device_t [old]));
955 }
956 cd->cd_devs = nsp;
957 }
958
959 static void
960 config_devlink(device_t dev)
961 {
962 struct cfdriver *cd = dev->dv_cfdriver;
963
964 /* put this device in the devices array */
965 config_makeroom(dev->dv_unit, cd);
966 if (cd->cd_devs[dev->dv_unit])
967 panic("config_attach: duplicate %s", device_xname(dev));
968 cd->cd_devs[dev->dv_unit] = dev;
969
970 /* It is safe to add a device to the tail of the list while
971 * readers are in the list, but not while a writer is in
972 * the list. Wait for any writer to complete.
973 */
974 mutex_enter(&alldevs_mtx);
975 while (alldevs_nwrite != 0 && alldevs_writer != curlwp)
976 cv_wait(&alldevs_cv, &alldevs_mtx);
977 TAILQ_INSERT_TAIL(&alldevs, dev, dv_list); /* link up */
978 cv_signal(&alldevs_cv);
979 mutex_exit(&alldevs_mtx);
980 }
981
982 static void
983 config_devunlink(device_t dev)
984 {
985 struct cfdriver *cd = dev->dv_cfdriver;
986 int i;
987
988 /* Unlink from device list. */
989 TAILQ_REMOVE(&alldevs, dev, dv_list);
990
991 /* Remove from cfdriver's array. */
992 cd->cd_devs[dev->dv_unit] = NULL;
993
994 /*
995 * If the device now has no units in use, deallocate its softc array.
996 */
997 for (i = 0; i < cd->cd_ndevs; i++) {
998 if (cd->cd_devs[i] != NULL)
999 return;
1000 }
1001 /* nothing found; deallocate */
1002 kmem_free(cd->cd_devs, sizeof(device_t [cd->cd_ndevs]));
1003 cd->cd_devs = NULL;
1004 cd->cd_ndevs = 0;
1005 }
1006
1007 static device_t
1008 config_devalloc(const device_t parent, const cfdata_t cf, const int *locs)
1009 {
1010 struct cfdriver *cd;
1011 struct cfattach *ca;
1012 size_t lname, lunit;
1013 const char *xunit;
1014 int myunit;
1015 char num[10];
1016 device_t dev;
1017 void *dev_private;
1018 const struct cfiattrdata *ia;
1019 device_lock_t dvl;
1020
1021 cd = config_cfdriver_lookup(cf->cf_name);
1022 if (cd == NULL)
1023 return NULL;
1024
1025 ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1026 if (ca == NULL)
1027 return NULL;
1028
1029 if ((ca->ca_flags & DVF_PRIV_ALLOC) == 0 &&
1030 ca->ca_devsize < sizeof(struct device))
1031 panic("config_devalloc: %s", cf->cf_atname);
1032
1033 #ifndef __BROKEN_CONFIG_UNIT_USAGE
1034 if (cf->cf_fstate == FSTATE_STAR) {
1035 for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
1036 if (cd->cd_devs[myunit] == NULL)
1037 break;
1038 /*
1039 * myunit is now the unit of the first NULL device pointer,
1040 * or max(cd->cd_ndevs,cf->cf_unit).
1041 */
1042 } else {
1043 myunit = cf->cf_unit;
1044 if (myunit < cd->cd_ndevs && cd->cd_devs[myunit] != NULL)
1045 return NULL;
1046 }
1047 #else
1048 myunit = cf->cf_unit;
1049 #endif /* ! __BROKEN_CONFIG_UNIT_USAGE */
1050
1051 /* compute length of name and decimal expansion of unit number */
1052 lname = strlen(cd->cd_name);
1053 xunit = number(&num[sizeof(num)], myunit);
1054 lunit = &num[sizeof(num)] - xunit;
1055 if (lname + lunit > sizeof(dev->dv_xname))
1056 panic("config_devalloc: device name too long");
1057
1058 /* get memory for all device vars */
1059 KASSERT((ca->ca_flags & DVF_PRIV_ALLOC) || ca->ca_devsize >= sizeof(struct device));
1060 if (ca->ca_devsize > 0) {
1061 dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
1062 if (dev_private == NULL)
1063 panic("config_devalloc: memory allocation for device softc failed");
1064 } else {
1065 KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
1066 dev_private = NULL;
1067 }
1068
1069 if ((ca->ca_flags & DVF_PRIV_ALLOC) != 0) {
1070 dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1071 } else {
1072 dev = dev_private;
1073 }
1074 if (dev == NULL)
1075 panic("config_devalloc: memory allocation for device_t failed");
1076
1077 dvl = device_getlock(dev);
1078
1079 mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
1080 cv_init(&dvl->dvl_cv, "pmfsusp");
1081
1082 dev->dv_class = cd->cd_class;
1083 dev->dv_cfdata = cf;
1084 dev->dv_cfdriver = cd;
1085 dev->dv_cfattach = ca;
1086 dev->dv_unit = myunit;
1087 dev->dv_activity_count = 0;
1088 dev->dv_activity_handlers = NULL;
1089 dev->dv_private = dev_private;
1090 memcpy(dev->dv_xname, cd->cd_name, lname);
1091 memcpy(dev->dv_xname + lname, xunit, lunit);
1092 dev->dv_parent = parent;
1093 if (parent != NULL)
1094 dev->dv_depth = parent->dv_depth + 1;
1095 else
1096 dev->dv_depth = 0;
1097 dev->dv_flags = DVF_ACTIVE; /* always initially active */
1098 dev->dv_flags |= ca->ca_flags; /* inherit flags from class */
1099 if (locs) {
1100 KASSERT(parent); /* no locators at root */
1101 ia = cfiattr_lookup(cf->cf_pspec->cfp_iattr,
1102 parent->dv_cfdriver);
1103 dev->dv_locators =
1104 kmem_alloc(sizeof(int [ia->ci_loclen + 1]), KM_SLEEP);
1105 *dev->dv_locators++ = sizeof(int [ia->ci_loclen + 1]);
1106 memcpy(dev->dv_locators, locs, sizeof(int [ia->ci_loclen]));
1107 }
1108 dev->dv_properties = prop_dictionary_create();
1109 KASSERT(dev->dv_properties != NULL);
1110
1111 prop_dictionary_set_cstring_nocopy(dev->dv_properties,
1112 "device-driver", dev->dv_cfdriver->cd_name);
1113 prop_dictionary_set_uint16(dev->dv_properties,
1114 "device-unit", dev->dv_unit);
1115
1116 return dev;
1117 }
1118
1119 static void
1120 config_devdealloc(device_t dev)
1121 {
1122 device_lock_t dvl = device_getlock(dev);
1123 int priv = (dev->dv_flags & DVF_PRIV_ALLOC);
1124
1125 cv_destroy(&dvl->dvl_cv);
1126 mutex_destroy(&dvl->dvl_mtx);
1127
1128 KASSERT(dev->dv_properties != NULL);
1129 prop_object_release(dev->dv_properties);
1130
1131 if (dev->dv_activity_handlers)
1132 panic("config_devdealloc with registered handlers");
1133
1134 if (dev->dv_locators) {
1135 size_t amount = *--dev->dv_locators;
1136 kmem_free(dev->dv_locators, amount);
1137 }
1138
1139 if (dev->dv_cfattach->ca_devsize > 0)
1140 kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
1141 if (priv)
1142 kmem_free(dev, sizeof(*dev));
1143 }
1144
1145 /*
1146 * Attach a found device.
1147 */
1148 device_t
1149 config_attach_loc(device_t parent, cfdata_t cf,
1150 const int *locs, void *aux, cfprint_t print)
1151 {
1152 device_t dev;
1153 struct cftable *ct;
1154 const char *drvname;
1155
1156 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1157 if (splash_progress_state)
1158 splash_progress_update(splash_progress_state);
1159 #endif
1160
1161 dev = config_devalloc(parent, cf, locs);
1162 if (!dev)
1163 panic("config_attach: allocation of device softc failed");
1164
1165 /* XXX redundant - see below? */
1166 if (cf->cf_fstate != FSTATE_STAR) {
1167 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1168 cf->cf_fstate = FSTATE_FOUND;
1169 }
1170 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1171 else
1172 cf->cf_unit++;
1173 #endif
1174
1175 config_devlink(dev);
1176
1177 if (config_do_twiddle && cold)
1178 twiddle();
1179 else
1180 aprint_naive("Found ");
1181 /*
1182 * We want the next two printfs for normal, verbose, and quiet,
1183 * but not silent (in which case, we're twiddling, instead).
1184 */
1185 if (parent == ROOT) {
1186 aprint_naive("%s (root)", device_xname(dev));
1187 aprint_normal("%s (root)", device_xname(dev));
1188 } else {
1189 aprint_naive("%s at %s", device_xname(dev), device_xname(parent));
1190 aprint_normal("%s at %s", device_xname(dev), device_xname(parent));
1191 if (print)
1192 (void) (*print)(aux, NULL);
1193 }
1194
1195 /*
1196 * Before attaching, clobber any unfound devices that are
1197 * otherwise identical.
1198 * XXX code above is redundant?
1199 */
1200 drvname = dev->dv_cfdriver->cd_name;
1201 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1202 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1203 if (STREQ(cf->cf_name, drvname) &&
1204 cf->cf_unit == dev->dv_unit) {
1205 if (cf->cf_fstate == FSTATE_NOTFOUND)
1206 cf->cf_fstate = FSTATE_FOUND;
1207 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1208 /*
1209 * Bump the unit number on all starred cfdata
1210 * entries for this device.
1211 */
1212 if (cf->cf_fstate == FSTATE_STAR)
1213 cf->cf_unit++;
1214 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
1215 }
1216 }
1217 }
1218 #ifdef __HAVE_DEVICE_REGISTER
1219 device_register(dev, aux);
1220 #endif
1221
1222 /* Let userland know */
1223 devmon_report_device(dev, true);
1224
1225 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1226 if (splash_progress_state)
1227 splash_progress_update(splash_progress_state);
1228 #endif
1229 (*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1230 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1231 if (splash_progress_state)
1232 splash_progress_update(splash_progress_state);
1233 #endif
1234
1235 if (!device_pmf_is_registered(dev))
1236 aprint_debug_dev(dev, "WARNING: power management not supported\n");
1237
1238 config_process_deferred(&deferred_config_queue, dev);
1239 return dev;
1240 }
1241
1242 device_t
1243 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print)
1244 {
1245
1246 return config_attach_loc(parent, cf, NULL, aux, print);
1247 }
1248
1249 /*
1250 * As above, but for pseudo-devices. Pseudo-devices attached in this
1251 * way are silently inserted into the device tree, and their children
1252 * attached.
1253 *
1254 * Note that because pseudo-devices are attached silently, any information
1255 * the attach routine wishes to print should be prefixed with the device
1256 * name by the attach routine.
1257 */
1258 device_t
1259 config_attach_pseudo(cfdata_t cf)
1260 {
1261 device_t dev;
1262
1263 dev = config_devalloc(ROOT, cf, NULL);
1264 if (!dev)
1265 return NULL;
1266
1267 /* XXX mark busy in cfdata */
1268
1269 if (cf->cf_fstate != FSTATE_STAR) {
1270 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1271 cf->cf_fstate = FSTATE_FOUND;
1272 }
1273
1274 config_devlink(dev);
1275
1276 #if 0 /* XXXJRT not yet */
1277 #ifdef __HAVE_DEVICE_REGISTER
1278 device_register(dev, NULL); /* like a root node */
1279 #endif
1280 #endif
1281 (*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1282 config_process_deferred(&deferred_config_queue, dev);
1283 return dev;
1284 }
1285
1286 /*
1287 * Detach a device. Optionally forced (e.g. because of hardware
1288 * removal) and quiet. Returns zero if successful, non-zero
1289 * (an error code) otherwise.
1290 *
1291 * Note that this code wants to be run from a process context, so
1292 * that the detach can sleep to allow processes which have a device
1293 * open to run and unwind their stacks.
1294 */
1295 int
1296 config_detach(device_t dev, int flags)
1297 {
1298 struct cftable *ct;
1299 cfdata_t cf;
1300 const struct cfattach *ca;
1301 struct cfdriver *cd;
1302 #ifdef DIAGNOSTIC
1303 device_t d;
1304 #endif
1305 int rv = 0;
1306
1307 #ifdef DIAGNOSTIC
1308 cf = dev->dv_cfdata;
1309 if (cf != NULL && cf->cf_fstate != FSTATE_FOUND &&
1310 cf->cf_fstate != FSTATE_STAR)
1311 panic("config_detach: %s: bad device fstate %d",
1312 device_xname(dev), cf ? cf->cf_fstate : -1);
1313 #endif
1314 cd = dev->dv_cfdriver;
1315 KASSERT(cd != NULL);
1316
1317 ca = dev->dv_cfattach;
1318 KASSERT(ca != NULL);
1319
1320 KASSERT(curlwp != NULL);
1321 mutex_enter(&alldevs_mtx);
1322 if (alldevs_nwrite > 0 && alldevs_writer == NULL)
1323 ;
1324 else while (alldevs_nread != 0 ||
1325 (alldevs_nwrite != 0 && alldevs_writer != curlwp))
1326 cv_wait(&alldevs_cv, &alldevs_mtx);
1327 if (alldevs_nwrite++ == 0)
1328 alldevs_writer = curlwp;
1329 mutex_exit(&alldevs_mtx);
1330
1331 /*
1332 * Ensure the device is deactivated. If the device doesn't
1333 * have an activation entry point, we allow DVF_ACTIVE to
1334 * remain set. Otherwise, if DVF_ACTIVE is still set, the
1335 * device is busy, and the detach fails.
1336 */
1337 if (!detachall &&
1338 (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
1339 (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
1340 rv = EOPNOTSUPP;
1341 } else if ((rv = config_deactivate(dev)) == EOPNOTSUPP)
1342 rv = 0; /* Do not treat EOPNOTSUPP as an error */
1343
1344 /*
1345 * Try to detach the device. If that's not possible, then
1346 * we either panic() (for the forced but failed case), or
1347 * return an error.
1348 */
1349 if (rv == 0) {
1350 if (ca->ca_detach != NULL)
1351 rv = (*ca->ca_detach)(dev, flags);
1352 else
1353 rv = EOPNOTSUPP;
1354 }
1355 if (rv != 0) {
1356 if ((flags & DETACH_FORCE) == 0)
1357 goto out;
1358 else
1359 panic("config_detach: forced detach of %s failed (%d)",
1360 device_xname(dev), rv);
1361 }
1362
1363 dev->dv_flags &= ~DVF_ACTIVE;
1364
1365 /*
1366 * The device has now been successfully detached.
1367 */
1368
1369 /* Let userland know */
1370 devmon_report_device(dev, false);
1371
1372 #ifdef DIAGNOSTIC
1373 /*
1374 * Sanity: If you're successfully detached, you should have no
1375 * children. (Note that because children must be attached
1376 * after parents, we only need to search the latter part of
1377 * the list.)
1378 */
1379 for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
1380 d = TAILQ_NEXT(d, dv_list)) {
1381 if (d->dv_parent == dev) {
1382 printf("config_detach: detached device %s"
1383 " has children %s\n", device_xname(dev), device_xname(d));
1384 panic("config_detach");
1385 }
1386 }
1387 #endif
1388
1389 /* notify the parent that the child is gone */
1390 if (dev->dv_parent) {
1391 device_t p = dev->dv_parent;
1392 if (p->dv_cfattach->ca_childdetached)
1393 (*p->dv_cfattach->ca_childdetached)(p, dev);
1394 }
1395
1396 /*
1397 * Mark cfdata to show that the unit can be reused, if possible.
1398 */
1399 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1400 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1401 if (STREQ(cf->cf_name, cd->cd_name)) {
1402 if (cf->cf_fstate == FSTATE_FOUND &&
1403 cf->cf_unit == dev->dv_unit)
1404 cf->cf_fstate = FSTATE_NOTFOUND;
1405 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1406 /*
1407 * Note that we can only re-use a starred
1408 * unit number if the unit being detached
1409 * had the last assigned unit number.
1410 */
1411 if (cf->cf_fstate == FSTATE_STAR &&
1412 cf->cf_unit == dev->dv_unit + 1)
1413 cf->cf_unit--;
1414 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
1415 }
1416 }
1417 }
1418
1419 config_devunlink(dev);
1420
1421 if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
1422 aprint_normal_dev(dev, "detached\n");
1423
1424 config_devdealloc(dev);
1425
1426 out:
1427 mutex_enter(&alldevs_mtx);
1428 KASSERT(alldevs_nwrite != 0);
1429 if (--alldevs_nwrite == 0)
1430 alldevs_writer = NULL;
1431 cv_signal(&alldevs_cv);
1432 mutex_exit(&alldevs_mtx);
1433 return rv;
1434 }
1435
1436 int
1437 config_detach_children(device_t parent, int flags)
1438 {
1439 device_t dv;
1440 deviter_t di;
1441 int error = 0;
1442
1443 for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
1444 dv = deviter_next(&di)) {
1445 if (device_parent(dv) != parent)
1446 continue;
1447 if ((error = config_detach(dv, flags)) != 0)
1448 break;
1449 }
1450 deviter_release(&di);
1451 return error;
1452 }
1453
1454 device_t
1455 shutdown_first(struct shutdown_state *s)
1456 {
1457 if (!s->initialized) {
1458 deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
1459 s->initialized = true;
1460 }
1461 return shutdown_next(s);
1462 }
1463
1464 device_t
1465 shutdown_next(struct shutdown_state *s)
1466 {
1467 device_t dv;
1468
1469 while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
1470 ;
1471
1472 if (dv == NULL)
1473 s->initialized = false;
1474
1475 return dv;
1476 }
1477
1478 bool
1479 config_detach_all(int how)
1480 {
1481 static struct shutdown_state s;
1482 device_t curdev;
1483 bool progress = false;
1484
1485 if ((how & RB_NOSYNC) != 0)
1486 return false;
1487
1488 for (curdev = shutdown_first(&s); curdev != NULL;
1489 curdev = shutdown_next(&s)) {
1490 aprint_debug(" detaching %s, ", device_xname(curdev));
1491 if (config_detach(curdev, DETACH_SHUTDOWN) == 0) {
1492 progress = true;
1493 aprint_debug("success.");
1494 } else
1495 aprint_debug("failed.");
1496 }
1497 return progress;
1498 }
1499
1500 int
1501 config_deactivate(device_t dev)
1502 {
1503 const struct cfattach *ca = dev->dv_cfattach;
1504 int rv = 0, oflags = dev->dv_flags;
1505
1506 if (ca->ca_activate == NULL)
1507 return EOPNOTSUPP;
1508
1509 if (dev->dv_flags & DVF_ACTIVE) {
1510 dev->dv_flags &= ~DVF_ACTIVE;
1511 rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
1512 if (rv)
1513 dev->dv_flags = oflags;
1514 }
1515 return rv;
1516 }
1517
1518 /*
1519 * Defer the configuration of the specified device until all
1520 * of its parent's devices have been attached.
1521 */
1522 void
1523 config_defer(device_t dev, void (*func)(device_t))
1524 {
1525 struct deferred_config *dc;
1526
1527 if (dev->dv_parent == NULL)
1528 panic("config_defer: can't defer config of a root device");
1529
1530 #ifdef DIAGNOSTIC
1531 for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
1532 dc = TAILQ_NEXT(dc, dc_queue)) {
1533 if (dc->dc_dev == dev)
1534 panic("config_defer: deferred twice");
1535 }
1536 #endif
1537
1538 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
1539 if (dc == NULL)
1540 panic("config_defer: unable to allocate callback");
1541
1542 dc->dc_dev = dev;
1543 dc->dc_func = func;
1544 TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
1545 config_pending_incr();
1546 }
1547
1548 /*
1549 * Defer some autoconfiguration for a device until after interrupts
1550 * are enabled.
1551 */
1552 void
1553 config_interrupts(device_t dev, void (*func)(device_t))
1554 {
1555 struct deferred_config *dc;
1556
1557 /*
1558 * If interrupts are enabled, callback now.
1559 */
1560 if (cold == 0) {
1561 (*func)(dev);
1562 return;
1563 }
1564
1565 #ifdef DIAGNOSTIC
1566 for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
1567 dc = TAILQ_NEXT(dc, dc_queue)) {
1568 if (dc->dc_dev == dev)
1569 panic("config_interrupts: deferred twice");
1570 }
1571 #endif
1572
1573 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
1574 if (dc == NULL)
1575 panic("config_interrupts: unable to allocate callback");
1576
1577 dc->dc_dev = dev;
1578 dc->dc_func = func;
1579 TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
1580 config_pending_incr();
1581 }
1582
1583 /*
1584 * Process a deferred configuration queue.
1585 */
1586 static void
1587 config_process_deferred(struct deferred_config_head *queue,
1588 device_t parent)
1589 {
1590 struct deferred_config *dc, *ndc;
1591
1592 for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
1593 ndc = TAILQ_NEXT(dc, dc_queue);
1594 if (parent == NULL || dc->dc_dev->dv_parent == parent) {
1595 TAILQ_REMOVE(queue, dc, dc_queue);
1596 (*dc->dc_func)(dc->dc_dev);
1597 kmem_free(dc, sizeof(*dc));
1598 config_pending_decr();
1599 }
1600 }
1601 }
1602
1603 /*
1604 * Manipulate the config_pending semaphore.
1605 */
1606 void
1607 config_pending_incr(void)
1608 {
1609
1610 mutex_enter(&config_misc_lock);
1611 config_pending++;
1612 mutex_exit(&config_misc_lock);
1613 }
1614
1615 void
1616 config_pending_decr(void)
1617 {
1618
1619 #ifdef DIAGNOSTIC
1620 if (config_pending == 0)
1621 panic("config_pending_decr: config_pending == 0");
1622 #endif
1623 mutex_enter(&config_misc_lock);
1624 config_pending--;
1625 if (config_pending == 0)
1626 cv_broadcast(&config_misc_cv);
1627 mutex_exit(&config_misc_lock);
1628 }
1629
1630 /*
1631 * Register a "finalization" routine. Finalization routines are
1632 * called iteratively once all real devices have been found during
1633 * autoconfiguration, for as long as any one finalizer has done
1634 * any work.
1635 */
1636 int
1637 config_finalize_register(device_t dev, int (*fn)(device_t))
1638 {
1639 struct finalize_hook *f;
1640
1641 /*
1642 * If finalization has already been done, invoke the
1643 * callback function now.
1644 */
1645 if (config_finalize_done) {
1646 while ((*fn)(dev) != 0)
1647 /* loop */ ;
1648 }
1649
1650 /* Ensure this isn't already on the list. */
1651 TAILQ_FOREACH(f, &config_finalize_list, f_list) {
1652 if (f->f_func == fn && f->f_dev == dev)
1653 return EEXIST;
1654 }
1655
1656 f = kmem_alloc(sizeof(*f), KM_SLEEP);
1657 f->f_func = fn;
1658 f->f_dev = dev;
1659 TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
1660
1661 return 0;
1662 }
1663
1664 void
1665 config_finalize(void)
1666 {
1667 struct finalize_hook *f;
1668 struct pdevinit *pdev;
1669 extern struct pdevinit pdevinit[];
1670 int errcnt, rv;
1671
1672 /*
1673 * Now that device driver threads have been created, wait for
1674 * them to finish any deferred autoconfiguration.
1675 */
1676 mutex_enter(&config_misc_lock);
1677 while (config_pending != 0)
1678 cv_wait(&config_misc_cv, &config_misc_lock);
1679 mutex_exit(&config_misc_lock);
1680
1681 KERNEL_LOCK(1, NULL);
1682
1683 /* Attach pseudo-devices. */
1684 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
1685 (*pdev->pdev_attach)(pdev->pdev_count);
1686
1687 /* Run the hooks until none of them does any work. */
1688 do {
1689 rv = 0;
1690 TAILQ_FOREACH(f, &config_finalize_list, f_list)
1691 rv |= (*f->f_func)(f->f_dev);
1692 } while (rv != 0);
1693
1694 config_finalize_done = 1;
1695
1696 /* Now free all the hooks. */
1697 while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
1698 TAILQ_REMOVE(&config_finalize_list, f, f_list);
1699 kmem_free(f, sizeof(*f));
1700 }
1701
1702 KERNEL_UNLOCK_ONE(NULL);
1703
1704 errcnt = aprint_get_error_count();
1705 if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
1706 (boothowto & AB_VERBOSE) == 0) {
1707 mutex_enter(&config_misc_lock);
1708 if (config_do_twiddle) {
1709 config_do_twiddle = 0;
1710 printf_nolog(" done.\n");
1711 }
1712 mutex_exit(&config_misc_lock);
1713 if (errcnt != 0) {
1714 printf("WARNING: %d error%s while detecting hardware; "
1715 "check system log.\n", errcnt,
1716 errcnt == 1 ? "" : "s");
1717 }
1718 }
1719 }
1720
1721 void
1722 config_twiddle_init()
1723 {
1724
1725 if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
1726 config_do_twiddle = 1;
1727 }
1728 callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
1729 }
1730
1731 void
1732 config_twiddle_fn(void *cookie)
1733 {
1734
1735 mutex_enter(&config_misc_lock);
1736 if (config_do_twiddle) {
1737 twiddle();
1738 callout_schedule(&config_twiddle_ch, mstohz(100));
1739 }
1740 mutex_exit(&config_misc_lock);
1741 }
1742
1743 /*
1744 * device_lookup:
1745 *
1746 * Look up a device instance for a given driver.
1747 */
1748 device_t
1749 device_lookup(cfdriver_t cd, int unit)
1750 {
1751
1752 if (unit < 0 || unit >= cd->cd_ndevs)
1753 return NULL;
1754
1755 return cd->cd_devs[unit];
1756 }
1757
1758 /*
1759 * device_lookup:
1760 *
1761 * Look up a device instance for a given driver.
1762 */
1763 void *
1764 device_lookup_private(cfdriver_t cd, int unit)
1765 {
1766 device_t dv;
1767
1768 if (unit < 0 || unit >= cd->cd_ndevs)
1769 return NULL;
1770
1771 if ((dv = cd->cd_devs[unit]) == NULL)
1772 return NULL;
1773
1774 return dv->dv_private;
1775 }
1776
1777 /*
1778 * Accessor functions for the device_t type.
1779 */
1780 devclass_t
1781 device_class(device_t dev)
1782 {
1783
1784 return dev->dv_class;
1785 }
1786
1787 cfdata_t
1788 device_cfdata(device_t dev)
1789 {
1790
1791 return dev->dv_cfdata;
1792 }
1793
1794 cfdriver_t
1795 device_cfdriver(device_t dev)
1796 {
1797
1798 return dev->dv_cfdriver;
1799 }
1800
1801 cfattach_t
1802 device_cfattach(device_t dev)
1803 {
1804
1805 return dev->dv_cfattach;
1806 }
1807
1808 int
1809 device_unit(device_t dev)
1810 {
1811
1812 return dev->dv_unit;
1813 }
1814
1815 const char *
1816 device_xname(device_t dev)
1817 {
1818
1819 return dev->dv_xname;
1820 }
1821
1822 device_t
1823 device_parent(device_t dev)
1824 {
1825
1826 return dev->dv_parent;
1827 }
1828
1829 bool
1830 device_activation(device_t dev, devact_level_t level)
1831 {
1832 int active_flags;
1833
1834 active_flags = DVF_ACTIVE;
1835 switch (level) {
1836 case DEVACT_LEVEL_FULL:
1837 active_flags |= DVF_CLASS_SUSPENDED;
1838 /*FALLTHROUGH*/
1839 case DEVACT_LEVEL_DRIVER:
1840 active_flags |= DVF_DRIVER_SUSPENDED;
1841 /*FALLTHROUGH*/
1842 case DEVACT_LEVEL_BUS:
1843 active_flags |= DVF_BUS_SUSPENDED;
1844 break;
1845 }
1846
1847 return (dev->dv_flags & active_flags) == DVF_ACTIVE;
1848 }
1849
1850 bool
1851 device_is_active(device_t dev)
1852 {
1853 int active_flags;
1854
1855 active_flags = DVF_ACTIVE;
1856 active_flags |= DVF_CLASS_SUSPENDED;
1857 active_flags |= DVF_DRIVER_SUSPENDED;
1858 active_flags |= DVF_BUS_SUSPENDED;
1859
1860 return (dev->dv_flags & active_flags) == DVF_ACTIVE;
1861 }
1862
1863 bool
1864 device_is_enabled(device_t dev)
1865 {
1866 return (dev->dv_flags & DVF_ACTIVE) == DVF_ACTIVE;
1867 }
1868
1869 bool
1870 device_has_power(device_t dev)
1871 {
1872 int active_flags;
1873
1874 active_flags = DVF_ACTIVE | DVF_BUS_SUSPENDED;
1875
1876 return (dev->dv_flags & active_flags) == DVF_ACTIVE;
1877 }
1878
1879 int
1880 device_locator(device_t dev, u_int locnum)
1881 {
1882
1883 KASSERT(dev->dv_locators != NULL);
1884 return dev->dv_locators[locnum];
1885 }
1886
1887 void *
1888 device_private(device_t dev)
1889 {
1890
1891 /*
1892 * The reason why device_private(NULL) is allowed is to simplify the
1893 * work of a lot of userspace request handlers (i.e., c/bdev
1894 * handlers) which grab cfdriver_t->cd_units[n].
1895 * It avoids having them test for it to be NULL and only then calling
1896 * device_private.
1897 */
1898 return dev == NULL ? NULL : dev->dv_private;
1899 }
1900
1901 prop_dictionary_t
1902 device_properties(device_t dev)
1903 {
1904
1905 return dev->dv_properties;
1906 }
1907
1908 /*
1909 * device_is_a:
1910 *
1911 * Returns true if the device is an instance of the specified
1912 * driver.
1913 */
1914 bool
1915 device_is_a(device_t dev, const char *dname)
1916 {
1917
1918 return strcmp(dev->dv_cfdriver->cd_name, dname) == 0;
1919 }
1920
1921 /*
1922 * device_find_by_xname:
1923 *
1924 * Returns the device of the given name or NULL if it doesn't exist.
1925 */
1926 device_t
1927 device_find_by_xname(const char *name)
1928 {
1929 device_t dv;
1930 deviter_t di;
1931
1932 for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
1933 if (strcmp(device_xname(dv), name) == 0)
1934 break;
1935 }
1936 deviter_release(&di);
1937
1938 return dv;
1939 }
1940
1941 /*
1942 * device_find_by_driver_unit:
1943 *
1944 * Returns the device of the given driver name and unit or
1945 * NULL if it doesn't exist.
1946 */
1947 device_t
1948 device_find_by_driver_unit(const char *name, int unit)
1949 {
1950 struct cfdriver *cd;
1951
1952 if ((cd = config_cfdriver_lookup(name)) == NULL)
1953 return NULL;
1954 return device_lookup(cd, unit);
1955 }
1956
1957 /*
1958 * Power management related functions.
1959 */
1960
1961 bool
1962 device_pmf_is_registered(device_t dev)
1963 {
1964 return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
1965 }
1966
1967 bool
1968 device_pmf_driver_suspend(device_t dev PMF_FN_ARGS)
1969 {
1970 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
1971 return true;
1972 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
1973 return false;
1974 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_DRIVER &&
1975 dev->dv_driver_suspend != NULL &&
1976 !(*dev->dv_driver_suspend)(dev PMF_FN_CALL))
1977 return false;
1978
1979 dev->dv_flags |= DVF_DRIVER_SUSPENDED;
1980 return true;
1981 }
1982
1983 bool
1984 device_pmf_driver_resume(device_t dev PMF_FN_ARGS)
1985 {
1986 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
1987 return true;
1988 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
1989 return false;
1990 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_DRIVER &&
1991 dev->dv_driver_resume != NULL &&
1992 !(*dev->dv_driver_resume)(dev PMF_FN_CALL))
1993 return false;
1994
1995 dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
1996 return true;
1997 }
1998
1999 bool
2000 device_pmf_driver_shutdown(device_t dev, int how)
2001 {
2002
2003 if (*dev->dv_driver_shutdown != NULL &&
2004 !(*dev->dv_driver_shutdown)(dev, how))
2005 return false;
2006 return true;
2007 }
2008
2009 bool
2010 device_pmf_driver_register(device_t dev,
2011 bool (*suspend)(device_t PMF_FN_PROTO),
2012 bool (*resume)(device_t PMF_FN_PROTO),
2013 bool (*shutdown)(device_t, int))
2014 {
2015 dev->dv_driver_suspend = suspend;
2016 dev->dv_driver_resume = resume;
2017 dev->dv_driver_shutdown = shutdown;
2018 dev->dv_flags |= DVF_POWER_HANDLERS;
2019 return true;
2020 }
2021
2022 static const char *
2023 curlwp_name(void)
2024 {
2025 if (curlwp->l_name != NULL)
2026 return curlwp->l_name;
2027 else
2028 return curlwp->l_proc->p_comm;
2029 }
2030
2031 void
2032 device_pmf_driver_deregister(device_t dev)
2033 {
2034 device_lock_t dvl = device_getlock(dev);
2035
2036 dev->dv_driver_suspend = NULL;
2037 dev->dv_driver_resume = NULL;
2038
2039 mutex_enter(&dvl->dvl_mtx);
2040 dev->dv_flags &= ~DVF_POWER_HANDLERS;
2041 while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
2042 /* Wake a thread that waits for the lock. That
2043 * thread will fail to acquire the lock, and then
2044 * it will wake the next thread that waits for the
2045 * lock, or else it will wake us.
2046 */
2047 cv_signal(&dvl->dvl_cv);
2048 pmflock_debug(dev, __func__, __LINE__);
2049 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2050 pmflock_debug(dev, __func__, __LINE__);
2051 }
2052 mutex_exit(&dvl->dvl_mtx);
2053 }
2054
2055 bool
2056 device_pmf_driver_child_register(device_t dev)
2057 {
2058 device_t parent = device_parent(dev);
2059
2060 if (parent == NULL || parent->dv_driver_child_register == NULL)
2061 return true;
2062 return (*parent->dv_driver_child_register)(dev);
2063 }
2064
2065 void
2066 device_pmf_driver_set_child_register(device_t dev,
2067 bool (*child_register)(device_t))
2068 {
2069 dev->dv_driver_child_register = child_register;
2070 }
2071
2072 static void
2073 pmflock_debug(device_t dev, const char *func, int line)
2074 {
2075 device_lock_t dvl = device_getlock(dev);
2076
2077 aprint_debug_dev(dev, "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n",
2078 func, line, curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait,
2079 dev->dv_flags);
2080 }
2081
2082 static bool
2083 device_pmf_lock1(device_t dev)
2084 {
2085 device_lock_t dvl = device_getlock(dev);
2086
2087 while (device_pmf_is_registered(dev) &&
2088 dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
2089 dvl->dvl_nwait++;
2090 pmflock_debug(dev, __func__, __LINE__);
2091 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2092 pmflock_debug(dev, __func__, __LINE__);
2093 dvl->dvl_nwait--;
2094 }
2095 if (!device_pmf_is_registered(dev)) {
2096 pmflock_debug(dev, __func__, __LINE__);
2097 /* We could not acquire the lock, but some other thread may
2098 * wait for it, also. Wake that thread.
2099 */
2100 cv_signal(&dvl->dvl_cv);
2101 return false;
2102 }
2103 dvl->dvl_nlock++;
2104 dvl->dvl_holder = curlwp;
2105 pmflock_debug(dev, __func__, __LINE__);
2106 return true;
2107 }
2108
2109 bool
2110 device_pmf_lock(device_t dev)
2111 {
2112 bool rc;
2113 device_lock_t dvl = device_getlock(dev);
2114
2115 mutex_enter(&dvl->dvl_mtx);
2116 rc = device_pmf_lock1(dev);
2117 mutex_exit(&dvl->dvl_mtx);
2118
2119 return rc;
2120 }
2121
2122 void
2123 device_pmf_unlock(device_t dev)
2124 {
2125 device_lock_t dvl = device_getlock(dev);
2126
2127 KASSERT(dvl->dvl_nlock > 0);
2128 mutex_enter(&dvl->dvl_mtx);
2129 if (--dvl->dvl_nlock == 0)
2130 dvl->dvl_holder = NULL;
2131 cv_signal(&dvl->dvl_cv);
2132 pmflock_debug(dev, __func__, __LINE__);
2133 mutex_exit(&dvl->dvl_mtx);
2134 }
2135
2136 device_lock_t
2137 device_getlock(device_t dev)
2138 {
2139 return &dev->dv_lock;
2140 }
2141
2142 void *
2143 device_pmf_bus_private(device_t dev)
2144 {
2145 return dev->dv_bus_private;
2146 }
2147
2148 bool
2149 device_pmf_bus_suspend(device_t dev PMF_FN_ARGS)
2150 {
2151 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2152 return true;
2153 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
2154 (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2155 return false;
2156 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_BUS &&
2157 dev->dv_bus_suspend != NULL &&
2158 !(*dev->dv_bus_suspend)(dev PMF_FN_CALL))
2159 return false;
2160
2161 dev->dv_flags |= DVF_BUS_SUSPENDED;
2162 return true;
2163 }
2164
2165 bool
2166 device_pmf_bus_resume(device_t dev PMF_FN_ARGS)
2167 {
2168 if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
2169 return true;
2170 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_BUS &&
2171 dev->dv_bus_resume != NULL &&
2172 !(*dev->dv_bus_resume)(dev PMF_FN_CALL))
2173 return false;
2174
2175 dev->dv_flags &= ~DVF_BUS_SUSPENDED;
2176 return true;
2177 }
2178
2179 bool
2180 device_pmf_bus_shutdown(device_t dev, int how)
2181 {
2182
2183 if (*dev->dv_bus_shutdown != NULL &&
2184 !(*dev->dv_bus_shutdown)(dev, how))
2185 return false;
2186 return true;
2187 }
2188
2189 void
2190 device_pmf_bus_register(device_t dev, void *priv,
2191 bool (*suspend)(device_t PMF_FN_PROTO),
2192 bool (*resume)(device_t PMF_FN_PROTO),
2193 bool (*shutdown)(device_t, int), void (*deregister)(device_t))
2194 {
2195 dev->dv_bus_private = priv;
2196 dev->dv_bus_resume = resume;
2197 dev->dv_bus_suspend = suspend;
2198 dev->dv_bus_shutdown = shutdown;
2199 dev->dv_bus_deregister = deregister;
2200 }
2201
2202 void
2203 device_pmf_bus_deregister(device_t dev)
2204 {
2205 if (dev->dv_bus_deregister == NULL)
2206 return;
2207 (*dev->dv_bus_deregister)(dev);
2208 dev->dv_bus_private = NULL;
2209 dev->dv_bus_suspend = NULL;
2210 dev->dv_bus_resume = NULL;
2211 dev->dv_bus_deregister = NULL;
2212 }
2213
2214 void *
2215 device_pmf_class_private(device_t dev)
2216 {
2217 return dev->dv_class_private;
2218 }
2219
2220 bool
2221 device_pmf_class_suspend(device_t dev PMF_FN_ARGS)
2222 {
2223 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
2224 return true;
2225 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_CLASS &&
2226 dev->dv_class_suspend != NULL &&
2227 !(*dev->dv_class_suspend)(dev PMF_FN_CALL))
2228 return false;
2229
2230 dev->dv_flags |= DVF_CLASS_SUSPENDED;
2231 return true;
2232 }
2233
2234 bool
2235 device_pmf_class_resume(device_t dev PMF_FN_ARGS)
2236 {
2237 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2238 return true;
2239 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
2240 (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2241 return false;
2242 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_CLASS &&
2243 dev->dv_class_resume != NULL &&
2244 !(*dev->dv_class_resume)(dev PMF_FN_CALL))
2245 return false;
2246
2247 dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
2248 return true;
2249 }
2250
2251 void
2252 device_pmf_class_register(device_t dev, void *priv,
2253 bool (*suspend)(device_t PMF_FN_PROTO),
2254 bool (*resume)(device_t PMF_FN_PROTO),
2255 void (*deregister)(device_t))
2256 {
2257 dev->dv_class_private = priv;
2258 dev->dv_class_suspend = suspend;
2259 dev->dv_class_resume = resume;
2260 dev->dv_class_deregister = deregister;
2261 }
2262
2263 void
2264 device_pmf_class_deregister(device_t dev)
2265 {
2266 if (dev->dv_class_deregister == NULL)
2267 return;
2268 (*dev->dv_class_deregister)(dev);
2269 dev->dv_class_private = NULL;
2270 dev->dv_class_suspend = NULL;
2271 dev->dv_class_resume = NULL;
2272 dev->dv_class_deregister = NULL;
2273 }
2274
2275 bool
2276 device_active(device_t dev, devactive_t type)
2277 {
2278 size_t i;
2279
2280 if (dev->dv_activity_count == 0)
2281 return false;
2282
2283 for (i = 0; i < dev->dv_activity_count; ++i) {
2284 if (dev->dv_activity_handlers[i] == NULL)
2285 break;
2286 (*dev->dv_activity_handlers[i])(dev, type);
2287 }
2288
2289 return true;
2290 }
2291
2292 bool
2293 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
2294 {
2295 void (**new_handlers)(device_t, devactive_t);
2296 void (**old_handlers)(device_t, devactive_t);
2297 size_t i, old_size, new_size;
2298 int s;
2299
2300 old_handlers = dev->dv_activity_handlers;
2301 old_size = dev->dv_activity_count;
2302
2303 for (i = 0; i < old_size; ++i) {
2304 KASSERT(old_handlers[i] != handler);
2305 if (old_handlers[i] == NULL) {
2306 old_handlers[i] = handler;
2307 return true;
2308 }
2309 }
2310
2311 new_size = old_size + 4;
2312 new_handlers = kmem_alloc(sizeof(void *[new_size]), KM_SLEEP);
2313
2314 memcpy(new_handlers, old_handlers, sizeof(void *[old_size]));
2315 new_handlers[old_size] = handler;
2316 memset(new_handlers + old_size + 1, 0,
2317 sizeof(int [new_size - (old_size+1)]));
2318
2319 s = splhigh();
2320 dev->dv_activity_count = new_size;
2321 dev->dv_activity_handlers = new_handlers;
2322 splx(s);
2323
2324 if (old_handlers != NULL)
2325 kmem_free(old_handlers, sizeof(void * [old_size]));
2326
2327 return true;
2328 }
2329
2330 void
2331 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
2332 {
2333 void (**old_handlers)(device_t, devactive_t);
2334 size_t i, old_size;
2335 int s;
2336
2337 old_handlers = dev->dv_activity_handlers;
2338 old_size = dev->dv_activity_count;
2339
2340 for (i = 0; i < old_size; ++i) {
2341 if (old_handlers[i] == handler)
2342 break;
2343 if (old_handlers[i] == NULL)
2344 return; /* XXX panic? */
2345 }
2346
2347 if (i == old_size)
2348 return; /* XXX panic? */
2349
2350 for (; i < old_size - 1; ++i) {
2351 if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
2352 continue;
2353
2354 if (i == 0) {
2355 s = splhigh();
2356 dev->dv_activity_count = 0;
2357 dev->dv_activity_handlers = NULL;
2358 splx(s);
2359 kmem_free(old_handlers, sizeof(void *[old_size]));
2360 }
2361 return;
2362 }
2363 old_handlers[i] = NULL;
2364 }
2365
2366 /*
2367 * Device Iteration
2368 *
2369 * deviter_t: a device iterator. Holds state for a "walk" visiting
2370 * each device_t's in the device tree.
2371 *
2372 * deviter_init(di, flags): initialize the device iterator `di'
2373 * to "walk" the device tree. deviter_next(di) will return
2374 * the first device_t in the device tree, or NULL if there are
2375 * no devices.
2376 *
2377 * `flags' is one or more of DEVITER_F_RW, indicating that the
2378 * caller intends to modify the device tree by calling
2379 * config_detach(9) on devices in the order that the iterator
2380 * returns them; DEVITER_F_ROOT_FIRST, asking for the devices
2381 * nearest the "root" of the device tree to be returned, first;
2382 * DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
2383 * the root of the device tree, first; and DEVITER_F_SHUTDOWN,
2384 * indicating both that deviter_init() should not respect any
2385 * locks on the device tree, and that deviter_next(di) may run
2386 * in more than one LWP before the walk has finished.
2387 *
2388 * Only one DEVITER_F_RW iterator may be in the device tree at
2389 * once.
2390 *
2391 * DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
2392 *
2393 * Results are undefined if the flags DEVITER_F_ROOT_FIRST and
2394 * DEVITER_F_LEAVES_FIRST are used in combination.
2395 *
2396 * deviter_first(di, flags): initialize the device iterator `di'
2397 * and return the first device_t in the device tree, or NULL
2398 * if there are no devices. The statement
2399 *
2400 * dv = deviter_first(di);
2401 *
2402 * is shorthand for
2403 *
2404 * deviter_init(di);
2405 * dv = deviter_next(di);
2406 *
2407 * deviter_next(di): return the next device_t in the device tree,
2408 * or NULL if there are no more devices. deviter_next(di)
2409 * is undefined if `di' was not initialized with deviter_init() or
2410 * deviter_first().
2411 *
2412 * deviter_release(di): stops iteration (subsequent calls to
2413 * deviter_next() will return NULL), releases any locks and
2414 * resources held by the device iterator.
2415 *
2416 * Device iteration does not return device_t's in any particular
2417 * order. An iterator will never return the same device_t twice.
2418 * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
2419 * is called repeatedly on the same `di', it will eventually return
2420 * NULL. It is ok to attach/detach devices during device iteration.
2421 */
2422 void
2423 deviter_init(deviter_t *di, deviter_flags_t flags)
2424 {
2425 device_t dv;
2426 bool rw;
2427
2428 mutex_enter(&alldevs_mtx);
2429 if ((flags & DEVITER_F_SHUTDOWN) != 0) {
2430 flags |= DEVITER_F_RW;
2431 alldevs_nwrite++;
2432 alldevs_writer = NULL;
2433 alldevs_nread = 0;
2434 } else {
2435 rw = (flags & DEVITER_F_RW) != 0;
2436
2437 if (alldevs_nwrite > 0 && alldevs_writer == NULL)
2438 ;
2439 else while ((alldevs_nwrite != 0 && alldevs_writer != curlwp) ||
2440 (rw && alldevs_nread != 0))
2441 cv_wait(&alldevs_cv, &alldevs_mtx);
2442
2443 if (rw) {
2444 if (alldevs_nwrite++ == 0)
2445 alldevs_writer = curlwp;
2446 } else
2447 alldevs_nread++;
2448 }
2449 mutex_exit(&alldevs_mtx);
2450
2451 memset(di, 0, sizeof(*di));
2452
2453 di->di_flags = flags;
2454
2455 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
2456 case DEVITER_F_LEAVES_FIRST:
2457 TAILQ_FOREACH(dv, &alldevs, dv_list)
2458 di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
2459 break;
2460 case DEVITER_F_ROOT_FIRST:
2461 TAILQ_FOREACH(dv, &alldevs, dv_list)
2462 di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
2463 break;
2464 default:
2465 break;
2466 }
2467
2468 deviter_reinit(di);
2469 }
2470
2471 static void
2472 deviter_reinit(deviter_t *di)
2473 {
2474 if ((di->di_flags & DEVITER_F_RW) != 0)
2475 di->di_prev = TAILQ_LAST(&alldevs, devicelist);
2476 else
2477 di->di_prev = TAILQ_FIRST(&alldevs);
2478 }
2479
2480 device_t
2481 deviter_first(deviter_t *di, deviter_flags_t flags)
2482 {
2483 deviter_init(di, flags);
2484 return deviter_next(di);
2485 }
2486
2487 static device_t
2488 deviter_next1(deviter_t *di)
2489 {
2490 device_t dv;
2491
2492 dv = di->di_prev;
2493
2494 if (dv == NULL)
2495 ;
2496 else if ((di->di_flags & DEVITER_F_RW) != 0)
2497 di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
2498 else
2499 di->di_prev = TAILQ_NEXT(dv, dv_list);
2500
2501 return dv;
2502 }
2503
2504 device_t
2505 deviter_next(deviter_t *di)
2506 {
2507 device_t dv = NULL;
2508
2509 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
2510 case 0:
2511 return deviter_next1(di);
2512 case DEVITER_F_LEAVES_FIRST:
2513 while (di->di_curdepth >= 0) {
2514 if ((dv = deviter_next1(di)) == NULL) {
2515 di->di_curdepth--;
2516 deviter_reinit(di);
2517 } else if (dv->dv_depth == di->di_curdepth)
2518 break;
2519 }
2520 return dv;
2521 case DEVITER_F_ROOT_FIRST:
2522 while (di->di_curdepth <= di->di_maxdepth) {
2523 if ((dv = deviter_next1(di)) == NULL) {
2524 di->di_curdepth++;
2525 deviter_reinit(di);
2526 } else if (dv->dv_depth == di->di_curdepth)
2527 break;
2528 }
2529 return dv;
2530 default:
2531 return NULL;
2532 }
2533 }
2534
2535 void
2536 deviter_release(deviter_t *di)
2537 {
2538 bool rw = (di->di_flags & DEVITER_F_RW) != 0;
2539
2540 mutex_enter(&alldevs_mtx);
2541 if (!rw) {
2542 --alldevs_nread;
2543 cv_signal(&alldevs_cv);
2544 } else if (alldevs_nwrite > 0 && alldevs_writer == NULL) {
2545 --alldevs_nwrite; /* shutting down: do not signal */
2546 } else {
2547 KASSERT(alldevs_nwrite != 0);
2548 if (--alldevs_nwrite == 0)
2549 alldevs_writer = NULL;
2550 cv_signal(&alldevs_cv);
2551 }
2552 mutex_exit(&alldevs_mtx);
2553 }
2554
2555 static void
2556 sysctl_detach_setup(struct sysctllog **clog)
2557 {
2558 const struct sysctlnode *node = NULL;
2559
2560 sysctl_createv(clog, 0, NULL, &node,
2561 CTLFLAG_PERMANENT,
2562 CTLTYPE_NODE, "kern", NULL,
2563 NULL, 0, NULL, 0,
2564 CTL_KERN, CTL_EOL);
2565
2566 if (node == NULL)
2567 return;
2568
2569 sysctl_createv(clog, 0, &node, NULL,
2570 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
2571 CTLTYPE_INT, "detachall",
2572 SYSCTL_DESCR("Detach all devices at shutdown"),
2573 NULL, 0, &detachall, 0,
2574 CTL_CREATE, CTL_EOL);
2575 }
2576