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