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