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