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