subr_autoconf.c revision 1.283 1 /* $NetBSD: subr_autoconf.c,v 1.283 2021/06/12 12:13:51 riastradh 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 #define __SUBR_AUTOCONF_PRIVATE /* see <sys/device.h> */
80
81 #include <sys/cdefs.h>
82 __KERNEL_RCSID(0, "$NetBSD: subr_autoconf.c,v 1.283 2021/06/12 12:13:51 riastradh Exp $");
83
84 #ifdef _KERNEL_OPT
85 #include "opt_ddb.h"
86 #include "drvctl.h"
87 #endif
88
89 #include <sys/param.h>
90 #include <sys/device.h>
91 #include <sys/disklabel.h>
92 #include <sys/conf.h>
93 #include <sys/kauth.h>
94 #include <sys/kmem.h>
95 #include <sys/systm.h>
96 #include <sys/kernel.h>
97 #include <sys/errno.h>
98 #include <sys/proc.h>
99 #include <sys/reboot.h>
100 #include <sys/kthread.h>
101 #include <sys/buf.h>
102 #include <sys/dirent.h>
103 #include <sys/mount.h>
104 #include <sys/namei.h>
105 #include <sys/unistd.h>
106 #include <sys/fcntl.h>
107 #include <sys/lockf.h>
108 #include <sys/callout.h>
109 #include <sys/devmon.h>
110 #include <sys/cpu.h>
111 #include <sys/sysctl.h>
112 #include <sys/stdarg.h>
113
114 #include <sys/disk.h>
115
116 #include <sys/rndsource.h>
117
118 #include <machine/limits.h>
119
120 /*
121 * Autoconfiguration subroutines.
122 */
123
124 /*
125 * Device autoconfiguration timings are mixed into the entropy pool.
126 */
127 static krndsource_t rnd_autoconf_source;
128
129 /*
130 * ioconf.c exports exactly two names: cfdata and cfroots. All system
131 * devices and drivers are found via these tables.
132 */
133 extern struct cfdata cfdata[];
134 extern const short cfroots[];
135
136 /*
137 * List of all cfdriver structures. We use this to detect duplicates
138 * when other cfdrivers are loaded.
139 */
140 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
141 extern struct cfdriver * const cfdriver_list_initial[];
142
143 /*
144 * Initial list of cfattach's.
145 */
146 extern const struct cfattachinit cfattachinit[];
147
148 /*
149 * List of cfdata tables. We always have one such list -- the one
150 * built statically when the kernel was configured.
151 */
152 struct cftablelist allcftables = TAILQ_HEAD_INITIALIZER(allcftables);
153 static struct cftable initcftable;
154
155 #define ROOT ((device_t)NULL)
156
157 struct matchinfo {
158 cfsubmatch_t fn;
159 device_t parent;
160 const int *locs;
161 void *aux;
162 struct cfdata *match;
163 int pri;
164 };
165
166 struct alldevs_foray {
167 int af_s;
168 struct devicelist af_garbage;
169 };
170
171 static char *number(char *, int);
172 static void mapply(struct matchinfo *, cfdata_t);
173 static void config_devdelete(device_t);
174 static void config_devunlink(device_t, struct devicelist *);
175 static void config_makeroom(int, struct cfdriver *);
176 static void config_devlink(device_t);
177 static void config_alldevs_enter(struct alldevs_foray *);
178 static void config_alldevs_exit(struct alldevs_foray *);
179 static void config_add_attrib_dict(device_t);
180
181 static void config_collect_garbage(struct devicelist *);
182 static void config_dump_garbage(struct devicelist *);
183
184 static void pmflock_debug(device_t, const char *, int);
185
186 static device_t deviter_next1(deviter_t *);
187 static void deviter_reinit(deviter_t *);
188
189 struct deferred_config {
190 TAILQ_ENTRY(deferred_config) dc_queue;
191 device_t dc_dev;
192 void (*dc_func)(device_t);
193 };
194
195 TAILQ_HEAD(deferred_config_head, deferred_config);
196
197 static struct deferred_config_head deferred_config_queue =
198 TAILQ_HEAD_INITIALIZER(deferred_config_queue);
199 static struct deferred_config_head interrupt_config_queue =
200 TAILQ_HEAD_INITIALIZER(interrupt_config_queue);
201 static int interrupt_config_threads = 8;
202 static struct deferred_config_head mountroot_config_queue =
203 TAILQ_HEAD_INITIALIZER(mountroot_config_queue);
204 static int mountroot_config_threads = 2;
205 static lwp_t **mountroot_config_lwpids;
206 static size_t mountroot_config_lwpids_size;
207 bool root_is_mounted = false;
208
209 static void config_process_deferred(struct deferred_config_head *, device_t);
210
211 /* Hooks to finalize configuration once all real devices have been found. */
212 struct finalize_hook {
213 TAILQ_ENTRY(finalize_hook) f_list;
214 int (*f_func)(device_t);
215 device_t f_dev;
216 };
217 static TAILQ_HEAD(, finalize_hook) config_finalize_list =
218 TAILQ_HEAD_INITIALIZER(config_finalize_list);
219 static int config_finalize_done;
220
221 /* list of all devices */
222 static struct devicelist alldevs = TAILQ_HEAD_INITIALIZER(alldevs);
223 static kmutex_t alldevs_lock __cacheline_aligned;
224 static devgen_t alldevs_gen = 1;
225 static int alldevs_nread = 0;
226 static int alldevs_nwrite = 0;
227 static bool alldevs_garbage = false;
228
229 static struct devicelist config_pending =
230 TAILQ_HEAD_INITIALIZER(config_pending);
231 static kmutex_t config_misc_lock;
232 static kcondvar_t config_misc_cv;
233
234 static bool detachall = false;
235
236 #define STREQ(s1, s2) \
237 (*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
238
239 static bool config_initialized = false; /* config_init() has been called. */
240
241 static int config_do_twiddle;
242 static callout_t config_twiddle_ch;
243
244 static void sysctl_detach_setup(struct sysctllog **);
245
246 int no_devmon_insert(const char *, prop_dictionary_t);
247 int (*devmon_insert_vec)(const char *, prop_dictionary_t) = no_devmon_insert;
248
249 typedef int (*cfdriver_fn)(struct cfdriver *);
250 static int
251 frob_cfdrivervec(struct cfdriver * const *cfdriverv,
252 cfdriver_fn drv_do, cfdriver_fn drv_undo,
253 const char *style, bool dopanic)
254 {
255 void (*pr)(const char *, ...) __printflike(1, 2) =
256 dopanic ? panic : printf;
257 int i, error = 0, e2 __diagused;
258
259 for (i = 0; cfdriverv[i] != NULL; i++) {
260 if ((error = drv_do(cfdriverv[i])) != 0) {
261 pr("configure: `%s' driver %s failed: %d",
262 cfdriverv[i]->cd_name, style, error);
263 goto bad;
264 }
265 }
266
267 KASSERT(error == 0);
268 return 0;
269
270 bad:
271 printf("\n");
272 for (i--; i >= 0; i--) {
273 e2 = drv_undo(cfdriverv[i]);
274 KASSERT(e2 == 0);
275 }
276
277 return error;
278 }
279
280 typedef int (*cfattach_fn)(const char *, struct cfattach *);
281 static int
282 frob_cfattachvec(const struct cfattachinit *cfattachv,
283 cfattach_fn att_do, cfattach_fn att_undo,
284 const char *style, bool dopanic)
285 {
286 const struct cfattachinit *cfai = NULL;
287 void (*pr)(const char *, ...) __printflike(1, 2) =
288 dopanic ? panic : printf;
289 int j = 0, error = 0, e2 __diagused;
290
291 for (cfai = &cfattachv[0]; cfai->cfai_name != NULL; cfai++) {
292 for (j = 0; cfai->cfai_list[j] != NULL; j++) {
293 if ((error = att_do(cfai->cfai_name,
294 cfai->cfai_list[j])) != 0) {
295 pr("configure: attachment `%s' "
296 "of `%s' driver %s failed: %d",
297 cfai->cfai_list[j]->ca_name,
298 cfai->cfai_name, style, error);
299 goto bad;
300 }
301 }
302 }
303
304 KASSERT(error == 0);
305 return 0;
306
307 bad:
308 /*
309 * Rollback in reverse order. dunno if super-important, but
310 * do that anyway. Although the code looks a little like
311 * someone did a little integration (in the math sense).
312 */
313 printf("\n");
314 if (cfai) {
315 bool last;
316
317 for (last = false; last == false; ) {
318 if (cfai == &cfattachv[0])
319 last = true;
320 for (j--; j >= 0; j--) {
321 e2 = att_undo(cfai->cfai_name,
322 cfai->cfai_list[j]);
323 KASSERT(e2 == 0);
324 }
325 if (!last) {
326 cfai--;
327 for (j = 0; cfai->cfai_list[j] != NULL; j++)
328 ;
329 }
330 }
331 }
332
333 return error;
334 }
335
336 /*
337 * Initialize the autoconfiguration data structures. Normally this
338 * is done by configure(), but some platforms need to do this very
339 * early (to e.g. initialize the console).
340 */
341 void
342 config_init(void)
343 {
344
345 KASSERT(config_initialized == false);
346
347 mutex_init(&alldevs_lock, MUTEX_DEFAULT, IPL_VM);
348
349 mutex_init(&config_misc_lock, MUTEX_DEFAULT, IPL_NONE);
350 cv_init(&config_misc_cv, "cfgmisc");
351
352 callout_init(&config_twiddle_ch, CALLOUT_MPSAFE);
353
354 frob_cfdrivervec(cfdriver_list_initial,
355 config_cfdriver_attach, NULL, "bootstrap", true);
356 frob_cfattachvec(cfattachinit,
357 config_cfattach_attach, NULL, "bootstrap", true);
358
359 initcftable.ct_cfdata = cfdata;
360 TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
361
362 rnd_attach_source(&rnd_autoconf_source, "autoconf", RND_TYPE_UNKNOWN,
363 RND_FLAG_COLLECT_TIME);
364
365 config_initialized = true;
366 }
367
368 /*
369 * Init or fini drivers and attachments. Either all or none
370 * are processed (via rollback). It would be nice if this were
371 * atomic to outside consumers, but with the current state of
372 * locking ...
373 */
374 int
375 config_init_component(struct cfdriver * const *cfdriverv,
376 const struct cfattachinit *cfattachv, struct cfdata *cfdatav)
377 {
378 int error;
379
380 KASSERT(KERNEL_LOCKED_P());
381
382 if ((error = frob_cfdrivervec(cfdriverv,
383 config_cfdriver_attach, config_cfdriver_detach, "init", false))!= 0)
384 return error;
385 if ((error = frob_cfattachvec(cfattachv,
386 config_cfattach_attach, config_cfattach_detach,
387 "init", false)) != 0) {
388 frob_cfdrivervec(cfdriverv,
389 config_cfdriver_detach, NULL, "init rollback", true);
390 return error;
391 }
392 if ((error = config_cfdata_attach(cfdatav, 1)) != 0) {
393 frob_cfattachvec(cfattachv,
394 config_cfattach_detach, NULL, "init rollback", true);
395 frob_cfdrivervec(cfdriverv,
396 config_cfdriver_detach, NULL, "init rollback", true);
397 return error;
398 }
399
400 return 0;
401 }
402
403 int
404 config_fini_component(struct cfdriver * const *cfdriverv,
405 const struct cfattachinit *cfattachv, struct cfdata *cfdatav)
406 {
407 int error;
408
409 KASSERT(KERNEL_LOCKED_P());
410
411 if ((error = config_cfdata_detach(cfdatav)) != 0)
412 return error;
413 if ((error = frob_cfattachvec(cfattachv,
414 config_cfattach_detach, config_cfattach_attach,
415 "fini", false)) != 0) {
416 if (config_cfdata_attach(cfdatav, 0) != 0)
417 panic("config_cfdata fini rollback failed");
418 return error;
419 }
420 if ((error = frob_cfdrivervec(cfdriverv,
421 config_cfdriver_detach, config_cfdriver_attach,
422 "fini", false)) != 0) {
423 frob_cfattachvec(cfattachv,
424 config_cfattach_attach, NULL, "fini rollback", true);
425 if (config_cfdata_attach(cfdatav, 0) != 0)
426 panic("config_cfdata fini rollback failed");
427 return error;
428 }
429
430 return 0;
431 }
432
433 void
434 config_init_mi(void)
435 {
436
437 if (!config_initialized)
438 config_init();
439
440 sysctl_detach_setup(NULL);
441 }
442
443 void
444 config_deferred(device_t dev)
445 {
446
447 KASSERT(KERNEL_LOCKED_P());
448
449 config_process_deferred(&deferred_config_queue, dev);
450 config_process_deferred(&interrupt_config_queue, dev);
451 config_process_deferred(&mountroot_config_queue, dev);
452 }
453
454 static void
455 config_interrupts_thread(void *cookie)
456 {
457 struct deferred_config *dc;
458 device_t dev;
459
460 mutex_enter(&config_misc_lock);
461 while ((dc = TAILQ_FIRST(&interrupt_config_queue)) != NULL) {
462 TAILQ_REMOVE(&interrupt_config_queue, dc, dc_queue);
463 mutex_exit(&config_misc_lock);
464
465 dev = dc->dc_dev;
466 (*dc->dc_func)(dev);
467 if (!device_pmf_is_registered(dev))
468 aprint_debug_dev(dev,
469 "WARNING: power management not supported\n");
470 config_pending_decr(dev);
471 kmem_free(dc, sizeof(*dc));
472
473 mutex_enter(&config_misc_lock);
474 }
475 mutex_exit(&config_misc_lock);
476
477 kthread_exit(0);
478 }
479
480 void
481 config_create_interruptthreads(void)
482 {
483 int i;
484
485 for (i = 0; i < interrupt_config_threads; i++) {
486 (void)kthread_create(PRI_NONE, 0/*XXXSMP */, NULL,
487 config_interrupts_thread, NULL, NULL, "configintr");
488 }
489 }
490
491 static void
492 config_mountroot_thread(void *cookie)
493 {
494 struct deferred_config *dc;
495
496 mutex_enter(&config_misc_lock);
497 while ((dc = TAILQ_FIRST(&mountroot_config_queue)) != NULL) {
498 TAILQ_REMOVE(&mountroot_config_queue, dc, dc_queue);
499 mutex_exit(&config_misc_lock);
500
501 (*dc->dc_func)(dc->dc_dev);
502 kmem_free(dc, sizeof(*dc));
503
504 mutex_enter(&config_misc_lock);
505 }
506 mutex_exit(&config_misc_lock);
507
508 kthread_exit(0);
509 }
510
511 void
512 config_create_mountrootthreads(void)
513 {
514 int i;
515
516 if (!root_is_mounted)
517 root_is_mounted = true;
518
519 mountroot_config_lwpids_size = sizeof(mountroot_config_lwpids) *
520 mountroot_config_threads;
521 mountroot_config_lwpids = kmem_alloc(mountroot_config_lwpids_size,
522 KM_NOSLEEP);
523 KASSERT(mountroot_config_lwpids);
524 for (i = 0; i < mountroot_config_threads; i++) {
525 mountroot_config_lwpids[i] = 0;
526 (void)kthread_create(PRI_NONE, KTHREAD_MUSTJOIN/* XXXSMP */,
527 NULL, config_mountroot_thread, NULL,
528 &mountroot_config_lwpids[i],
529 "configroot");
530 }
531 }
532
533 void
534 config_finalize_mountroot(void)
535 {
536 int i, error;
537
538 for (i = 0; i < mountroot_config_threads; i++) {
539 if (mountroot_config_lwpids[i] == 0)
540 continue;
541
542 error = kthread_join(mountroot_config_lwpids[i]);
543 if (error)
544 printf("%s: thread %x joined with error %d\n",
545 __func__, i, error);
546 }
547 kmem_free(mountroot_config_lwpids, mountroot_config_lwpids_size);
548 }
549
550 /*
551 * Announce device attach/detach to userland listeners.
552 */
553
554 int
555 no_devmon_insert(const char *name, prop_dictionary_t p)
556 {
557
558 return ENODEV;
559 }
560
561 static void
562 devmon_report_device(device_t dev, bool isattach)
563 {
564 prop_dictionary_t ev, dict = device_properties(dev);
565 const char *parent;
566 const char *what;
567 const char *where;
568 device_t pdev = device_parent(dev);
569
570 /* If currently no drvctl device, just return */
571 if (devmon_insert_vec == no_devmon_insert)
572 return;
573
574 ev = prop_dictionary_create();
575 if (ev == NULL)
576 return;
577
578 what = (isattach ? "device-attach" : "device-detach");
579 parent = (pdev == NULL ? "root" : device_xname(pdev));
580 if (prop_dictionary_get_string(dict, "location", &where)) {
581 prop_dictionary_set_string(ev, "location", where);
582 aprint_debug("ev: %s %s at %s in [%s]\n",
583 what, device_xname(dev), parent, where);
584 }
585 if (!prop_dictionary_set_string(ev, "device", device_xname(dev)) ||
586 !prop_dictionary_set_string(ev, "parent", parent)) {
587 prop_object_release(ev);
588 return;
589 }
590
591 if ((*devmon_insert_vec)(what, ev) != 0)
592 prop_object_release(ev);
593 }
594
595 /*
596 * Add a cfdriver to the system.
597 */
598 int
599 config_cfdriver_attach(struct cfdriver *cd)
600 {
601 struct cfdriver *lcd;
602
603 /* Make sure this driver isn't already in the system. */
604 LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
605 if (STREQ(lcd->cd_name, cd->cd_name))
606 return EEXIST;
607 }
608
609 LIST_INIT(&cd->cd_attach);
610 LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
611
612 return 0;
613 }
614
615 /*
616 * Remove a cfdriver from the system.
617 */
618 int
619 config_cfdriver_detach(struct cfdriver *cd)
620 {
621 struct alldevs_foray af;
622 int i, rc = 0;
623
624 config_alldevs_enter(&af);
625 /* Make sure there are no active instances. */
626 for (i = 0; i < cd->cd_ndevs; i++) {
627 if (cd->cd_devs[i] != NULL) {
628 rc = EBUSY;
629 break;
630 }
631 }
632 config_alldevs_exit(&af);
633
634 if (rc != 0)
635 return rc;
636
637 /* ...and no attachments loaded. */
638 if (LIST_EMPTY(&cd->cd_attach) == 0)
639 return EBUSY;
640
641 LIST_REMOVE(cd, cd_list);
642
643 KASSERT(cd->cd_devs == NULL);
644
645 return 0;
646 }
647
648 /*
649 * Look up a cfdriver by name.
650 */
651 struct cfdriver *
652 config_cfdriver_lookup(const char *name)
653 {
654 struct cfdriver *cd;
655
656 LIST_FOREACH(cd, &allcfdrivers, cd_list) {
657 if (STREQ(cd->cd_name, name))
658 return cd;
659 }
660
661 return NULL;
662 }
663
664 /*
665 * Add a cfattach to the specified driver.
666 */
667 int
668 config_cfattach_attach(const char *driver, struct cfattach *ca)
669 {
670 struct cfattach *lca;
671 struct cfdriver *cd;
672
673 cd = config_cfdriver_lookup(driver);
674 if (cd == NULL)
675 return ESRCH;
676
677 /* Make sure this attachment isn't already on this driver. */
678 LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
679 if (STREQ(lca->ca_name, ca->ca_name))
680 return EEXIST;
681 }
682
683 LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
684
685 return 0;
686 }
687
688 /*
689 * Remove a cfattach from the specified driver.
690 */
691 int
692 config_cfattach_detach(const char *driver, struct cfattach *ca)
693 {
694 struct alldevs_foray af;
695 struct cfdriver *cd;
696 device_t dev;
697 int i, rc = 0;
698
699 cd = config_cfdriver_lookup(driver);
700 if (cd == NULL)
701 return ESRCH;
702
703 config_alldevs_enter(&af);
704 /* Make sure there are no active instances. */
705 for (i = 0; i < cd->cd_ndevs; i++) {
706 if ((dev = cd->cd_devs[i]) == NULL)
707 continue;
708 if (dev->dv_cfattach == ca) {
709 rc = EBUSY;
710 break;
711 }
712 }
713 config_alldevs_exit(&af);
714
715 if (rc != 0)
716 return rc;
717
718 LIST_REMOVE(ca, ca_list);
719
720 return 0;
721 }
722
723 /*
724 * Look up a cfattach by name.
725 */
726 static struct cfattach *
727 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
728 {
729 struct cfattach *ca;
730
731 LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
732 if (STREQ(ca->ca_name, atname))
733 return ca;
734 }
735
736 return NULL;
737 }
738
739 /*
740 * Look up a cfattach by driver/attachment name.
741 */
742 struct cfattach *
743 config_cfattach_lookup(const char *name, const char *atname)
744 {
745 struct cfdriver *cd;
746
747 cd = config_cfdriver_lookup(name);
748 if (cd == NULL)
749 return NULL;
750
751 return config_cfattach_lookup_cd(cd, atname);
752 }
753
754 /*
755 * Apply the matching function and choose the best. This is used
756 * a few times and we want to keep the code small.
757 */
758 static void
759 mapply(struct matchinfo *m, cfdata_t cf)
760 {
761 int pri;
762
763 if (m->fn != NULL) {
764 pri = (*m->fn)(m->parent, cf, m->locs, m->aux);
765 } else {
766 pri = config_match(m->parent, cf, m->aux);
767 }
768 if (pri > m->pri) {
769 m->match = cf;
770 m->pri = pri;
771 }
772 }
773
774 int
775 config_stdsubmatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
776 {
777 const struct cfiattrdata *ci;
778 const struct cflocdesc *cl;
779 int nlocs, i;
780
781 ci = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
782 KASSERT(ci);
783 nlocs = ci->ci_loclen;
784 KASSERT(!nlocs || locs);
785 for (i = 0; i < nlocs; i++) {
786 cl = &ci->ci_locdesc[i];
787 if (cl->cld_defaultstr != NULL &&
788 cf->cf_loc[i] == cl->cld_default)
789 continue;
790 if (cf->cf_loc[i] == locs[i])
791 continue;
792 return 0;
793 }
794
795 return config_match(parent, cf, aux);
796 }
797
798 /*
799 * Helper function: check whether the driver supports the interface attribute
800 * and return its descriptor structure.
801 */
802 static const struct cfiattrdata *
803 cfdriver_get_iattr(const struct cfdriver *cd, const char *ia)
804 {
805 const struct cfiattrdata * const *cpp;
806
807 if (cd->cd_attrs == NULL)
808 return 0;
809
810 for (cpp = cd->cd_attrs; *cpp; cpp++) {
811 if (STREQ((*cpp)->ci_name, ia)) {
812 /* Match. */
813 return *cpp;
814 }
815 }
816 return 0;
817 }
818
819 #if defined(DIAGNOSTIC)
820 static int
821 cfdriver_iattr_count(const struct cfdriver *cd)
822 {
823 const struct cfiattrdata * const *cpp;
824 int i;
825
826 if (cd->cd_attrs == NULL)
827 return 0;
828
829 for (i = 0, cpp = cd->cd_attrs; *cpp; cpp++) {
830 i++;
831 }
832 return i;
833 }
834 #endif /* DIAGNOSTIC */
835
836 /*
837 * Lookup an interface attribute description by name.
838 * If the driver is given, consider only its supported attributes.
839 */
840 const struct cfiattrdata *
841 cfiattr_lookup(const char *name, const struct cfdriver *cd)
842 {
843 const struct cfdriver *d;
844 const struct cfiattrdata *ia;
845
846 if (cd)
847 return cfdriver_get_iattr(cd, name);
848
849 LIST_FOREACH(d, &allcfdrivers, cd_list) {
850 ia = cfdriver_get_iattr(d, name);
851 if (ia)
852 return ia;
853 }
854 return 0;
855 }
856
857 /*
858 * Determine if `parent' is a potential parent for a device spec based
859 * on `cfp'.
860 */
861 static int
862 cfparent_match(const device_t parent, const struct cfparent *cfp)
863 {
864 struct cfdriver *pcd;
865
866 /* We don't match root nodes here. */
867 if (cfp == NULL)
868 return 0;
869
870 pcd = parent->dv_cfdriver;
871 KASSERT(pcd != NULL);
872
873 /*
874 * First, ensure this parent has the correct interface
875 * attribute.
876 */
877 if (!cfdriver_get_iattr(pcd, cfp->cfp_iattr))
878 return 0;
879
880 /*
881 * If no specific parent device instance was specified (i.e.
882 * we're attaching to the attribute only), we're done!
883 */
884 if (cfp->cfp_parent == NULL)
885 return 1;
886
887 /*
888 * Check the parent device's name.
889 */
890 if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
891 return 0; /* not the same parent */
892
893 /*
894 * Make sure the unit number matches.
895 */
896 if (cfp->cfp_unit == DVUNIT_ANY || /* wildcard */
897 cfp->cfp_unit == parent->dv_unit)
898 return 1;
899
900 /* Unit numbers don't match. */
901 return 0;
902 }
903
904 /*
905 * Helper for config_cfdata_attach(): check all devices whether it could be
906 * parent any attachment in the config data table passed, and rescan.
907 */
908 static void
909 rescan_with_cfdata(const struct cfdata *cf)
910 {
911 device_t d;
912 const struct cfdata *cf1;
913 deviter_t di;
914
915 KASSERT(KERNEL_LOCKED_P());
916
917 /*
918 * "alldevs" is likely longer than a modules's cfdata, so make it
919 * the outer loop.
920 */
921 for (d = deviter_first(&di, 0); d != NULL; d = deviter_next(&di)) {
922
923 if (!(d->dv_cfattach->ca_rescan))
924 continue;
925
926 for (cf1 = cf; cf1->cf_name; cf1++) {
927
928 if (!cfparent_match(d, cf1->cf_pspec))
929 continue;
930
931 (*d->dv_cfattach->ca_rescan)(d,
932 cfdata_ifattr(cf1), cf1->cf_loc);
933
934 config_deferred(d);
935 }
936 }
937 deviter_release(&di);
938 }
939
940 /*
941 * Attach a supplemental config data table and rescan potential
942 * parent devices if required.
943 */
944 int
945 config_cfdata_attach(cfdata_t cf, int scannow)
946 {
947 struct cftable *ct;
948
949 KASSERT(KERNEL_LOCKED_P());
950
951 ct = kmem_alloc(sizeof(*ct), KM_SLEEP);
952 ct->ct_cfdata = cf;
953 TAILQ_INSERT_TAIL(&allcftables, ct, ct_list);
954
955 if (scannow)
956 rescan_with_cfdata(cf);
957
958 return 0;
959 }
960
961 /*
962 * Helper for config_cfdata_detach: check whether a device is
963 * found through any attachment in the config data table.
964 */
965 static int
966 dev_in_cfdata(device_t d, cfdata_t cf)
967 {
968 const struct cfdata *cf1;
969
970 for (cf1 = cf; cf1->cf_name; cf1++)
971 if (d->dv_cfdata == cf1)
972 return 1;
973
974 return 0;
975 }
976
977 /*
978 * Detach a supplemental config data table. Detach all devices found
979 * through that table (and thus keeping references to it) before.
980 */
981 int
982 config_cfdata_detach(cfdata_t cf)
983 {
984 device_t d;
985 int error = 0;
986 struct cftable *ct;
987 deviter_t di;
988
989 for (d = deviter_first(&di, DEVITER_F_RW); d != NULL;
990 d = deviter_next(&di)) {
991 if (!dev_in_cfdata(d, cf))
992 continue;
993 if ((error = config_detach(d, 0)) != 0)
994 break;
995 }
996 deviter_release(&di);
997 if (error) {
998 aprint_error_dev(d, "unable to detach instance\n");
999 return error;
1000 }
1001
1002 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1003 if (ct->ct_cfdata == cf) {
1004 TAILQ_REMOVE(&allcftables, ct, ct_list);
1005 kmem_free(ct, sizeof(*ct));
1006 return 0;
1007 }
1008 }
1009
1010 /* not found -- shouldn't happen */
1011 return EINVAL;
1012 }
1013
1014 /*
1015 * Invoke the "match" routine for a cfdata entry on behalf of
1016 * an external caller, usually a direct config "submatch" routine.
1017 */
1018 int
1019 config_match(device_t parent, cfdata_t cf, void *aux)
1020 {
1021 struct cfattach *ca;
1022
1023 KASSERT(KERNEL_LOCKED_P());
1024
1025 ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
1026 if (ca == NULL) {
1027 /* No attachment for this entry, oh well. */
1028 return 0;
1029 }
1030
1031 return (*ca->ca_match)(parent, cf, aux);
1032 }
1033
1034 /*
1035 * Invoke the "probe" routine for a cfdata entry on behalf of
1036 * an external caller, usually an indirect config "search" routine.
1037 */
1038 int
1039 config_probe(device_t parent, cfdata_t cf, void *aux)
1040 {
1041 /*
1042 * This is currently a synonym for config_match(), but this
1043 * is an implementation detail; "match" and "probe" routines
1044 * have different behaviors.
1045 *
1046 * XXX config_probe() should return a bool, because there is
1047 * XXX no match score for probe -- it's either there or it's
1048 * XXX not, but some ports abuse the return value as a way
1049 * XXX to attach "critical" devices before "non-critical"
1050 * XXX devices.
1051 */
1052 return config_match(parent, cf, aux);
1053 }
1054
1055 static void
1056 config_get_cfargs(cfarg_t tag,
1057 cfsubmatch_t *fnp, /* output */
1058 const char **ifattrp, /* output */
1059 const int **locsp, /* output */
1060 devhandle_t *handlep, /* output */
1061 va_list ap)
1062 {
1063 cfsubmatch_t fn = NULL;
1064 const char *ifattr = NULL;
1065 const int *locs = NULL;
1066 devhandle_t handle;
1067
1068 devhandle_invalidate(&handle);
1069
1070 while (tag != CFARG_EOL) {
1071 switch (tag) {
1072 /*
1073 * CFARG_SUBMATCH and CFARG_SEARCH are synonyms, but this
1074 * is merely an implementation detail. They are distinct
1075 * from the caller's point of view.
1076 */
1077 case CFARG_SUBMATCH:
1078 case CFARG_SEARCH:
1079 /* Only allow one function to be specified. */
1080 if (fn != NULL) {
1081 panic("%s: caller specified both "
1082 "SUBMATCH and SEARCH", __func__);
1083 }
1084 fn = va_arg(ap, cfsubmatch_t);
1085 break;
1086
1087 case CFARG_IATTR:
1088 ifattr = va_arg(ap, const char *);
1089 break;
1090
1091 case CFARG_LOCATORS:
1092 locs = va_arg(ap, const int *);
1093 break;
1094
1095 case CFARG_DEVHANDLE:
1096 handle = va_arg(ap, devhandle_t);
1097 break;
1098
1099 default:
1100 panic("%s: unknown cfarg tag: %d\n",
1101 __func__, tag);
1102 }
1103 tag = va_arg(ap, cfarg_t);
1104 }
1105
1106 if (fnp != NULL)
1107 *fnp = fn;
1108 if (ifattrp != NULL)
1109 *ifattrp = ifattr;
1110 if (locsp != NULL)
1111 *locsp = locs;
1112 if (handlep != NULL)
1113 *handlep = handle;
1114 }
1115
1116 /*
1117 * Iterate over all potential children of some device, calling the given
1118 * function (default being the child's match function) for each one.
1119 * Nonzero returns are matches; the highest value returned is considered
1120 * the best match. Return the `found child' if we got a match, or NULL
1121 * otherwise. The `aux' pointer is simply passed on through.
1122 *
1123 * Note that this function is designed so that it can be used to apply
1124 * an arbitrary function to all potential children (its return value
1125 * can be ignored).
1126 */
1127 cfdata_t
1128 config_vsearch(device_t parent, void *aux, cfarg_t tag, va_list ap)
1129 {
1130 cfsubmatch_t fn;
1131 const char *ifattr;
1132 const int *locs;
1133 struct cftable *ct;
1134 cfdata_t cf;
1135 struct matchinfo m;
1136
1137 config_get_cfargs(tag, &fn, &ifattr, &locs, NULL, ap);
1138
1139 KASSERT(config_initialized);
1140 KASSERT(!ifattr || cfdriver_get_iattr(parent->dv_cfdriver, ifattr));
1141 KASSERT(ifattr || cfdriver_iattr_count(parent->dv_cfdriver) < 2);
1142
1143 m.fn = fn;
1144 m.parent = parent;
1145 m.locs = locs;
1146 m.aux = aux;
1147 m.match = NULL;
1148 m.pri = 0;
1149
1150 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1151 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1152
1153 /* We don't match root nodes here. */
1154 if (!cf->cf_pspec)
1155 continue;
1156
1157 /*
1158 * Skip cf if no longer eligible, otherwise scan
1159 * through parents for one matching `parent', and
1160 * try match function.
1161 */
1162 if (cf->cf_fstate == FSTATE_FOUND)
1163 continue;
1164 if (cf->cf_fstate == FSTATE_DNOTFOUND ||
1165 cf->cf_fstate == FSTATE_DSTAR)
1166 continue;
1167
1168 /*
1169 * If an interface attribute was specified,
1170 * consider only children which attach to
1171 * that attribute.
1172 */
1173 if (ifattr && !STREQ(ifattr, cfdata_ifattr(cf)))
1174 continue;
1175
1176 if (cfparent_match(parent, cf->cf_pspec))
1177 mapply(&m, cf);
1178 }
1179 }
1180 return m.match;
1181 }
1182
1183 cfdata_t
1184 config_search(device_t parent, void *aux, cfarg_t tag, ...)
1185 {
1186 cfdata_t cf;
1187 va_list ap;
1188
1189 va_start(ap, tag);
1190 cf = config_vsearch(parent, aux, tag, ap);
1191 va_end(ap);
1192
1193 return cf;
1194 }
1195
1196 /*
1197 * Find the given root device.
1198 * This is much like config_search, but there is no parent.
1199 * Don't bother with multiple cfdata tables; the root node
1200 * must always be in the initial table.
1201 */
1202 cfdata_t
1203 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
1204 {
1205 cfdata_t cf;
1206 const short *p;
1207 struct matchinfo m;
1208
1209 m.fn = fn;
1210 m.parent = ROOT;
1211 m.aux = aux;
1212 m.match = NULL;
1213 m.pri = 0;
1214 m.locs = 0;
1215 /*
1216 * Look at root entries for matching name. We do not bother
1217 * with found-state here since only one root should ever be
1218 * searched (and it must be done first).
1219 */
1220 for (p = cfroots; *p >= 0; p++) {
1221 cf = &cfdata[*p];
1222 if (strcmp(cf->cf_name, rootname) == 0)
1223 mapply(&m, cf);
1224 }
1225 return m.match;
1226 }
1227
1228 static const char * const msgs[] = {
1229 [QUIET] = "",
1230 [UNCONF] = " not configured\n",
1231 [UNSUPP] = " unsupported\n",
1232 };
1233
1234 /*
1235 * The given `aux' argument describes a device that has been found
1236 * on the given parent, but not necessarily configured. Locate the
1237 * configuration data for that device (using the submatch function
1238 * provided, or using candidates' cd_match configuration driver
1239 * functions) and attach it, and return its device_t. If the device was
1240 * not configured, call the given `print' function and return NULL.
1241 */
1242 device_t
1243 config_vfound(device_t parent, void *aux, cfprint_t print, cfarg_t tag,
1244 va_list ap)
1245 {
1246 cfdata_t cf;
1247 va_list nap;
1248
1249 va_copy(nap, ap);
1250 cf = config_vsearch(parent, aux, tag, nap);
1251 va_end(nap);
1252
1253 if (cf != NULL) {
1254 return config_vattach(parent, cf, aux, print, tag, ap);
1255 }
1256
1257 if (print) {
1258 if (config_do_twiddle && cold)
1259 twiddle();
1260
1261 const int pret = (*print)(aux, device_xname(parent));
1262 KASSERT(pret >= 0);
1263 KASSERT(pret < __arraycount(msgs));
1264 KASSERT(msgs[pret] != NULL);
1265 aprint_normal("%s", msgs[pret]);
1266 }
1267
1268 /*
1269 * This has the effect of mixing in a single timestamp to the
1270 * entropy pool. Experiments indicate the estimator will almost
1271 * always attribute one bit of entropy to this sample; analysis
1272 * of device attach/detach timestamps on FreeBSD indicates 4
1273 * bits of entropy/sample so this seems appropriately conservative.
1274 */
1275 rnd_add_uint32(&rnd_autoconf_source, 0);
1276 return NULL;
1277 }
1278
1279 device_t
1280 config_found(device_t parent, void *aux, cfprint_t print, cfarg_t tag, ...)
1281 {
1282 device_t dev;
1283 va_list ap;
1284
1285 va_start(ap, tag);
1286 dev = config_vfound(parent, aux, print, tag, ap);
1287 va_end(ap);
1288
1289 return dev;
1290 }
1291
1292 /*
1293 * As above, but for root devices.
1294 */
1295 device_t
1296 config_rootfound(const char *rootname, void *aux)
1297 {
1298 cfdata_t cf;
1299 device_t dev = NULL;
1300
1301 KERNEL_LOCK(1, NULL);
1302 if ((cf = config_rootsearch(NULL, rootname, aux)) != NULL)
1303 dev = config_attach(ROOT, cf, aux, NULL, CFARG_EOL);
1304 else
1305 aprint_error("root device %s not configured\n", rootname);
1306 KERNEL_UNLOCK_ONE(NULL);
1307 return dev;
1308 }
1309
1310 /* just like sprintf(buf, "%d") except that it works from the end */
1311 static char *
1312 number(char *ep, int n)
1313 {
1314
1315 *--ep = 0;
1316 while (n >= 10) {
1317 *--ep = (n % 10) + '0';
1318 n /= 10;
1319 }
1320 *--ep = n + '0';
1321 return ep;
1322 }
1323
1324 /*
1325 * Expand the size of the cd_devs array if necessary.
1326 *
1327 * The caller must hold alldevs_lock. config_makeroom() may release and
1328 * re-acquire alldevs_lock, so callers should re-check conditions such
1329 * as alldevs_nwrite == 0 and alldevs_nread == 0 when config_makeroom()
1330 * returns.
1331 */
1332 static void
1333 config_makeroom(int n, struct cfdriver *cd)
1334 {
1335 int ondevs, nndevs;
1336 device_t *osp, *nsp;
1337
1338 KASSERT(mutex_owned(&alldevs_lock));
1339 alldevs_nwrite++;
1340
1341 for (nndevs = MAX(4, cd->cd_ndevs); nndevs <= n; nndevs += nndevs)
1342 ;
1343
1344 while (n >= cd->cd_ndevs) {
1345 /*
1346 * Need to expand the array.
1347 */
1348 ondevs = cd->cd_ndevs;
1349 osp = cd->cd_devs;
1350
1351 /*
1352 * Release alldevs_lock around allocation, which may
1353 * sleep.
1354 */
1355 mutex_exit(&alldevs_lock);
1356 nsp = kmem_alloc(sizeof(device_t) * nndevs, KM_SLEEP);
1357 mutex_enter(&alldevs_lock);
1358
1359 /*
1360 * If another thread moved the array while we did
1361 * not hold alldevs_lock, try again.
1362 */
1363 if (cd->cd_devs != osp) {
1364 mutex_exit(&alldevs_lock);
1365 kmem_free(nsp, sizeof(device_t) * nndevs);
1366 mutex_enter(&alldevs_lock);
1367 continue;
1368 }
1369
1370 memset(nsp + ondevs, 0, sizeof(device_t) * (nndevs - ondevs));
1371 if (ondevs != 0)
1372 memcpy(nsp, cd->cd_devs, sizeof(device_t) * ondevs);
1373
1374 cd->cd_ndevs = nndevs;
1375 cd->cd_devs = nsp;
1376 if (ondevs != 0) {
1377 mutex_exit(&alldevs_lock);
1378 kmem_free(osp, sizeof(device_t) * ondevs);
1379 mutex_enter(&alldevs_lock);
1380 }
1381 }
1382 KASSERT(mutex_owned(&alldevs_lock));
1383 alldevs_nwrite--;
1384 }
1385
1386 /*
1387 * Put dev into the devices list.
1388 */
1389 static void
1390 config_devlink(device_t dev)
1391 {
1392
1393 mutex_enter(&alldevs_lock);
1394
1395 KASSERT(device_cfdriver(dev)->cd_devs[dev->dv_unit] == dev);
1396
1397 dev->dv_add_gen = alldevs_gen;
1398 /* It is safe to add a device to the tail of the list while
1399 * readers and writers are in the list.
1400 */
1401 TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);
1402 mutex_exit(&alldevs_lock);
1403 }
1404
1405 static void
1406 config_devfree(device_t dev)
1407 {
1408 KASSERT(dev->dv_flags & DVF_PRIV_ALLOC);
1409
1410 if (dev->dv_cfattach->ca_devsize > 0)
1411 kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
1412 kmem_free(dev, sizeof(*dev));
1413 }
1414
1415 /*
1416 * Caller must hold alldevs_lock.
1417 */
1418 static void
1419 config_devunlink(device_t dev, struct devicelist *garbage)
1420 {
1421 struct device_garbage *dg = &dev->dv_garbage;
1422 cfdriver_t cd = device_cfdriver(dev);
1423 int i;
1424
1425 KASSERT(mutex_owned(&alldevs_lock));
1426
1427 /* Unlink from device list. Link to garbage list. */
1428 TAILQ_REMOVE(&alldevs, dev, dv_list);
1429 TAILQ_INSERT_TAIL(garbage, dev, dv_list);
1430
1431 /* Remove from cfdriver's array. */
1432 cd->cd_devs[dev->dv_unit] = NULL;
1433
1434 /*
1435 * If the device now has no units in use, unlink its softc array.
1436 */
1437 for (i = 0; i < cd->cd_ndevs; i++) {
1438 if (cd->cd_devs[i] != NULL)
1439 break;
1440 }
1441 /* Nothing found. Unlink, now. Deallocate, later. */
1442 if (i == cd->cd_ndevs) {
1443 dg->dg_ndevs = cd->cd_ndevs;
1444 dg->dg_devs = cd->cd_devs;
1445 cd->cd_devs = NULL;
1446 cd->cd_ndevs = 0;
1447 }
1448 }
1449
1450 static void
1451 config_devdelete(device_t dev)
1452 {
1453 struct device_garbage *dg = &dev->dv_garbage;
1454 device_lock_t dvl = device_getlock(dev);
1455
1456 if (dg->dg_devs != NULL)
1457 kmem_free(dg->dg_devs, sizeof(device_t) * dg->dg_ndevs);
1458
1459 cv_destroy(&dvl->dvl_cv);
1460 mutex_destroy(&dvl->dvl_mtx);
1461
1462 KASSERT(dev->dv_properties != NULL);
1463 prop_object_release(dev->dv_properties);
1464
1465 if (dev->dv_activity_handlers)
1466 panic("%s with registered handlers", __func__);
1467
1468 if (dev->dv_locators) {
1469 size_t amount = *--dev->dv_locators;
1470 kmem_free(dev->dv_locators, amount);
1471 }
1472
1473 config_devfree(dev);
1474 }
1475
1476 static int
1477 config_unit_nextfree(cfdriver_t cd, cfdata_t cf)
1478 {
1479 int unit;
1480
1481 if (cf->cf_fstate == FSTATE_STAR) {
1482 for (unit = cf->cf_unit; unit < cd->cd_ndevs; unit++)
1483 if (cd->cd_devs[unit] == NULL)
1484 break;
1485 /*
1486 * unit is now the unit of the first NULL device pointer,
1487 * or max(cd->cd_ndevs,cf->cf_unit).
1488 */
1489 } else {
1490 unit = cf->cf_unit;
1491 if (unit < cd->cd_ndevs && cd->cd_devs[unit] != NULL)
1492 unit = -1;
1493 }
1494 return unit;
1495 }
1496
1497 static int
1498 config_unit_alloc(device_t dev, cfdriver_t cd, cfdata_t cf)
1499 {
1500 struct alldevs_foray af;
1501 int unit;
1502
1503 config_alldevs_enter(&af);
1504 for (;;) {
1505 unit = config_unit_nextfree(cd, cf);
1506 if (unit == -1)
1507 break;
1508 if (unit < cd->cd_ndevs) {
1509 cd->cd_devs[unit] = dev;
1510 dev->dv_unit = unit;
1511 break;
1512 }
1513 config_makeroom(unit, cd);
1514 }
1515 config_alldevs_exit(&af);
1516
1517 return unit;
1518 }
1519
1520 static device_t
1521 config_vdevalloc(const device_t parent, const cfdata_t cf, cfarg_t tag,
1522 va_list ap)
1523 {
1524 cfdriver_t cd;
1525 cfattach_t ca;
1526 size_t lname, lunit;
1527 const char *xunit;
1528 int myunit;
1529 char num[10];
1530 device_t dev;
1531 void *dev_private;
1532 const struct cfiattrdata *ia;
1533 device_lock_t dvl;
1534 const int *locs;
1535
1536 cd = config_cfdriver_lookup(cf->cf_name);
1537 if (cd == NULL)
1538 return NULL;
1539
1540 ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1541 if (ca == NULL)
1542 return NULL;
1543
1544 /* get memory for all device vars */
1545 KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
1546 if (ca->ca_devsize > 0) {
1547 dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
1548 } else {
1549 dev_private = NULL;
1550 }
1551 dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1552
1553 /*
1554 * If a handle was supplied to config_attach(), we'll get it
1555 * assigned automatically here. If not, then we'll get the
1556 * default invalid handle.
1557 */
1558 config_get_cfargs(tag, NULL, NULL, &locs, &dev->dv_handle, ap);
1559
1560 dev->dv_class = cd->cd_class;
1561 dev->dv_cfdata = cf;
1562 dev->dv_cfdriver = cd;
1563 dev->dv_cfattach = ca;
1564 dev->dv_activity_count = 0;
1565 dev->dv_activity_handlers = NULL;
1566 dev->dv_private = dev_private;
1567 dev->dv_flags = ca->ca_flags; /* inherit flags from class */
1568
1569 myunit = config_unit_alloc(dev, cd, cf);
1570 if (myunit == -1) {
1571 config_devfree(dev);
1572 return NULL;
1573 }
1574
1575 /* compute length of name and decimal expansion of unit number */
1576 lname = strlen(cd->cd_name);
1577 xunit = number(&num[sizeof(num)], myunit);
1578 lunit = &num[sizeof(num)] - xunit;
1579 if (lname + lunit > sizeof(dev->dv_xname))
1580 panic("config_vdevalloc: device name too long");
1581
1582 dvl = device_getlock(dev);
1583
1584 mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
1585 cv_init(&dvl->dvl_cv, "pmfsusp");
1586
1587 memcpy(dev->dv_xname, cd->cd_name, lname);
1588 memcpy(dev->dv_xname + lname, xunit, lunit);
1589 dev->dv_parent = parent;
1590 if (parent != NULL)
1591 dev->dv_depth = parent->dv_depth + 1;
1592 else
1593 dev->dv_depth = 0;
1594 dev->dv_flags |= DVF_ACTIVE; /* always initially active */
1595 if (locs) {
1596 KASSERT(parent); /* no locators at root */
1597 ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
1598 dev->dv_locators =
1599 kmem_alloc(sizeof(int) * (ia->ci_loclen + 1), KM_SLEEP);
1600 *dev->dv_locators++ = sizeof(int) * (ia->ci_loclen + 1);
1601 memcpy(dev->dv_locators, locs, sizeof(int) * ia->ci_loclen);
1602 }
1603 dev->dv_properties = prop_dictionary_create();
1604 KASSERT(dev->dv_properties != NULL);
1605
1606 prop_dictionary_set_string_nocopy(dev->dv_properties,
1607 "device-driver", dev->dv_cfdriver->cd_name);
1608 prop_dictionary_set_uint16(dev->dv_properties,
1609 "device-unit", dev->dv_unit);
1610 if (parent != NULL) {
1611 prop_dictionary_set_string(dev->dv_properties,
1612 "device-parent", device_xname(parent));
1613 }
1614
1615 if (dev->dv_cfdriver->cd_attrs != NULL)
1616 config_add_attrib_dict(dev);
1617
1618 return dev;
1619 }
1620
1621 static device_t
1622 config_devalloc(const device_t parent, const cfdata_t cf, cfarg_t tag, ...)
1623 {
1624 device_t dev;
1625 va_list ap;
1626
1627 va_start(ap, tag);
1628 dev = config_vdevalloc(parent, cf, tag, ap);
1629 va_end(ap);
1630
1631 return dev;
1632 }
1633
1634 /*
1635 * Create an array of device attach attributes and add it
1636 * to the device's dv_properties dictionary.
1637 *
1638 * <key>interface-attributes</key>
1639 * <array>
1640 * <dict>
1641 * <key>attribute-name</key>
1642 * <string>foo</string>
1643 * <key>locators</key>
1644 * <array>
1645 * <dict>
1646 * <key>loc-name</key>
1647 * <string>foo-loc1</string>
1648 * </dict>
1649 * <dict>
1650 * <key>loc-name</key>
1651 * <string>foo-loc2</string>
1652 * <key>default</key>
1653 * <string>foo-loc2-default</string>
1654 * </dict>
1655 * ...
1656 * </array>
1657 * </dict>
1658 * ...
1659 * </array>
1660 */
1661
1662 static void
1663 config_add_attrib_dict(device_t dev)
1664 {
1665 int i, j;
1666 const struct cfiattrdata *ci;
1667 prop_dictionary_t attr_dict, loc_dict;
1668 prop_array_t attr_array, loc_array;
1669
1670 if ((attr_array = prop_array_create()) == NULL)
1671 return;
1672
1673 for (i = 0; ; i++) {
1674 if ((ci = dev->dv_cfdriver->cd_attrs[i]) == NULL)
1675 break;
1676 if ((attr_dict = prop_dictionary_create()) == NULL)
1677 break;
1678 prop_dictionary_set_string_nocopy(attr_dict, "attribute-name",
1679 ci->ci_name);
1680
1681 /* Create an array of the locator names and defaults */
1682
1683 if (ci->ci_loclen != 0 &&
1684 (loc_array = prop_array_create()) != NULL) {
1685 for (j = 0; j < ci->ci_loclen; j++) {
1686 loc_dict = prop_dictionary_create();
1687 if (loc_dict == NULL)
1688 continue;
1689 prop_dictionary_set_string_nocopy(loc_dict,
1690 "loc-name", ci->ci_locdesc[j].cld_name);
1691 if (ci->ci_locdesc[j].cld_defaultstr != NULL)
1692 prop_dictionary_set_string_nocopy(
1693 loc_dict, "default",
1694 ci->ci_locdesc[j].cld_defaultstr);
1695 prop_array_set(loc_array, j, loc_dict);
1696 prop_object_release(loc_dict);
1697 }
1698 prop_dictionary_set_and_rel(attr_dict, "locators",
1699 loc_array);
1700 }
1701 prop_array_add(attr_array, attr_dict);
1702 prop_object_release(attr_dict);
1703 }
1704 if (i == 0)
1705 prop_object_release(attr_array);
1706 else
1707 prop_dictionary_set_and_rel(dev->dv_properties,
1708 "interface-attributes", attr_array);
1709
1710 return;
1711 }
1712
1713 /*
1714 * Attach a found device.
1715 */
1716 device_t
1717 config_vattach(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1718 cfarg_t tag, va_list ap)
1719 {
1720 device_t dev;
1721 struct cftable *ct;
1722 const char *drvname;
1723 bool deferred;
1724
1725 KASSERT(KERNEL_LOCKED_P());
1726
1727 dev = config_vdevalloc(parent, cf, tag, ap);
1728 if (!dev)
1729 panic("config_attach: allocation of device softc failed");
1730
1731 /* XXX redundant - see below? */
1732 if (cf->cf_fstate != FSTATE_STAR) {
1733 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1734 cf->cf_fstate = FSTATE_FOUND;
1735 }
1736
1737 config_devlink(dev);
1738
1739 if (config_do_twiddle && cold)
1740 twiddle();
1741 else
1742 aprint_naive("Found ");
1743 /*
1744 * We want the next two printfs for normal, verbose, and quiet,
1745 * but not silent (in which case, we're twiddling, instead).
1746 */
1747 if (parent == ROOT) {
1748 aprint_naive("%s (root)", device_xname(dev));
1749 aprint_normal("%s (root)", device_xname(dev));
1750 } else {
1751 aprint_naive("%s at %s", device_xname(dev),
1752 device_xname(parent));
1753 aprint_normal("%s at %s", device_xname(dev),
1754 device_xname(parent));
1755 if (print)
1756 (void) (*print)(aux, NULL);
1757 }
1758
1759 /*
1760 * Before attaching, clobber any unfound devices that are
1761 * otherwise identical.
1762 * XXX code above is redundant?
1763 */
1764 drvname = dev->dv_cfdriver->cd_name;
1765 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1766 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1767 if (STREQ(cf->cf_name, drvname) &&
1768 cf->cf_unit == dev->dv_unit) {
1769 if (cf->cf_fstate == FSTATE_NOTFOUND)
1770 cf->cf_fstate = FSTATE_FOUND;
1771 }
1772 }
1773 }
1774 device_register(dev, aux);
1775
1776 /* Let userland know */
1777 devmon_report_device(dev, true);
1778
1779 config_pending_incr(dev);
1780 (*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1781 config_pending_decr(dev);
1782
1783 mutex_enter(&config_misc_lock);
1784 deferred = (dev->dv_pending != 0);
1785 mutex_exit(&config_misc_lock);
1786
1787 if (!deferred && !device_pmf_is_registered(dev))
1788 aprint_debug_dev(dev,
1789 "WARNING: power management not supported\n");
1790
1791 config_process_deferred(&deferred_config_queue, dev);
1792
1793 device_register_post_config(dev, aux);
1794 return dev;
1795 }
1796
1797 device_t
1798 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1799 cfarg_t tag, ...)
1800 {
1801 device_t dev;
1802 va_list ap;
1803
1804 KASSERT(KERNEL_LOCKED_P());
1805
1806 va_start(ap, tag);
1807 dev = config_vattach(parent, cf, aux, print, tag, ap);
1808 va_end(ap);
1809
1810 return dev;
1811 }
1812
1813 /*
1814 * As above, but for pseudo-devices. Pseudo-devices attached in this
1815 * way are silently inserted into the device tree, and their children
1816 * attached.
1817 *
1818 * Note that because pseudo-devices are attached silently, any information
1819 * the attach routine wishes to print should be prefixed with the device
1820 * name by the attach routine.
1821 */
1822 device_t
1823 config_attach_pseudo(cfdata_t cf)
1824 {
1825 device_t dev;
1826
1827 KASSERT(KERNEL_LOCKED_P());
1828
1829 dev = config_devalloc(ROOT, cf, CFARG_EOL);
1830 if (!dev)
1831 return NULL;
1832
1833 /* XXX mark busy in cfdata */
1834
1835 if (cf->cf_fstate != FSTATE_STAR) {
1836 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1837 cf->cf_fstate = FSTATE_FOUND;
1838 }
1839
1840 config_devlink(dev);
1841
1842 #if 0 /* XXXJRT not yet */
1843 device_register(dev, NULL); /* like a root node */
1844 #endif
1845
1846 /* Let userland know */
1847 devmon_report_device(dev, true);
1848
1849 config_pending_incr(dev);
1850 (*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1851 config_pending_decr(dev);
1852
1853 config_process_deferred(&deferred_config_queue, dev);
1854 return dev;
1855 }
1856
1857 /*
1858 * Caller must hold alldevs_lock.
1859 */
1860 static void
1861 config_collect_garbage(struct devicelist *garbage)
1862 {
1863 device_t dv;
1864
1865 KASSERT(!cpu_intr_p());
1866 KASSERT(!cpu_softintr_p());
1867 KASSERT(mutex_owned(&alldevs_lock));
1868
1869 while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
1870 TAILQ_FOREACH(dv, &alldevs, dv_list) {
1871 if (dv->dv_del_gen != 0)
1872 break;
1873 }
1874 if (dv == NULL) {
1875 alldevs_garbage = false;
1876 break;
1877 }
1878 config_devunlink(dv, garbage);
1879 }
1880 KASSERT(mutex_owned(&alldevs_lock));
1881 }
1882
1883 static void
1884 config_dump_garbage(struct devicelist *garbage)
1885 {
1886 device_t dv;
1887
1888 while ((dv = TAILQ_FIRST(garbage)) != NULL) {
1889 TAILQ_REMOVE(garbage, dv, dv_list);
1890 config_devdelete(dv);
1891 }
1892 }
1893
1894 static int
1895 config_detach_enter(device_t dev)
1896 {
1897 int error;
1898
1899 mutex_enter(&config_misc_lock);
1900 for (;;) {
1901 if (dev->dv_pending == 0 && dev->dv_detaching == NULL) {
1902 dev->dv_detaching = curlwp;
1903 error = 0;
1904 break;
1905 }
1906 KASSERTMSG(dev->dv_detaching != curlwp,
1907 "recursively detaching %s", device_xname(dev));
1908 error = cv_wait_sig(&config_misc_cv, &config_misc_lock);
1909 if (error)
1910 break;
1911 }
1912 KASSERT(error || dev->dv_detaching == curlwp);
1913 mutex_exit(&config_misc_lock);
1914
1915 return error;
1916 }
1917
1918 static void
1919 config_detach_exit(device_t dev)
1920 {
1921
1922 mutex_enter(&config_misc_lock);
1923 KASSERT(dev->dv_detaching == curlwp);
1924 dev->dv_detaching = NULL;
1925 cv_broadcast(&config_misc_cv);
1926 mutex_exit(&config_misc_lock);
1927 }
1928
1929 /*
1930 * Detach a device. Optionally forced (e.g. because of hardware
1931 * removal) and quiet. Returns zero if successful, non-zero
1932 * (an error code) otherwise.
1933 *
1934 * Note that this code wants to be run from a process context, so
1935 * that the detach can sleep to allow processes which have a device
1936 * open to run and unwind their stacks.
1937 */
1938 int
1939 config_detach(device_t dev, int flags)
1940 {
1941 struct alldevs_foray af;
1942 struct cftable *ct;
1943 cfdata_t cf;
1944 const struct cfattach *ca;
1945 struct cfdriver *cd;
1946 device_t d __diagused;
1947 int rv = 0;
1948
1949 KASSERT(KERNEL_LOCKED_P());
1950
1951 cf = dev->dv_cfdata;
1952 KASSERTMSG((cf == NULL || cf->cf_fstate == FSTATE_FOUND ||
1953 cf->cf_fstate == FSTATE_STAR),
1954 "config_detach: %s: bad device fstate: %d",
1955 device_xname(dev), cf ? cf->cf_fstate : -1);
1956
1957 cd = dev->dv_cfdriver;
1958 KASSERT(cd != NULL);
1959
1960 ca = dev->dv_cfattach;
1961 KASSERT(ca != NULL);
1962
1963 /*
1964 * Only one detach at a time, please -- and not until fully
1965 * attached.
1966 */
1967 rv = config_detach_enter(dev);
1968 if (rv)
1969 return rv;
1970
1971 mutex_enter(&alldevs_lock);
1972 if (dev->dv_del_gen != 0) {
1973 mutex_exit(&alldevs_lock);
1974 #ifdef DIAGNOSTIC
1975 printf("%s: %s is already detached\n", __func__,
1976 device_xname(dev));
1977 #endif /* DIAGNOSTIC */
1978 config_detach_exit(dev);
1979 return ENOENT;
1980 }
1981 alldevs_nwrite++;
1982 mutex_exit(&alldevs_lock);
1983
1984 if (!detachall &&
1985 (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
1986 (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
1987 rv = EOPNOTSUPP;
1988 } else if (ca->ca_detach != NULL) {
1989 rv = (*ca->ca_detach)(dev, flags);
1990 } else
1991 rv = EOPNOTSUPP;
1992
1993 /*
1994 * If it was not possible to detach the device, then we either
1995 * panic() (for the forced but failed case), or return an error.
1996 *
1997 * If it was possible to detach the device, ensure that the
1998 * device is deactivated.
1999 */
2000 if (rv == 0)
2001 dev->dv_flags &= ~DVF_ACTIVE;
2002 else if ((flags & DETACH_FORCE) == 0)
2003 goto out;
2004 else {
2005 panic("config_detach: forced detach of %s failed (%d)",
2006 device_xname(dev), rv);
2007 }
2008
2009 /*
2010 * The device has now been successfully detached.
2011 */
2012
2013 /* Let userland know */
2014 devmon_report_device(dev, false);
2015
2016 #ifdef DIAGNOSTIC
2017 /*
2018 * Sanity: If you're successfully detached, you should have no
2019 * children. (Note that because children must be attached
2020 * after parents, we only need to search the latter part of
2021 * the list.)
2022 */
2023 for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
2024 d = TAILQ_NEXT(d, dv_list)) {
2025 if (d->dv_parent == dev && d->dv_del_gen == 0) {
2026 printf("config_detach: detached device %s"
2027 " has children %s\n", device_xname(dev),
2028 device_xname(d));
2029 panic("config_detach");
2030 }
2031 }
2032 #endif
2033
2034 /* notify the parent that the child is gone */
2035 if (dev->dv_parent) {
2036 device_t p = dev->dv_parent;
2037 if (p->dv_cfattach->ca_childdetached)
2038 (*p->dv_cfattach->ca_childdetached)(p, dev);
2039 }
2040
2041 /*
2042 * Mark cfdata to show that the unit can be reused, if possible.
2043 */
2044 TAILQ_FOREACH(ct, &allcftables, ct_list) {
2045 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
2046 if (STREQ(cf->cf_name, cd->cd_name)) {
2047 if (cf->cf_fstate == FSTATE_FOUND &&
2048 cf->cf_unit == dev->dv_unit)
2049 cf->cf_fstate = FSTATE_NOTFOUND;
2050 }
2051 }
2052 }
2053
2054 if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
2055 aprint_normal_dev(dev, "detached\n");
2056
2057 out:
2058 config_detach_exit(dev);
2059
2060 config_alldevs_enter(&af);
2061 KASSERT(alldevs_nwrite != 0);
2062 --alldevs_nwrite;
2063 if (rv == 0 && dev->dv_del_gen == 0) {
2064 if (alldevs_nwrite == 0 && alldevs_nread == 0)
2065 config_devunlink(dev, &af.af_garbage);
2066 else {
2067 dev->dv_del_gen = alldevs_gen;
2068 alldevs_garbage = true;
2069 }
2070 }
2071 config_alldevs_exit(&af);
2072
2073 return rv;
2074 }
2075
2076 int
2077 config_detach_children(device_t parent, int flags)
2078 {
2079 device_t dv;
2080 deviter_t di;
2081 int error = 0;
2082
2083 KASSERT(KERNEL_LOCKED_P());
2084
2085 for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
2086 dv = deviter_next(&di)) {
2087 if (device_parent(dv) != parent)
2088 continue;
2089 if ((error = config_detach(dv, flags)) != 0)
2090 break;
2091 }
2092 deviter_release(&di);
2093 return error;
2094 }
2095
2096 device_t
2097 shutdown_first(struct shutdown_state *s)
2098 {
2099 if (!s->initialized) {
2100 deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
2101 s->initialized = true;
2102 }
2103 return shutdown_next(s);
2104 }
2105
2106 device_t
2107 shutdown_next(struct shutdown_state *s)
2108 {
2109 device_t dv;
2110
2111 while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
2112 ;
2113
2114 if (dv == NULL)
2115 s->initialized = false;
2116
2117 return dv;
2118 }
2119
2120 bool
2121 config_detach_all(int how)
2122 {
2123 static struct shutdown_state s;
2124 device_t curdev;
2125 bool progress = false;
2126 int flags;
2127
2128 KERNEL_LOCK(1, NULL);
2129
2130 if ((how & (RB_NOSYNC|RB_DUMP)) != 0)
2131 goto out;
2132
2133 if ((how & RB_POWERDOWN) == RB_POWERDOWN)
2134 flags = DETACH_SHUTDOWN | DETACH_POWEROFF;
2135 else
2136 flags = DETACH_SHUTDOWN;
2137
2138 for (curdev = shutdown_first(&s); curdev != NULL;
2139 curdev = shutdown_next(&s)) {
2140 aprint_debug(" detaching %s, ", device_xname(curdev));
2141 if (config_detach(curdev, flags) == 0) {
2142 progress = true;
2143 aprint_debug("success.");
2144 } else
2145 aprint_debug("failed.");
2146 }
2147
2148 out: KERNEL_UNLOCK_ONE(NULL);
2149 return progress;
2150 }
2151
2152 static bool
2153 device_is_ancestor_of(device_t ancestor, device_t descendant)
2154 {
2155 device_t dv;
2156
2157 for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
2158 if (device_parent(dv) == ancestor)
2159 return true;
2160 }
2161 return false;
2162 }
2163
2164 int
2165 config_deactivate(device_t dev)
2166 {
2167 deviter_t di;
2168 const struct cfattach *ca;
2169 device_t descendant;
2170 int s, rv = 0, oflags;
2171
2172 for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
2173 descendant != NULL;
2174 descendant = deviter_next(&di)) {
2175 if (dev != descendant &&
2176 !device_is_ancestor_of(dev, descendant))
2177 continue;
2178
2179 if ((descendant->dv_flags & DVF_ACTIVE) == 0)
2180 continue;
2181
2182 ca = descendant->dv_cfattach;
2183 oflags = descendant->dv_flags;
2184
2185 descendant->dv_flags &= ~DVF_ACTIVE;
2186 if (ca->ca_activate == NULL)
2187 continue;
2188 s = splhigh();
2189 rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
2190 splx(s);
2191 if (rv != 0)
2192 descendant->dv_flags = oflags;
2193 }
2194 deviter_release(&di);
2195 return rv;
2196 }
2197
2198 /*
2199 * Defer the configuration of the specified device until all
2200 * of its parent's devices have been attached.
2201 */
2202 void
2203 config_defer(device_t dev, void (*func)(device_t))
2204 {
2205 struct deferred_config *dc;
2206
2207 if (dev->dv_parent == NULL)
2208 panic("config_defer: can't defer config of a root device");
2209
2210 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2211
2212 config_pending_incr(dev);
2213
2214 mutex_enter(&config_misc_lock);
2215 #ifdef DIAGNOSTIC
2216 struct deferred_config *odc;
2217 TAILQ_FOREACH(odc, &deferred_config_queue, dc_queue) {
2218 if (odc->dc_dev == dev)
2219 panic("config_defer: deferred twice");
2220 }
2221 #endif
2222 dc->dc_dev = dev;
2223 dc->dc_func = func;
2224 TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
2225 mutex_exit(&config_misc_lock);
2226 }
2227
2228 /*
2229 * Defer some autoconfiguration for a device until after interrupts
2230 * are enabled.
2231 */
2232 void
2233 config_interrupts(device_t dev, void (*func)(device_t))
2234 {
2235 struct deferred_config *dc;
2236
2237 /*
2238 * If interrupts are enabled, callback now.
2239 */
2240 if (cold == 0) {
2241 (*func)(dev);
2242 return;
2243 }
2244
2245 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2246
2247 config_pending_incr(dev);
2248
2249 mutex_enter(&config_misc_lock);
2250 #ifdef DIAGNOSTIC
2251 struct deferred_config *odc;
2252 TAILQ_FOREACH(odc, &interrupt_config_queue, dc_queue) {
2253 if (odc->dc_dev == dev)
2254 panic("config_interrupts: deferred twice");
2255 }
2256 #endif
2257 dc->dc_dev = dev;
2258 dc->dc_func = func;
2259 TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
2260 mutex_exit(&config_misc_lock);
2261 }
2262
2263 /*
2264 * Defer some autoconfiguration for a device until after root file system
2265 * is mounted (to load firmware etc).
2266 */
2267 void
2268 config_mountroot(device_t dev, void (*func)(device_t))
2269 {
2270 struct deferred_config *dc;
2271
2272 /*
2273 * If root file system is mounted, callback now.
2274 */
2275 if (root_is_mounted) {
2276 (*func)(dev);
2277 return;
2278 }
2279
2280 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2281
2282 mutex_enter(&config_misc_lock);
2283 #ifdef DIAGNOSTIC
2284 struct deferred_config *odc;
2285 TAILQ_FOREACH(odc, &mountroot_config_queue, dc_queue) {
2286 if (odc->dc_dev == dev)
2287 panic("%s: deferred twice", __func__);
2288 }
2289 #endif
2290
2291 dc->dc_dev = dev;
2292 dc->dc_func = func;
2293 TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
2294 mutex_exit(&config_misc_lock);
2295 }
2296
2297 /*
2298 * Process a deferred configuration queue.
2299 */
2300 static void
2301 config_process_deferred(struct deferred_config_head *queue, device_t parent)
2302 {
2303 struct deferred_config *dc;
2304
2305 KASSERT(KERNEL_LOCKED_P());
2306
2307 mutex_enter(&config_misc_lock);
2308 dc = TAILQ_FIRST(queue);
2309 while (dc) {
2310 if (parent == NULL || dc->dc_dev->dv_parent == parent) {
2311 TAILQ_REMOVE(queue, dc, dc_queue);
2312 mutex_exit(&config_misc_lock);
2313
2314 (*dc->dc_func)(dc->dc_dev);
2315 config_pending_decr(dc->dc_dev);
2316 kmem_free(dc, sizeof(*dc));
2317
2318 mutex_enter(&config_misc_lock);
2319 /* Restart, queue might have changed */
2320 dc = TAILQ_FIRST(queue);
2321 } else {
2322 dc = TAILQ_NEXT(dc, dc_queue);
2323 }
2324 }
2325 mutex_exit(&config_misc_lock);
2326 }
2327
2328 /*
2329 * Manipulate the config_pending semaphore.
2330 */
2331 void
2332 config_pending_incr(device_t dev)
2333 {
2334
2335 mutex_enter(&config_misc_lock);
2336 KASSERTMSG(dev->dv_pending < INT_MAX,
2337 "%s: excess config_pending_incr", device_xname(dev));
2338 if (dev->dv_pending++ == 0)
2339 TAILQ_INSERT_TAIL(&config_pending, dev, dv_pending_list);
2340 #ifdef DEBUG_AUTOCONF
2341 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2342 #endif
2343 mutex_exit(&config_misc_lock);
2344 }
2345
2346 void
2347 config_pending_decr(device_t dev)
2348 {
2349
2350 mutex_enter(&config_misc_lock);
2351 KASSERTMSG(dev->dv_pending > 0,
2352 "%s: excess config_pending_decr", device_xname(dev));
2353 if (--dev->dv_pending == 0) {
2354 TAILQ_REMOVE(&config_pending, dev, dv_pending_list);
2355 cv_broadcast(&config_misc_cv);
2356 }
2357 #ifdef DEBUG_AUTOCONF
2358 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2359 #endif
2360 mutex_exit(&config_misc_lock);
2361 }
2362
2363 /*
2364 * Register a "finalization" routine. Finalization routines are
2365 * called iteratively once all real devices have been found during
2366 * autoconfiguration, for as long as any one finalizer has done
2367 * any work.
2368 */
2369 int
2370 config_finalize_register(device_t dev, int (*fn)(device_t))
2371 {
2372 struct finalize_hook *f;
2373 int error = 0;
2374
2375 KERNEL_LOCK(1, NULL);
2376
2377 /*
2378 * If finalization has already been done, invoke the
2379 * callback function now.
2380 */
2381 if (config_finalize_done) {
2382 while ((*fn)(dev) != 0)
2383 /* loop */ ;
2384 goto out;
2385 }
2386
2387 /* Ensure this isn't already on the list. */
2388 TAILQ_FOREACH(f, &config_finalize_list, f_list) {
2389 if (f->f_func == fn && f->f_dev == dev) {
2390 error = EEXIST;
2391 goto out;
2392 }
2393 }
2394
2395 f = kmem_alloc(sizeof(*f), KM_SLEEP);
2396 f->f_func = fn;
2397 f->f_dev = dev;
2398 TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
2399
2400 /* Success! */
2401 error = 0;
2402
2403 out: KERNEL_UNLOCK_ONE(NULL);
2404 return error;
2405 }
2406
2407 void
2408 config_finalize(void)
2409 {
2410 struct finalize_hook *f;
2411 struct pdevinit *pdev;
2412 extern struct pdevinit pdevinit[];
2413 int errcnt, rv;
2414
2415 /*
2416 * Now that device driver threads have been created, wait for
2417 * them to finish any deferred autoconfiguration.
2418 */
2419 mutex_enter(&config_misc_lock);
2420 while (!TAILQ_EMPTY(&config_pending)) {
2421 device_t dev;
2422 TAILQ_FOREACH(dev, &config_pending, dv_pending_list)
2423 aprint_debug_dev(dev, "holding up boot\n");
2424 cv_wait(&config_misc_cv, &config_misc_lock);
2425 }
2426 mutex_exit(&config_misc_lock);
2427
2428 KERNEL_LOCK(1, NULL);
2429
2430 /* Attach pseudo-devices. */
2431 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
2432 (*pdev->pdev_attach)(pdev->pdev_count);
2433
2434 /* Run the hooks until none of them does any work. */
2435 do {
2436 rv = 0;
2437 TAILQ_FOREACH(f, &config_finalize_list, f_list)
2438 rv |= (*f->f_func)(f->f_dev);
2439 } while (rv != 0);
2440
2441 config_finalize_done = 1;
2442
2443 /* Now free all the hooks. */
2444 while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
2445 TAILQ_REMOVE(&config_finalize_list, f, f_list);
2446 kmem_free(f, sizeof(*f));
2447 }
2448
2449 KERNEL_UNLOCK_ONE(NULL);
2450
2451 errcnt = aprint_get_error_count();
2452 if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
2453 (boothowto & AB_VERBOSE) == 0) {
2454 mutex_enter(&config_misc_lock);
2455 if (config_do_twiddle) {
2456 config_do_twiddle = 0;
2457 printf_nolog(" done.\n");
2458 }
2459 mutex_exit(&config_misc_lock);
2460 }
2461 if (errcnt != 0) {
2462 printf("WARNING: %d error%s while detecting hardware; "
2463 "check system log.\n", errcnt,
2464 errcnt == 1 ? "" : "s");
2465 }
2466 }
2467
2468 void
2469 config_twiddle_init(void)
2470 {
2471
2472 if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
2473 config_do_twiddle = 1;
2474 }
2475 callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
2476 }
2477
2478 void
2479 config_twiddle_fn(void *cookie)
2480 {
2481
2482 mutex_enter(&config_misc_lock);
2483 if (config_do_twiddle) {
2484 twiddle();
2485 callout_schedule(&config_twiddle_ch, mstohz(100));
2486 }
2487 mutex_exit(&config_misc_lock);
2488 }
2489
2490 static void
2491 config_alldevs_enter(struct alldevs_foray *af)
2492 {
2493 TAILQ_INIT(&af->af_garbage);
2494 mutex_enter(&alldevs_lock);
2495 config_collect_garbage(&af->af_garbage);
2496 }
2497
2498 static void
2499 config_alldevs_exit(struct alldevs_foray *af)
2500 {
2501 mutex_exit(&alldevs_lock);
2502 config_dump_garbage(&af->af_garbage);
2503 }
2504
2505 /*
2506 * device_lookup:
2507 *
2508 * Look up a device instance for a given driver.
2509 */
2510 device_t
2511 device_lookup(cfdriver_t cd, int unit)
2512 {
2513 device_t dv;
2514
2515 mutex_enter(&alldevs_lock);
2516 if (unit < 0 || unit >= cd->cd_ndevs)
2517 dv = NULL;
2518 else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
2519 dv = NULL;
2520 mutex_exit(&alldevs_lock);
2521
2522 return dv;
2523 }
2524
2525 /*
2526 * device_lookup_private:
2527 *
2528 * Look up a softc instance for a given driver.
2529 */
2530 void *
2531 device_lookup_private(cfdriver_t cd, int unit)
2532 {
2533
2534 return device_private(device_lookup(cd, unit));
2535 }
2536
2537 /*
2538 * device_find_by_xname:
2539 *
2540 * Returns the device of the given name or NULL if it doesn't exist.
2541 */
2542 device_t
2543 device_find_by_xname(const char *name)
2544 {
2545 device_t dv;
2546 deviter_t di;
2547
2548 for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
2549 if (strcmp(device_xname(dv), name) == 0)
2550 break;
2551 }
2552 deviter_release(&di);
2553
2554 return dv;
2555 }
2556
2557 /*
2558 * device_find_by_driver_unit:
2559 *
2560 * Returns the device of the given driver name and unit or
2561 * NULL if it doesn't exist.
2562 */
2563 device_t
2564 device_find_by_driver_unit(const char *name, int unit)
2565 {
2566 struct cfdriver *cd;
2567
2568 if ((cd = config_cfdriver_lookup(name)) == NULL)
2569 return NULL;
2570 return device_lookup(cd, unit);
2571 }
2572
2573 static bool
2574 match_strcmp(const char * const s1, const char * const s2)
2575 {
2576 return strcmp(s1, s2) == 0;
2577 }
2578
2579 static bool
2580 match_pmatch(const char * const s1, const char * const s2)
2581 {
2582 return pmatch(s1, s2, NULL) == 2;
2583 }
2584
2585 static bool
2586 strarray_match_internal(const char ** const strings,
2587 unsigned int const nstrings, const char * const str,
2588 unsigned int * const indexp,
2589 bool (*match_fn)(const char *, const char *))
2590 {
2591 unsigned int i;
2592
2593 if (strings == NULL || nstrings == 0) {
2594 return false;
2595 }
2596
2597 for (i = 0; i < nstrings; i++) {
2598 if ((*match_fn)(strings[i], str)) {
2599 *indexp = i;
2600 return true;
2601 }
2602 }
2603
2604 return false;
2605 }
2606
2607 static int
2608 strarray_match(const char ** const strings, unsigned int const nstrings,
2609 const char * const str)
2610 {
2611 unsigned int idx;
2612
2613 if (strarray_match_internal(strings, nstrings, str, &idx,
2614 match_strcmp)) {
2615 return (int)(nstrings - idx);
2616 }
2617 return 0;
2618 }
2619
2620 static int
2621 strarray_pmatch(const char ** const strings, unsigned int const nstrings,
2622 const char * const pattern)
2623 {
2624 unsigned int idx;
2625
2626 if (strarray_match_internal(strings, nstrings, pattern, &idx,
2627 match_pmatch)) {
2628 return (int)(nstrings - idx);
2629 }
2630 return 0;
2631 }
2632
2633 static int
2634 device_compatible_match_strarray_internal(
2635 const char **device_compats, int ndevice_compats,
2636 const struct device_compatible_entry *driver_compats,
2637 const struct device_compatible_entry **matching_entryp,
2638 int (*match_fn)(const char **, unsigned int, const char *))
2639 {
2640 const struct device_compatible_entry *dce = NULL;
2641 int rv;
2642
2643 if (ndevice_compats == 0 || device_compats == NULL ||
2644 driver_compats == NULL)
2645 return 0;
2646
2647 for (dce = driver_compats; dce->compat != NULL; dce++) {
2648 rv = (*match_fn)(device_compats, ndevice_compats, dce->compat);
2649 if (rv != 0) {
2650 if (matching_entryp != NULL) {
2651 *matching_entryp = dce;
2652 }
2653 return rv;
2654 }
2655 }
2656 return 0;
2657 }
2658
2659 /*
2660 * device_compatible_match:
2661 *
2662 * Match a driver's "compatible" data against a device's
2663 * "compatible" strings. Returns resulted weighted by
2664 * which device "compatible" string was matched.
2665 */
2666 int
2667 device_compatible_match(const char **device_compats, int ndevice_compats,
2668 const struct device_compatible_entry *driver_compats)
2669 {
2670 return device_compatible_match_strarray_internal(device_compats,
2671 ndevice_compats, driver_compats, NULL, strarray_match);
2672 }
2673
2674 /*
2675 * device_compatible_pmatch:
2676 *
2677 * Like device_compatible_match(), but uses pmatch(9) to compare
2678 * the device "compatible" strings against patterns in the
2679 * driver's "compatible" data.
2680 */
2681 int
2682 device_compatible_pmatch(const char **device_compats, int ndevice_compats,
2683 const struct device_compatible_entry *driver_compats)
2684 {
2685 return device_compatible_match_strarray_internal(device_compats,
2686 ndevice_compats, driver_compats, NULL, strarray_pmatch);
2687 }
2688
2689 static int
2690 device_compatible_match_strlist_internal(
2691 const char * const device_compats, size_t const device_compatsize,
2692 const struct device_compatible_entry *driver_compats,
2693 const struct device_compatible_entry **matching_entryp,
2694 int (*match_fn)(const char *, size_t, const char *))
2695 {
2696 const struct device_compatible_entry *dce = NULL;
2697 int rv;
2698
2699 if (device_compats == NULL || device_compatsize == 0 ||
2700 driver_compats == NULL)
2701 return 0;
2702
2703 for (dce = driver_compats; dce->compat != NULL; dce++) {
2704 rv = (*match_fn)(device_compats, device_compatsize,
2705 dce->compat);
2706 if (rv != 0) {
2707 if (matching_entryp != NULL) {
2708 *matching_entryp = dce;
2709 }
2710 return rv;
2711 }
2712 }
2713 return 0;
2714 }
2715
2716 /*
2717 * device_compatible_match_strlist:
2718 *
2719 * Like device_compatible_match(), but take the device
2720 * "compatible" strings as an OpenFirmware-style string
2721 * list.
2722 */
2723 int
2724 device_compatible_match_strlist(
2725 const char * const device_compats, size_t const device_compatsize,
2726 const struct device_compatible_entry *driver_compats)
2727 {
2728 return device_compatible_match_strlist_internal(device_compats,
2729 device_compatsize, driver_compats, NULL, strlist_match);
2730 }
2731
2732 /*
2733 * device_compatible_pmatch_strlist:
2734 *
2735 * Like device_compatible_pmatch(), but take the device
2736 * "compatible" strings as an OpenFirmware-style string
2737 * list.
2738 */
2739 int
2740 device_compatible_pmatch_strlist(
2741 const char * const device_compats, size_t const device_compatsize,
2742 const struct device_compatible_entry *driver_compats)
2743 {
2744 return device_compatible_match_strlist_internal(device_compats,
2745 device_compatsize, driver_compats, NULL, strlist_pmatch);
2746 }
2747
2748 static int
2749 device_compatible_match_id_internal(
2750 uintptr_t const id, uintptr_t const mask, uintptr_t const sentinel_id,
2751 const struct device_compatible_entry *driver_compats,
2752 const struct device_compatible_entry **matching_entryp)
2753 {
2754 const struct device_compatible_entry *dce = NULL;
2755
2756 if (mask == 0)
2757 return 0;
2758
2759 for (dce = driver_compats; dce->id != sentinel_id; dce++) {
2760 if ((id & mask) == dce->id) {
2761 if (matching_entryp != NULL) {
2762 *matching_entryp = dce;
2763 }
2764 return 1;
2765 }
2766 }
2767 return 0;
2768 }
2769
2770 /*
2771 * device_compatible_match_id:
2772 *
2773 * Like device_compatible_match(), but takes a single
2774 * unsigned integer device ID.
2775 */
2776 int
2777 device_compatible_match_id(
2778 uintptr_t const id, uintptr_t const sentinel_id,
2779 const struct device_compatible_entry *driver_compats)
2780 {
2781 return device_compatible_match_id_internal(id, (uintptr_t)-1,
2782 sentinel_id, driver_compats, NULL);
2783 }
2784
2785 /*
2786 * device_compatible_lookup:
2787 *
2788 * Look up and return the device_compatible_entry, using the
2789 * same matching criteria used by device_compatible_match().
2790 */
2791 const struct device_compatible_entry *
2792 device_compatible_lookup(const char **device_compats, int ndevice_compats,
2793 const struct device_compatible_entry *driver_compats)
2794 {
2795 const struct device_compatible_entry *dce;
2796
2797 if (device_compatible_match_strarray_internal(device_compats,
2798 ndevice_compats, driver_compats, &dce, strarray_match)) {
2799 return dce;
2800 }
2801 return NULL;
2802 }
2803
2804 /*
2805 * device_compatible_plookup:
2806 *
2807 * Look up and return the device_compatible_entry, using the
2808 * same matching criteria used by device_compatible_pmatch().
2809 */
2810 const struct device_compatible_entry *
2811 device_compatible_plookup(const char **device_compats, int ndevice_compats,
2812 const struct device_compatible_entry *driver_compats)
2813 {
2814 const struct device_compatible_entry *dce;
2815
2816 if (device_compatible_match_strarray_internal(device_compats,
2817 ndevice_compats, driver_compats, &dce, strarray_pmatch)) {
2818 return dce;
2819 }
2820 return NULL;
2821 }
2822
2823 /*
2824 * device_compatible_lookup_strlist:
2825 *
2826 * Like device_compatible_lookup(), but take the device
2827 * "compatible" strings as an OpenFirmware-style string
2828 * list.
2829 */
2830 const struct device_compatible_entry *
2831 device_compatible_lookup_strlist(
2832 const char * const device_compats, size_t const device_compatsize,
2833 const struct device_compatible_entry *driver_compats)
2834 {
2835 const struct device_compatible_entry *dce;
2836
2837 if (device_compatible_match_strlist_internal(device_compats,
2838 device_compatsize, driver_compats, &dce, strlist_match)) {
2839 return dce;
2840 }
2841 return NULL;
2842 }
2843
2844 /*
2845 * device_compatible_plookup_strlist:
2846 *
2847 * Like device_compatible_plookup(), but take the device
2848 * "compatible" strings as an OpenFirmware-style string
2849 * list.
2850 */
2851 const struct device_compatible_entry *
2852 device_compatible_plookup_strlist(
2853 const char * const device_compats, size_t const device_compatsize,
2854 const struct device_compatible_entry *driver_compats)
2855 {
2856 const struct device_compatible_entry *dce;
2857
2858 if (device_compatible_match_strlist_internal(device_compats,
2859 device_compatsize, driver_compats, &dce, strlist_pmatch)) {
2860 return dce;
2861 }
2862 return NULL;
2863 }
2864
2865 /*
2866 * device_compatible_lookup_id:
2867 *
2868 * Like device_compatible_lookup(), but takes a single
2869 * unsigned integer device ID.
2870 */
2871 const struct device_compatible_entry *
2872 device_compatible_lookup_id(
2873 uintptr_t const id, uintptr_t const sentinel_id,
2874 const struct device_compatible_entry *driver_compats)
2875 {
2876 const struct device_compatible_entry *dce;
2877
2878 if (device_compatible_match_id_internal(id, (uintptr_t)-1,
2879 sentinel_id, driver_compats, &dce)) {
2880 return dce;
2881 }
2882 return NULL;
2883 }
2884
2885 /*
2886 * Power management related functions.
2887 */
2888
2889 bool
2890 device_pmf_is_registered(device_t dev)
2891 {
2892 return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
2893 }
2894
2895 bool
2896 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
2897 {
2898 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2899 return true;
2900 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2901 return false;
2902 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2903 dev->dv_driver_suspend != NULL &&
2904 !(*dev->dv_driver_suspend)(dev, qual))
2905 return false;
2906
2907 dev->dv_flags |= DVF_DRIVER_SUSPENDED;
2908 return true;
2909 }
2910
2911 bool
2912 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
2913 {
2914 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2915 return true;
2916 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2917 return false;
2918 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2919 dev->dv_driver_resume != NULL &&
2920 !(*dev->dv_driver_resume)(dev, qual))
2921 return false;
2922
2923 dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
2924 return true;
2925 }
2926
2927 bool
2928 device_pmf_driver_shutdown(device_t dev, int how)
2929 {
2930
2931 if (*dev->dv_driver_shutdown != NULL &&
2932 !(*dev->dv_driver_shutdown)(dev, how))
2933 return false;
2934 return true;
2935 }
2936
2937 bool
2938 device_pmf_driver_register(device_t dev,
2939 bool (*suspend)(device_t, const pmf_qual_t *),
2940 bool (*resume)(device_t, const pmf_qual_t *),
2941 bool (*shutdown)(device_t, int))
2942 {
2943 dev->dv_driver_suspend = suspend;
2944 dev->dv_driver_resume = resume;
2945 dev->dv_driver_shutdown = shutdown;
2946 dev->dv_flags |= DVF_POWER_HANDLERS;
2947 return true;
2948 }
2949
2950 static const char *
2951 curlwp_name(void)
2952 {
2953 if (curlwp->l_name != NULL)
2954 return curlwp->l_name;
2955 else
2956 return curlwp->l_proc->p_comm;
2957 }
2958
2959 void
2960 device_pmf_driver_deregister(device_t dev)
2961 {
2962 device_lock_t dvl = device_getlock(dev);
2963
2964 dev->dv_driver_suspend = NULL;
2965 dev->dv_driver_resume = NULL;
2966
2967 mutex_enter(&dvl->dvl_mtx);
2968 dev->dv_flags &= ~DVF_POWER_HANDLERS;
2969 while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
2970 /* Wake a thread that waits for the lock. That
2971 * thread will fail to acquire the lock, and then
2972 * it will wake the next thread that waits for the
2973 * lock, or else it will wake us.
2974 */
2975 cv_signal(&dvl->dvl_cv);
2976 pmflock_debug(dev, __func__, __LINE__);
2977 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2978 pmflock_debug(dev, __func__, __LINE__);
2979 }
2980 mutex_exit(&dvl->dvl_mtx);
2981 }
2982
2983 bool
2984 device_pmf_driver_child_register(device_t dev)
2985 {
2986 device_t parent = device_parent(dev);
2987
2988 if (parent == NULL || parent->dv_driver_child_register == NULL)
2989 return true;
2990 return (*parent->dv_driver_child_register)(dev);
2991 }
2992
2993 void
2994 device_pmf_driver_set_child_register(device_t dev,
2995 bool (*child_register)(device_t))
2996 {
2997 dev->dv_driver_child_register = child_register;
2998 }
2999
3000 static void
3001 pmflock_debug(device_t dev, const char *func, int line)
3002 {
3003 device_lock_t dvl = device_getlock(dev);
3004
3005 aprint_debug_dev(dev,
3006 "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n", func, line,
3007 curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait, dev->dv_flags);
3008 }
3009
3010 static bool
3011 device_pmf_lock1(device_t dev)
3012 {
3013 device_lock_t dvl = device_getlock(dev);
3014
3015 while (device_pmf_is_registered(dev) &&
3016 dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
3017 dvl->dvl_nwait++;
3018 pmflock_debug(dev, __func__, __LINE__);
3019 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
3020 pmflock_debug(dev, __func__, __LINE__);
3021 dvl->dvl_nwait--;
3022 }
3023 if (!device_pmf_is_registered(dev)) {
3024 pmflock_debug(dev, __func__, __LINE__);
3025 /* We could not acquire the lock, but some other thread may
3026 * wait for it, also. Wake that thread.
3027 */
3028 cv_signal(&dvl->dvl_cv);
3029 return false;
3030 }
3031 dvl->dvl_nlock++;
3032 dvl->dvl_holder = curlwp;
3033 pmflock_debug(dev, __func__, __LINE__);
3034 return true;
3035 }
3036
3037 bool
3038 device_pmf_lock(device_t dev)
3039 {
3040 bool rc;
3041 device_lock_t dvl = device_getlock(dev);
3042
3043 mutex_enter(&dvl->dvl_mtx);
3044 rc = device_pmf_lock1(dev);
3045 mutex_exit(&dvl->dvl_mtx);
3046
3047 return rc;
3048 }
3049
3050 void
3051 device_pmf_unlock(device_t dev)
3052 {
3053 device_lock_t dvl = device_getlock(dev);
3054
3055 KASSERT(dvl->dvl_nlock > 0);
3056 mutex_enter(&dvl->dvl_mtx);
3057 if (--dvl->dvl_nlock == 0)
3058 dvl->dvl_holder = NULL;
3059 cv_signal(&dvl->dvl_cv);
3060 pmflock_debug(dev, __func__, __LINE__);
3061 mutex_exit(&dvl->dvl_mtx);
3062 }
3063
3064 device_lock_t
3065 device_getlock(device_t dev)
3066 {
3067 return &dev->dv_lock;
3068 }
3069
3070 void *
3071 device_pmf_bus_private(device_t dev)
3072 {
3073 return dev->dv_bus_private;
3074 }
3075
3076 bool
3077 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
3078 {
3079 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
3080 return true;
3081 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
3082 (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
3083 return false;
3084 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
3085 dev->dv_bus_suspend != NULL &&
3086 !(*dev->dv_bus_suspend)(dev, qual))
3087 return false;
3088
3089 dev->dv_flags |= DVF_BUS_SUSPENDED;
3090 return true;
3091 }
3092
3093 bool
3094 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
3095 {
3096 if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
3097 return true;
3098 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
3099 dev->dv_bus_resume != NULL &&
3100 !(*dev->dv_bus_resume)(dev, qual))
3101 return false;
3102
3103 dev->dv_flags &= ~DVF_BUS_SUSPENDED;
3104 return true;
3105 }
3106
3107 bool
3108 device_pmf_bus_shutdown(device_t dev, int how)
3109 {
3110
3111 if (*dev->dv_bus_shutdown != NULL &&
3112 !(*dev->dv_bus_shutdown)(dev, how))
3113 return false;
3114 return true;
3115 }
3116
3117 void
3118 device_pmf_bus_register(device_t dev, void *priv,
3119 bool (*suspend)(device_t, const pmf_qual_t *),
3120 bool (*resume)(device_t, const pmf_qual_t *),
3121 bool (*shutdown)(device_t, int), void (*deregister)(device_t))
3122 {
3123 dev->dv_bus_private = priv;
3124 dev->dv_bus_resume = resume;
3125 dev->dv_bus_suspend = suspend;
3126 dev->dv_bus_shutdown = shutdown;
3127 dev->dv_bus_deregister = deregister;
3128 }
3129
3130 void
3131 device_pmf_bus_deregister(device_t dev)
3132 {
3133 if (dev->dv_bus_deregister == NULL)
3134 return;
3135 (*dev->dv_bus_deregister)(dev);
3136 dev->dv_bus_private = NULL;
3137 dev->dv_bus_suspend = NULL;
3138 dev->dv_bus_resume = NULL;
3139 dev->dv_bus_deregister = NULL;
3140 }
3141
3142 void *
3143 device_pmf_class_private(device_t dev)
3144 {
3145 return dev->dv_class_private;
3146 }
3147
3148 bool
3149 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
3150 {
3151 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
3152 return true;
3153 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3154 dev->dv_class_suspend != NULL &&
3155 !(*dev->dv_class_suspend)(dev, qual))
3156 return false;
3157
3158 dev->dv_flags |= DVF_CLASS_SUSPENDED;
3159 return true;
3160 }
3161
3162 bool
3163 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
3164 {
3165 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
3166 return true;
3167 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
3168 (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
3169 return false;
3170 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3171 dev->dv_class_resume != NULL &&
3172 !(*dev->dv_class_resume)(dev, qual))
3173 return false;
3174
3175 dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
3176 return true;
3177 }
3178
3179 void
3180 device_pmf_class_register(device_t dev, void *priv,
3181 bool (*suspend)(device_t, const pmf_qual_t *),
3182 bool (*resume)(device_t, const pmf_qual_t *),
3183 void (*deregister)(device_t))
3184 {
3185 dev->dv_class_private = priv;
3186 dev->dv_class_suspend = suspend;
3187 dev->dv_class_resume = resume;
3188 dev->dv_class_deregister = deregister;
3189 }
3190
3191 void
3192 device_pmf_class_deregister(device_t dev)
3193 {
3194 if (dev->dv_class_deregister == NULL)
3195 return;
3196 (*dev->dv_class_deregister)(dev);
3197 dev->dv_class_private = NULL;
3198 dev->dv_class_suspend = NULL;
3199 dev->dv_class_resume = NULL;
3200 dev->dv_class_deregister = NULL;
3201 }
3202
3203 bool
3204 device_active(device_t dev, devactive_t type)
3205 {
3206 size_t i;
3207
3208 if (dev->dv_activity_count == 0)
3209 return false;
3210
3211 for (i = 0; i < dev->dv_activity_count; ++i) {
3212 if (dev->dv_activity_handlers[i] == NULL)
3213 break;
3214 (*dev->dv_activity_handlers[i])(dev, type);
3215 }
3216
3217 return true;
3218 }
3219
3220 bool
3221 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
3222 {
3223 void (**new_handlers)(device_t, devactive_t);
3224 void (**old_handlers)(device_t, devactive_t);
3225 size_t i, old_size, new_size;
3226 int s;
3227
3228 old_handlers = dev->dv_activity_handlers;
3229 old_size = dev->dv_activity_count;
3230
3231 KASSERT(old_size == 0 || old_handlers != NULL);
3232
3233 for (i = 0; i < old_size; ++i) {
3234 KASSERT(old_handlers[i] != handler);
3235 if (old_handlers[i] == NULL) {
3236 old_handlers[i] = handler;
3237 return true;
3238 }
3239 }
3240
3241 new_size = old_size + 4;
3242 new_handlers = kmem_alloc(sizeof(void *) * new_size, KM_SLEEP);
3243
3244 for (i = 0; i < old_size; ++i)
3245 new_handlers[i] = old_handlers[i];
3246 new_handlers[old_size] = handler;
3247 for (i = old_size+1; i < new_size; ++i)
3248 new_handlers[i] = NULL;
3249
3250 s = splhigh();
3251 dev->dv_activity_count = new_size;
3252 dev->dv_activity_handlers = new_handlers;
3253 splx(s);
3254
3255 if (old_size > 0)
3256 kmem_free(old_handlers, sizeof(void *) * old_size);
3257
3258 return true;
3259 }
3260
3261 void
3262 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
3263 {
3264 void (**old_handlers)(device_t, devactive_t);
3265 size_t i, old_size;
3266 int s;
3267
3268 old_handlers = dev->dv_activity_handlers;
3269 old_size = dev->dv_activity_count;
3270
3271 for (i = 0; i < old_size; ++i) {
3272 if (old_handlers[i] == handler)
3273 break;
3274 if (old_handlers[i] == NULL)
3275 return; /* XXX panic? */
3276 }
3277
3278 if (i == old_size)
3279 return; /* XXX panic? */
3280
3281 for (; i < old_size - 1; ++i) {
3282 if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
3283 continue;
3284
3285 if (i == 0) {
3286 s = splhigh();
3287 dev->dv_activity_count = 0;
3288 dev->dv_activity_handlers = NULL;
3289 splx(s);
3290 kmem_free(old_handlers, sizeof(void *) * old_size);
3291 }
3292 return;
3293 }
3294 old_handlers[i] = NULL;
3295 }
3296
3297 /* Return true iff the device_t `dev' exists at generation `gen'. */
3298 static bool
3299 device_exists_at(device_t dv, devgen_t gen)
3300 {
3301 return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
3302 dv->dv_add_gen <= gen;
3303 }
3304
3305 static bool
3306 deviter_visits(const deviter_t *di, device_t dv)
3307 {
3308 return device_exists_at(dv, di->di_gen);
3309 }
3310
3311 /*
3312 * Device Iteration
3313 *
3314 * deviter_t: a device iterator. Holds state for a "walk" visiting
3315 * each device_t's in the device tree.
3316 *
3317 * deviter_init(di, flags): initialize the device iterator `di'
3318 * to "walk" the device tree. deviter_next(di) will return
3319 * the first device_t in the device tree, or NULL if there are
3320 * no devices.
3321 *
3322 * `flags' is one or more of DEVITER_F_RW, indicating that the
3323 * caller intends to modify the device tree by calling
3324 * config_detach(9) on devices in the order that the iterator
3325 * returns them; DEVITER_F_ROOT_FIRST, asking for the devices
3326 * nearest the "root" of the device tree to be returned, first;
3327 * DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
3328 * the root of the device tree, first; and DEVITER_F_SHUTDOWN,
3329 * indicating both that deviter_init() should not respect any
3330 * locks on the device tree, and that deviter_next(di) may run
3331 * in more than one LWP before the walk has finished.
3332 *
3333 * Only one DEVITER_F_RW iterator may be in the device tree at
3334 * once.
3335 *
3336 * DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
3337 *
3338 * Results are undefined if the flags DEVITER_F_ROOT_FIRST and
3339 * DEVITER_F_LEAVES_FIRST are used in combination.
3340 *
3341 * deviter_first(di, flags): initialize the device iterator `di'
3342 * and return the first device_t in the device tree, or NULL
3343 * if there are no devices. The statement
3344 *
3345 * dv = deviter_first(di);
3346 *
3347 * is shorthand for
3348 *
3349 * deviter_init(di);
3350 * dv = deviter_next(di);
3351 *
3352 * deviter_next(di): return the next device_t in the device tree,
3353 * or NULL if there are no more devices. deviter_next(di)
3354 * is undefined if `di' was not initialized with deviter_init() or
3355 * deviter_first().
3356 *
3357 * deviter_release(di): stops iteration (subsequent calls to
3358 * deviter_next() will return NULL), releases any locks and
3359 * resources held by the device iterator.
3360 *
3361 * Device iteration does not return device_t's in any particular
3362 * order. An iterator will never return the same device_t twice.
3363 * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
3364 * is called repeatedly on the same `di', it will eventually return
3365 * NULL. It is ok to attach/detach devices during device iteration.
3366 */
3367 void
3368 deviter_init(deviter_t *di, deviter_flags_t flags)
3369 {
3370 device_t dv;
3371
3372 memset(di, 0, sizeof(*di));
3373
3374 if ((flags & DEVITER_F_SHUTDOWN) != 0)
3375 flags |= DEVITER_F_RW;
3376
3377 mutex_enter(&alldevs_lock);
3378 if ((flags & DEVITER_F_RW) != 0)
3379 alldevs_nwrite++;
3380 else
3381 alldevs_nread++;
3382 di->di_gen = alldevs_gen++;
3383 di->di_flags = flags;
3384
3385 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3386 case DEVITER_F_LEAVES_FIRST:
3387 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3388 if (!deviter_visits(di, dv))
3389 continue;
3390 di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
3391 }
3392 break;
3393 case DEVITER_F_ROOT_FIRST:
3394 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3395 if (!deviter_visits(di, dv))
3396 continue;
3397 di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
3398 }
3399 break;
3400 default:
3401 break;
3402 }
3403
3404 deviter_reinit(di);
3405 mutex_exit(&alldevs_lock);
3406 }
3407
3408 static void
3409 deviter_reinit(deviter_t *di)
3410 {
3411
3412 KASSERT(mutex_owned(&alldevs_lock));
3413 if ((di->di_flags & DEVITER_F_RW) != 0)
3414 di->di_prev = TAILQ_LAST(&alldevs, devicelist);
3415 else
3416 di->di_prev = TAILQ_FIRST(&alldevs);
3417 }
3418
3419 device_t
3420 deviter_first(deviter_t *di, deviter_flags_t flags)
3421 {
3422
3423 deviter_init(di, flags);
3424 return deviter_next(di);
3425 }
3426
3427 static device_t
3428 deviter_next2(deviter_t *di)
3429 {
3430 device_t dv;
3431
3432 KASSERT(mutex_owned(&alldevs_lock));
3433
3434 dv = di->di_prev;
3435
3436 if (dv == NULL)
3437 return NULL;
3438
3439 if ((di->di_flags & DEVITER_F_RW) != 0)
3440 di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
3441 else
3442 di->di_prev = TAILQ_NEXT(dv, dv_list);
3443
3444 return dv;
3445 }
3446
3447 static device_t
3448 deviter_next1(deviter_t *di)
3449 {
3450 device_t dv;
3451
3452 KASSERT(mutex_owned(&alldevs_lock));
3453
3454 do {
3455 dv = deviter_next2(di);
3456 } while (dv != NULL && !deviter_visits(di, dv));
3457
3458 return dv;
3459 }
3460
3461 device_t
3462 deviter_next(deviter_t *di)
3463 {
3464 device_t dv = NULL;
3465
3466 mutex_enter(&alldevs_lock);
3467 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3468 case 0:
3469 dv = deviter_next1(di);
3470 break;
3471 case DEVITER_F_LEAVES_FIRST:
3472 while (di->di_curdepth >= 0) {
3473 if ((dv = deviter_next1(di)) == NULL) {
3474 di->di_curdepth--;
3475 deviter_reinit(di);
3476 } else if (dv->dv_depth == di->di_curdepth)
3477 break;
3478 }
3479 break;
3480 case DEVITER_F_ROOT_FIRST:
3481 while (di->di_curdepth <= di->di_maxdepth) {
3482 if ((dv = deviter_next1(di)) == NULL) {
3483 di->di_curdepth++;
3484 deviter_reinit(di);
3485 } else if (dv->dv_depth == di->di_curdepth)
3486 break;
3487 }
3488 break;
3489 default:
3490 break;
3491 }
3492 mutex_exit(&alldevs_lock);
3493
3494 return dv;
3495 }
3496
3497 void
3498 deviter_release(deviter_t *di)
3499 {
3500 bool rw = (di->di_flags & DEVITER_F_RW) != 0;
3501
3502 mutex_enter(&alldevs_lock);
3503 if (rw)
3504 --alldevs_nwrite;
3505 else
3506 --alldevs_nread;
3507 /* XXX wake a garbage-collection thread */
3508 mutex_exit(&alldevs_lock);
3509 }
3510
3511 const char *
3512 cfdata_ifattr(const struct cfdata *cf)
3513 {
3514 return cf->cf_pspec->cfp_iattr;
3515 }
3516
3517 bool
3518 ifattr_match(const char *snull, const char *t)
3519 {
3520 return (snull == NULL) || strcmp(snull, t) == 0;
3521 }
3522
3523 void
3524 null_childdetached(device_t self, device_t child)
3525 {
3526 /* do nothing */
3527 }
3528
3529 static void
3530 sysctl_detach_setup(struct sysctllog **clog)
3531 {
3532
3533 sysctl_createv(clog, 0, NULL, NULL,
3534 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3535 CTLTYPE_BOOL, "detachall",
3536 SYSCTL_DESCR("Detach all devices at shutdown"),
3537 NULL, 0, &detachall, 0,
3538 CTL_KERN, CTL_CREATE, CTL_EOL);
3539 }
3540