Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.70
      1 /* $NetBSD: subr_autoconf.c,v 1.70 2002/09/27 06:12:55 thorpej 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. All advertising materials mentioning features or use of this software
     59  *    must display the following acknowledgement:
     60  *	This product includes software developed by the University of
     61  *	California, Berkeley and its contributors.
     62  * 4. Neither the name of the University nor the names of its contributors
     63  *    may be used to endorse or promote products derived from this software
     64  *    without specific prior written permission.
     65  *
     66  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     67  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     68  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     69  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     70  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     71  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     72  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     73  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     74  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     75  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     76  * SUCH DAMAGE.
     77  *
     78  * from: Header: subr_autoconf.c,v 1.12 93/02/01 19:31:48 torek Exp  (LBL)
     79  *
     80  *	@(#)subr_autoconf.c	8.3 (Berkeley) 5/17/94
     81  */
     82 
     83 #include <sys/cdefs.h>
     84 __KERNEL_RCSID(0, "$NetBSD: subr_autoconf.c,v 1.70 2002/09/27 06:12:55 thorpej Exp $");
     85 
     86 #include "opt_ddb.h"
     87 
     88 #include <sys/param.h>
     89 #include <sys/device.h>
     90 #include <sys/malloc.h>
     91 #include <sys/systm.h>
     92 #include <sys/kernel.h>
     93 #include <sys/errno.h>
     94 #include <sys/proc.h>
     95 #include <machine/limits.h>
     96 
     97 #include "opt_userconf.h"
     98 #ifdef USERCONF
     99 #include <sys/userconf.h>
    100 #include <sys/reboot.h>
    101 #endif
    102 
    103 /*
    104  * Autoconfiguration subroutines.
    105  */
    106 
    107 /*
    108  * ioconf.c exports exactly two names: cfdata and cfroots.  All system
    109  * devices and drivers are found via these tables.
    110  */
    111 extern struct cfdata cfdata[];
    112 extern short cfroots[];
    113 
    114 /*
    115  * List of all cfdriver structures.  We use this to detect duplicates
    116  * when other cfdrivers are loaded.
    117  */
    118 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
    119 extern struct cfdriver * const cfdriver_list_initial[];
    120 
    121 /*
    122  * List of cfdata tables.  We always have one such list -- the one
    123  * built statically when the kernel was configured.
    124  */
    125 struct cftablelist allcftables;
    126 static struct cftable initcftable;
    127 
    128 #define	ROOT ((struct device *)NULL)
    129 
    130 struct matchinfo {
    131 	cfmatch_t fn;
    132 	struct	device *parent;
    133 	void	*aux;
    134 	struct	cfdata *match;
    135 	int	pri;
    136 };
    137 
    138 static char *number(char *, int);
    139 static void mapply(struct matchinfo *, struct cfdata *);
    140 
    141 struct deferred_config {
    142 	TAILQ_ENTRY(deferred_config) dc_queue;
    143 	struct device *dc_dev;
    144 	void (*dc_func)(struct device *);
    145 };
    146 
    147 TAILQ_HEAD(deferred_config_head, deferred_config);
    148 
    149 struct deferred_config_head deferred_config_queue;
    150 struct deferred_config_head interrupt_config_queue;
    151 
    152 static void config_process_deferred(struct deferred_config_head *,
    153 	struct device *);
    154 
    155 /* list of all devices */
    156 struct devicelist alldevs;
    157 
    158 /* list of all events */
    159 struct evcntlist allevents = TAILQ_HEAD_INITIALIZER(allevents);
    160 
    161 __volatile int config_pending;		/* semaphore for mountroot */
    162 
    163 #define	STREQ(s1, s2)			\
    164 	(*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
    165 
    166 /*
    167  * Configure the system's hardware.
    168  */
    169 void
    170 configure(void)
    171 {
    172 	int i;
    173 
    174 	/* allcfdrivers is statically initialized. */
    175 	for (i = 0; cfdriver_list_initial[i] != NULL; i++)
    176 		if (config_cfdriver_attach(cfdriver_list_initial[i]) != 0)
    177 			panic("configure: duplicate `%s' drivers",
    178 			    cfdriver_list_initial[i]->cd_name);
    179 
    180 	TAILQ_INIT(&allcftables);
    181 	initcftable.ct_cfdata = cfdata;
    182 	TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
    183 
    184 	TAILQ_INIT(&deferred_config_queue);
    185 	TAILQ_INIT(&interrupt_config_queue);
    186 	TAILQ_INIT(&alldevs);
    187 
    188 #ifdef USERCONF
    189 	if (boothowto & RB_USERCONF)
    190 		user_config();
    191 #endif
    192 
    193 	/*
    194 	 * Do the machine-dependent portion of autoconfiguration.  This
    195 	 * sets the configuration machinery here in motion by "finding"
    196 	 * the root bus.  When this function returns, we expect interrupts
    197 	 * to be enabled.
    198 	 */
    199 	cpu_configure();
    200 
    201 	/*
    202 	 * Now that we've found all the hardware, start the real time
    203 	 * and statistics clocks.
    204 	 */
    205 	initclocks();
    206 
    207 	cold = 0;	/* clocks are running, we're warm now! */
    208 
    209 	/*
    210 	 * Now callback to finish configuration for devices which want
    211 	 * to do this once interrupts are enabled.
    212 	 */
    213 	config_process_deferred(&interrupt_config_queue, NULL);
    214 }
    215 
    216 /*
    217  * Add a cfdriver to the system.
    218  */
    219 int
    220 config_cfdriver_attach(struct cfdriver *cd)
    221 {
    222 	struct cfdriver *lcd;
    223 
    224 	/* Make sure this driver isn't already in the system. */
    225 	LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
    226 		if (STREQ(lcd->cd_name, cd->cd_name))
    227 			return (EEXIST);
    228 	}
    229 
    230 	LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
    231 
    232 	return (0);
    233 }
    234 
    235 /*
    236  * Remove a cfdriver from the system.
    237  */
    238 int
    239 config_cfdriver_detach(struct cfdriver *cd)
    240 {
    241 	int i;
    242 
    243 	/* Make sure there are no active instances. */
    244 	for (i = 0; i < cd->cd_ndevs; i++) {
    245 		if (cd->cd_devs[i] != NULL)
    246 			return (EBUSY);
    247 	}
    248 
    249 	LIST_REMOVE(cd, cd_list);
    250 
    251 	KASSERT(cd->cd_devs == NULL);
    252 
    253 	return (0);
    254 }
    255 
    256 /*
    257  * Look up a cfdriver by name.
    258  */
    259 static struct cfdriver *
    260 config_cfdriver_lookup(const char *name)
    261 {
    262 	struct cfdriver *cd;
    263 
    264 	/*
    265 	 * It is sometimes necessary to use the autoconfiguration
    266 	 * framework quite early (e.g. to initialize the console).
    267 	 * We support this by noticing an empty cfdriver list and
    268 	 * searching the initial static list instead.
    269 	 */
    270 	if (LIST_EMPTY(&allcfdrivers)) {
    271 		int i;
    272 
    273 		for (i = 0; cfdriver_list_initial[i] != NULL; i++) {
    274 			if (STREQ(cfdriver_list_initial[i]->cd_name, name))
    275 				return (cfdriver_list_initial[i]);
    276 		}
    277 	}
    278 
    279 	LIST_FOREACH(cd, &allcfdrivers, cd_list) {
    280 		if (STREQ(cd->cd_name, name))
    281 			return (cd);
    282 	}
    283 
    284 	return (NULL);
    285 }
    286 
    287 /*
    288  * Apply the matching function and choose the best.  This is used
    289  * a few times and we want to keep the code small.
    290  */
    291 static void
    292 mapply(struct matchinfo *m, struct cfdata *cf)
    293 {
    294 	int pri;
    295 
    296 	if (m->fn != NULL)
    297 		pri = (*m->fn)(m->parent, cf, m->aux);
    298 	else {
    299 	        if (cf->cf_attach->ca_match == NULL) {
    300 			panic("mapply: no match function for '%s' device\n",
    301 			    cf->cf_name);
    302 		}
    303 		pri = (*cf->cf_attach->ca_match)(m->parent, cf, m->aux);
    304 	}
    305 	if (pri > m->pri) {
    306 		m->match = cf;
    307 		m->pri = pri;
    308 	}
    309 }
    310 
    311 /*
    312  * Determine if `parent' is a potential parent for a device spec based
    313  * on `cfp'.
    314  */
    315 static int
    316 cfparent_match(struct device *parent, const struct cfparent *cfp)
    317 {
    318 	struct cfdriver *pcd;
    319 	const char * const *cpp;
    320 	const char *cp;
    321 
    322 	/* We don't match root nodes here. */
    323 	if (cfp == NULL)
    324 		return (0);
    325 
    326 	pcd = config_cfdriver_lookup(parent->dv_cfdata->cf_name);
    327 	KASSERT(pcd != NULL);
    328 
    329 	/*
    330 	 * First, ensure this parent has the correct interface
    331 	 * attribute.
    332 	 */
    333 	if (pcd->cd_attrs == NULL)
    334 		return (0);	/* no interface attributes -> no children */
    335 	for (cpp = pcd->cd_attrs; (cp = *cpp) != NULL; cpp++) {
    336 		if (STREQ(cp, cfp->cfp_iattr)) {
    337 			/* Match. */
    338 			break;
    339 		}
    340 	}
    341 	if (cp == NULL)
    342 		return (0);	/* doesn't carry the req'd attribute */
    343 
    344 	/*
    345 	 * If no specific parent device instance was specified (i.e.
    346 	 * we're attaching to the attribute only), we're done!
    347 	 */
    348 	if (cfp->cfp_parent == NULL)
    349 		return (1);
    350 
    351 	/*
    352 	 * Check the parent device's name.
    353 	 */
    354 	if (pcd->cd_name[0] != cfp->cfp_parent[0] ||
    355 	    strcmp(pcd->cd_name, cfp->cfp_parent) != 0)
    356 		return (0);	/* not the same parent */
    357 
    358 	/*
    359 	 * Make sure the unit number matches.
    360 	 */
    361 	if (cfp->cfp_unit == -1 ||	/* wildcard */
    362 	    cfp->cfp_unit == parent->dv_unit)
    363 		return (1);
    364 
    365 	/* Unit numbers don't match. */
    366 	return (0);
    367 }
    368 
    369 /*
    370  * Invoke the "match" routine for a cfdata entry on behalf of
    371  * an external caller, usually a "submatch" routine.
    372  */
    373 int
    374 config_match(struct device *parent, struct cfdata *cf, void *aux)
    375 {
    376 
    377 	return ((*cf->cf_attach->ca_match)(parent, cf, aux));
    378 }
    379 
    380 /*
    381  * Iterate over all potential children of some device, calling the given
    382  * function (default being the child's match function) for each one.
    383  * Nonzero returns are matches; the highest value returned is considered
    384  * the best match.  Return the `found child' if we got a match, or NULL
    385  * otherwise.  The `aux' pointer is simply passed on through.
    386  *
    387  * Note that this function is designed so that it can be used to apply
    388  * an arbitrary function to all potential children (its return value
    389  * can be ignored).
    390  */
    391 struct cfdata *
    392 config_search(cfmatch_t fn, struct device *parent, void *aux)
    393 {
    394 	struct cftable *ct;
    395 	struct cfdata *cf;
    396 	struct matchinfo m;
    397 
    398 	m.fn = fn;
    399 	m.parent = parent;
    400 	m.aux = aux;
    401 	m.match = NULL;
    402 	m.pri = 0;
    403 
    404 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    405 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    406 			/*
    407 			 * Skip cf if no longer eligible, otherwise scan
    408 			 * through parents for one matching `parent', and
    409 			 * try match function.
    410 			 */
    411 			if (cf->cf_fstate == FSTATE_FOUND)
    412 				continue;
    413 			if (cf->cf_fstate == FSTATE_DNOTFOUND ||
    414 			    cf->cf_fstate == FSTATE_DSTAR)
    415 				continue;
    416 			if (cfparent_match(parent, cf->cf_pspec))
    417 				mapply(&m, cf);
    418 		}
    419 	}
    420 	return (m.match);
    421 }
    422 
    423 /*
    424  * Find the given root device.
    425  * This is much like config_search, but there is no parent.
    426  * Don't bother with multiple cfdata tables; the root node
    427  * must always be in the initial table.
    428  */
    429 struct cfdata *
    430 config_rootsearch(cfmatch_t fn, const char *rootname, void *aux)
    431 {
    432 	struct cfdata *cf;
    433 	short *p;
    434 	struct matchinfo m;
    435 
    436 	m.fn = fn;
    437 	m.parent = ROOT;
    438 	m.aux = aux;
    439 	m.match = NULL;
    440 	m.pri = 0;
    441 	/*
    442 	 * Look at root entries for matching name.  We do not bother
    443 	 * with found-state here since only one root should ever be
    444 	 * searched (and it must be done first).
    445 	 */
    446 	for (p = cfroots; *p >= 0; p++) {
    447 		cf = &cfdata[*p];
    448 		if (strcmp(cf->cf_name, rootname) == 0)
    449 			mapply(&m, cf);
    450 	}
    451 	return (m.match);
    452 }
    453 
    454 static const char *msgs[3] = { "", " not configured\n", " unsupported\n" };
    455 
    456 /*
    457  * The given `aux' argument describes a device that has been found
    458  * on the given parent, but not necessarily configured.  Locate the
    459  * configuration data for that device (using the submatch function
    460  * provided, or using candidates' cd_match configuration driver
    461  * functions) and attach it, and return true.  If the device was
    462  * not configured, call the given `print' function and return 0.
    463  */
    464 struct device *
    465 config_found_sm(struct device *parent, void *aux, cfprint_t print,
    466     cfmatch_t submatch)
    467 {
    468 	struct cfdata *cf;
    469 
    470 	if ((cf = config_search(submatch, parent, aux)) != NULL)
    471 		return (config_attach(parent, cf, aux, print));
    472 	if (print)
    473 		printf("%s", msgs[(*print)(aux, parent->dv_xname)]);
    474 	return (NULL);
    475 }
    476 
    477 /*
    478  * As above, but for root devices.
    479  */
    480 struct device *
    481 config_rootfound(const char *rootname, void *aux)
    482 {
    483 	struct cfdata *cf;
    484 
    485 	if ((cf = config_rootsearch((cfmatch_t)NULL, rootname, aux)) != NULL)
    486 		return (config_attach(ROOT, cf, aux, (cfprint_t)NULL));
    487 	printf("root device %s not configured\n", rootname);
    488 	return (NULL);
    489 }
    490 
    491 /* just like sprintf(buf, "%d") except that it works from the end */
    492 static char *
    493 number(char *ep, int n)
    494 {
    495 
    496 	*--ep = 0;
    497 	while (n >= 10) {
    498 		*--ep = (n % 10) + '0';
    499 		n /= 10;
    500 	}
    501 	*--ep = n + '0';
    502 	return (ep);
    503 }
    504 
    505 /*
    506  * Expand the size of the cd_devs array if necessary.
    507  */
    508 void
    509 config_makeroom(int n, struct cfdriver *cd)
    510 {
    511 	int old, new;
    512 	void **nsp;
    513 
    514 	if (n < cd->cd_ndevs)
    515 		return;
    516 
    517 	/*
    518 	 * Need to expand the array.
    519 	 */
    520 	old = cd->cd_ndevs;
    521 	if (old == 0)
    522 		new = MINALLOCSIZE / sizeof(void *);
    523 	else
    524 		new = old * 2;
    525 	while (new <= n)
    526 		new *= 2;
    527 	cd->cd_ndevs = new;
    528 	nsp = malloc(new * sizeof(void *), M_DEVBUF,
    529 	    cold ? M_NOWAIT : M_WAITOK);
    530 	if (nsp == NULL)
    531 		panic("config_attach: %sing dev array",
    532 		    old != 0 ? "expand" : "creat");
    533 	memset(nsp + old, 0, (new - old) * sizeof(void *));
    534 	if (old != 0) {
    535 		memcpy(nsp, cd->cd_devs, old * sizeof(void *));
    536 		free(cd->cd_devs, M_DEVBUF);
    537 	}
    538 	cd->cd_devs = nsp;
    539 }
    540 
    541 /*
    542  * Attach a found device.  Allocates memory for device variables.
    543  */
    544 struct device *
    545 config_attach(struct device *parent, struct cfdata *cf, void *aux,
    546 	cfprint_t print)
    547 {
    548 	struct device *dev;
    549 	struct cftable *ct;
    550 	struct cfdriver *cd;
    551 	struct cfattach *ca;
    552 	size_t lname, lunit;
    553 	const char *xunit;
    554 	int myunit;
    555 	char num[10];
    556 
    557 	cd = config_cfdriver_lookup(cf->cf_name);
    558 	KASSERT(cd != NULL);
    559 	ca = cf->cf_attach;
    560 	if (ca->ca_devsize < sizeof(struct device))
    561 		panic("config_attach");
    562 
    563 #ifndef __BROKEN_CONFIG_UNIT_USAGE
    564 	if (cf->cf_fstate == FSTATE_STAR) {
    565 		for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
    566 			if (cd->cd_devs[myunit] == NULL)
    567 				break;
    568 		/*
    569 		 * myunit is now the unit of the first NULL device pointer,
    570 		 * or max(cd->cd_ndevs,cf->cf_unit).
    571 		 */
    572 	} else {
    573 		myunit = cf->cf_unit;
    574 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
    575 		cf->cf_fstate = FSTATE_FOUND;
    576 	}
    577 #else
    578 	myunit = cf->cf_unit;
    579 	if (cf->cf_fstate == FSTATE_STAR)
    580 		cf->cf_unit++;
    581 	else {
    582 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
    583 		cf->cf_fstate = FSTATE_FOUND;
    584 	}
    585 #endif /* ! __BROKEN_CONFIG_UNIT_USAGE */
    586 
    587 	/* compute length of name and decimal expansion of unit number */
    588 	lname = strlen(cd->cd_name);
    589 	xunit = number(&num[sizeof(num)], myunit);
    590 	lunit = &num[sizeof(num)] - xunit;
    591 	if (lname + lunit > sizeof(dev->dv_xname))
    592 		panic("config_attach: device name too long");
    593 
    594 	/* get memory for all device vars */
    595 	dev = (struct device *)malloc(ca->ca_devsize, M_DEVBUF,
    596 	    cold ? M_NOWAIT : M_WAITOK);
    597 	if (!dev)
    598 	    panic("config_attach: memory allocation for device softc failed");
    599 	memset(dev, 0, ca->ca_devsize);
    600 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
    601 	dev->dv_class = cd->cd_class;
    602 	dev->dv_cfdata = cf;
    603 	dev->dv_unit = myunit;
    604 	memcpy(dev->dv_xname, cd->cd_name, lname);
    605 	memcpy(dev->dv_xname + lname, xunit, lunit);
    606 	dev->dv_parent = parent;
    607 	dev->dv_flags = DVF_ACTIVE;	/* always initially active */
    608 
    609 	if (parent == ROOT)
    610 		printf("%s (root)", dev->dv_xname);
    611 	else {
    612 		printf("%s at %s", dev->dv_xname, parent->dv_xname);
    613 		if (print)
    614 			(void) (*print)(aux, NULL);
    615 	}
    616 
    617 	/* put this device in the devices array */
    618 	config_makeroom(dev->dv_unit, cd);
    619 	if (cd->cd_devs[dev->dv_unit])
    620 		panic("config_attach: duplicate %s", dev->dv_xname);
    621 	cd->cd_devs[dev->dv_unit] = dev;
    622 
    623 	/*
    624 	 * Before attaching, clobber any unfound devices that are
    625 	 * otherwise identical.
    626 	 */
    627 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    628 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    629 			if (STREQ(cf->cf_name, cd->cd_name) &&
    630 			    cf->cf_unit == dev->dv_unit) {
    631 				if (cf->cf_fstate == FSTATE_NOTFOUND)
    632 					cf->cf_fstate = FSTATE_FOUND;
    633 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    634 				/*
    635 				 * Bump the unit number on all starred cfdata
    636 				 * entries for this device.
    637 				 */
    638 				if (cf->cf_fstate == FSTATE_STAR)
    639 					cf->cf_unit++;
    640 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    641 			}
    642 		}
    643 	}
    644 #ifdef __HAVE_DEVICE_REGISTER
    645 	device_register(dev, aux);
    646 #endif
    647 	(*ca->ca_attach)(parent, dev, aux);
    648 	config_process_deferred(&deferred_config_queue, dev);
    649 	return (dev);
    650 }
    651 
    652 /*
    653  * Detach a device.  Optionally forced (e.g. because of hardware
    654  * removal) and quiet.  Returns zero if successful, non-zero
    655  * (an error code) otherwise.
    656  *
    657  * Note that this code wants to be run from a process context, so
    658  * that the detach can sleep to allow processes which have a device
    659  * open to run and unwind their stacks.
    660  */
    661 int
    662 config_detach(struct device *dev, int flags)
    663 {
    664 	struct cftable *ct;
    665 	struct cfdata *cf;
    666 	struct cfattach *ca;
    667 	struct cfdriver *cd;
    668 #ifdef DIAGNOSTIC
    669 	struct device *d;
    670 #endif
    671 	int rv = 0, i;
    672 
    673 	cf = dev->dv_cfdata;
    674 #ifdef DIAGNOSTIC
    675 	if (cf->cf_fstate != FSTATE_FOUND && cf->cf_fstate != FSTATE_STAR)
    676 		panic("config_detach: bad device fstate");
    677 #endif
    678 	cd = config_cfdriver_lookup(cf->cf_name);
    679 	KASSERT(cd != NULL);
    680 	ca = cf->cf_attach;
    681 
    682 	/*
    683 	 * Ensure the device is deactivated.  If the device doesn't
    684 	 * have an activation entry point, we allow DVF_ACTIVE to
    685 	 * remain set.  Otherwise, if DVF_ACTIVE is still set, the
    686 	 * device is busy, and the detach fails.
    687 	 */
    688 	if (ca->ca_activate != NULL)
    689 		rv = config_deactivate(dev);
    690 
    691 	/*
    692 	 * Try to detach the device.  If that's not possible, then
    693 	 * we either panic() (for the forced but failed case), or
    694 	 * return an error.
    695 	 */
    696 	if (rv == 0) {
    697 		if (ca->ca_detach != NULL)
    698 			rv = (*ca->ca_detach)(dev, flags);
    699 		else
    700 			rv = EOPNOTSUPP;
    701 	}
    702 	if (rv != 0) {
    703 		if ((flags & DETACH_FORCE) == 0)
    704 			return (rv);
    705 		else
    706 			panic("config_detach: forced detach of %s failed (%d)",
    707 			    dev->dv_xname, rv);
    708 	}
    709 
    710 	/*
    711 	 * The device has now been successfully detached.
    712 	 */
    713 
    714 #ifdef DIAGNOSTIC
    715 	/*
    716 	 * Sanity: If you're successfully detached, you should have no
    717 	 * children.  (Note that because children must be attached
    718 	 * after parents, we only need to search the latter part of
    719 	 * the list.)
    720 	 */
    721 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
    722 	    d = TAILQ_NEXT(d, dv_list)) {
    723 		if (d->dv_parent == dev) {
    724 			printf("config_detach: detached device %s"
    725 			    " has children %s\n", dev->dv_xname, d->dv_xname);
    726 			panic("config_detach");
    727 		}
    728 	}
    729 #endif
    730 
    731 	/*
    732 	 * Mark cfdata to show that the unit can be reused, if possible.
    733 	 */
    734 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    735 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    736 			if (STREQ(cf->cf_name, cd->cd_name)) {
    737 				if (cf->cf_fstate == FSTATE_FOUND &&
    738 				    cf->cf_unit == dev->dv_unit)
    739 					cf->cf_fstate = FSTATE_NOTFOUND;
    740 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    741 				/*
    742 				 * Note that we can only re-use a starred
    743 				 * unit number if the unit being detached
    744 				 * had the last assigned unit number.
    745 				 */
    746 				if (cf->cf_fstate == FSTATE_STAR &&
    747 				    cf->cf_unit == dev->dv_unit + 1)
    748 					cf->cf_unit--;
    749 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    750 			}
    751 		}
    752 	}
    753 
    754 	/*
    755 	 * Unlink from device list.
    756 	 */
    757 	TAILQ_REMOVE(&alldevs, dev, dv_list);
    758 
    759 	/*
    760 	 * Remove from cfdriver's array, tell the world, and free softc.
    761 	 */
    762 	cd->cd_devs[dev->dv_unit] = NULL;
    763 	if ((flags & DETACH_QUIET) == 0)
    764 		printf("%s detached\n", dev->dv_xname);
    765 	free(dev, M_DEVBUF);
    766 
    767 	/*
    768 	 * If the device now has no units in use, deallocate its softc array.
    769 	 */
    770 	for (i = 0; i < cd->cd_ndevs; i++)
    771 		if (cd->cd_devs[i] != NULL)
    772 			break;
    773 	if (i == cd->cd_ndevs) {		/* nothing found; deallocate */
    774 		free(cd->cd_devs, M_DEVBUF);
    775 		cd->cd_devs = NULL;
    776 		cd->cd_ndevs = 0;
    777 	}
    778 
    779 	/*
    780 	 * Return success.
    781 	 */
    782 	return (0);
    783 }
    784 
    785 int
    786 config_activate(struct device *dev)
    787 {
    788 	struct cfattach *ca = dev->dv_cfdata->cf_attach;
    789 	int rv = 0, oflags = dev->dv_flags;
    790 
    791 	if (ca->ca_activate == NULL)
    792 		return (EOPNOTSUPP);
    793 
    794 	if ((dev->dv_flags & DVF_ACTIVE) == 0) {
    795 		dev->dv_flags |= DVF_ACTIVE;
    796 		rv = (*ca->ca_activate)(dev, DVACT_ACTIVATE);
    797 		if (rv)
    798 			dev->dv_flags = oflags;
    799 	}
    800 	return (rv);
    801 }
    802 
    803 int
    804 config_deactivate(struct device *dev)
    805 {
    806 	struct cfattach *ca = dev->dv_cfdata->cf_attach;
    807 	int rv = 0, oflags = dev->dv_flags;
    808 
    809 	if (ca->ca_activate == NULL)
    810 		return (EOPNOTSUPP);
    811 
    812 	if (dev->dv_flags & DVF_ACTIVE) {
    813 		dev->dv_flags &= ~DVF_ACTIVE;
    814 		rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
    815 		if (rv)
    816 			dev->dv_flags = oflags;
    817 	}
    818 	return (rv);
    819 }
    820 
    821 /*
    822  * Defer the configuration of the specified device until all
    823  * of its parent's devices have been attached.
    824  */
    825 void
    826 config_defer(struct device *dev, void (*func)(struct device *))
    827 {
    828 	struct deferred_config *dc;
    829 
    830 	if (dev->dv_parent == NULL)
    831 		panic("config_defer: can't defer config of a root device");
    832 
    833 #ifdef DIAGNOSTIC
    834 	for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
    835 	     dc = TAILQ_NEXT(dc, dc_queue)) {
    836 		if (dc->dc_dev == dev)
    837 			panic("config_defer: deferred twice");
    838 	}
    839 #endif
    840 
    841 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
    842 	if (dc == NULL)
    843 		panic("config_defer: unable to allocate callback");
    844 
    845 	dc->dc_dev = dev;
    846 	dc->dc_func = func;
    847 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
    848 	config_pending_incr();
    849 }
    850 
    851 /*
    852  * Defer some autoconfiguration for a device until after interrupts
    853  * are enabled.
    854  */
    855 void
    856 config_interrupts(struct device *dev, void (*func)(struct device *))
    857 {
    858 	struct deferred_config *dc;
    859 
    860 	/*
    861 	 * If interrupts are enabled, callback now.
    862 	 */
    863 	if (cold == 0) {
    864 		(*func)(dev);
    865 		return;
    866 	}
    867 
    868 #ifdef DIAGNOSTIC
    869 	for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
    870 	     dc = TAILQ_NEXT(dc, dc_queue)) {
    871 		if (dc->dc_dev == dev)
    872 			panic("config_interrupts: deferred twice");
    873 	}
    874 #endif
    875 
    876 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
    877 	if (dc == NULL)
    878 		panic("config_interrupts: unable to allocate callback");
    879 
    880 	dc->dc_dev = dev;
    881 	dc->dc_func = func;
    882 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
    883 	config_pending_incr();
    884 }
    885 
    886 /*
    887  * Process a deferred configuration queue.
    888  */
    889 static void
    890 config_process_deferred(struct deferred_config_head *queue,
    891     struct device *parent)
    892 {
    893 	struct deferred_config *dc, *ndc;
    894 
    895 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
    896 		ndc = TAILQ_NEXT(dc, dc_queue);
    897 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
    898 			TAILQ_REMOVE(queue, dc, dc_queue);
    899 			(*dc->dc_func)(dc->dc_dev);
    900 			free(dc, M_DEVBUF);
    901 			config_pending_decr();
    902 		}
    903 	}
    904 }
    905 
    906 /*
    907  * Manipulate the config_pending semaphore.
    908  */
    909 void
    910 config_pending_incr(void)
    911 {
    912 
    913 	config_pending++;
    914 }
    915 
    916 void
    917 config_pending_decr(void)
    918 {
    919 
    920 #ifdef DIAGNOSTIC
    921 	if (config_pending == 0)
    922 		panic("config_pending_decr: config_pending == 0");
    923 #endif
    924 	config_pending--;
    925 	if (config_pending == 0)
    926 		wakeup((void *)&config_pending);
    927 }
    928 
    929 /*
    930  * Attach a statically-initialized event.  The type and string pointers
    931  * are already set up.
    932  */
    933 void
    934 evcnt_attach_static(struct evcnt *ev)
    935 {
    936 	int len;
    937 
    938 	len = strlen(ev->ev_group);
    939 #ifdef DIAGNOSTIC
    940 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
    941 		panic("evcnt_attach_static: group length (%s)", ev->ev_group);
    942 #endif
    943 	ev->ev_grouplen = len;
    944 
    945 	len = strlen(ev->ev_name);
    946 #ifdef DIAGNOSTIC
    947 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
    948 		panic("evcnt_attach_static: name length (%s)", ev->ev_name);
    949 #endif
    950 	ev->ev_namelen = len;
    951 
    952 	TAILQ_INSERT_TAIL(&allevents, ev, ev_list);
    953 }
    954 
    955 /*
    956  * Attach a dynamically-initialized event.  Zero it, set up the type
    957  * and string pointers and then act like it was statically initialized.
    958  */
    959 void
    960 evcnt_attach_dynamic(struct evcnt *ev, int type, const struct evcnt *parent,
    961     const char *group, const char *name)
    962 {
    963 
    964 	memset(ev, 0, sizeof *ev);
    965 	ev->ev_type = type;
    966 	ev->ev_parent = parent;
    967 	ev->ev_group = group;
    968 	ev->ev_name = name;
    969 	evcnt_attach_static(ev);
    970 }
    971 
    972 /*
    973  * Detach an event.
    974  */
    975 void
    976 evcnt_detach(struct evcnt *ev)
    977 {
    978 
    979 	TAILQ_REMOVE(&allevents, ev, ev_list);
    980 }
    981 
    982 #ifdef DDB
    983 void
    984 event_print(int full, void (*pr)(const char *, ...))
    985 {
    986 	struct evcnt *evp;
    987 
    988 	TAILQ_FOREACH(evp, &allevents, ev_list) {
    989 		if (evp->ev_count == 0 && !full)
    990 			continue;
    991 
    992 		(*pr)("evcnt type %d: %s %s = %lld\n", evp->ev_type,
    993 		    evp->ev_group, evp->ev_name, evp->ev_count);
    994 	}
    995 }
    996 #endif /* DDB */
    997