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