Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.69
      1 /* $NetBSD: subr_autoconf.c,v 1.69 2002/09/27 05:45:03 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.69 2002/09/27 05:45:03 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)[0] == (s2)[0] && 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 	pcd = config_cfdriver_lookup(parent->dv_cfdata->cf_name);
    323 	KASSERT(pcd != NULL);
    324 
    325 	/*
    326 	 * First, ensure this parent has the correct interface
    327 	 * attribute.
    328 	 */
    329 	if (pcd->cd_attrs == NULL)
    330 		return (0);	/* no interface attributes -> no children */
    331 	for (cpp = pcd->cd_attrs; (cp = *cpp) != NULL; cpp++) {
    332 		if (STREQ(cp, cfp->cfp_iattr)) {
    333 			/* Match. */
    334 			break;
    335 		}
    336 	}
    337 	if (cp == NULL)
    338 		return (0);	/* doesn't carry the req'd attribute */
    339 
    340 	/*
    341 	 * If no specific parent device instance was specified (i.e.
    342 	 * we're attaching to the attribute only), we're done!
    343 	 */
    344 	if (cfp->cfp_parent == NULL)
    345 		return (1);
    346 
    347 	/*
    348 	 * Check the parent device's name.
    349 	 */
    350 	if (pcd->cd_name[0] != cfp->cfp_parent[0] ||
    351 	    strcmp(pcd->cd_name, cfp->cfp_parent) != 0)
    352 		return (0);	/* not the same parent */
    353 
    354 	/*
    355 	 * Make sure the unit number matches.
    356 	 */
    357 	if (cfp->cfp_unit == -1 ||	/* wildcard */
    358 	    cfp->cfp_unit == parent->dv_unit)
    359 		return (1);
    360 
    361 	/* Unit numbers don't match. */
    362 	return (0);
    363 }
    364 
    365 /*
    366  * Invoke the "match" routine for a cfdata entry on behalf of
    367  * an external caller, usually a "submatch" routine.
    368  */
    369 int
    370 config_match(struct device *parent, struct cfdata *cf, void *aux)
    371 {
    372 
    373 	return ((*cf->cf_attach->ca_match)(parent, cf, aux));
    374 }
    375 
    376 /*
    377  * Iterate over all potential children of some device, calling the given
    378  * function (default being the child's match function) for each one.
    379  * Nonzero returns are matches; the highest value returned is considered
    380  * the best match.  Return the `found child' if we got a match, or NULL
    381  * otherwise.  The `aux' pointer is simply passed on through.
    382  *
    383  * Note that this function is designed so that it can be used to apply
    384  * an arbitrary function to all potential children (its return value
    385  * can be ignored).
    386  */
    387 struct cfdata *
    388 config_search(cfmatch_t fn, struct device *parent, void *aux)
    389 {
    390 	struct cftable *ct;
    391 	struct cfdata *cf;
    392 	struct matchinfo m;
    393 
    394 	m.fn = fn;
    395 	m.parent = parent;
    396 	m.aux = aux;
    397 	m.match = NULL;
    398 	m.pri = 0;
    399 
    400 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    401 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    402 			/*
    403 			 * Skip cf if no longer eligible, otherwise scan
    404 			 * through parents for one matching `parent', and
    405 			 * try match function.
    406 			 */
    407 			if (cf->cf_fstate == FSTATE_FOUND)
    408 				continue;
    409 			if (cf->cf_fstate == FSTATE_DNOTFOUND ||
    410 			    cf->cf_fstate == FSTATE_DSTAR)
    411 				continue;
    412 			if (cfparent_match(parent, cf->cf_pspec))
    413 				mapply(&m, cf);
    414 		}
    415 	}
    416 	return (m.match);
    417 }
    418 
    419 /*
    420  * Find the given root device.
    421  * This is much like config_search, but there is no parent.
    422  * Don't bother with multiple cfdata tables; the root node
    423  * must always be in the initial table.
    424  */
    425 struct cfdata *
    426 config_rootsearch(cfmatch_t fn, const char *rootname, void *aux)
    427 {
    428 	struct cfdata *cf;
    429 	short *p;
    430 	struct matchinfo m;
    431 
    432 	m.fn = fn;
    433 	m.parent = ROOT;
    434 	m.aux = aux;
    435 	m.match = NULL;
    436 	m.pri = 0;
    437 	/*
    438 	 * Look at root entries for matching name.  We do not bother
    439 	 * with found-state here since only one root should ever be
    440 	 * searched (and it must be done first).
    441 	 */
    442 	for (p = cfroots; *p >= 0; p++) {
    443 		cf = &cfdata[*p];
    444 		if (strcmp(cf->cf_name, rootname) == 0)
    445 			mapply(&m, cf);
    446 	}
    447 	return (m.match);
    448 }
    449 
    450 static const char *msgs[3] = { "", " not configured\n", " unsupported\n" };
    451 
    452 /*
    453  * The given `aux' argument describes a device that has been found
    454  * on the given parent, but not necessarily configured.  Locate the
    455  * configuration data for that device (using the submatch function
    456  * provided, or using candidates' cd_match configuration driver
    457  * functions) and attach it, and return true.  If the device was
    458  * not configured, call the given `print' function and return 0.
    459  */
    460 struct device *
    461 config_found_sm(struct device *parent, void *aux, cfprint_t print,
    462     cfmatch_t submatch)
    463 {
    464 	struct cfdata *cf;
    465 
    466 	if ((cf = config_search(submatch, parent, aux)) != NULL)
    467 		return (config_attach(parent, cf, aux, print));
    468 	if (print)
    469 		printf("%s", msgs[(*print)(aux, parent->dv_xname)]);
    470 	return (NULL);
    471 }
    472 
    473 /*
    474  * As above, but for root devices.
    475  */
    476 struct device *
    477 config_rootfound(const char *rootname, void *aux)
    478 {
    479 	struct cfdata *cf;
    480 
    481 	if ((cf = config_rootsearch((cfmatch_t)NULL, rootname, aux)) != NULL)
    482 		return (config_attach(ROOT, cf, aux, (cfprint_t)NULL));
    483 	printf("root device %s not configured\n", rootname);
    484 	return (NULL);
    485 }
    486 
    487 /* just like sprintf(buf, "%d") except that it works from the end */
    488 static char *
    489 number(char *ep, int n)
    490 {
    491 
    492 	*--ep = 0;
    493 	while (n >= 10) {
    494 		*--ep = (n % 10) + '0';
    495 		n /= 10;
    496 	}
    497 	*--ep = n + '0';
    498 	return (ep);
    499 }
    500 
    501 /*
    502  * Expand the size of the cd_devs array if necessary.
    503  */
    504 void
    505 config_makeroom(int n, struct cfdriver *cd)
    506 {
    507 	int old, new;
    508 	void **nsp;
    509 
    510 	if (n < cd->cd_ndevs)
    511 		return;
    512 
    513 	/*
    514 	 * Need to expand the array.
    515 	 */
    516 	old = cd->cd_ndevs;
    517 	if (old == 0)
    518 		new = MINALLOCSIZE / sizeof(void *);
    519 	else
    520 		new = old * 2;
    521 	while (new <= n)
    522 		new *= 2;
    523 	cd->cd_ndevs = new;
    524 	nsp = malloc(new * sizeof(void *), M_DEVBUF,
    525 	    cold ? M_NOWAIT : M_WAITOK);
    526 	if (nsp == NULL)
    527 		panic("config_attach: %sing dev array",
    528 		    old != 0 ? "expand" : "creat");
    529 	memset(nsp + old, 0, (new - old) * sizeof(void *));
    530 	if (old != 0) {
    531 		memcpy(nsp, cd->cd_devs, old * sizeof(void *));
    532 		free(cd->cd_devs, M_DEVBUF);
    533 	}
    534 	cd->cd_devs = nsp;
    535 }
    536 
    537 /*
    538  * Attach a found device.  Allocates memory for device variables.
    539  */
    540 struct device *
    541 config_attach(struct device *parent, struct cfdata *cf, void *aux,
    542 	cfprint_t print)
    543 {
    544 	struct device *dev;
    545 	struct cftable *ct;
    546 	struct cfdriver *cd;
    547 	struct cfattach *ca;
    548 	size_t lname, lunit;
    549 	const char *xunit;
    550 	int myunit;
    551 	char num[10];
    552 
    553 	cd = config_cfdriver_lookup(cf->cf_name);
    554 	KASSERT(cd != NULL);
    555 	ca = cf->cf_attach;
    556 	if (ca->ca_devsize < sizeof(struct device))
    557 		panic("config_attach");
    558 
    559 #ifndef __BROKEN_CONFIG_UNIT_USAGE
    560 	if (cf->cf_fstate == FSTATE_STAR) {
    561 		for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
    562 			if (cd->cd_devs[myunit] == NULL)
    563 				break;
    564 		/*
    565 		 * myunit is now the unit of the first NULL device pointer,
    566 		 * or max(cd->cd_ndevs,cf->cf_unit).
    567 		 */
    568 	} else {
    569 		myunit = cf->cf_unit;
    570 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
    571 		cf->cf_fstate = FSTATE_FOUND;
    572 	}
    573 #else
    574 	myunit = cf->cf_unit;
    575 	if (cf->cf_fstate == FSTATE_STAR)
    576 		cf->cf_unit++;
    577 	else {
    578 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
    579 		cf->cf_fstate = FSTATE_FOUND;
    580 	}
    581 #endif /* ! __BROKEN_CONFIG_UNIT_USAGE */
    582 
    583 	/* compute length of name and decimal expansion of unit number */
    584 	lname = strlen(cd->cd_name);
    585 	xunit = number(&num[sizeof(num)], myunit);
    586 	lunit = &num[sizeof(num)] - xunit;
    587 	if (lname + lunit > sizeof(dev->dv_xname))
    588 		panic("config_attach: device name too long");
    589 
    590 	/* get memory for all device vars */
    591 	dev = (struct device *)malloc(ca->ca_devsize, M_DEVBUF,
    592 	    cold ? M_NOWAIT : M_WAITOK);
    593 	if (!dev)
    594 	    panic("config_attach: memory allocation for device softc failed");
    595 	memset(dev, 0, ca->ca_devsize);
    596 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
    597 	dev->dv_class = cd->cd_class;
    598 	dev->dv_cfdata = cf;
    599 	dev->dv_unit = myunit;
    600 	memcpy(dev->dv_xname, cd->cd_name, lname);
    601 	memcpy(dev->dv_xname + lname, xunit, lunit);
    602 	dev->dv_parent = parent;
    603 	dev->dv_flags = DVF_ACTIVE;	/* always initially active */
    604 
    605 	if (parent == ROOT)
    606 		printf("%s (root)", dev->dv_xname);
    607 	else {
    608 		printf("%s at %s", dev->dv_xname, parent->dv_xname);
    609 		if (print)
    610 			(void) (*print)(aux, NULL);
    611 	}
    612 
    613 	/* put this device in the devices array */
    614 	config_makeroom(dev->dv_unit, cd);
    615 	if (cd->cd_devs[dev->dv_unit])
    616 		panic("config_attach: duplicate %s", dev->dv_xname);
    617 	cd->cd_devs[dev->dv_unit] = dev;
    618 
    619 	/*
    620 	 * Before attaching, clobber any unfound devices that are
    621 	 * otherwise identical.
    622 	 */
    623 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    624 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    625 			if (STREQ(cf->cf_name, cd->cd_name) &&
    626 			    cf->cf_unit == dev->dv_unit) {
    627 				if (cf->cf_fstate == FSTATE_NOTFOUND)
    628 					cf->cf_fstate = FSTATE_FOUND;
    629 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    630 				/*
    631 				 * Bump the unit number on all starred cfdata
    632 				 * entries for this device.
    633 				 */
    634 				if (cf->cf_fstate == FSTATE_STAR)
    635 					cf->cf_unit++;
    636 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    637 			}
    638 		}
    639 	}
    640 #ifdef __HAVE_DEVICE_REGISTER
    641 	device_register(dev, aux);
    642 #endif
    643 	(*ca->ca_attach)(parent, dev, aux);
    644 	config_process_deferred(&deferred_config_queue, dev);
    645 	return (dev);
    646 }
    647 
    648 /*
    649  * Detach a device.  Optionally forced (e.g. because of hardware
    650  * removal) and quiet.  Returns zero if successful, non-zero
    651  * (an error code) otherwise.
    652  *
    653  * Note that this code wants to be run from a process context, so
    654  * that the detach can sleep to allow processes which have a device
    655  * open to run and unwind their stacks.
    656  */
    657 int
    658 config_detach(struct device *dev, int flags)
    659 {
    660 	struct cftable *ct;
    661 	struct cfdata *cf;
    662 	struct cfattach *ca;
    663 	struct cfdriver *cd;
    664 #ifdef DIAGNOSTIC
    665 	struct device *d;
    666 #endif
    667 	int rv = 0, i;
    668 
    669 	cf = dev->dv_cfdata;
    670 #ifdef DIAGNOSTIC
    671 	if (cf->cf_fstate != FSTATE_FOUND && cf->cf_fstate != FSTATE_STAR)
    672 		panic("config_detach: bad device fstate");
    673 #endif
    674 	cd = config_cfdriver_lookup(cf->cf_name);
    675 	KASSERT(cd != NULL);
    676 	ca = cf->cf_attach;
    677 
    678 	/*
    679 	 * Ensure the device is deactivated.  If the device doesn't
    680 	 * have an activation entry point, we allow DVF_ACTIVE to
    681 	 * remain set.  Otherwise, if DVF_ACTIVE is still set, the
    682 	 * device is busy, and the detach fails.
    683 	 */
    684 	if (ca->ca_activate != NULL)
    685 		rv = config_deactivate(dev);
    686 
    687 	/*
    688 	 * Try to detach the device.  If that's not possible, then
    689 	 * we either panic() (for the forced but failed case), or
    690 	 * return an error.
    691 	 */
    692 	if (rv == 0) {
    693 		if (ca->ca_detach != NULL)
    694 			rv = (*ca->ca_detach)(dev, flags);
    695 		else
    696 			rv = EOPNOTSUPP;
    697 	}
    698 	if (rv != 0) {
    699 		if ((flags & DETACH_FORCE) == 0)
    700 			return (rv);
    701 		else
    702 			panic("config_detach: forced detach of %s failed (%d)",
    703 			    dev->dv_xname, rv);
    704 	}
    705 
    706 	/*
    707 	 * The device has now been successfully detached.
    708 	 */
    709 
    710 #ifdef DIAGNOSTIC
    711 	/*
    712 	 * Sanity: If you're successfully detached, you should have no
    713 	 * children.  (Note that because children must be attached
    714 	 * after parents, we only need to search the latter part of
    715 	 * the list.)
    716 	 */
    717 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
    718 	    d = TAILQ_NEXT(d, dv_list)) {
    719 		if (d->dv_parent == dev) {
    720 			printf("config_detach: detached device %s"
    721 			    " has children %s\n", dev->dv_xname, d->dv_xname);
    722 			panic("config_detach");
    723 		}
    724 	}
    725 #endif
    726 
    727 	/*
    728 	 * Mark cfdata to show that the unit can be reused, if possible.
    729 	 */
    730 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    731 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    732 			if (STREQ(cf->cf_name, cd->cd_name)) {
    733 				if (cf->cf_fstate == FSTATE_FOUND &&
    734 				    cf->cf_unit == dev->dv_unit)
    735 					cf->cf_fstate = FSTATE_NOTFOUND;
    736 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    737 				/*
    738 				 * Note that we can only re-use a starred
    739 				 * unit number if the unit being detached
    740 				 * had the last assigned unit number.
    741 				 */
    742 				if (cf->cf_fstate == FSTATE_STAR &&
    743 				    cf->cf_unit == dev->dv_unit + 1)
    744 					cf->cf_unit--;
    745 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    746 			}
    747 		}
    748 	}
    749 
    750 	/*
    751 	 * Unlink from device list.
    752 	 */
    753 	TAILQ_REMOVE(&alldevs, dev, dv_list);
    754 
    755 	/*
    756 	 * Remove from cfdriver's array, tell the world, and free softc.
    757 	 */
    758 	cd->cd_devs[dev->dv_unit] = NULL;
    759 	if ((flags & DETACH_QUIET) == 0)
    760 		printf("%s detached\n", dev->dv_xname);
    761 	free(dev, M_DEVBUF);
    762 
    763 	/*
    764 	 * If the device now has no units in use, deallocate its softc array.
    765 	 */
    766 	for (i = 0; i < cd->cd_ndevs; i++)
    767 		if (cd->cd_devs[i] != NULL)
    768 			break;
    769 	if (i == cd->cd_ndevs) {		/* nothing found; deallocate */
    770 		free(cd->cd_devs, M_DEVBUF);
    771 		cd->cd_devs = NULL;
    772 		cd->cd_ndevs = 0;
    773 	}
    774 
    775 	/*
    776 	 * Return success.
    777 	 */
    778 	return (0);
    779 }
    780 
    781 int
    782 config_activate(struct device *dev)
    783 {
    784 	struct cfattach *ca = dev->dv_cfdata->cf_attach;
    785 	int rv = 0, oflags = dev->dv_flags;
    786 
    787 	if (ca->ca_activate == NULL)
    788 		return (EOPNOTSUPP);
    789 
    790 	if ((dev->dv_flags & DVF_ACTIVE) == 0) {
    791 		dev->dv_flags |= DVF_ACTIVE;
    792 		rv = (*ca->ca_activate)(dev, DVACT_ACTIVATE);
    793 		if (rv)
    794 			dev->dv_flags = oflags;
    795 	}
    796 	return (rv);
    797 }
    798 
    799 int
    800 config_deactivate(struct device *dev)
    801 {
    802 	struct cfattach *ca = dev->dv_cfdata->cf_attach;
    803 	int rv = 0, oflags = dev->dv_flags;
    804 
    805 	if (ca->ca_activate == NULL)
    806 		return (EOPNOTSUPP);
    807 
    808 	if (dev->dv_flags & DVF_ACTIVE) {
    809 		dev->dv_flags &= ~DVF_ACTIVE;
    810 		rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
    811 		if (rv)
    812 			dev->dv_flags = oflags;
    813 	}
    814 	return (rv);
    815 }
    816 
    817 /*
    818  * Defer the configuration of the specified device until all
    819  * of its parent's devices have been attached.
    820  */
    821 void
    822 config_defer(struct device *dev, void (*func)(struct device *))
    823 {
    824 	struct deferred_config *dc;
    825 
    826 	if (dev->dv_parent == NULL)
    827 		panic("config_defer: can't defer config of a root device");
    828 
    829 #ifdef DIAGNOSTIC
    830 	for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
    831 	     dc = TAILQ_NEXT(dc, dc_queue)) {
    832 		if (dc->dc_dev == dev)
    833 			panic("config_defer: deferred twice");
    834 	}
    835 #endif
    836 
    837 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
    838 	if (dc == NULL)
    839 		panic("config_defer: unable to allocate callback");
    840 
    841 	dc->dc_dev = dev;
    842 	dc->dc_func = func;
    843 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
    844 	config_pending_incr();
    845 }
    846 
    847 /*
    848  * Defer some autoconfiguration for a device until after interrupts
    849  * are enabled.
    850  */
    851 void
    852 config_interrupts(struct device *dev, void (*func)(struct device *))
    853 {
    854 	struct deferred_config *dc;
    855 
    856 	/*
    857 	 * If interrupts are enabled, callback now.
    858 	 */
    859 	if (cold == 0) {
    860 		(*func)(dev);
    861 		return;
    862 	}
    863 
    864 #ifdef DIAGNOSTIC
    865 	for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
    866 	     dc = TAILQ_NEXT(dc, dc_queue)) {
    867 		if (dc->dc_dev == dev)
    868 			panic("config_interrupts: deferred twice");
    869 	}
    870 #endif
    871 
    872 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
    873 	if (dc == NULL)
    874 		panic("config_interrupts: unable to allocate callback");
    875 
    876 	dc->dc_dev = dev;
    877 	dc->dc_func = func;
    878 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
    879 	config_pending_incr();
    880 }
    881 
    882 /*
    883  * Process a deferred configuration queue.
    884  */
    885 static void
    886 config_process_deferred(struct deferred_config_head *queue,
    887     struct device *parent)
    888 {
    889 	struct deferred_config *dc, *ndc;
    890 
    891 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
    892 		ndc = TAILQ_NEXT(dc, dc_queue);
    893 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
    894 			TAILQ_REMOVE(queue, dc, dc_queue);
    895 			(*dc->dc_func)(dc->dc_dev);
    896 			free(dc, M_DEVBUF);
    897 			config_pending_decr();
    898 		}
    899 	}
    900 }
    901 
    902 /*
    903  * Manipulate the config_pending semaphore.
    904  */
    905 void
    906 config_pending_incr(void)
    907 {
    908 
    909 	config_pending++;
    910 }
    911 
    912 void
    913 config_pending_decr(void)
    914 {
    915 
    916 #ifdef DIAGNOSTIC
    917 	if (config_pending == 0)
    918 		panic("config_pending_decr: config_pending == 0");
    919 #endif
    920 	config_pending--;
    921 	if (config_pending == 0)
    922 		wakeup((void *)&config_pending);
    923 }
    924 
    925 /*
    926  * Attach a statically-initialized event.  The type and string pointers
    927  * are already set up.
    928  */
    929 void
    930 evcnt_attach_static(struct evcnt *ev)
    931 {
    932 	int len;
    933 
    934 	len = strlen(ev->ev_group);
    935 #ifdef DIAGNOSTIC
    936 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
    937 		panic("evcnt_attach_static: group length (%s)", ev->ev_group);
    938 #endif
    939 	ev->ev_grouplen = len;
    940 
    941 	len = strlen(ev->ev_name);
    942 #ifdef DIAGNOSTIC
    943 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
    944 		panic("evcnt_attach_static: name length (%s)", ev->ev_name);
    945 #endif
    946 	ev->ev_namelen = len;
    947 
    948 	TAILQ_INSERT_TAIL(&allevents, ev, ev_list);
    949 }
    950 
    951 /*
    952  * Attach a dynamically-initialized event.  Zero it, set up the type
    953  * and string pointers and then act like it was statically initialized.
    954  */
    955 void
    956 evcnt_attach_dynamic(struct evcnt *ev, int type, const struct evcnt *parent,
    957     const char *group, const char *name)
    958 {
    959 
    960 	memset(ev, 0, sizeof *ev);
    961 	ev->ev_type = type;
    962 	ev->ev_parent = parent;
    963 	ev->ev_group = group;
    964 	ev->ev_name = name;
    965 	evcnt_attach_static(ev);
    966 }
    967 
    968 /*
    969  * Detach an event.
    970  */
    971 void
    972 evcnt_detach(struct evcnt *ev)
    973 {
    974 
    975 	TAILQ_REMOVE(&allevents, ev, ev_list);
    976 }
    977 
    978 #ifdef DDB
    979 void
    980 event_print(int full, void (*pr)(const char *, ...))
    981 {
    982 	struct evcnt *evp;
    983 
    984 	TAILQ_FOREACH(evp, &allevents, ev_list) {
    985 		if (evp->ev_count == 0 && !full)
    986 			continue;
    987 
    988 		(*pr)("evcnt type %d: %s %s = %lld\n", evp->ev_type,
    989 		    evp->ev_group, evp->ev_name, evp->ev_count);
    990 	}
    991 }
    992 #endif /* DDB */
    993