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