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