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