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