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