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