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