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