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