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