subr_autoconf.c revision 1.278 1 /* $NetBSD: subr_autoconf.c,v 1.278 2021/04/24 23:37:00 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.278 2021/04/24 23:37:00 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 direct config "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 /*
1024 * Invoke the "probe" routine for a cfdata entry on behalf of
1025 * an external caller, usually an indirect config "search" routine.
1026 */
1027 int
1028 config_probe(device_t parent, cfdata_t cf, void *aux)
1029 {
1030 /*
1031 * This is currently a synonym for config_match(), but this
1032 * is an implementation detail; "match" and "probe" routines
1033 * have different behaviors.
1034 *
1035 * XXX config_probe() should return a bool, because there is
1036 * XXX no match score for probe -- it's either there or it's
1037 * XXX not, but some ports abuse the return value as a way
1038 * XXX to attach "critical" devices before "non-critical"
1039 * XXX devices.
1040 */
1041 return config_match(parent, cf, aux);
1042 }
1043
1044 static void
1045 config_get_cfargs(cfarg_t tag,
1046 cfsubmatch_t *fnp, /* output */
1047 const char **ifattrp, /* output */
1048 const int **locsp, /* output */
1049 devhandle_t *handlep, /* output */
1050 va_list ap)
1051 {
1052 cfsubmatch_t fn = NULL;
1053 const char *ifattr = NULL;
1054 const int *locs = NULL;
1055 devhandle_t handle;
1056
1057 devhandle_invalidate(&handle);
1058
1059 while (tag != CFARG_EOL) {
1060 switch (tag) {
1061 /*
1062 * CFARG_SUBMATCH and CFARG_SEARCH are synonyms, but this
1063 * is merely an implementation detail. They are distinct
1064 * from the caller's point of view.
1065 */
1066 case CFARG_SUBMATCH:
1067 case CFARG_SEARCH:
1068 /* Only allow one function to be specified. */
1069 if (fn != NULL) {
1070 panic("%s: caller specified both "
1071 "SUBMATCH and SEARCH", __func__);
1072 }
1073 fn = va_arg(ap, cfsubmatch_t);
1074 break;
1075
1076 case CFARG_IATTR:
1077 ifattr = va_arg(ap, const char *);
1078 break;
1079
1080 case CFARG_LOCATORS:
1081 locs = va_arg(ap, const int *);
1082 break;
1083
1084 case CFARG_DEVHANDLE:
1085 handle = va_arg(ap, devhandle_t);
1086 break;
1087
1088 default:
1089 panic("%s: unknown cfarg tag: %d\n",
1090 __func__, tag);
1091 }
1092 tag = va_arg(ap, cfarg_t);
1093 }
1094
1095 if (fnp != NULL)
1096 *fnp = fn;
1097 if (ifattrp != NULL)
1098 *ifattrp = ifattr;
1099 if (locsp != NULL)
1100 *locsp = locs;
1101 if (handlep != NULL)
1102 *handlep = handle;
1103 }
1104
1105 /*
1106 * Iterate over all potential children of some device, calling the given
1107 * function (default being the child's match function) for each one.
1108 * Nonzero returns are matches; the highest value returned is considered
1109 * the best match. Return the `found child' if we got a match, or NULL
1110 * otherwise. The `aux' pointer is simply passed on through.
1111 *
1112 * Note that this function is designed so that it can be used to apply
1113 * an arbitrary function to all potential children (its return value
1114 * can be ignored).
1115 */
1116 static cfdata_t
1117 config_vsearch(device_t parent, void *aux, cfarg_t tag, va_list ap)
1118 {
1119 cfsubmatch_t fn;
1120 const char *ifattr;
1121 const int *locs;
1122 struct cftable *ct;
1123 cfdata_t cf;
1124 struct matchinfo m;
1125
1126 config_get_cfargs(tag, &fn, &ifattr, &locs, NULL, ap);
1127
1128 KASSERT(config_initialized);
1129 KASSERT(!ifattr || cfdriver_get_iattr(parent->dv_cfdriver, ifattr));
1130 KASSERT(ifattr || cfdriver_iattr_count(parent->dv_cfdriver) < 2);
1131
1132 m.fn = fn;
1133 m.parent = parent;
1134 m.locs = locs;
1135 m.aux = aux;
1136 m.match = NULL;
1137 m.pri = 0;
1138
1139 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1140 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1141
1142 /* We don't match root nodes here. */
1143 if (!cf->cf_pspec)
1144 continue;
1145
1146 /*
1147 * Skip cf if no longer eligible, otherwise scan
1148 * through parents for one matching `parent', and
1149 * try match function.
1150 */
1151 if (cf->cf_fstate == FSTATE_FOUND)
1152 continue;
1153 if (cf->cf_fstate == FSTATE_DNOTFOUND ||
1154 cf->cf_fstate == FSTATE_DSTAR)
1155 continue;
1156
1157 /*
1158 * If an interface attribute was specified,
1159 * consider only children which attach to
1160 * that attribute.
1161 */
1162 if (ifattr && !STREQ(ifattr, cfdata_ifattr(cf)))
1163 continue;
1164
1165 if (cfparent_match(parent, cf->cf_pspec))
1166 mapply(&m, cf);
1167 }
1168 }
1169 return m.match;
1170 }
1171
1172 cfdata_t
1173 config_search(device_t parent, void *aux, cfarg_t tag, ...)
1174 {
1175 cfdata_t cf;
1176 va_list ap;
1177
1178 va_start(ap, tag);
1179 cf = config_vsearch(parent, aux, tag, ap);
1180 va_end(ap);
1181
1182 return cf;
1183 }
1184
1185 /*
1186 * Find the given root device.
1187 * This is much like config_search, but there is no parent.
1188 * Don't bother with multiple cfdata tables; the root node
1189 * must always be in the initial table.
1190 */
1191 cfdata_t
1192 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
1193 {
1194 cfdata_t cf;
1195 const short *p;
1196 struct matchinfo m;
1197
1198 m.fn = fn;
1199 m.parent = ROOT;
1200 m.aux = aux;
1201 m.match = NULL;
1202 m.pri = 0;
1203 m.locs = 0;
1204 /*
1205 * Look at root entries for matching name. We do not bother
1206 * with found-state here since only one root should ever be
1207 * searched (and it must be done first).
1208 */
1209 for (p = cfroots; *p >= 0; p++) {
1210 cf = &cfdata[*p];
1211 if (strcmp(cf->cf_name, rootname) == 0)
1212 mapply(&m, cf);
1213 }
1214 return m.match;
1215 }
1216
1217 static const char * const msgs[3] = { "", " not configured\n", " unsupported\n" };
1218
1219 /*
1220 * The given `aux' argument describes a device that has been found
1221 * on the given parent, but not necessarily configured. Locate the
1222 * configuration data for that device (using the submatch function
1223 * provided, or using candidates' cd_match configuration driver
1224 * functions) and attach it, and return its device_t. If the device was
1225 * not configured, call the given `print' function and return NULL.
1226 */
1227 static device_t
1228 config_vfound(device_t parent, void *aux, cfprint_t print, cfarg_t tag,
1229 va_list ap)
1230 {
1231 cfdata_t cf;
1232 va_list nap;
1233
1234 va_copy(nap, ap);
1235 cf = config_vsearch(parent, aux, tag, nap);
1236 va_end(nap);
1237
1238 if (cf != NULL) {
1239 return config_vattach(parent, cf, aux, print, tag, ap);
1240 }
1241
1242 if (print) {
1243 if (config_do_twiddle && cold)
1244 twiddle();
1245 aprint_normal("%s", msgs[(*print)(aux, device_xname(parent))]);
1246 }
1247
1248 /*
1249 * This has the effect of mixing in a single timestamp to the
1250 * entropy pool. Experiments indicate the estimator will almost
1251 * always attribute one bit of entropy to this sample; analysis
1252 * of device attach/detach timestamps on FreeBSD indicates 4
1253 * bits of entropy/sample so this seems appropriately conservative.
1254 */
1255 rnd_add_uint32(&rnd_autoconf_source, 0);
1256 return NULL;
1257 }
1258
1259 device_t
1260 config_found(device_t parent, void *aux, cfprint_t print, cfarg_t tag, ...)
1261 {
1262 device_t dev;
1263 va_list ap;
1264
1265 va_start(ap, tag);
1266 dev = config_vfound(parent, aux, print, tag, ap);
1267 va_end(ap);
1268
1269 return dev;
1270 }
1271
1272 /*
1273 * As above, but for root devices.
1274 */
1275 device_t
1276 config_rootfound(const char *rootname, void *aux)
1277 {
1278 cfdata_t cf;
1279
1280 if ((cf = config_rootsearch(NULL, rootname, aux)) != NULL)
1281 return config_attach(ROOT, cf, aux, NULL, CFARG_EOL);
1282 aprint_error("root device %s not configured\n", rootname);
1283 return NULL;
1284 }
1285
1286 /* just like sprintf(buf, "%d") except that it works from the end */
1287 static char *
1288 number(char *ep, int n)
1289 {
1290
1291 *--ep = 0;
1292 while (n >= 10) {
1293 *--ep = (n % 10) + '0';
1294 n /= 10;
1295 }
1296 *--ep = n + '0';
1297 return ep;
1298 }
1299
1300 /*
1301 * Expand the size of the cd_devs array if necessary.
1302 *
1303 * The caller must hold alldevs_lock. config_makeroom() may release and
1304 * re-acquire alldevs_lock, so callers should re-check conditions such
1305 * as alldevs_nwrite == 0 and alldevs_nread == 0 when config_makeroom()
1306 * returns.
1307 */
1308 static void
1309 config_makeroom(int n, struct cfdriver *cd)
1310 {
1311 int ondevs, nndevs;
1312 device_t *osp, *nsp;
1313
1314 KASSERT(mutex_owned(&alldevs_lock));
1315 alldevs_nwrite++;
1316
1317 for (nndevs = MAX(4, cd->cd_ndevs); nndevs <= n; nndevs += nndevs)
1318 ;
1319
1320 while (n >= cd->cd_ndevs) {
1321 /*
1322 * Need to expand the array.
1323 */
1324 ondevs = cd->cd_ndevs;
1325 osp = cd->cd_devs;
1326
1327 /*
1328 * Release alldevs_lock around allocation, which may
1329 * sleep.
1330 */
1331 mutex_exit(&alldevs_lock);
1332 nsp = kmem_alloc(sizeof(device_t) * nndevs, KM_SLEEP);
1333 mutex_enter(&alldevs_lock);
1334
1335 /*
1336 * If another thread moved the array while we did
1337 * not hold alldevs_lock, try again.
1338 */
1339 if (cd->cd_devs != osp) {
1340 mutex_exit(&alldevs_lock);
1341 kmem_free(nsp, sizeof(device_t) * nndevs);
1342 mutex_enter(&alldevs_lock);
1343 continue;
1344 }
1345
1346 memset(nsp + ondevs, 0, sizeof(device_t) * (nndevs - ondevs));
1347 if (ondevs != 0)
1348 memcpy(nsp, cd->cd_devs, sizeof(device_t) * ondevs);
1349
1350 cd->cd_ndevs = nndevs;
1351 cd->cd_devs = nsp;
1352 if (ondevs != 0) {
1353 mutex_exit(&alldevs_lock);
1354 kmem_free(osp, sizeof(device_t) * ondevs);
1355 mutex_enter(&alldevs_lock);
1356 }
1357 }
1358 KASSERT(mutex_owned(&alldevs_lock));
1359 alldevs_nwrite--;
1360 }
1361
1362 /*
1363 * Put dev into the devices list.
1364 */
1365 static void
1366 config_devlink(device_t dev)
1367 {
1368
1369 mutex_enter(&alldevs_lock);
1370
1371 KASSERT(device_cfdriver(dev)->cd_devs[dev->dv_unit] == dev);
1372
1373 dev->dv_add_gen = alldevs_gen;
1374 /* It is safe to add a device to the tail of the list while
1375 * readers and writers are in the list.
1376 */
1377 TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);
1378 mutex_exit(&alldevs_lock);
1379 }
1380
1381 static void
1382 config_devfree(device_t dev)
1383 {
1384 KASSERT(dev->dv_flags & DVF_PRIV_ALLOC);
1385
1386 if (dev->dv_cfattach->ca_devsize > 0)
1387 kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
1388 kmem_free(dev, sizeof(*dev));
1389 }
1390
1391 /*
1392 * Caller must hold alldevs_lock.
1393 */
1394 static void
1395 config_devunlink(device_t dev, struct devicelist *garbage)
1396 {
1397 struct device_garbage *dg = &dev->dv_garbage;
1398 cfdriver_t cd = device_cfdriver(dev);
1399 int i;
1400
1401 KASSERT(mutex_owned(&alldevs_lock));
1402
1403 /* Unlink from device list. Link to garbage list. */
1404 TAILQ_REMOVE(&alldevs, dev, dv_list);
1405 TAILQ_INSERT_TAIL(garbage, dev, dv_list);
1406
1407 /* Remove from cfdriver's array. */
1408 cd->cd_devs[dev->dv_unit] = NULL;
1409
1410 /*
1411 * If the device now has no units in use, unlink its softc array.
1412 */
1413 for (i = 0; i < cd->cd_ndevs; i++) {
1414 if (cd->cd_devs[i] != NULL)
1415 break;
1416 }
1417 /* Nothing found. Unlink, now. Deallocate, later. */
1418 if (i == cd->cd_ndevs) {
1419 dg->dg_ndevs = cd->cd_ndevs;
1420 dg->dg_devs = cd->cd_devs;
1421 cd->cd_devs = NULL;
1422 cd->cd_ndevs = 0;
1423 }
1424 }
1425
1426 static void
1427 config_devdelete(device_t dev)
1428 {
1429 struct device_garbage *dg = &dev->dv_garbage;
1430 device_lock_t dvl = device_getlock(dev);
1431
1432 if (dg->dg_devs != NULL)
1433 kmem_free(dg->dg_devs, sizeof(device_t) * dg->dg_ndevs);
1434
1435 cv_destroy(&dvl->dvl_cv);
1436 mutex_destroy(&dvl->dvl_mtx);
1437
1438 KASSERT(dev->dv_properties != NULL);
1439 prop_object_release(dev->dv_properties);
1440
1441 if (dev->dv_activity_handlers)
1442 panic("%s with registered handlers", __func__);
1443
1444 if (dev->dv_locators) {
1445 size_t amount = *--dev->dv_locators;
1446 kmem_free(dev->dv_locators, amount);
1447 }
1448
1449 config_devfree(dev);
1450 }
1451
1452 static int
1453 config_unit_nextfree(cfdriver_t cd, cfdata_t cf)
1454 {
1455 int unit;
1456
1457 if (cf->cf_fstate == FSTATE_STAR) {
1458 for (unit = cf->cf_unit; unit < cd->cd_ndevs; unit++)
1459 if (cd->cd_devs[unit] == NULL)
1460 break;
1461 /*
1462 * unit is now the unit of the first NULL device pointer,
1463 * or max(cd->cd_ndevs,cf->cf_unit).
1464 */
1465 } else {
1466 unit = cf->cf_unit;
1467 if (unit < cd->cd_ndevs && cd->cd_devs[unit] != NULL)
1468 unit = -1;
1469 }
1470 return unit;
1471 }
1472
1473 static int
1474 config_unit_alloc(device_t dev, cfdriver_t cd, cfdata_t cf)
1475 {
1476 struct alldevs_foray af;
1477 int unit;
1478
1479 config_alldevs_enter(&af);
1480 for (;;) {
1481 unit = config_unit_nextfree(cd, cf);
1482 if (unit == -1)
1483 break;
1484 if (unit < cd->cd_ndevs) {
1485 cd->cd_devs[unit] = dev;
1486 dev->dv_unit = unit;
1487 break;
1488 }
1489 config_makeroom(unit, cd);
1490 }
1491 config_alldevs_exit(&af);
1492
1493 return unit;
1494 }
1495
1496 static device_t
1497 config_vdevalloc(const device_t parent, const cfdata_t cf, cfarg_t tag,
1498 va_list ap)
1499 {
1500 cfdriver_t cd;
1501 cfattach_t ca;
1502 size_t lname, lunit;
1503 const char *xunit;
1504 int myunit;
1505 char num[10];
1506 device_t dev;
1507 void *dev_private;
1508 const struct cfiattrdata *ia;
1509 device_lock_t dvl;
1510 const int *locs;
1511
1512 cd = config_cfdriver_lookup(cf->cf_name);
1513 if (cd == NULL)
1514 return NULL;
1515
1516 ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1517 if (ca == NULL)
1518 return NULL;
1519
1520 /* get memory for all device vars */
1521 KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
1522 if (ca->ca_devsize > 0) {
1523 dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
1524 } else {
1525 dev_private = NULL;
1526 }
1527 dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1528
1529 /*
1530 * If a handle was supplied to config_attach(), we'll get it
1531 * assigned automatically here. If not, then we'll get the
1532 * default invalid handle.
1533 */
1534 config_get_cfargs(tag, NULL, NULL, &locs, &dev->dv_handle, ap);
1535
1536 dev->dv_class = cd->cd_class;
1537 dev->dv_cfdata = cf;
1538 dev->dv_cfdriver = cd;
1539 dev->dv_cfattach = ca;
1540 dev->dv_activity_count = 0;
1541 dev->dv_activity_handlers = NULL;
1542 dev->dv_private = dev_private;
1543 dev->dv_flags = ca->ca_flags; /* inherit flags from class */
1544
1545 myunit = config_unit_alloc(dev, cd, cf);
1546 if (myunit == -1) {
1547 config_devfree(dev);
1548 return NULL;
1549 }
1550
1551 /* compute length of name and decimal expansion of unit number */
1552 lname = strlen(cd->cd_name);
1553 xunit = number(&num[sizeof(num)], myunit);
1554 lunit = &num[sizeof(num)] - xunit;
1555 if (lname + lunit > sizeof(dev->dv_xname))
1556 panic("config_vdevalloc: device name too long");
1557
1558 dvl = device_getlock(dev);
1559
1560 mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
1561 cv_init(&dvl->dvl_cv, "pmfsusp");
1562
1563 memcpy(dev->dv_xname, cd->cd_name, lname);
1564 memcpy(dev->dv_xname + lname, xunit, lunit);
1565 dev->dv_parent = parent;
1566 if (parent != NULL)
1567 dev->dv_depth = parent->dv_depth + 1;
1568 else
1569 dev->dv_depth = 0;
1570 dev->dv_flags |= DVF_ACTIVE; /* always initially active */
1571 if (locs) {
1572 KASSERT(parent); /* no locators at root */
1573 ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
1574 dev->dv_locators =
1575 kmem_alloc(sizeof(int) * (ia->ci_loclen + 1), KM_SLEEP);
1576 *dev->dv_locators++ = sizeof(int) * (ia->ci_loclen + 1);
1577 memcpy(dev->dv_locators, locs, sizeof(int) * ia->ci_loclen);
1578 }
1579 dev->dv_properties = prop_dictionary_create();
1580 KASSERT(dev->dv_properties != NULL);
1581
1582 prop_dictionary_set_string_nocopy(dev->dv_properties,
1583 "device-driver", dev->dv_cfdriver->cd_name);
1584 prop_dictionary_set_uint16(dev->dv_properties,
1585 "device-unit", dev->dv_unit);
1586 if (parent != NULL) {
1587 prop_dictionary_set_string(dev->dv_properties,
1588 "device-parent", device_xname(parent));
1589 }
1590
1591 if (dev->dv_cfdriver->cd_attrs != NULL)
1592 config_add_attrib_dict(dev);
1593
1594 return dev;
1595 }
1596
1597 static device_t
1598 config_devalloc(const device_t parent, const cfdata_t cf, cfarg_t tag, ...)
1599 {
1600 device_t dev;
1601 va_list ap;
1602
1603 va_start(ap, tag);
1604 dev = config_vdevalloc(parent, cf, tag, ap);
1605 va_end(ap);
1606
1607 return dev;
1608 }
1609
1610 /*
1611 * Create an array of device attach attributes and add it
1612 * to the device's dv_properties dictionary.
1613 *
1614 * <key>interface-attributes</key>
1615 * <array>
1616 * <dict>
1617 * <key>attribute-name</key>
1618 * <string>foo</string>
1619 * <key>locators</key>
1620 * <array>
1621 * <dict>
1622 * <key>loc-name</key>
1623 * <string>foo-loc1</string>
1624 * </dict>
1625 * <dict>
1626 * <key>loc-name</key>
1627 * <string>foo-loc2</string>
1628 * <key>default</key>
1629 * <string>foo-loc2-default</string>
1630 * </dict>
1631 * ...
1632 * </array>
1633 * </dict>
1634 * ...
1635 * </array>
1636 */
1637
1638 static void
1639 config_add_attrib_dict(device_t dev)
1640 {
1641 int i, j;
1642 const struct cfiattrdata *ci;
1643 prop_dictionary_t attr_dict, loc_dict;
1644 prop_array_t attr_array, loc_array;
1645
1646 if ((attr_array = prop_array_create()) == NULL)
1647 return;
1648
1649 for (i = 0; ; i++) {
1650 if ((ci = dev->dv_cfdriver->cd_attrs[i]) == NULL)
1651 break;
1652 if ((attr_dict = prop_dictionary_create()) == NULL)
1653 break;
1654 prop_dictionary_set_string_nocopy(attr_dict, "attribute-name",
1655 ci->ci_name);
1656
1657 /* Create an array of the locator names and defaults */
1658
1659 if (ci->ci_loclen != 0 &&
1660 (loc_array = prop_array_create()) != NULL) {
1661 for (j = 0; j < ci->ci_loclen; j++) {
1662 loc_dict = prop_dictionary_create();
1663 if (loc_dict == NULL)
1664 continue;
1665 prop_dictionary_set_string_nocopy(loc_dict,
1666 "loc-name", ci->ci_locdesc[j].cld_name);
1667 if (ci->ci_locdesc[j].cld_defaultstr != NULL)
1668 prop_dictionary_set_string_nocopy(
1669 loc_dict, "default",
1670 ci->ci_locdesc[j].cld_defaultstr);
1671 prop_array_set(loc_array, j, loc_dict);
1672 prop_object_release(loc_dict);
1673 }
1674 prop_dictionary_set_and_rel(attr_dict, "locators",
1675 loc_array);
1676 }
1677 prop_array_add(attr_array, attr_dict);
1678 prop_object_release(attr_dict);
1679 }
1680 if (i == 0)
1681 prop_object_release(attr_array);
1682 else
1683 prop_dictionary_set_and_rel(dev->dv_properties,
1684 "interface-attributes", attr_array);
1685
1686 return;
1687 }
1688
1689 /*
1690 * Attach a found device.
1691 */
1692 static device_t
1693 config_vattach(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1694 cfarg_t tag, va_list ap)
1695 {
1696 device_t dev;
1697 struct cftable *ct;
1698 const char *drvname;
1699
1700 dev = config_vdevalloc(parent, cf, tag, ap);
1701 if (!dev)
1702 panic("config_attach: allocation of device softc failed");
1703
1704 /* XXX redundant - see below? */
1705 if (cf->cf_fstate != FSTATE_STAR) {
1706 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1707 cf->cf_fstate = FSTATE_FOUND;
1708 }
1709
1710 config_devlink(dev);
1711
1712 if (config_do_twiddle && cold)
1713 twiddle();
1714 else
1715 aprint_naive("Found ");
1716 /*
1717 * We want the next two printfs for normal, verbose, and quiet,
1718 * but not silent (in which case, we're twiddling, instead).
1719 */
1720 if (parent == ROOT) {
1721 aprint_naive("%s (root)", device_xname(dev));
1722 aprint_normal("%s (root)", device_xname(dev));
1723 } else {
1724 aprint_naive("%s at %s", device_xname(dev),
1725 device_xname(parent));
1726 aprint_normal("%s at %s", device_xname(dev),
1727 device_xname(parent));
1728 if (print)
1729 (void) (*print)(aux, NULL);
1730 }
1731
1732 /*
1733 * Before attaching, clobber any unfound devices that are
1734 * otherwise identical.
1735 * XXX code above is redundant?
1736 */
1737 drvname = dev->dv_cfdriver->cd_name;
1738 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1739 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1740 if (STREQ(cf->cf_name, drvname) &&
1741 cf->cf_unit == dev->dv_unit) {
1742 if (cf->cf_fstate == FSTATE_NOTFOUND)
1743 cf->cf_fstate = FSTATE_FOUND;
1744 }
1745 }
1746 }
1747 device_register(dev, aux);
1748
1749 /* Let userland know */
1750 devmon_report_device(dev, true);
1751
1752 (*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1753
1754 if (((dev->dv_flags & DVF_ATTACH_INPROGRESS) == 0)
1755 && !device_pmf_is_registered(dev))
1756 aprint_debug_dev(dev,
1757 "WARNING: power management not supported\n");
1758
1759 config_process_deferred(&deferred_config_queue, dev);
1760
1761 device_register_post_config(dev, aux);
1762 return dev;
1763 }
1764
1765 device_t
1766 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1767 cfarg_t tag, ...)
1768 {
1769 device_t dev;
1770 va_list ap;
1771
1772 va_start(ap, tag);
1773 dev = config_vattach(parent, cf, aux, print, tag, ap);
1774 va_end(ap);
1775
1776 return dev;
1777 }
1778
1779 /*
1780 * As above, but for pseudo-devices. Pseudo-devices attached in this
1781 * way are silently inserted into the device tree, and their children
1782 * attached.
1783 *
1784 * Note that because pseudo-devices are attached silently, any information
1785 * the attach routine wishes to print should be prefixed with the device
1786 * name by the attach routine.
1787 */
1788 device_t
1789 config_attach_pseudo(cfdata_t cf)
1790 {
1791 device_t dev;
1792
1793 dev = config_devalloc(ROOT, cf, CFARG_EOL);
1794 if (!dev)
1795 return NULL;
1796
1797 /* XXX mark busy in cfdata */
1798
1799 if (cf->cf_fstate != FSTATE_STAR) {
1800 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1801 cf->cf_fstate = FSTATE_FOUND;
1802 }
1803
1804 config_devlink(dev);
1805
1806 #if 0 /* XXXJRT not yet */
1807 device_register(dev, NULL); /* like a root node */
1808 #endif
1809
1810 /* Let userland know */
1811 devmon_report_device(dev, true);
1812
1813 (*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1814
1815 config_process_deferred(&deferred_config_queue, dev);
1816 return dev;
1817 }
1818
1819 /*
1820 * Caller must hold alldevs_lock.
1821 */
1822 static void
1823 config_collect_garbage(struct devicelist *garbage)
1824 {
1825 device_t dv;
1826
1827 KASSERT(!cpu_intr_p());
1828 KASSERT(!cpu_softintr_p());
1829 KASSERT(mutex_owned(&alldevs_lock));
1830
1831 while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
1832 TAILQ_FOREACH(dv, &alldevs, dv_list) {
1833 if (dv->dv_del_gen != 0)
1834 break;
1835 }
1836 if (dv == NULL) {
1837 alldevs_garbage = false;
1838 break;
1839 }
1840 config_devunlink(dv, garbage);
1841 }
1842 KASSERT(mutex_owned(&alldevs_lock));
1843 }
1844
1845 static void
1846 config_dump_garbage(struct devicelist *garbage)
1847 {
1848 device_t dv;
1849
1850 while ((dv = TAILQ_FIRST(garbage)) != NULL) {
1851 TAILQ_REMOVE(garbage, dv, dv_list);
1852 config_devdelete(dv);
1853 }
1854 }
1855
1856 /*
1857 * Detach a device. Optionally forced (e.g. because of hardware
1858 * removal) and quiet. Returns zero if successful, non-zero
1859 * (an error code) otherwise.
1860 *
1861 * Note that this code wants to be run from a process context, so
1862 * that the detach can sleep to allow processes which have a device
1863 * open to run and unwind their stacks.
1864 */
1865 int
1866 config_detach(device_t dev, int flags)
1867 {
1868 struct alldevs_foray af;
1869 struct cftable *ct;
1870 cfdata_t cf;
1871 const struct cfattach *ca;
1872 struct cfdriver *cd;
1873 device_t d __diagused;
1874 int rv = 0;
1875
1876 cf = dev->dv_cfdata;
1877 KASSERTMSG((cf == NULL || cf->cf_fstate == FSTATE_FOUND ||
1878 cf->cf_fstate == FSTATE_STAR),
1879 "config_detach: %s: bad device fstate: %d",
1880 device_xname(dev), cf ? cf->cf_fstate : -1);
1881
1882 cd = dev->dv_cfdriver;
1883 KASSERT(cd != NULL);
1884
1885 ca = dev->dv_cfattach;
1886 KASSERT(ca != NULL);
1887
1888 mutex_enter(&alldevs_lock);
1889 if (dev->dv_del_gen != 0) {
1890 mutex_exit(&alldevs_lock);
1891 #ifdef DIAGNOSTIC
1892 printf("%s: %s is already detached\n", __func__,
1893 device_xname(dev));
1894 #endif /* DIAGNOSTIC */
1895 return ENOENT;
1896 }
1897 alldevs_nwrite++;
1898 mutex_exit(&alldevs_lock);
1899
1900 if (!detachall &&
1901 (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
1902 (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
1903 rv = EOPNOTSUPP;
1904 } else if (ca->ca_detach != NULL) {
1905 rv = (*ca->ca_detach)(dev, flags);
1906 } else
1907 rv = EOPNOTSUPP;
1908
1909 /*
1910 * If it was not possible to detach the device, then we either
1911 * panic() (for the forced but failed case), or return an error.
1912 *
1913 * If it was possible to detach the device, ensure that the
1914 * device is deactivated.
1915 */
1916 if (rv == 0)
1917 dev->dv_flags &= ~DVF_ACTIVE;
1918 else if ((flags & DETACH_FORCE) == 0)
1919 goto out;
1920 else {
1921 panic("config_detach: forced detach of %s failed (%d)",
1922 device_xname(dev), rv);
1923 }
1924
1925 /*
1926 * The device has now been successfully detached.
1927 */
1928
1929 /* Let userland know */
1930 devmon_report_device(dev, false);
1931
1932 #ifdef DIAGNOSTIC
1933 /*
1934 * Sanity: If you're successfully detached, you should have no
1935 * children. (Note that because children must be attached
1936 * after parents, we only need to search the latter part of
1937 * the list.)
1938 */
1939 for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
1940 d = TAILQ_NEXT(d, dv_list)) {
1941 if (d->dv_parent == dev && d->dv_del_gen == 0) {
1942 printf("config_detach: detached device %s"
1943 " has children %s\n", device_xname(dev),
1944 device_xname(d));
1945 panic("config_detach");
1946 }
1947 }
1948 #endif
1949
1950 /* notify the parent that the child is gone */
1951 if (dev->dv_parent) {
1952 device_t p = dev->dv_parent;
1953 if (p->dv_cfattach->ca_childdetached)
1954 (*p->dv_cfattach->ca_childdetached)(p, dev);
1955 }
1956
1957 /*
1958 * Mark cfdata to show that the unit can be reused, if possible.
1959 */
1960 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1961 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1962 if (STREQ(cf->cf_name, cd->cd_name)) {
1963 if (cf->cf_fstate == FSTATE_FOUND &&
1964 cf->cf_unit == dev->dv_unit)
1965 cf->cf_fstate = FSTATE_NOTFOUND;
1966 }
1967 }
1968 }
1969
1970 if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
1971 aprint_normal_dev(dev, "detached\n");
1972
1973 out:
1974 config_alldevs_enter(&af);
1975 KASSERT(alldevs_nwrite != 0);
1976 --alldevs_nwrite;
1977 if (rv == 0 && dev->dv_del_gen == 0) {
1978 if (alldevs_nwrite == 0 && alldevs_nread == 0)
1979 config_devunlink(dev, &af.af_garbage);
1980 else {
1981 dev->dv_del_gen = alldevs_gen;
1982 alldevs_garbage = true;
1983 }
1984 }
1985 config_alldevs_exit(&af);
1986
1987 return rv;
1988 }
1989
1990 int
1991 config_detach_children(device_t parent, int flags)
1992 {
1993 device_t dv;
1994 deviter_t di;
1995 int error = 0;
1996
1997 for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
1998 dv = deviter_next(&di)) {
1999 if (device_parent(dv) != parent)
2000 continue;
2001 if ((error = config_detach(dv, flags)) != 0)
2002 break;
2003 }
2004 deviter_release(&di);
2005 return error;
2006 }
2007
2008 device_t
2009 shutdown_first(struct shutdown_state *s)
2010 {
2011 if (!s->initialized) {
2012 deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
2013 s->initialized = true;
2014 }
2015 return shutdown_next(s);
2016 }
2017
2018 device_t
2019 shutdown_next(struct shutdown_state *s)
2020 {
2021 device_t dv;
2022
2023 while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
2024 ;
2025
2026 if (dv == NULL)
2027 s->initialized = false;
2028
2029 return dv;
2030 }
2031
2032 bool
2033 config_detach_all(int how)
2034 {
2035 static struct shutdown_state s;
2036 device_t curdev;
2037 bool progress = false;
2038 int flags;
2039
2040 if ((how & (RB_NOSYNC|RB_DUMP)) != 0)
2041 return false;
2042
2043 if ((how & RB_POWERDOWN) == RB_POWERDOWN)
2044 flags = DETACH_SHUTDOWN | DETACH_POWEROFF;
2045 else
2046 flags = DETACH_SHUTDOWN;
2047
2048 for (curdev = shutdown_first(&s); curdev != NULL;
2049 curdev = shutdown_next(&s)) {
2050 aprint_debug(" detaching %s, ", device_xname(curdev));
2051 if (config_detach(curdev, flags) == 0) {
2052 progress = true;
2053 aprint_debug("success.");
2054 } else
2055 aprint_debug("failed.");
2056 }
2057 return progress;
2058 }
2059
2060 static bool
2061 device_is_ancestor_of(device_t ancestor, device_t descendant)
2062 {
2063 device_t dv;
2064
2065 for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
2066 if (device_parent(dv) == ancestor)
2067 return true;
2068 }
2069 return false;
2070 }
2071
2072 int
2073 config_deactivate(device_t dev)
2074 {
2075 deviter_t di;
2076 const struct cfattach *ca;
2077 device_t descendant;
2078 int s, rv = 0, oflags;
2079
2080 for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
2081 descendant != NULL;
2082 descendant = deviter_next(&di)) {
2083 if (dev != descendant &&
2084 !device_is_ancestor_of(dev, descendant))
2085 continue;
2086
2087 if ((descendant->dv_flags & DVF_ACTIVE) == 0)
2088 continue;
2089
2090 ca = descendant->dv_cfattach;
2091 oflags = descendant->dv_flags;
2092
2093 descendant->dv_flags &= ~DVF_ACTIVE;
2094 if (ca->ca_activate == NULL)
2095 continue;
2096 s = splhigh();
2097 rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
2098 splx(s);
2099 if (rv != 0)
2100 descendant->dv_flags = oflags;
2101 }
2102 deviter_release(&di);
2103 return rv;
2104 }
2105
2106 /*
2107 * Defer the configuration of the specified device until all
2108 * of its parent's devices have been attached.
2109 */
2110 void
2111 config_defer(device_t dev, void (*func)(device_t))
2112 {
2113 struct deferred_config *dc;
2114
2115 if (dev->dv_parent == NULL)
2116 panic("config_defer: can't defer config of a root device");
2117
2118 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2119
2120 config_pending_incr(dev);
2121
2122 mutex_enter(&config_misc_lock);
2123 #ifdef DIAGNOSTIC
2124 struct deferred_config *odc;
2125 TAILQ_FOREACH(odc, &deferred_config_queue, dc_queue) {
2126 if (odc->dc_dev == dev)
2127 panic("config_defer: deferred twice");
2128 }
2129 #endif
2130 dc->dc_dev = dev;
2131 dc->dc_func = func;
2132 TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
2133 mutex_exit(&config_misc_lock);
2134 }
2135
2136 /*
2137 * Defer some autoconfiguration for a device until after interrupts
2138 * are enabled.
2139 */
2140 void
2141 config_interrupts(device_t dev, void (*func)(device_t))
2142 {
2143 struct deferred_config *dc;
2144
2145 /*
2146 * If interrupts are enabled, callback now.
2147 */
2148 if (cold == 0) {
2149 (*func)(dev);
2150 return;
2151 }
2152
2153 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2154
2155 config_pending_incr(dev);
2156
2157 mutex_enter(&config_misc_lock);
2158 #ifdef DIAGNOSTIC
2159 struct deferred_config *odc;
2160 TAILQ_FOREACH(odc, &interrupt_config_queue, dc_queue) {
2161 if (odc->dc_dev == dev)
2162 panic("config_interrupts: deferred twice");
2163 }
2164 #endif
2165 dc->dc_dev = dev;
2166 dc->dc_func = func;
2167 TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
2168 dev->dv_flags |= DVF_ATTACH_INPROGRESS;
2169 mutex_exit(&config_misc_lock);
2170 }
2171
2172 /*
2173 * Defer some autoconfiguration for a device until after root file system
2174 * is mounted (to load firmware etc).
2175 */
2176 void
2177 config_mountroot(device_t dev, void (*func)(device_t))
2178 {
2179 struct deferred_config *dc;
2180
2181 /*
2182 * If root file system is mounted, callback now.
2183 */
2184 if (root_is_mounted) {
2185 (*func)(dev);
2186 return;
2187 }
2188
2189 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2190
2191 mutex_enter(&config_misc_lock);
2192 #ifdef DIAGNOSTIC
2193 struct deferred_config *odc;
2194 TAILQ_FOREACH(odc, &mountroot_config_queue, dc_queue) {
2195 if (odc->dc_dev == dev)
2196 panic("%s: deferred twice", __func__);
2197 }
2198 #endif
2199
2200 dc->dc_dev = dev;
2201 dc->dc_func = func;
2202 TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
2203 mutex_exit(&config_misc_lock);
2204 }
2205
2206 /*
2207 * Process a deferred configuration queue.
2208 */
2209 static void
2210 config_process_deferred(struct deferred_config_head *queue, device_t parent)
2211 {
2212 struct deferred_config *dc;
2213
2214 mutex_enter(&config_misc_lock);
2215 dc = TAILQ_FIRST(queue);
2216 while (dc) {
2217 if (parent == NULL || dc->dc_dev->dv_parent == parent) {
2218 TAILQ_REMOVE(queue, dc, dc_queue);
2219 mutex_exit(&config_misc_lock);
2220
2221 (*dc->dc_func)(dc->dc_dev);
2222 config_pending_decr(dc->dc_dev);
2223 kmem_free(dc, sizeof(*dc));
2224
2225 mutex_enter(&config_misc_lock);
2226 /* Restart, queue might have changed */
2227 dc = TAILQ_FIRST(queue);
2228 } else {
2229 dc = TAILQ_NEXT(dc, dc_queue);
2230 }
2231 }
2232 mutex_exit(&config_misc_lock);
2233 }
2234
2235 /*
2236 * Manipulate the config_pending semaphore.
2237 */
2238 void
2239 config_pending_incr(device_t dev)
2240 {
2241
2242 mutex_enter(&config_misc_lock);
2243 KASSERTMSG(dev->dv_pending < INT_MAX,
2244 "%s: excess config_pending_incr", device_xname(dev));
2245 if (dev->dv_pending++ == 0)
2246 TAILQ_INSERT_TAIL(&config_pending, dev, dv_pending_list);
2247 #ifdef DEBUG_AUTOCONF
2248 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2249 #endif
2250 mutex_exit(&config_misc_lock);
2251 }
2252
2253 void
2254 config_pending_decr(device_t dev)
2255 {
2256
2257 mutex_enter(&config_misc_lock);
2258 KASSERTMSG(dev->dv_pending > 0,
2259 "%s: excess config_pending_decr", device_xname(dev));
2260 if (--dev->dv_pending == 0)
2261 TAILQ_REMOVE(&config_pending, dev, dv_pending_list);
2262 #ifdef DEBUG_AUTOCONF
2263 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2264 #endif
2265 if (TAILQ_EMPTY(&config_pending))
2266 cv_broadcast(&config_misc_cv);
2267 mutex_exit(&config_misc_lock);
2268 }
2269
2270 /*
2271 * Register a "finalization" routine. Finalization routines are
2272 * called iteratively once all real devices have been found during
2273 * autoconfiguration, for as long as any one finalizer has done
2274 * any work.
2275 */
2276 int
2277 config_finalize_register(device_t dev, int (*fn)(device_t))
2278 {
2279 struct finalize_hook *f;
2280
2281 /*
2282 * If finalization has already been done, invoke the
2283 * callback function now.
2284 */
2285 if (config_finalize_done) {
2286 while ((*fn)(dev) != 0)
2287 /* loop */ ;
2288 return 0;
2289 }
2290
2291 /* Ensure this isn't already on the list. */
2292 TAILQ_FOREACH(f, &config_finalize_list, f_list) {
2293 if (f->f_func == fn && f->f_dev == dev)
2294 return EEXIST;
2295 }
2296
2297 f = kmem_alloc(sizeof(*f), KM_SLEEP);
2298 f->f_func = fn;
2299 f->f_dev = dev;
2300 TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
2301
2302 return 0;
2303 }
2304
2305 void
2306 config_finalize(void)
2307 {
2308 struct finalize_hook *f;
2309 struct pdevinit *pdev;
2310 extern struct pdevinit pdevinit[];
2311 int errcnt, rv;
2312
2313 /*
2314 * Now that device driver threads have been created, wait for
2315 * them to finish any deferred autoconfiguration.
2316 */
2317 mutex_enter(&config_misc_lock);
2318 while (!TAILQ_EMPTY(&config_pending)) {
2319 device_t dev;
2320 TAILQ_FOREACH(dev, &config_pending, dv_pending_list)
2321 aprint_debug_dev(dev, "holding up boot\n");
2322 cv_wait(&config_misc_cv, &config_misc_lock);
2323 }
2324 mutex_exit(&config_misc_lock);
2325
2326 KERNEL_LOCK(1, NULL);
2327
2328 /* Attach pseudo-devices. */
2329 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
2330 (*pdev->pdev_attach)(pdev->pdev_count);
2331
2332 /* Run the hooks until none of them does any work. */
2333 do {
2334 rv = 0;
2335 TAILQ_FOREACH(f, &config_finalize_list, f_list)
2336 rv |= (*f->f_func)(f->f_dev);
2337 } while (rv != 0);
2338
2339 config_finalize_done = 1;
2340
2341 /* Now free all the hooks. */
2342 while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
2343 TAILQ_REMOVE(&config_finalize_list, f, f_list);
2344 kmem_free(f, sizeof(*f));
2345 }
2346
2347 KERNEL_UNLOCK_ONE(NULL);
2348
2349 errcnt = aprint_get_error_count();
2350 if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
2351 (boothowto & AB_VERBOSE) == 0) {
2352 mutex_enter(&config_misc_lock);
2353 if (config_do_twiddle) {
2354 config_do_twiddle = 0;
2355 printf_nolog(" done.\n");
2356 }
2357 mutex_exit(&config_misc_lock);
2358 }
2359 if (errcnt != 0) {
2360 printf("WARNING: %d error%s while detecting hardware; "
2361 "check system log.\n", errcnt,
2362 errcnt == 1 ? "" : "s");
2363 }
2364 }
2365
2366 void
2367 config_twiddle_init(void)
2368 {
2369
2370 if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
2371 config_do_twiddle = 1;
2372 }
2373 callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
2374 }
2375
2376 void
2377 config_twiddle_fn(void *cookie)
2378 {
2379
2380 mutex_enter(&config_misc_lock);
2381 if (config_do_twiddle) {
2382 twiddle();
2383 callout_schedule(&config_twiddle_ch, mstohz(100));
2384 }
2385 mutex_exit(&config_misc_lock);
2386 }
2387
2388 static void
2389 config_alldevs_enter(struct alldevs_foray *af)
2390 {
2391 TAILQ_INIT(&af->af_garbage);
2392 mutex_enter(&alldevs_lock);
2393 config_collect_garbage(&af->af_garbage);
2394 }
2395
2396 static void
2397 config_alldevs_exit(struct alldevs_foray *af)
2398 {
2399 mutex_exit(&alldevs_lock);
2400 config_dump_garbage(&af->af_garbage);
2401 }
2402
2403 /*
2404 * device_lookup:
2405 *
2406 * Look up a device instance for a given driver.
2407 */
2408 device_t
2409 device_lookup(cfdriver_t cd, int unit)
2410 {
2411 device_t dv;
2412
2413 mutex_enter(&alldevs_lock);
2414 if (unit < 0 || unit >= cd->cd_ndevs)
2415 dv = NULL;
2416 else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
2417 dv = NULL;
2418 mutex_exit(&alldevs_lock);
2419
2420 return dv;
2421 }
2422
2423 /*
2424 * device_lookup_private:
2425 *
2426 * Look up a softc instance for a given driver.
2427 */
2428 void *
2429 device_lookup_private(cfdriver_t cd, int unit)
2430 {
2431
2432 return device_private(device_lookup(cd, unit));
2433 }
2434
2435 /*
2436 * device_find_by_xname:
2437 *
2438 * Returns the device of the given name or NULL if it doesn't exist.
2439 */
2440 device_t
2441 device_find_by_xname(const char *name)
2442 {
2443 device_t dv;
2444 deviter_t di;
2445
2446 for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
2447 if (strcmp(device_xname(dv), name) == 0)
2448 break;
2449 }
2450 deviter_release(&di);
2451
2452 return dv;
2453 }
2454
2455 /*
2456 * device_find_by_driver_unit:
2457 *
2458 * Returns the device of the given driver name and unit or
2459 * NULL if it doesn't exist.
2460 */
2461 device_t
2462 device_find_by_driver_unit(const char *name, int unit)
2463 {
2464 struct cfdriver *cd;
2465
2466 if ((cd = config_cfdriver_lookup(name)) == NULL)
2467 return NULL;
2468 return device_lookup(cd, unit);
2469 }
2470
2471 static bool
2472 match_strcmp(const char * const s1, const char * const s2)
2473 {
2474 return strcmp(s1, s2) == 0;
2475 }
2476
2477 static bool
2478 match_pmatch(const char * const s1, const char * const s2)
2479 {
2480 return pmatch(s1, s2, NULL) == 2;
2481 }
2482
2483 static bool
2484 strarray_match_internal(const char ** const strings,
2485 unsigned int const nstrings, const char * const str,
2486 unsigned int * const indexp,
2487 bool (*match_fn)(const char *, const char *))
2488 {
2489 unsigned int i;
2490
2491 if (strings == NULL || nstrings == 0) {
2492 return false;
2493 }
2494
2495 for (i = 0; i < nstrings; i++) {
2496 if ((*match_fn)(strings[i], str)) {
2497 *indexp = i;
2498 return true;
2499 }
2500 }
2501
2502 return false;
2503 }
2504
2505 static int
2506 strarray_match(const char ** const strings, unsigned int const nstrings,
2507 const char * const str)
2508 {
2509 unsigned int idx;
2510
2511 if (strarray_match_internal(strings, nstrings, str, &idx,
2512 match_strcmp)) {
2513 return (int)(nstrings - idx);
2514 }
2515 return 0;
2516 }
2517
2518 static int
2519 strarray_pmatch(const char ** const strings, unsigned int const nstrings,
2520 const char * const pattern)
2521 {
2522 unsigned int idx;
2523
2524 if (strarray_match_internal(strings, nstrings, pattern, &idx,
2525 match_pmatch)) {
2526 return (int)(nstrings - idx);
2527 }
2528 return 0;
2529 }
2530
2531 static int
2532 device_compatible_match_strarray_internal(
2533 const char **device_compats, int ndevice_compats,
2534 const struct device_compatible_entry *driver_compats,
2535 const struct device_compatible_entry **matching_entryp,
2536 int (*match_fn)(const char **, unsigned int, const char *))
2537 {
2538 const struct device_compatible_entry *dce = NULL;
2539 int rv;
2540
2541 if (ndevice_compats == 0 || device_compats == NULL ||
2542 driver_compats == NULL)
2543 return 0;
2544
2545 for (dce = driver_compats; dce->compat != NULL; dce++) {
2546 rv = (*match_fn)(device_compats, ndevice_compats, dce->compat);
2547 if (rv != 0) {
2548 if (matching_entryp != NULL) {
2549 *matching_entryp = dce;
2550 }
2551 return rv;
2552 }
2553 }
2554 return 0;
2555 }
2556
2557 /*
2558 * device_compatible_match:
2559 *
2560 * Match a driver's "compatible" data against a device's
2561 * "compatible" strings. Returns resulted weighted by
2562 * which device "compatible" string was matched.
2563 */
2564 int
2565 device_compatible_match(const char **device_compats, int ndevice_compats,
2566 const struct device_compatible_entry *driver_compats)
2567 {
2568 return device_compatible_match_strarray_internal(device_compats,
2569 ndevice_compats, driver_compats, NULL, strarray_match);
2570 }
2571
2572 /*
2573 * device_compatible_pmatch:
2574 *
2575 * Like device_compatible_match(), but uses pmatch(9) to compare
2576 * the device "compatible" strings against patterns in the
2577 * driver's "compatible" data.
2578 */
2579 int
2580 device_compatible_pmatch(const char **device_compats, int ndevice_compats,
2581 const struct device_compatible_entry *driver_compats)
2582 {
2583 return device_compatible_match_strarray_internal(device_compats,
2584 ndevice_compats, driver_compats, NULL, strarray_pmatch);
2585 }
2586
2587 static int
2588 device_compatible_match_strlist_internal(
2589 const char * const device_compats, size_t const device_compatsize,
2590 const struct device_compatible_entry *driver_compats,
2591 const struct device_compatible_entry **matching_entryp,
2592 int (*match_fn)(const char *, size_t, const char *))
2593 {
2594 const struct device_compatible_entry *dce = NULL;
2595 int rv;
2596
2597 if (device_compats == NULL || device_compatsize == 0 ||
2598 driver_compats == NULL)
2599 return 0;
2600
2601 for (dce = driver_compats; dce->compat != NULL; dce++) {
2602 rv = (*match_fn)(device_compats, device_compatsize,
2603 dce->compat);
2604 if (rv != 0) {
2605 if (matching_entryp != NULL) {
2606 *matching_entryp = dce;
2607 }
2608 return rv;
2609 }
2610 }
2611 return 0;
2612 }
2613
2614 /*
2615 * device_compatible_match_strlist:
2616 *
2617 * Like device_compatible_match(), but take the device
2618 * "compatible" strings as an OpenFirmware-style string
2619 * list.
2620 */
2621 int
2622 device_compatible_match_strlist(
2623 const char * const device_compats, size_t const device_compatsize,
2624 const struct device_compatible_entry *driver_compats)
2625 {
2626 return device_compatible_match_strlist_internal(device_compats,
2627 device_compatsize, driver_compats, NULL, strlist_match);
2628 }
2629
2630 /*
2631 * device_compatible_pmatch_strlist:
2632 *
2633 * Like device_compatible_pmatch(), but take the device
2634 * "compatible" strings as an OpenFirmware-style string
2635 * list.
2636 */
2637 int
2638 device_compatible_pmatch_strlist(
2639 const char * const device_compats, size_t const device_compatsize,
2640 const struct device_compatible_entry *driver_compats)
2641 {
2642 return device_compatible_match_strlist_internal(device_compats,
2643 device_compatsize, driver_compats, NULL, strlist_pmatch);
2644 }
2645
2646 static int
2647 device_compatible_match_id_internal(
2648 uintptr_t const id, uintptr_t const mask, uintptr_t const sentinel_id,
2649 const struct device_compatible_entry *driver_compats,
2650 const struct device_compatible_entry **matching_entryp)
2651 {
2652 const struct device_compatible_entry *dce = NULL;
2653
2654 if (mask == 0)
2655 return 0;
2656
2657 for (dce = driver_compats; dce->id != sentinel_id; dce++) {
2658 if ((id & mask) == dce->id) {
2659 if (matching_entryp != NULL) {
2660 *matching_entryp = dce;
2661 }
2662 return 1;
2663 }
2664 }
2665 return 0;
2666 }
2667
2668 /*
2669 * device_compatible_match_id:
2670 *
2671 * Like device_compatible_match(), but takes a single
2672 * unsigned integer device ID.
2673 */
2674 int
2675 device_compatible_match_id(
2676 uintptr_t const id, uintptr_t const sentinel_id,
2677 const struct device_compatible_entry *driver_compats)
2678 {
2679 return device_compatible_match_id_internal(id, (uintptr_t)-1,
2680 sentinel_id, driver_compats, NULL);
2681 }
2682
2683 /*
2684 * device_compatible_lookup:
2685 *
2686 * Look up and return the device_compatible_entry, using the
2687 * same matching criteria used by device_compatible_match().
2688 */
2689 const struct device_compatible_entry *
2690 device_compatible_lookup(const char **device_compats, int ndevice_compats,
2691 const struct device_compatible_entry *driver_compats)
2692 {
2693 const struct device_compatible_entry *dce;
2694
2695 if (device_compatible_match_strarray_internal(device_compats,
2696 ndevice_compats, driver_compats, &dce, strarray_match)) {
2697 return dce;
2698 }
2699 return NULL;
2700 }
2701
2702 /*
2703 * device_compatible_plookup:
2704 *
2705 * Look up and return the device_compatible_entry, using the
2706 * same matching criteria used by device_compatible_pmatch().
2707 */
2708 const struct device_compatible_entry *
2709 device_compatible_plookup(const char **device_compats, int ndevice_compats,
2710 const struct device_compatible_entry *driver_compats)
2711 {
2712 const struct device_compatible_entry *dce;
2713
2714 if (device_compatible_match_strarray_internal(device_compats,
2715 ndevice_compats, driver_compats, &dce, strarray_pmatch)) {
2716 return dce;
2717 }
2718 return NULL;
2719 }
2720
2721 /*
2722 * device_compatible_lookup_strlist:
2723 *
2724 * Like device_compatible_lookup(), but take the device
2725 * "compatible" strings as an OpenFirmware-style string
2726 * list.
2727 */
2728 const struct device_compatible_entry *
2729 device_compatible_lookup_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_match)) {
2737 return dce;
2738 }
2739 return NULL;
2740 }
2741
2742 /*
2743 * device_compatible_plookup_strlist:
2744 *
2745 * Like device_compatible_plookup(), but take the device
2746 * "compatible" strings as an OpenFirmware-style string
2747 * list.
2748 */
2749 const struct device_compatible_entry *
2750 device_compatible_plookup_strlist(
2751 const char * const device_compats, size_t const device_compatsize,
2752 const struct device_compatible_entry *driver_compats)
2753 {
2754 const struct device_compatible_entry *dce;
2755
2756 if (device_compatible_match_strlist_internal(device_compats,
2757 device_compatsize, driver_compats, &dce, strlist_pmatch)) {
2758 return dce;
2759 }
2760 return NULL;
2761 }
2762
2763 /*
2764 * device_compatible_lookup_id:
2765 *
2766 * Like device_compatible_lookup(), but takes a single
2767 * unsigned integer device ID.
2768 */
2769 const struct device_compatible_entry *
2770 device_compatible_lookup_id(
2771 uintptr_t const id, uintptr_t const sentinel_id,
2772 const struct device_compatible_entry *driver_compats)
2773 {
2774 const struct device_compatible_entry *dce;
2775
2776 if (device_compatible_match_id_internal(id, (uintptr_t)-1,
2777 sentinel_id, driver_compats, &dce)) {
2778 return dce;
2779 }
2780 return NULL;
2781 }
2782
2783 /*
2784 * Power management related functions.
2785 */
2786
2787 bool
2788 device_pmf_is_registered(device_t dev)
2789 {
2790 return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
2791 }
2792
2793 bool
2794 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
2795 {
2796 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2797 return true;
2798 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2799 return false;
2800 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2801 dev->dv_driver_suspend != NULL &&
2802 !(*dev->dv_driver_suspend)(dev, qual))
2803 return false;
2804
2805 dev->dv_flags |= DVF_DRIVER_SUSPENDED;
2806 return true;
2807 }
2808
2809 bool
2810 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
2811 {
2812 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2813 return true;
2814 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2815 return false;
2816 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2817 dev->dv_driver_resume != NULL &&
2818 !(*dev->dv_driver_resume)(dev, qual))
2819 return false;
2820
2821 dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
2822 return true;
2823 }
2824
2825 bool
2826 device_pmf_driver_shutdown(device_t dev, int how)
2827 {
2828
2829 if (*dev->dv_driver_shutdown != NULL &&
2830 !(*dev->dv_driver_shutdown)(dev, how))
2831 return false;
2832 return true;
2833 }
2834
2835 bool
2836 device_pmf_driver_register(device_t dev,
2837 bool (*suspend)(device_t, const pmf_qual_t *),
2838 bool (*resume)(device_t, const pmf_qual_t *),
2839 bool (*shutdown)(device_t, int))
2840 {
2841 dev->dv_driver_suspend = suspend;
2842 dev->dv_driver_resume = resume;
2843 dev->dv_driver_shutdown = shutdown;
2844 dev->dv_flags |= DVF_POWER_HANDLERS;
2845 return true;
2846 }
2847
2848 static const char *
2849 curlwp_name(void)
2850 {
2851 if (curlwp->l_name != NULL)
2852 return curlwp->l_name;
2853 else
2854 return curlwp->l_proc->p_comm;
2855 }
2856
2857 void
2858 device_pmf_driver_deregister(device_t dev)
2859 {
2860 device_lock_t dvl = device_getlock(dev);
2861
2862 dev->dv_driver_suspend = NULL;
2863 dev->dv_driver_resume = NULL;
2864
2865 mutex_enter(&dvl->dvl_mtx);
2866 dev->dv_flags &= ~DVF_POWER_HANDLERS;
2867 while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
2868 /* Wake a thread that waits for the lock. That
2869 * thread will fail to acquire the lock, and then
2870 * it will wake the next thread that waits for the
2871 * lock, or else it will wake us.
2872 */
2873 cv_signal(&dvl->dvl_cv);
2874 pmflock_debug(dev, __func__, __LINE__);
2875 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2876 pmflock_debug(dev, __func__, __LINE__);
2877 }
2878 mutex_exit(&dvl->dvl_mtx);
2879 }
2880
2881 bool
2882 device_pmf_driver_child_register(device_t dev)
2883 {
2884 device_t parent = device_parent(dev);
2885
2886 if (parent == NULL || parent->dv_driver_child_register == NULL)
2887 return true;
2888 return (*parent->dv_driver_child_register)(dev);
2889 }
2890
2891 void
2892 device_pmf_driver_set_child_register(device_t dev,
2893 bool (*child_register)(device_t))
2894 {
2895 dev->dv_driver_child_register = child_register;
2896 }
2897
2898 static void
2899 pmflock_debug(device_t dev, const char *func, int line)
2900 {
2901 device_lock_t dvl = device_getlock(dev);
2902
2903 aprint_debug_dev(dev,
2904 "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n", func, line,
2905 curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait, dev->dv_flags);
2906 }
2907
2908 static bool
2909 device_pmf_lock1(device_t dev)
2910 {
2911 device_lock_t dvl = device_getlock(dev);
2912
2913 while (device_pmf_is_registered(dev) &&
2914 dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
2915 dvl->dvl_nwait++;
2916 pmflock_debug(dev, __func__, __LINE__);
2917 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2918 pmflock_debug(dev, __func__, __LINE__);
2919 dvl->dvl_nwait--;
2920 }
2921 if (!device_pmf_is_registered(dev)) {
2922 pmflock_debug(dev, __func__, __LINE__);
2923 /* We could not acquire the lock, but some other thread may
2924 * wait for it, also. Wake that thread.
2925 */
2926 cv_signal(&dvl->dvl_cv);
2927 return false;
2928 }
2929 dvl->dvl_nlock++;
2930 dvl->dvl_holder = curlwp;
2931 pmflock_debug(dev, __func__, __LINE__);
2932 return true;
2933 }
2934
2935 bool
2936 device_pmf_lock(device_t dev)
2937 {
2938 bool rc;
2939 device_lock_t dvl = device_getlock(dev);
2940
2941 mutex_enter(&dvl->dvl_mtx);
2942 rc = device_pmf_lock1(dev);
2943 mutex_exit(&dvl->dvl_mtx);
2944
2945 return rc;
2946 }
2947
2948 void
2949 device_pmf_unlock(device_t dev)
2950 {
2951 device_lock_t dvl = device_getlock(dev);
2952
2953 KASSERT(dvl->dvl_nlock > 0);
2954 mutex_enter(&dvl->dvl_mtx);
2955 if (--dvl->dvl_nlock == 0)
2956 dvl->dvl_holder = NULL;
2957 cv_signal(&dvl->dvl_cv);
2958 pmflock_debug(dev, __func__, __LINE__);
2959 mutex_exit(&dvl->dvl_mtx);
2960 }
2961
2962 device_lock_t
2963 device_getlock(device_t dev)
2964 {
2965 return &dev->dv_lock;
2966 }
2967
2968 void *
2969 device_pmf_bus_private(device_t dev)
2970 {
2971 return dev->dv_bus_private;
2972 }
2973
2974 bool
2975 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
2976 {
2977 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2978 return true;
2979 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
2980 (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2981 return false;
2982 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
2983 dev->dv_bus_suspend != NULL &&
2984 !(*dev->dv_bus_suspend)(dev, qual))
2985 return false;
2986
2987 dev->dv_flags |= DVF_BUS_SUSPENDED;
2988 return true;
2989 }
2990
2991 bool
2992 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
2993 {
2994 if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
2995 return true;
2996 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
2997 dev->dv_bus_resume != NULL &&
2998 !(*dev->dv_bus_resume)(dev, qual))
2999 return false;
3000
3001 dev->dv_flags &= ~DVF_BUS_SUSPENDED;
3002 return true;
3003 }
3004
3005 bool
3006 device_pmf_bus_shutdown(device_t dev, int how)
3007 {
3008
3009 if (*dev->dv_bus_shutdown != NULL &&
3010 !(*dev->dv_bus_shutdown)(dev, how))
3011 return false;
3012 return true;
3013 }
3014
3015 void
3016 device_pmf_bus_register(device_t dev, void *priv,
3017 bool (*suspend)(device_t, const pmf_qual_t *),
3018 bool (*resume)(device_t, const pmf_qual_t *),
3019 bool (*shutdown)(device_t, int), void (*deregister)(device_t))
3020 {
3021 dev->dv_bus_private = priv;
3022 dev->dv_bus_resume = resume;
3023 dev->dv_bus_suspend = suspend;
3024 dev->dv_bus_shutdown = shutdown;
3025 dev->dv_bus_deregister = deregister;
3026 }
3027
3028 void
3029 device_pmf_bus_deregister(device_t dev)
3030 {
3031 if (dev->dv_bus_deregister == NULL)
3032 return;
3033 (*dev->dv_bus_deregister)(dev);
3034 dev->dv_bus_private = NULL;
3035 dev->dv_bus_suspend = NULL;
3036 dev->dv_bus_resume = NULL;
3037 dev->dv_bus_deregister = NULL;
3038 }
3039
3040 void *
3041 device_pmf_class_private(device_t dev)
3042 {
3043 return dev->dv_class_private;
3044 }
3045
3046 bool
3047 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
3048 {
3049 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
3050 return true;
3051 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3052 dev->dv_class_suspend != NULL &&
3053 !(*dev->dv_class_suspend)(dev, qual))
3054 return false;
3055
3056 dev->dv_flags |= DVF_CLASS_SUSPENDED;
3057 return true;
3058 }
3059
3060 bool
3061 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
3062 {
3063 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
3064 return true;
3065 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
3066 (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
3067 return false;
3068 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3069 dev->dv_class_resume != NULL &&
3070 !(*dev->dv_class_resume)(dev, qual))
3071 return false;
3072
3073 dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
3074 return true;
3075 }
3076
3077 void
3078 device_pmf_class_register(device_t dev, void *priv,
3079 bool (*suspend)(device_t, const pmf_qual_t *),
3080 bool (*resume)(device_t, const pmf_qual_t *),
3081 void (*deregister)(device_t))
3082 {
3083 dev->dv_class_private = priv;
3084 dev->dv_class_suspend = suspend;
3085 dev->dv_class_resume = resume;
3086 dev->dv_class_deregister = deregister;
3087 }
3088
3089 void
3090 device_pmf_class_deregister(device_t dev)
3091 {
3092 if (dev->dv_class_deregister == NULL)
3093 return;
3094 (*dev->dv_class_deregister)(dev);
3095 dev->dv_class_private = NULL;
3096 dev->dv_class_suspend = NULL;
3097 dev->dv_class_resume = NULL;
3098 dev->dv_class_deregister = NULL;
3099 }
3100
3101 bool
3102 device_active(device_t dev, devactive_t type)
3103 {
3104 size_t i;
3105
3106 if (dev->dv_activity_count == 0)
3107 return false;
3108
3109 for (i = 0; i < dev->dv_activity_count; ++i) {
3110 if (dev->dv_activity_handlers[i] == NULL)
3111 break;
3112 (*dev->dv_activity_handlers[i])(dev, type);
3113 }
3114
3115 return true;
3116 }
3117
3118 bool
3119 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
3120 {
3121 void (**new_handlers)(device_t, devactive_t);
3122 void (**old_handlers)(device_t, devactive_t);
3123 size_t i, old_size, new_size;
3124 int s;
3125
3126 old_handlers = dev->dv_activity_handlers;
3127 old_size = dev->dv_activity_count;
3128
3129 KASSERT(old_size == 0 || old_handlers != NULL);
3130
3131 for (i = 0; i < old_size; ++i) {
3132 KASSERT(old_handlers[i] != handler);
3133 if (old_handlers[i] == NULL) {
3134 old_handlers[i] = handler;
3135 return true;
3136 }
3137 }
3138
3139 new_size = old_size + 4;
3140 new_handlers = kmem_alloc(sizeof(void *) * new_size, KM_SLEEP);
3141
3142 for (i = 0; i < old_size; ++i)
3143 new_handlers[i] = old_handlers[i];
3144 new_handlers[old_size] = handler;
3145 for (i = old_size+1; i < new_size; ++i)
3146 new_handlers[i] = NULL;
3147
3148 s = splhigh();
3149 dev->dv_activity_count = new_size;
3150 dev->dv_activity_handlers = new_handlers;
3151 splx(s);
3152
3153 if (old_size > 0)
3154 kmem_free(old_handlers, sizeof(void *) * old_size);
3155
3156 return true;
3157 }
3158
3159 void
3160 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
3161 {
3162 void (**old_handlers)(device_t, devactive_t);
3163 size_t i, old_size;
3164 int s;
3165
3166 old_handlers = dev->dv_activity_handlers;
3167 old_size = dev->dv_activity_count;
3168
3169 for (i = 0; i < old_size; ++i) {
3170 if (old_handlers[i] == handler)
3171 break;
3172 if (old_handlers[i] == NULL)
3173 return; /* XXX panic? */
3174 }
3175
3176 if (i == old_size)
3177 return; /* XXX panic? */
3178
3179 for (; i < old_size - 1; ++i) {
3180 if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
3181 continue;
3182
3183 if (i == 0) {
3184 s = splhigh();
3185 dev->dv_activity_count = 0;
3186 dev->dv_activity_handlers = NULL;
3187 splx(s);
3188 kmem_free(old_handlers, sizeof(void *) * old_size);
3189 }
3190 return;
3191 }
3192 old_handlers[i] = NULL;
3193 }
3194
3195 /* Return true iff the device_t `dev' exists at generation `gen'. */
3196 static bool
3197 device_exists_at(device_t dv, devgen_t gen)
3198 {
3199 return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
3200 dv->dv_add_gen <= gen;
3201 }
3202
3203 static bool
3204 deviter_visits(const deviter_t *di, device_t dv)
3205 {
3206 return device_exists_at(dv, di->di_gen);
3207 }
3208
3209 /*
3210 * Device Iteration
3211 *
3212 * deviter_t: a device iterator. Holds state for a "walk" visiting
3213 * each device_t's in the device tree.
3214 *
3215 * deviter_init(di, flags): initialize the device iterator `di'
3216 * to "walk" the device tree. deviter_next(di) will return
3217 * the first device_t in the device tree, or NULL if there are
3218 * no devices.
3219 *
3220 * `flags' is one or more of DEVITER_F_RW, indicating that the
3221 * caller intends to modify the device tree by calling
3222 * config_detach(9) on devices in the order that the iterator
3223 * returns them; DEVITER_F_ROOT_FIRST, asking for the devices
3224 * nearest the "root" of the device tree to be returned, first;
3225 * DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
3226 * the root of the device tree, first; and DEVITER_F_SHUTDOWN,
3227 * indicating both that deviter_init() should not respect any
3228 * locks on the device tree, and that deviter_next(di) may run
3229 * in more than one LWP before the walk has finished.
3230 *
3231 * Only one DEVITER_F_RW iterator may be in the device tree at
3232 * once.
3233 *
3234 * DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
3235 *
3236 * Results are undefined if the flags DEVITER_F_ROOT_FIRST and
3237 * DEVITER_F_LEAVES_FIRST are used in combination.
3238 *
3239 * deviter_first(di, flags): initialize the device iterator `di'
3240 * and return the first device_t in the device tree, or NULL
3241 * if there are no devices. The statement
3242 *
3243 * dv = deviter_first(di);
3244 *
3245 * is shorthand for
3246 *
3247 * deviter_init(di);
3248 * dv = deviter_next(di);
3249 *
3250 * deviter_next(di): return the next device_t in the device tree,
3251 * or NULL if there are no more devices. deviter_next(di)
3252 * is undefined if `di' was not initialized with deviter_init() or
3253 * deviter_first().
3254 *
3255 * deviter_release(di): stops iteration (subsequent calls to
3256 * deviter_next() will return NULL), releases any locks and
3257 * resources held by the device iterator.
3258 *
3259 * Device iteration does not return device_t's in any particular
3260 * order. An iterator will never return the same device_t twice.
3261 * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
3262 * is called repeatedly on the same `di', it will eventually return
3263 * NULL. It is ok to attach/detach devices during device iteration.
3264 */
3265 void
3266 deviter_init(deviter_t *di, deviter_flags_t flags)
3267 {
3268 device_t dv;
3269
3270 memset(di, 0, sizeof(*di));
3271
3272 if ((flags & DEVITER_F_SHUTDOWN) != 0)
3273 flags |= DEVITER_F_RW;
3274
3275 mutex_enter(&alldevs_lock);
3276 if ((flags & DEVITER_F_RW) != 0)
3277 alldevs_nwrite++;
3278 else
3279 alldevs_nread++;
3280 di->di_gen = alldevs_gen++;
3281 di->di_flags = flags;
3282
3283 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3284 case DEVITER_F_LEAVES_FIRST:
3285 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3286 if (!deviter_visits(di, dv))
3287 continue;
3288 di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
3289 }
3290 break;
3291 case DEVITER_F_ROOT_FIRST:
3292 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3293 if (!deviter_visits(di, dv))
3294 continue;
3295 di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
3296 }
3297 break;
3298 default:
3299 break;
3300 }
3301
3302 deviter_reinit(di);
3303 mutex_exit(&alldevs_lock);
3304 }
3305
3306 static void
3307 deviter_reinit(deviter_t *di)
3308 {
3309
3310 KASSERT(mutex_owned(&alldevs_lock));
3311 if ((di->di_flags & DEVITER_F_RW) != 0)
3312 di->di_prev = TAILQ_LAST(&alldevs, devicelist);
3313 else
3314 di->di_prev = TAILQ_FIRST(&alldevs);
3315 }
3316
3317 device_t
3318 deviter_first(deviter_t *di, deviter_flags_t flags)
3319 {
3320
3321 deviter_init(di, flags);
3322 return deviter_next(di);
3323 }
3324
3325 static device_t
3326 deviter_next2(deviter_t *di)
3327 {
3328 device_t dv;
3329
3330 KASSERT(mutex_owned(&alldevs_lock));
3331
3332 dv = di->di_prev;
3333
3334 if (dv == NULL)
3335 return NULL;
3336
3337 if ((di->di_flags & DEVITER_F_RW) != 0)
3338 di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
3339 else
3340 di->di_prev = TAILQ_NEXT(dv, dv_list);
3341
3342 return dv;
3343 }
3344
3345 static device_t
3346 deviter_next1(deviter_t *di)
3347 {
3348 device_t dv;
3349
3350 KASSERT(mutex_owned(&alldevs_lock));
3351
3352 do {
3353 dv = deviter_next2(di);
3354 } while (dv != NULL && !deviter_visits(di, dv));
3355
3356 return dv;
3357 }
3358
3359 device_t
3360 deviter_next(deviter_t *di)
3361 {
3362 device_t dv = NULL;
3363
3364 mutex_enter(&alldevs_lock);
3365 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3366 case 0:
3367 dv = deviter_next1(di);
3368 break;
3369 case DEVITER_F_LEAVES_FIRST:
3370 while (di->di_curdepth >= 0) {
3371 if ((dv = deviter_next1(di)) == NULL) {
3372 di->di_curdepth--;
3373 deviter_reinit(di);
3374 } else if (dv->dv_depth == di->di_curdepth)
3375 break;
3376 }
3377 break;
3378 case DEVITER_F_ROOT_FIRST:
3379 while (di->di_curdepth <= di->di_maxdepth) {
3380 if ((dv = deviter_next1(di)) == NULL) {
3381 di->di_curdepth++;
3382 deviter_reinit(di);
3383 } else if (dv->dv_depth == di->di_curdepth)
3384 break;
3385 }
3386 break;
3387 default:
3388 break;
3389 }
3390 mutex_exit(&alldevs_lock);
3391
3392 return dv;
3393 }
3394
3395 void
3396 deviter_release(deviter_t *di)
3397 {
3398 bool rw = (di->di_flags & DEVITER_F_RW) != 0;
3399
3400 mutex_enter(&alldevs_lock);
3401 if (rw)
3402 --alldevs_nwrite;
3403 else
3404 --alldevs_nread;
3405 /* XXX wake a garbage-collection thread */
3406 mutex_exit(&alldevs_lock);
3407 }
3408
3409 const char *
3410 cfdata_ifattr(const struct cfdata *cf)
3411 {
3412 return cf->cf_pspec->cfp_iattr;
3413 }
3414
3415 bool
3416 ifattr_match(const char *snull, const char *t)
3417 {
3418 return (snull == NULL) || strcmp(snull, t) == 0;
3419 }
3420
3421 void
3422 null_childdetached(device_t self, device_t child)
3423 {
3424 /* do nothing */
3425 }
3426
3427 static void
3428 sysctl_detach_setup(struct sysctllog **clog)
3429 {
3430
3431 sysctl_createv(clog, 0, NULL, NULL,
3432 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3433 CTLTYPE_BOOL, "detachall",
3434 SYSCTL_DESCR("Detach all devices at shutdown"),
3435 NULL, 0, &detachall, 0,
3436 CTL_KERN, CTL_CREATE, CTL_EOL);
3437 }
3438