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