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