Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.223.2.5
      1 /* $NetBSD: subr_autoconf.c,v 1.223.2.5 2017/12/03 11:38:45 jdolecek 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.223.2.5 2017/12/03 11:38:45 jdolecek 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 		dev->dv_maxphys = parent->dv_maxphys;
   1435 	} else {
   1436 		dev->dv_depth = 0;
   1437 		dev->dv_maxphys = MACHINE_MAXPHYS;
   1438 	}
   1439 	aprint_debug_dev(dev, "dv_maxphys = %d", dev->dv_maxphys);
   1440 	dev->dv_flags |= DVF_ACTIVE;	/* always initially active */
   1441 	if (locs) {
   1442 		KASSERT(parent); /* no locators at root */
   1443 		ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
   1444 		dev->dv_locators =
   1445 		    kmem_alloc(sizeof(int [ia->ci_loclen + 1]), KM_SLEEP);
   1446 		*dev->dv_locators++ = sizeof(int [ia->ci_loclen + 1]);
   1447 		memcpy(dev->dv_locators, locs, sizeof(int [ia->ci_loclen]));
   1448 	}
   1449 	dev->dv_properties = prop_dictionary_create();
   1450 	KASSERT(dev->dv_properties != NULL);
   1451 
   1452 	prop_dictionary_set_cstring_nocopy(dev->dv_properties,
   1453 	    "device-driver", dev->dv_cfdriver->cd_name);
   1454 	prop_dictionary_set_uint16(dev->dv_properties,
   1455 	    "device-unit", dev->dv_unit);
   1456 	if (parent != NULL) {
   1457 		prop_dictionary_set_cstring(dev->dv_properties,
   1458 		    "device-parent", device_xname(parent));
   1459 	}
   1460 
   1461 	if (dev->dv_cfdriver->cd_attrs != NULL)
   1462 		config_add_attrib_dict(dev);
   1463 
   1464 	return dev;
   1465 }
   1466 
   1467 /*
   1468  * Create an array of device attach attributes and add it
   1469  * to the device's dv_properties dictionary.
   1470  *
   1471  * <key>interface-attributes</key>
   1472  * <array>
   1473  *    <dict>
   1474  *       <key>attribute-name</key>
   1475  *       <string>foo</string>
   1476  *       <key>locators</key>
   1477  *       <array>
   1478  *          <dict>
   1479  *             <key>loc-name</key>
   1480  *             <string>foo-loc1</string>
   1481  *          </dict>
   1482  *          <dict>
   1483  *             <key>loc-name</key>
   1484  *             <string>foo-loc2</string>
   1485  *             <key>default</key>
   1486  *             <string>foo-loc2-default</string>
   1487  *          </dict>
   1488  *          ...
   1489  *       </array>
   1490  *    </dict>
   1491  *    ...
   1492  * </array>
   1493  */
   1494 
   1495 static void
   1496 config_add_attrib_dict(device_t dev)
   1497 {
   1498 	int i, j;
   1499 	const struct cfiattrdata *ci;
   1500 	prop_dictionary_t attr_dict, loc_dict;
   1501 	prop_array_t attr_array, loc_array;
   1502 
   1503 	if ((attr_array = prop_array_create()) == NULL)
   1504 		return;
   1505 
   1506 	for (i = 0; ; i++) {
   1507 		if ((ci = dev->dv_cfdriver->cd_attrs[i]) == NULL)
   1508 			break;
   1509 		if ((attr_dict = prop_dictionary_create()) == NULL)
   1510 			break;
   1511 		prop_dictionary_set_cstring_nocopy(attr_dict, "attribute-name",
   1512 		    ci->ci_name);
   1513 
   1514 		/* Create an array of the locator names and defaults */
   1515 
   1516 		if (ci->ci_loclen != 0 &&
   1517 		    (loc_array = prop_array_create()) != NULL) {
   1518 			for (j = 0; j < ci->ci_loclen; j++) {
   1519 				loc_dict = prop_dictionary_create();
   1520 				if (loc_dict == NULL)
   1521 					continue;
   1522 				prop_dictionary_set_cstring_nocopy(loc_dict,
   1523 				    "loc-name", ci->ci_locdesc[j].cld_name);
   1524 				if (ci->ci_locdesc[j].cld_defaultstr != NULL)
   1525 					prop_dictionary_set_cstring_nocopy(
   1526 					    loc_dict, "default",
   1527 					    ci->ci_locdesc[j].cld_defaultstr);
   1528 				prop_array_set(loc_array, j, loc_dict);
   1529 				prop_object_release(loc_dict);
   1530 			}
   1531 			prop_dictionary_set_and_rel(attr_dict, "locators",
   1532 			    loc_array);
   1533 		}
   1534 		prop_array_add(attr_array, attr_dict);
   1535 		prop_object_release(attr_dict);
   1536 	}
   1537 	if (i == 0)
   1538 		prop_object_release(attr_array);
   1539 	else
   1540 		prop_dictionary_set_and_rel(dev->dv_properties,
   1541 		    "interface-attributes", attr_array);
   1542 
   1543 	return;
   1544 }
   1545 
   1546 /*
   1547  * Attach a found device.
   1548  */
   1549 device_t
   1550 config_attach_loc(device_t parent, cfdata_t cf,
   1551 	const int *locs, void *aux, cfprint_t print)
   1552 {
   1553 	device_t dev;
   1554 	struct cftable *ct;
   1555 	const char *drvname;
   1556 
   1557 	dev = config_devalloc(parent, cf, locs);
   1558 	if (!dev)
   1559 		panic("config_attach: allocation of device softc failed");
   1560 
   1561 	/* XXX redundant - see below? */
   1562 	if (cf->cf_fstate != FSTATE_STAR) {
   1563 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
   1564 		cf->cf_fstate = FSTATE_FOUND;
   1565 	}
   1566 
   1567 	config_devlink(dev);
   1568 
   1569 	if (config_do_twiddle && cold)
   1570 		twiddle();
   1571 	else
   1572 		aprint_naive("Found ");
   1573 	/*
   1574 	 * We want the next two printfs for normal, verbose, and quiet,
   1575 	 * but not silent (in which case, we're twiddling, instead).
   1576 	 */
   1577 	if (parent == ROOT) {
   1578 		aprint_naive("%s (root)", device_xname(dev));
   1579 		aprint_normal("%s (root)", device_xname(dev));
   1580 	} else {
   1581 		aprint_naive("%s at %s", device_xname(dev),
   1582 		    device_xname(parent));
   1583 		aprint_normal("%s at %s", device_xname(dev),
   1584 		    device_xname(parent));
   1585 		if (print)
   1586 			(void) (*print)(aux, NULL);
   1587 	}
   1588 
   1589 	/*
   1590 	 * Before attaching, clobber any unfound devices that are
   1591 	 * otherwise identical.
   1592 	 * XXX code above is redundant?
   1593 	 */
   1594 	drvname = dev->dv_cfdriver->cd_name;
   1595 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
   1596 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
   1597 			if (STREQ(cf->cf_name, drvname) &&
   1598 			    cf->cf_unit == dev->dv_unit) {
   1599 				if (cf->cf_fstate == FSTATE_NOTFOUND)
   1600 					cf->cf_fstate = FSTATE_FOUND;
   1601 			}
   1602 		}
   1603 	}
   1604 	device_register(dev, aux);
   1605 
   1606 	/* Let userland know */
   1607 	devmon_report_device(dev, true);
   1608 
   1609 	(*dev->dv_cfattach->ca_attach)(parent, dev, aux);
   1610 
   1611 	if (!device_pmf_is_registered(dev))
   1612 		aprint_debug_dev(dev, "WARNING: power management not "
   1613 		    "supported\n");
   1614 
   1615 	config_process_deferred(&deferred_config_queue, dev);
   1616 
   1617 	device_register_post_config(dev, aux);
   1618 	return dev;
   1619 }
   1620 
   1621 device_t
   1622 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print)
   1623 {
   1624 
   1625 	return config_attach_loc(parent, cf, NULL, aux, print);
   1626 }
   1627 
   1628 /*
   1629  * As above, but for pseudo-devices.  Pseudo-devices attached in this
   1630  * way are silently inserted into the device tree, and their children
   1631  * attached.
   1632  *
   1633  * Note that because pseudo-devices are attached silently, any information
   1634  * the attach routine wishes to print should be prefixed with the device
   1635  * name by the attach routine.
   1636  */
   1637 device_t
   1638 config_attach_pseudo(cfdata_t cf)
   1639 {
   1640 	device_t dev;
   1641 
   1642 	dev = config_devalloc(ROOT, cf, NULL);
   1643 	if (!dev)
   1644 		return NULL;
   1645 
   1646 	/* XXX mark busy in cfdata */
   1647 
   1648 	if (cf->cf_fstate != FSTATE_STAR) {
   1649 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
   1650 		cf->cf_fstate = FSTATE_FOUND;
   1651 	}
   1652 
   1653 	config_devlink(dev);
   1654 
   1655 #if 0	/* XXXJRT not yet */
   1656 	device_register(dev, NULL);	/* like a root node */
   1657 #endif
   1658 
   1659 	/* Let userland know */
   1660 	devmon_report_device(dev, true);
   1661 
   1662 	(*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
   1663 
   1664 	config_process_deferred(&deferred_config_queue, dev);
   1665 	return dev;
   1666 }
   1667 
   1668 /*
   1669  * Caller must hold alldevs.lock.
   1670  */
   1671 static void
   1672 config_collect_garbage(struct devicelist *garbage)
   1673 {
   1674 	device_t dv;
   1675 
   1676 	KASSERT(!cpu_intr_p());
   1677 	KASSERT(!cpu_softintr_p());
   1678 	KASSERT(mutex_owned(&alldevs.lock));
   1679 
   1680 	while (alldevs.nwrite == 0 && alldevs.nread == 0 && alldevs.garbage) {
   1681 		TAILQ_FOREACH(dv, &alldevs.list, dv_list) {
   1682 			if (dv->dv_del_gen != 0)
   1683 				break;
   1684 		}
   1685 		if (dv == NULL) {
   1686 			alldevs.garbage = false;
   1687 			break;
   1688 		}
   1689 		config_devunlink(dv, garbage);
   1690 	}
   1691 	KASSERT(mutex_owned(&alldevs.lock));
   1692 }
   1693 
   1694 static void
   1695 config_dump_garbage(struct devicelist *garbage)
   1696 {
   1697 	device_t dv;
   1698 
   1699 	while ((dv = TAILQ_FIRST(garbage)) != NULL) {
   1700 		TAILQ_REMOVE(garbage, dv, dv_list);
   1701 		config_devdelete(dv);
   1702 	}
   1703 }
   1704 
   1705 /*
   1706  * Detach a device.  Optionally forced (e.g. because of hardware
   1707  * removal) and quiet.  Returns zero if successful, non-zero
   1708  * (an error code) otherwise.
   1709  *
   1710  * Note that this code wants to be run from a process context, so
   1711  * that the detach can sleep to allow processes which have a device
   1712  * open to run and unwind their stacks.
   1713  */
   1714 int
   1715 config_detach(device_t dev, int flags)
   1716 {
   1717 	struct alldevs_foray af;
   1718 	struct cftable *ct;
   1719 	cfdata_t cf;
   1720 	const struct cfattach *ca;
   1721 	struct cfdriver *cd;
   1722 	device_t d __diagused;
   1723 	int rv = 0;
   1724 
   1725 	cf = dev->dv_cfdata;
   1726 	KASSERTMSG((cf == NULL || cf->cf_fstate == FSTATE_FOUND ||
   1727 		cf->cf_fstate == FSTATE_STAR),
   1728 	    "config_detach: %s: bad device fstate: %d",
   1729 	    device_xname(dev), cf ? cf->cf_fstate : -1);
   1730 
   1731 	cd = dev->dv_cfdriver;
   1732 	KASSERT(cd != NULL);
   1733 
   1734 	ca = dev->dv_cfattach;
   1735 	KASSERT(ca != NULL);
   1736 
   1737 	mutex_enter(&alldevs.lock);
   1738 	if (dev->dv_del_gen != 0) {
   1739 		mutex_exit(&alldevs.lock);
   1740 #ifdef DIAGNOSTIC
   1741 		printf("%s: %s is already detached\n", __func__,
   1742 		    device_xname(dev));
   1743 #endif /* DIAGNOSTIC */
   1744 		return ENOENT;
   1745 	}
   1746 	alldevs.nwrite++;
   1747 	mutex_exit(&alldevs.lock);
   1748 
   1749 	if (!detachall &&
   1750 	    (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
   1751 	    (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
   1752 		rv = EOPNOTSUPP;
   1753 	} else if (ca->ca_detach != NULL) {
   1754 		rv = (*ca->ca_detach)(dev, flags);
   1755 	} else
   1756 		rv = EOPNOTSUPP;
   1757 
   1758 	/*
   1759 	 * If it was not possible to detach the device, then we either
   1760 	 * panic() (for the forced but failed case), or return an error.
   1761 	 *
   1762 	 * If it was possible to detach the device, ensure that the
   1763 	 * device is deactivated.
   1764 	 */
   1765 	if (rv == 0)
   1766 		dev->dv_flags &= ~DVF_ACTIVE;
   1767 	else if ((flags & DETACH_FORCE) == 0)
   1768 		goto out;
   1769 	else {
   1770 		panic("config_detach: forced detach of %s failed (%d)",
   1771 		    device_xname(dev), rv);
   1772 	}
   1773 
   1774 	/*
   1775 	 * The device has now been successfully detached.
   1776 	 */
   1777 
   1778 	/* Let userland know */
   1779 	devmon_report_device(dev, false);
   1780 
   1781 #ifdef DIAGNOSTIC
   1782 	/*
   1783 	 * Sanity: If you're successfully detached, you should have no
   1784 	 * children.  (Note that because children must be attached
   1785 	 * after parents, we only need to search the latter part of
   1786 	 * the list.)
   1787 	 */
   1788 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
   1789 	    d = TAILQ_NEXT(d, dv_list)) {
   1790 		if (d->dv_parent == dev && d->dv_del_gen == 0) {
   1791 			printf("config_detach: detached device %s"
   1792 			    " has children %s\n", device_xname(dev),
   1793 			    device_xname(d));
   1794 			panic("config_detach");
   1795 		}
   1796 	}
   1797 #endif
   1798 
   1799 	/* notify the parent that the child is gone */
   1800 	if (dev->dv_parent) {
   1801 		device_t p = dev->dv_parent;
   1802 		if (p->dv_cfattach->ca_childdetached)
   1803 			(*p->dv_cfattach->ca_childdetached)(p, dev);
   1804 	}
   1805 
   1806 	/*
   1807 	 * Mark cfdata to show that the unit can be reused, if possible.
   1808 	 */
   1809 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
   1810 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
   1811 			if (STREQ(cf->cf_name, cd->cd_name)) {
   1812 				if (cf->cf_fstate == FSTATE_FOUND &&
   1813 				    cf->cf_unit == dev->dv_unit)
   1814 					cf->cf_fstate = FSTATE_NOTFOUND;
   1815 			}
   1816 		}
   1817 	}
   1818 
   1819 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
   1820 		aprint_normal_dev(dev, "detached\n");
   1821 
   1822 out:
   1823 	config_alldevs_enter(&af);
   1824 	KASSERT(alldevs.nwrite != 0);
   1825 	--alldevs.nwrite;
   1826 	if (rv == 0 && dev->dv_del_gen == 0) {
   1827 		if (alldevs.nwrite == 0 && alldevs.nread == 0)
   1828 			config_devunlink(dev, &af.af_garbage);
   1829 		else {
   1830 			dev->dv_del_gen = alldevs.gen;
   1831 			alldevs.garbage = true;
   1832 		}
   1833 	}
   1834 	config_alldevs_exit(&af);
   1835 
   1836 	return rv;
   1837 }
   1838 
   1839 int
   1840 config_detach_children(device_t parent, int flags)
   1841 {
   1842 	device_t dv;
   1843 	deviter_t di;
   1844 	int error = 0;
   1845 
   1846 	for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
   1847 	     dv = deviter_next(&di)) {
   1848 		if (device_parent(dv) != parent)
   1849 			continue;
   1850 		if ((error = config_detach(dv, flags)) != 0)
   1851 			break;
   1852 	}
   1853 	deviter_release(&di);
   1854 	return error;
   1855 }
   1856 
   1857 device_t
   1858 shutdown_first(struct shutdown_state *s)
   1859 {
   1860 	if (!s->initialized) {
   1861 		deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
   1862 		s->initialized = true;
   1863 	}
   1864 	return shutdown_next(s);
   1865 }
   1866 
   1867 device_t
   1868 shutdown_next(struct shutdown_state *s)
   1869 {
   1870 	device_t dv;
   1871 
   1872 	while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
   1873 		;
   1874 
   1875 	if (dv == NULL)
   1876 		s->initialized = false;
   1877 
   1878 	return dv;
   1879 }
   1880 
   1881 bool
   1882 config_detach_all(int how)
   1883 {
   1884 	static struct shutdown_state s;
   1885 	device_t curdev;
   1886 	bool progress = false;
   1887 	int flags;
   1888 
   1889 	if ((how & (RB_NOSYNC|RB_DUMP)) != 0)
   1890 		return false;
   1891 
   1892 	if ((how & RB_POWERDOWN) == RB_POWERDOWN)
   1893 		flags = DETACH_SHUTDOWN | DETACH_POWEROFF;
   1894 	else
   1895 		flags = DETACH_SHUTDOWN;
   1896 
   1897 	for (curdev = shutdown_first(&s); curdev != NULL;
   1898 	     curdev = shutdown_next(&s)) {
   1899 		aprint_debug(" detaching %s, ", device_xname(curdev));
   1900 		if (config_detach(curdev, flags) == 0) {
   1901 			progress = true;
   1902 			aprint_debug("success.");
   1903 		} else
   1904 			aprint_debug("failed.");
   1905 	}
   1906 	return progress;
   1907 }
   1908 
   1909 static bool
   1910 device_is_ancestor_of(device_t ancestor, device_t descendant)
   1911 {
   1912 	device_t dv;
   1913 
   1914 	for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
   1915 		if (device_parent(dv) == ancestor)
   1916 			return true;
   1917 	}
   1918 	return false;
   1919 }
   1920 
   1921 int
   1922 config_deactivate(device_t dev)
   1923 {
   1924 	deviter_t di;
   1925 	const struct cfattach *ca;
   1926 	device_t descendant;
   1927 	int s, rv = 0, oflags;
   1928 
   1929 	for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
   1930 	     descendant != NULL;
   1931 	     descendant = deviter_next(&di)) {
   1932 		if (dev != descendant &&
   1933 		    !device_is_ancestor_of(dev, descendant))
   1934 			continue;
   1935 
   1936 		if ((descendant->dv_flags & DVF_ACTIVE) == 0)
   1937 			continue;
   1938 
   1939 		ca = descendant->dv_cfattach;
   1940 		oflags = descendant->dv_flags;
   1941 
   1942 		descendant->dv_flags &= ~DVF_ACTIVE;
   1943 		if (ca->ca_activate == NULL)
   1944 			continue;
   1945 		s = splhigh();
   1946 		rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
   1947 		splx(s);
   1948 		if (rv != 0)
   1949 			descendant->dv_flags = oflags;
   1950 	}
   1951 	deviter_release(&di);
   1952 	return rv;
   1953 }
   1954 
   1955 /*
   1956  * Defer the configuration of the specified device until all
   1957  * of its parent's devices have been attached.
   1958  */
   1959 void
   1960 config_defer(device_t dev, void (*func)(device_t))
   1961 {
   1962 	struct deferred_config *dc;
   1963 
   1964 	if (dev->dv_parent == NULL)
   1965 		panic("config_defer: can't defer config of a root device");
   1966 
   1967 #ifdef DIAGNOSTIC
   1968 	TAILQ_FOREACH(dc, &deferred_config_queue, dc_queue) {
   1969 		if (dc->dc_dev == dev)
   1970 			panic("config_defer: deferred twice");
   1971 	}
   1972 #endif
   1973 
   1974 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   1975 	dc->dc_dev = dev;
   1976 	dc->dc_func = func;
   1977 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
   1978 	config_pending_incr(dev);
   1979 }
   1980 
   1981 /*
   1982  * Defer some autoconfiguration for a device until after interrupts
   1983  * are enabled.
   1984  */
   1985 void
   1986 config_interrupts(device_t dev, void (*func)(device_t))
   1987 {
   1988 	struct deferred_config *dc;
   1989 
   1990 	/*
   1991 	 * If interrupts are enabled, callback now.
   1992 	 */
   1993 	if (cold == 0) {
   1994 		(*func)(dev);
   1995 		return;
   1996 	}
   1997 
   1998 #ifdef DIAGNOSTIC
   1999 	TAILQ_FOREACH(dc, &interrupt_config_queue, dc_queue) {
   2000 		if (dc->dc_dev == dev)
   2001 			panic("config_interrupts: deferred twice");
   2002 	}
   2003 #endif
   2004 
   2005 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   2006 	dc->dc_dev = dev;
   2007 	dc->dc_func = func;
   2008 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
   2009 	config_pending_incr(dev);
   2010 }
   2011 
   2012 /*
   2013  * Defer some autoconfiguration for a device until after root file system
   2014  * is mounted (to load firmware etc).
   2015  */
   2016 void
   2017 config_mountroot(device_t dev, void (*func)(device_t))
   2018 {
   2019 	struct deferred_config *dc;
   2020 
   2021 	/*
   2022 	 * If root file system is mounted, callback now.
   2023 	 */
   2024 	if (root_is_mounted) {
   2025 		(*func)(dev);
   2026 		return;
   2027 	}
   2028 
   2029 #ifdef DIAGNOSTIC
   2030 	TAILQ_FOREACH(dc, &mountroot_config_queue, dc_queue) {
   2031 		if (dc->dc_dev == dev)
   2032 			panic("%s: deferred twice", __func__);
   2033 	}
   2034 #endif
   2035 
   2036 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   2037 	dc->dc_dev = dev;
   2038 	dc->dc_func = func;
   2039 	TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
   2040 }
   2041 
   2042 /*
   2043  * Process a deferred configuration queue.
   2044  */
   2045 static void
   2046 config_process_deferred(struct deferred_config_head *queue, device_t parent)
   2047 {
   2048 	struct deferred_config *dc, *ndc;
   2049 
   2050 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
   2051 		ndc = TAILQ_NEXT(dc, dc_queue);
   2052 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
   2053 			TAILQ_REMOVE(queue, dc, dc_queue);
   2054 			(*dc->dc_func)(dc->dc_dev);
   2055 			config_pending_decr(dc->dc_dev);
   2056 			kmem_free(dc, sizeof(*dc));
   2057 		}
   2058 	}
   2059 }
   2060 
   2061 /*
   2062  * Manipulate the config_pending semaphore.
   2063  */
   2064 void
   2065 config_pending_incr(device_t dev)
   2066 {
   2067 
   2068 	mutex_enter(&config_misc_lock);
   2069 	config_pending++;
   2070 #ifdef DEBUG_AUTOCONF
   2071 	printf("%s: %s %d\n", __func__, device_xname(dev), config_pending);
   2072 #endif
   2073 	mutex_exit(&config_misc_lock);
   2074 }
   2075 
   2076 void
   2077 config_pending_decr(device_t dev)
   2078 {
   2079 
   2080 	KASSERT(0 < config_pending);
   2081 	mutex_enter(&config_misc_lock);
   2082 	config_pending--;
   2083 #ifdef DEBUG_AUTOCONF
   2084 	printf("%s: %s %d\n", __func__, device_xname(dev), config_pending);
   2085 #endif
   2086 	if (config_pending == 0)
   2087 		cv_broadcast(&config_misc_cv);
   2088 	mutex_exit(&config_misc_lock);
   2089 }
   2090 
   2091 /*
   2092  * Register a "finalization" routine.  Finalization routines are
   2093  * called iteratively once all real devices have been found during
   2094  * autoconfiguration, for as long as any one finalizer has done
   2095  * any work.
   2096  */
   2097 int
   2098 config_finalize_register(device_t dev, int (*fn)(device_t))
   2099 {
   2100 	struct finalize_hook *f;
   2101 
   2102 	/*
   2103 	 * If finalization has already been done, invoke the
   2104 	 * callback function now.
   2105 	 */
   2106 	if (config_finalize_done) {
   2107 		while ((*fn)(dev) != 0)
   2108 			/* loop */ ;
   2109 		return 0;
   2110 	}
   2111 
   2112 	/* Ensure this isn't already on the list. */
   2113 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
   2114 		if (f->f_func == fn && f->f_dev == dev)
   2115 			return EEXIST;
   2116 	}
   2117 
   2118 	f = kmem_alloc(sizeof(*f), KM_SLEEP);
   2119 	f->f_func = fn;
   2120 	f->f_dev = dev;
   2121 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
   2122 
   2123 	return 0;
   2124 }
   2125 
   2126 void
   2127 config_finalize(void)
   2128 {
   2129 	struct finalize_hook *f;
   2130 	struct pdevinit *pdev;
   2131 	extern struct pdevinit pdevinit[];
   2132 	int errcnt, rv;
   2133 
   2134 	/*
   2135 	 * Now that device driver threads have been created, wait for
   2136 	 * them to finish any deferred autoconfiguration.
   2137 	 */
   2138 	mutex_enter(&config_misc_lock);
   2139 	while (config_pending != 0)
   2140 		cv_wait(&config_misc_cv, &config_misc_lock);
   2141 	mutex_exit(&config_misc_lock);
   2142 
   2143 	KERNEL_LOCK(1, NULL);
   2144 
   2145 	/* Attach pseudo-devices. */
   2146 	for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
   2147 		(*pdev->pdev_attach)(pdev->pdev_count);
   2148 
   2149 	/* Run the hooks until none of them does any work. */
   2150 	do {
   2151 		rv = 0;
   2152 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
   2153 			rv |= (*f->f_func)(f->f_dev);
   2154 	} while (rv != 0);
   2155 
   2156 	config_finalize_done = 1;
   2157 
   2158 	/* Now free all the hooks. */
   2159 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
   2160 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
   2161 		kmem_free(f, sizeof(*f));
   2162 	}
   2163 
   2164 	KERNEL_UNLOCK_ONE(NULL);
   2165 
   2166 	errcnt = aprint_get_error_count();
   2167 	if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
   2168 	    (boothowto & AB_VERBOSE) == 0) {
   2169 		mutex_enter(&config_misc_lock);
   2170 		if (config_do_twiddle) {
   2171 			config_do_twiddle = 0;
   2172 			printf_nolog(" done.\n");
   2173 		}
   2174 		mutex_exit(&config_misc_lock);
   2175 	}
   2176 	if (errcnt != 0) {
   2177 		printf("WARNING: %d error%s while detecting hardware; "
   2178 		    "check system log.\n", errcnt,
   2179 		    errcnt == 1 ? "" : "s");
   2180 	}
   2181 }
   2182 
   2183 void
   2184 config_twiddle_init(void)
   2185 {
   2186 
   2187 	if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
   2188 		config_do_twiddle = 1;
   2189 	}
   2190 	callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
   2191 }
   2192 
   2193 void
   2194 config_twiddle_fn(void *cookie)
   2195 {
   2196 
   2197 	mutex_enter(&config_misc_lock);
   2198 	if (config_do_twiddle) {
   2199 		twiddle();
   2200 		callout_schedule(&config_twiddle_ch, mstohz(100));
   2201 	}
   2202 	mutex_exit(&config_misc_lock);
   2203 }
   2204 
   2205 static void
   2206 config_alldevs_enter(struct alldevs_foray *af)
   2207 {
   2208 	TAILQ_INIT(&af->af_garbage);
   2209 	mutex_enter(&alldevs.lock);
   2210 	config_collect_garbage(&af->af_garbage);
   2211 }
   2212 
   2213 static void
   2214 config_alldevs_exit(struct alldevs_foray *af)
   2215 {
   2216 	mutex_exit(&alldevs.lock);
   2217 	config_dump_garbage(&af->af_garbage);
   2218 }
   2219 
   2220 /*
   2221  * device_lookup:
   2222  *
   2223  *	Look up a device instance for a given driver.
   2224  */
   2225 device_t
   2226 device_lookup(cfdriver_t cd, int unit)
   2227 {
   2228 	device_t dv;
   2229 
   2230 	mutex_enter(&alldevs.lock);
   2231 	if (unit < 0 || unit >= cd->cd_ndevs)
   2232 		dv = NULL;
   2233 	else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
   2234 		dv = NULL;
   2235 	mutex_exit(&alldevs.lock);
   2236 
   2237 	return dv;
   2238 }
   2239 
   2240 /*
   2241  * device_lookup_private:
   2242  *
   2243  *	Look up a softc instance for a given driver.
   2244  */
   2245 void *
   2246 device_lookup_private(cfdriver_t cd, int unit)
   2247 {
   2248 
   2249 	return device_private(device_lookup(cd, unit));
   2250 }
   2251 
   2252 /*
   2253  * device_find_by_xname:
   2254  *
   2255  *	Returns the device of the given name or NULL if it doesn't exist.
   2256  */
   2257 device_t
   2258 device_find_by_xname(const char *name)
   2259 {
   2260 	device_t dv;
   2261 	deviter_t di;
   2262 
   2263 	for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
   2264 		if (strcmp(device_xname(dv), name) == 0)
   2265 			break;
   2266 	}
   2267 	deviter_release(&di);
   2268 
   2269 	return dv;
   2270 }
   2271 
   2272 /*
   2273  * device_find_by_driver_unit:
   2274  *
   2275  *	Returns the device of the given driver name and unit or
   2276  *	NULL if it doesn't exist.
   2277  */
   2278 device_t
   2279 device_find_by_driver_unit(const char *name, int unit)
   2280 {
   2281 	struct cfdriver *cd;
   2282 
   2283 	if ((cd = config_cfdriver_lookup(name)) == NULL)
   2284 		return NULL;
   2285 	return device_lookup(cd, unit);
   2286 }
   2287 
   2288 /*
   2289  * Power management related functions.
   2290  */
   2291 
   2292 bool
   2293 device_pmf_is_registered(device_t dev)
   2294 {
   2295 	return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
   2296 }
   2297 
   2298 bool
   2299 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
   2300 {
   2301 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2302 		return true;
   2303 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2304 		return false;
   2305 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2306 	    dev->dv_driver_suspend != NULL &&
   2307 	    !(*dev->dv_driver_suspend)(dev, qual))
   2308 		return false;
   2309 
   2310 	dev->dv_flags |= DVF_DRIVER_SUSPENDED;
   2311 	return true;
   2312 }
   2313 
   2314 bool
   2315 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
   2316 {
   2317 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2318 		return true;
   2319 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2320 		return false;
   2321 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2322 	    dev->dv_driver_resume != NULL &&
   2323 	    !(*dev->dv_driver_resume)(dev, qual))
   2324 		return false;
   2325 
   2326 	dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
   2327 	return true;
   2328 }
   2329 
   2330 bool
   2331 device_pmf_driver_shutdown(device_t dev, int how)
   2332 {
   2333 
   2334 	if (*dev->dv_driver_shutdown != NULL &&
   2335 	    !(*dev->dv_driver_shutdown)(dev, how))
   2336 		return false;
   2337 	return true;
   2338 }
   2339 
   2340 bool
   2341 device_pmf_driver_register(device_t dev,
   2342     bool (*suspend)(device_t, const pmf_qual_t *),
   2343     bool (*resume)(device_t, const pmf_qual_t *),
   2344     bool (*shutdown)(device_t, int))
   2345 {
   2346 	dev->dv_driver_suspend = suspend;
   2347 	dev->dv_driver_resume = resume;
   2348 	dev->dv_driver_shutdown = shutdown;
   2349 	dev->dv_flags |= DVF_POWER_HANDLERS;
   2350 	return true;
   2351 }
   2352 
   2353 static const char *
   2354 curlwp_name(void)
   2355 {
   2356 	if (curlwp->l_name != NULL)
   2357 		return curlwp->l_name;
   2358 	else
   2359 		return curlwp->l_proc->p_comm;
   2360 }
   2361 
   2362 void
   2363 device_pmf_driver_deregister(device_t dev)
   2364 {
   2365 	device_lock_t dvl = device_getlock(dev);
   2366 
   2367 	dev->dv_driver_suspend = NULL;
   2368 	dev->dv_driver_resume = NULL;
   2369 
   2370 	mutex_enter(&dvl->dvl_mtx);
   2371 	dev->dv_flags &= ~DVF_POWER_HANDLERS;
   2372 	while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
   2373 		/* Wake a thread that waits for the lock.  That
   2374 		 * thread will fail to acquire the lock, and then
   2375 		 * it will wake the next thread that waits for the
   2376 		 * lock, or else it will wake us.
   2377 		 */
   2378 		cv_signal(&dvl->dvl_cv);
   2379 		pmflock_debug(dev, __func__, __LINE__);
   2380 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2381 		pmflock_debug(dev, __func__, __LINE__);
   2382 	}
   2383 	mutex_exit(&dvl->dvl_mtx);
   2384 }
   2385 
   2386 bool
   2387 device_pmf_driver_child_register(device_t dev)
   2388 {
   2389 	device_t parent = device_parent(dev);
   2390 
   2391 	if (parent == NULL || parent->dv_driver_child_register == NULL)
   2392 		return true;
   2393 	return (*parent->dv_driver_child_register)(dev);
   2394 }
   2395 
   2396 void
   2397 device_pmf_driver_set_child_register(device_t dev,
   2398     bool (*child_register)(device_t))
   2399 {
   2400 	dev->dv_driver_child_register = child_register;
   2401 }
   2402 
   2403 static void
   2404 pmflock_debug(device_t dev, const char *func, int line)
   2405 {
   2406 	device_lock_t dvl = device_getlock(dev);
   2407 
   2408 	aprint_debug_dev(dev,
   2409 	    "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n", func, line,
   2410 	    curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait, dev->dv_flags);
   2411 }
   2412 
   2413 static bool
   2414 device_pmf_lock1(device_t dev)
   2415 {
   2416 	device_lock_t dvl = device_getlock(dev);
   2417 
   2418 	while (device_pmf_is_registered(dev) &&
   2419 	    dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
   2420 		dvl->dvl_nwait++;
   2421 		pmflock_debug(dev, __func__, __LINE__);
   2422 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2423 		pmflock_debug(dev, __func__, __LINE__);
   2424 		dvl->dvl_nwait--;
   2425 	}
   2426 	if (!device_pmf_is_registered(dev)) {
   2427 		pmflock_debug(dev, __func__, __LINE__);
   2428 		/* We could not acquire the lock, but some other thread may
   2429 		 * wait for it, also.  Wake that thread.
   2430 		 */
   2431 		cv_signal(&dvl->dvl_cv);
   2432 		return false;
   2433 	}
   2434 	dvl->dvl_nlock++;
   2435 	dvl->dvl_holder = curlwp;
   2436 	pmflock_debug(dev, __func__, __LINE__);
   2437 	return true;
   2438 }
   2439 
   2440 bool
   2441 device_pmf_lock(device_t dev)
   2442 {
   2443 	bool rc;
   2444 	device_lock_t dvl = device_getlock(dev);
   2445 
   2446 	mutex_enter(&dvl->dvl_mtx);
   2447 	rc = device_pmf_lock1(dev);
   2448 	mutex_exit(&dvl->dvl_mtx);
   2449 
   2450 	return rc;
   2451 }
   2452 
   2453 void
   2454 device_pmf_unlock(device_t dev)
   2455 {
   2456 	device_lock_t dvl = device_getlock(dev);
   2457 
   2458 	KASSERT(dvl->dvl_nlock > 0);
   2459 	mutex_enter(&dvl->dvl_mtx);
   2460 	if (--dvl->dvl_nlock == 0)
   2461 		dvl->dvl_holder = NULL;
   2462 	cv_signal(&dvl->dvl_cv);
   2463 	pmflock_debug(dev, __func__, __LINE__);
   2464 	mutex_exit(&dvl->dvl_mtx);
   2465 }
   2466 
   2467 device_lock_t
   2468 device_getlock(device_t dev)
   2469 {
   2470 	return &dev->dv_lock;
   2471 }
   2472 
   2473 void *
   2474 device_pmf_bus_private(device_t dev)
   2475 {
   2476 	return dev->dv_bus_private;
   2477 }
   2478 
   2479 bool
   2480 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
   2481 {
   2482 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2483 		return true;
   2484 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
   2485 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2486 		return false;
   2487 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2488 	    dev->dv_bus_suspend != NULL &&
   2489 	    !(*dev->dv_bus_suspend)(dev, qual))
   2490 		return false;
   2491 
   2492 	dev->dv_flags |= DVF_BUS_SUSPENDED;
   2493 	return true;
   2494 }
   2495 
   2496 bool
   2497 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
   2498 {
   2499 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
   2500 		return true;
   2501 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2502 	    dev->dv_bus_resume != NULL &&
   2503 	    !(*dev->dv_bus_resume)(dev, qual))
   2504 		return false;
   2505 
   2506 	dev->dv_flags &= ~DVF_BUS_SUSPENDED;
   2507 	return true;
   2508 }
   2509 
   2510 bool
   2511 device_pmf_bus_shutdown(device_t dev, int how)
   2512 {
   2513 
   2514 	if (*dev->dv_bus_shutdown != NULL &&
   2515 	    !(*dev->dv_bus_shutdown)(dev, how))
   2516 		return false;
   2517 	return true;
   2518 }
   2519 
   2520 void
   2521 device_pmf_bus_register(device_t dev, void *priv,
   2522     bool (*suspend)(device_t, const pmf_qual_t *),
   2523     bool (*resume)(device_t, const pmf_qual_t *),
   2524     bool (*shutdown)(device_t, int), void (*deregister)(device_t))
   2525 {
   2526 	dev->dv_bus_private = priv;
   2527 	dev->dv_bus_resume = resume;
   2528 	dev->dv_bus_suspend = suspend;
   2529 	dev->dv_bus_shutdown = shutdown;
   2530 	dev->dv_bus_deregister = deregister;
   2531 }
   2532 
   2533 void
   2534 device_pmf_bus_deregister(device_t dev)
   2535 {
   2536 	if (dev->dv_bus_deregister == NULL)
   2537 		return;
   2538 	(*dev->dv_bus_deregister)(dev);
   2539 	dev->dv_bus_private = NULL;
   2540 	dev->dv_bus_suspend = NULL;
   2541 	dev->dv_bus_resume = NULL;
   2542 	dev->dv_bus_deregister = NULL;
   2543 }
   2544 
   2545 void *
   2546 device_pmf_class_private(device_t dev)
   2547 {
   2548 	return dev->dv_class_private;
   2549 }
   2550 
   2551 bool
   2552 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
   2553 {
   2554 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
   2555 		return true;
   2556 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2557 	    dev->dv_class_suspend != NULL &&
   2558 	    !(*dev->dv_class_suspend)(dev, qual))
   2559 		return false;
   2560 
   2561 	dev->dv_flags |= DVF_CLASS_SUSPENDED;
   2562 	return true;
   2563 }
   2564 
   2565 bool
   2566 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
   2567 {
   2568 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2569 		return true;
   2570 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
   2571 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2572 		return false;
   2573 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2574 	    dev->dv_class_resume != NULL &&
   2575 	    !(*dev->dv_class_resume)(dev, qual))
   2576 		return false;
   2577 
   2578 	dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
   2579 	return true;
   2580 }
   2581 
   2582 void
   2583 device_pmf_class_register(device_t dev, void *priv,
   2584     bool (*suspend)(device_t, const pmf_qual_t *),
   2585     bool (*resume)(device_t, const pmf_qual_t *),
   2586     void (*deregister)(device_t))
   2587 {
   2588 	dev->dv_class_private = priv;
   2589 	dev->dv_class_suspend = suspend;
   2590 	dev->dv_class_resume = resume;
   2591 	dev->dv_class_deregister = deregister;
   2592 }
   2593 
   2594 void
   2595 device_pmf_class_deregister(device_t dev)
   2596 {
   2597 	if (dev->dv_class_deregister == NULL)
   2598 		return;
   2599 	(*dev->dv_class_deregister)(dev);
   2600 	dev->dv_class_private = NULL;
   2601 	dev->dv_class_suspend = NULL;
   2602 	dev->dv_class_resume = NULL;
   2603 	dev->dv_class_deregister = NULL;
   2604 }
   2605 
   2606 bool
   2607 device_active(device_t dev, devactive_t type)
   2608 {
   2609 	size_t i;
   2610 
   2611 	if (dev->dv_activity_count == 0)
   2612 		return false;
   2613 
   2614 	for (i = 0; i < dev->dv_activity_count; ++i) {
   2615 		if (dev->dv_activity_handlers[i] == NULL)
   2616 			break;
   2617 		(*dev->dv_activity_handlers[i])(dev, type);
   2618 	}
   2619 
   2620 	return true;
   2621 }
   2622 
   2623 bool
   2624 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
   2625 {
   2626 	void (**new_handlers)(device_t, devactive_t);
   2627 	void (**old_handlers)(device_t, devactive_t);
   2628 	size_t i, old_size, new_size;
   2629 	int s;
   2630 
   2631 	old_handlers = dev->dv_activity_handlers;
   2632 	old_size = dev->dv_activity_count;
   2633 
   2634 	KASSERT(old_size == 0 || old_handlers != NULL);
   2635 
   2636 	for (i = 0; i < old_size; ++i) {
   2637 		KASSERT(old_handlers[i] != handler);
   2638 		if (old_handlers[i] == NULL) {
   2639 			old_handlers[i] = handler;
   2640 			return true;
   2641 		}
   2642 	}
   2643 
   2644 	new_size = old_size + 4;
   2645 	new_handlers = kmem_alloc(sizeof(void *[new_size]), KM_SLEEP);
   2646 
   2647 	for (i = 0; i < old_size; ++i)
   2648 		new_handlers[i] = old_handlers[i];
   2649 	new_handlers[old_size] = handler;
   2650 	for (i = old_size+1; i < new_size; ++i)
   2651 		new_handlers[i] = NULL;
   2652 
   2653 	s = splhigh();
   2654 	dev->dv_activity_count = new_size;
   2655 	dev->dv_activity_handlers = new_handlers;
   2656 	splx(s);
   2657 
   2658 	if (old_size > 0)
   2659 		kmem_free(old_handlers, sizeof(void * [old_size]));
   2660 
   2661 	return true;
   2662 }
   2663 
   2664 void
   2665 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
   2666 {
   2667 	void (**old_handlers)(device_t, devactive_t);
   2668 	size_t i, old_size;
   2669 	int s;
   2670 
   2671 	old_handlers = dev->dv_activity_handlers;
   2672 	old_size = dev->dv_activity_count;
   2673 
   2674 	for (i = 0; i < old_size; ++i) {
   2675 		if (old_handlers[i] == handler)
   2676 			break;
   2677 		if (old_handlers[i] == NULL)
   2678 			return; /* XXX panic? */
   2679 	}
   2680 
   2681 	if (i == old_size)
   2682 		return; /* XXX panic? */
   2683 
   2684 	for (; i < old_size - 1; ++i) {
   2685 		if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
   2686 			continue;
   2687 
   2688 		if (i == 0) {
   2689 			s = splhigh();
   2690 			dev->dv_activity_count = 0;
   2691 			dev->dv_activity_handlers = NULL;
   2692 			splx(s);
   2693 			kmem_free(old_handlers, sizeof(void *[old_size]));
   2694 		}
   2695 		return;
   2696 	}
   2697 	old_handlers[i] = NULL;
   2698 }
   2699 
   2700 /* Return true iff the device_t `dev' exists at generation `gen'. */
   2701 static bool
   2702 device_exists_at(device_t dv, devgen_t gen)
   2703 {
   2704 	return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
   2705 	    dv->dv_add_gen <= gen;
   2706 }
   2707 
   2708 static bool
   2709 deviter_visits(const deviter_t *di, device_t dv)
   2710 {
   2711 	return device_exists_at(dv, di->di_gen);
   2712 }
   2713 
   2714 /*
   2715  * Device Iteration
   2716  *
   2717  * deviter_t: a device iterator.  Holds state for a "walk" visiting
   2718  *     each device_t's in the device tree.
   2719  *
   2720  * deviter_init(di, flags): initialize the device iterator `di'
   2721  *     to "walk" the device tree.  deviter_next(di) will return
   2722  *     the first device_t in the device tree, or NULL if there are
   2723  *     no devices.
   2724  *
   2725  *     `flags' is one or more of DEVITER_F_RW, indicating that the
   2726  *     caller intends to modify the device tree by calling
   2727  *     config_detach(9) on devices in the order that the iterator
   2728  *     returns them; DEVITER_F_ROOT_FIRST, asking for the devices
   2729  *     nearest the "root" of the device tree to be returned, first;
   2730  *     DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
   2731  *     the root of the device tree, first; and DEVITER_F_SHUTDOWN,
   2732  *     indicating both that deviter_init() should not respect any
   2733  *     locks on the device tree, and that deviter_next(di) may run
   2734  *     in more than one LWP before the walk has finished.
   2735  *
   2736  *     Only one DEVITER_F_RW iterator may be in the device tree at
   2737  *     once.
   2738  *
   2739  *     DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
   2740  *
   2741  *     Results are undefined if the flags DEVITER_F_ROOT_FIRST and
   2742  *     DEVITER_F_LEAVES_FIRST are used in combination.
   2743  *
   2744  * deviter_first(di, flags): initialize the device iterator `di'
   2745  *     and return the first device_t in the device tree, or NULL
   2746  *     if there are no devices.  The statement
   2747  *
   2748  *         dv = deviter_first(di);
   2749  *
   2750  *     is shorthand for
   2751  *
   2752  *         deviter_init(di);
   2753  *         dv = deviter_next(di);
   2754  *
   2755  * deviter_next(di): return the next device_t in the device tree,
   2756  *     or NULL if there are no more devices.  deviter_next(di)
   2757  *     is undefined if `di' was not initialized with deviter_init() or
   2758  *     deviter_first().
   2759  *
   2760  * deviter_release(di): stops iteration (subsequent calls to
   2761  *     deviter_next() will return NULL), releases any locks and
   2762  *     resources held by the device iterator.
   2763  *
   2764  * Device iteration does not return device_t's in any particular
   2765  * order.  An iterator will never return the same device_t twice.
   2766  * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
   2767  * is called repeatedly on the same `di', it will eventually return
   2768  * NULL.  It is ok to attach/detach devices during device iteration.
   2769  */
   2770 void
   2771 deviter_init(deviter_t *di, deviter_flags_t flags)
   2772 {
   2773 	device_t dv;
   2774 
   2775 	memset(di, 0, sizeof(*di));
   2776 
   2777 	if ((flags & DEVITER_F_SHUTDOWN) != 0)
   2778 		flags |= DEVITER_F_RW;
   2779 
   2780 	mutex_enter(&alldevs.lock);
   2781 	if ((flags & DEVITER_F_RW) != 0)
   2782 		alldevs.nwrite++;
   2783 	else
   2784 		alldevs.nread++;
   2785 	di->di_gen = alldevs.gen++;
   2786 	di->di_flags = flags;
   2787 
   2788 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   2789 	case DEVITER_F_LEAVES_FIRST:
   2790 		TAILQ_FOREACH(dv, &alldevs.list, dv_list) {
   2791 			if (!deviter_visits(di, dv))
   2792 				continue;
   2793 			di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
   2794 		}
   2795 		break;
   2796 	case DEVITER_F_ROOT_FIRST:
   2797 		TAILQ_FOREACH(dv, &alldevs.list, dv_list) {
   2798 			if (!deviter_visits(di, dv))
   2799 				continue;
   2800 			di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
   2801 		}
   2802 		break;
   2803 	default:
   2804 		break;
   2805 	}
   2806 
   2807 	deviter_reinit(di);
   2808 	mutex_exit(&alldevs.lock);
   2809 }
   2810 
   2811 static void
   2812 deviter_reinit(deviter_t *di)
   2813 {
   2814 
   2815 	KASSERT(mutex_owned(&alldevs.lock));
   2816 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2817 		di->di_prev = TAILQ_LAST(&alldevs.list, devicelist);
   2818 	else
   2819 		di->di_prev = TAILQ_FIRST(&alldevs.list);
   2820 }
   2821 
   2822 device_t
   2823 deviter_first(deviter_t *di, deviter_flags_t flags)
   2824 {
   2825 
   2826 	deviter_init(di, flags);
   2827 	return deviter_next(di);
   2828 }
   2829 
   2830 static device_t
   2831 deviter_next2(deviter_t *di)
   2832 {
   2833 	device_t dv;
   2834 
   2835 	KASSERT(mutex_owned(&alldevs.lock));
   2836 
   2837 	dv = di->di_prev;
   2838 
   2839 	if (dv == NULL)
   2840 		return NULL;
   2841 
   2842 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2843 		di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
   2844 	else
   2845 		di->di_prev = TAILQ_NEXT(dv, dv_list);
   2846 
   2847 	return dv;
   2848 }
   2849 
   2850 static device_t
   2851 deviter_next1(deviter_t *di)
   2852 {
   2853 	device_t dv;
   2854 
   2855 	KASSERT(mutex_owned(&alldevs.lock));
   2856 
   2857 	do {
   2858 		dv = deviter_next2(di);
   2859 	} while (dv != NULL && !deviter_visits(di, dv));
   2860 
   2861 	return dv;
   2862 }
   2863 
   2864 device_t
   2865 deviter_next(deviter_t *di)
   2866 {
   2867 	device_t dv = NULL;
   2868 
   2869 	mutex_enter(&alldevs.lock);
   2870 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   2871 	case 0:
   2872 		dv = deviter_next1(di);
   2873 		break;
   2874 	case DEVITER_F_LEAVES_FIRST:
   2875 		while (di->di_curdepth >= 0) {
   2876 			if ((dv = deviter_next1(di)) == NULL) {
   2877 				di->di_curdepth--;
   2878 				deviter_reinit(di);
   2879 			} else if (dv->dv_depth == di->di_curdepth)
   2880 				break;
   2881 		}
   2882 		break;
   2883 	case DEVITER_F_ROOT_FIRST:
   2884 		while (di->di_curdepth <= di->di_maxdepth) {
   2885 			if ((dv = deviter_next1(di)) == NULL) {
   2886 				di->di_curdepth++;
   2887 				deviter_reinit(di);
   2888 			} else if (dv->dv_depth == di->di_curdepth)
   2889 				break;
   2890 		}
   2891 		break;
   2892 	default:
   2893 		break;
   2894 	}
   2895 	mutex_exit(&alldevs.lock);
   2896 
   2897 	return dv;
   2898 }
   2899 
   2900 void
   2901 deviter_release(deviter_t *di)
   2902 {
   2903 	bool rw = (di->di_flags & DEVITER_F_RW) != 0;
   2904 
   2905 	mutex_enter(&alldevs.lock);
   2906 	if (rw)
   2907 		--alldevs.nwrite;
   2908 	else
   2909 		--alldevs.nread;
   2910 	/* XXX wake a garbage-collection thread */
   2911 	mutex_exit(&alldevs.lock);
   2912 }
   2913 
   2914 const char *
   2915 cfdata_ifattr(const struct cfdata *cf)
   2916 {
   2917 	return cf->cf_pspec->cfp_iattr;
   2918 }
   2919 
   2920 bool
   2921 ifattr_match(const char *snull, const char *t)
   2922 {
   2923 	return (snull == NULL) || strcmp(snull, t) == 0;
   2924 }
   2925 
   2926 void
   2927 null_childdetached(device_t self, device_t child)
   2928 {
   2929 	/* do nothing */
   2930 }
   2931 
   2932 static void
   2933 sysctl_detach_setup(struct sysctllog **clog)
   2934 {
   2935 
   2936 	sysctl_createv(clog, 0, NULL, NULL,
   2937 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   2938 		CTLTYPE_BOOL, "detachall",
   2939 		SYSCTL_DESCR("Detach all devices at shutdown"),
   2940 		NULL, 0, &detachall, 0,
   2941 		CTL_KERN, CTL_CREATE, CTL_EOL);
   2942 }
   2943