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