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