xref: /netbsd-src/sys/kern/subr_autoconf.c (revision 21e37cc72a480a47828990a439cde7ac9ffaf0c6)
1 /* $NetBSD: subr_autoconf.c,v 1.89 2004/02/17 05:03:16 rtr 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.89 2004/02/17 05:03:16 rtr Exp $");
81 
82 #include "opt_ddb.h"
83 
84 #include <sys/param.h>
85 #include <sys/device.h>
86 #include <sys/malloc.h>
87 #include <sys/systm.h>
88 #include <sys/kernel.h>
89 #include <sys/errno.h>
90 #include <sys/proc.h>
91 #include <sys/reboot.h>
92 #include <machine/limits.h>
93 
94 #include "opt_userconf.h"
95 #ifdef USERCONF
96 #include <sys/userconf.h>
97 #endif
98 
99 /*
100  * Autoconfiguration subroutines.
101  */
102 
103 /*
104  * ioconf.c exports exactly two names: cfdata and cfroots.  All system
105  * devices and drivers are found via these tables.
106  */
107 extern struct cfdata cfdata[];
108 extern const short cfroots[];
109 
110 /*
111  * List of all cfdriver structures.  We use this to detect duplicates
112  * when other cfdrivers are loaded.
113  */
114 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
115 extern struct cfdriver * const cfdriver_list_initial[];
116 
117 /*
118  * Initial list of cfattach's.
119  */
120 extern const struct cfattachinit cfattachinit[];
121 
122 /*
123  * List of cfdata tables.  We always have one such list -- the one
124  * built statically when the kernel was configured.
125  */
126 struct cftablelist allcftables;
127 static struct cftable initcftable;
128 
129 /*
130  * Database of device properties.
131  */
132 propdb_t dev_propdb;
133 
134 #define	ROOT ((struct device *)NULL)
135 
136 struct matchinfo {
137 	cfmatch_t fn;
138 	struct	device *parent;
139 	void	*aux;
140 	struct	cfdata *match;
141 	int	pri;
142 };
143 
144 static char *number(char *, int);
145 static void mapply(struct matchinfo *, struct cfdata *);
146 
147 struct deferred_config {
148 	TAILQ_ENTRY(deferred_config) dc_queue;
149 	struct device *dc_dev;
150 	void (*dc_func)(struct device *);
151 };
152 
153 TAILQ_HEAD(deferred_config_head, deferred_config);
154 
155 struct deferred_config_head deferred_config_queue;
156 struct deferred_config_head interrupt_config_queue;
157 
158 static void config_process_deferred(struct deferred_config_head *,
159 	struct device *);
160 
161 /* Hooks to finalize configuration once all real devices have been found. */
162 struct finalize_hook {
163 	TAILQ_ENTRY(finalize_hook) f_list;
164 	int (*f_func)(struct device *);
165 	struct device *f_dev;
166 };
167 static TAILQ_HEAD(, finalize_hook) config_finalize_list;
168 static int config_finalize_done;
169 
170 /* list of all devices */
171 struct devicelist alldevs;
172 
173 __volatile int config_pending;		/* semaphore for mountroot */
174 
175 #define	STREQ(s1, s2)			\
176 	(*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
177 
178 static int config_initialized;		/* config_init() has been called. */
179 
180 static int config_do_twiddle;
181 
182 /*
183  * Initialize the autoconfiguration data structures.  Normally this
184  * is done by configure(), but some platforms need to do this very
185  * early (to e.g. initialize the console).
186  */
187 void
188 config_init(void)
189 {
190 	const struct cfattachinit *cfai;
191 	int i, j;
192 
193 	if (config_initialized)
194 		return;
195 
196 	/* allcfdrivers is statically initialized. */
197 	for (i = 0; cfdriver_list_initial[i] != NULL; i++) {
198 		if (config_cfdriver_attach(cfdriver_list_initial[i]) != 0)
199 			panic("configure: duplicate `%s' drivers",
200 			    cfdriver_list_initial[i]->cd_name);
201 	}
202 
203 	for (cfai = &cfattachinit[0]; cfai->cfai_name != NULL; cfai++) {
204 		for (j = 0; cfai->cfai_list[j] != NULL; j++) {
205 			if (config_cfattach_attach(cfai->cfai_name,
206 						   cfai->cfai_list[j]) != 0)
207 				panic("configure: duplicate `%s' attachment "
208 				    "of `%s' driver",
209 				    cfai->cfai_list[j]->ca_name,
210 				    cfai->cfai_name);
211 		}
212 	}
213 
214 	TAILQ_INIT(&allcftables);
215 	initcftable.ct_cfdata = cfdata;
216 	TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
217 
218 	TAILQ_INIT(&deferred_config_queue);
219 	TAILQ_INIT(&interrupt_config_queue);
220 	TAILQ_INIT(&config_finalize_list);
221 	TAILQ_INIT(&alldevs);
222 
223 	config_initialized = 1;
224 }
225 
226 /*
227  * Configure the system's hardware.
228  */
229 void
230 configure(void)
231 {
232 	int errcnt;
233 
234 	/* Initialize data structures. */
235 	config_init();
236 
237 	/* Initialize the device property database. */
238 	dev_propdb = propdb_create("device properties");
239 	if (dev_propdb == NULL)
240 		panic("unable to create device property database");
241 
242 #ifdef USERCONF
243 	if (boothowto & RB_USERCONF)
244 		user_config();
245 #endif
246 
247 	if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
248 		config_do_twiddle = 1;
249 		printf_nolog("Detecting hardware...");
250 	}
251 
252 	/*
253 	 * Do the machine-dependent portion of autoconfiguration.  This
254 	 * sets the configuration machinery here in motion by "finding"
255 	 * the root bus.  When this function returns, we expect interrupts
256 	 * to be enabled.
257 	 */
258 	cpu_configure();
259 
260 	/*
261 	 * Now that we've found all the hardware, start the real time
262 	 * and statistics clocks.
263 	 */
264 	initclocks();
265 
266 	cold = 0;	/* clocks are running, we're warm now! */
267 
268 	/*
269 	 * Now callback to finish configuration for devices which want
270 	 * to do this once interrupts are enabled.
271 	 */
272 	config_process_deferred(&interrupt_config_queue, NULL);
273 
274 	errcnt = aprint_get_error_count();
275 	if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
276 	    (boothowto & AB_VERBOSE) == 0) {
277 		if (config_do_twiddle) {
278 			config_do_twiddle = 0;
279 			printf_nolog("done.\n");
280 		}
281 		if (errcnt != 0) {
282 			printf("WARNING: %d error%s while detecting hardware; "
283 			    "check system log.\n", errcnt,
284 			    errcnt == 1 ? "" : "s");
285 		}
286 	}
287 }
288 
289 /*
290  * Add a cfdriver to the system.
291  */
292 int
293 config_cfdriver_attach(struct cfdriver *cd)
294 {
295 	struct cfdriver *lcd;
296 
297 	/* Make sure this driver isn't already in the system. */
298 	LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
299 		if (STREQ(lcd->cd_name, cd->cd_name))
300 			return (EEXIST);
301 	}
302 
303 	LIST_INIT(&cd->cd_attach);
304 	LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
305 
306 	return (0);
307 }
308 
309 /*
310  * Remove a cfdriver from the system.
311  */
312 int
313 config_cfdriver_detach(struct cfdriver *cd)
314 {
315 	int i;
316 
317 	/* Make sure there are no active instances. */
318 	for (i = 0; i < cd->cd_ndevs; i++) {
319 		if (cd->cd_devs[i] != NULL)
320 			return (EBUSY);
321 	}
322 
323 	/* ...and no attachments loaded. */
324 	if (LIST_EMPTY(&cd->cd_attach) == 0)
325 		return (EBUSY);
326 
327 	LIST_REMOVE(cd, cd_list);
328 
329 	KASSERT(cd->cd_devs == NULL);
330 
331 	return (0);
332 }
333 
334 /*
335  * Look up a cfdriver by name.
336  */
337 struct cfdriver *
338 config_cfdriver_lookup(const char *name)
339 {
340 	struct cfdriver *cd;
341 
342 	LIST_FOREACH(cd, &allcfdrivers, cd_list) {
343 		if (STREQ(cd->cd_name, name))
344 			return (cd);
345 	}
346 
347 	return (NULL);
348 }
349 
350 /*
351  * Add a cfattach to the specified driver.
352  */
353 int
354 config_cfattach_attach(const char *driver, struct cfattach *ca)
355 {
356 	struct cfattach *lca;
357 	struct cfdriver *cd;
358 
359 	cd = config_cfdriver_lookup(driver);
360 	if (cd == NULL)
361 		return (ESRCH);
362 
363 	/* Make sure this attachment isn't already on this driver. */
364 	LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
365 		if (STREQ(lca->ca_name, ca->ca_name))
366 			return (EEXIST);
367 	}
368 
369 	LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
370 
371 	return (0);
372 }
373 
374 /*
375  * Remove a cfattach from the specified driver.
376  */
377 int
378 config_cfattach_detach(const char *driver, struct cfattach *ca)
379 {
380 	struct cfdriver *cd;
381 	struct device *dev;
382 	int i;
383 
384 	cd = config_cfdriver_lookup(driver);
385 	if (cd == NULL)
386 		return (ESRCH);
387 
388 	/* Make sure there are no active instances. */
389 	for (i = 0; i < cd->cd_ndevs; i++) {
390 		if ((dev = cd->cd_devs[i]) == NULL)
391 			continue;
392 		if (dev->dv_cfattach == ca)
393 			return (EBUSY);
394 	}
395 
396 	LIST_REMOVE(ca, ca_list);
397 
398 	return (0);
399 }
400 
401 /*
402  * Look up a cfattach by name.
403  */
404 static struct cfattach *
405 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
406 {
407 	struct cfattach *ca;
408 
409 	LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
410 		if (STREQ(ca->ca_name, atname))
411 			return (ca);
412 	}
413 
414 	return (NULL);
415 }
416 
417 /*
418  * Look up a cfattach by driver/attachment name.
419  */
420 struct cfattach *
421 config_cfattach_lookup(const char *name, const char *atname)
422 {
423 	struct cfdriver *cd;
424 
425 	cd = config_cfdriver_lookup(name);
426 	if (cd == NULL)
427 		return (NULL);
428 
429 	return (config_cfattach_lookup_cd(cd, atname));
430 }
431 
432 /*
433  * Apply the matching function and choose the best.  This is used
434  * a few times and we want to keep the code small.
435  */
436 static void
437 mapply(struct matchinfo *m, struct cfdata *cf)
438 {
439 	int pri;
440 
441 	if (m->fn != NULL)
442 		pri = (*m->fn)(m->parent, cf, m->aux);
443 	else {
444 		struct cfattach *ca;
445 
446 		ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
447 		if (ca == NULL) {
448 			/* No attachment for this entry, oh well. */
449 			return;
450 		}
451 	        if (ca->ca_match == NULL) {
452 			panic("mapply: no match function for '%s' attachment "
453 			    "of '%s'", cf->cf_atname, cf->cf_name);
454 		}
455 		pri = (*ca->ca_match)(m->parent, cf, m->aux);
456 	}
457 	if (pri > m->pri) {
458 		m->match = cf;
459 		m->pri = pri;
460 	}
461 }
462 
463 /*
464  * Determine if `parent' is a potential parent for a device spec based
465  * on `cfp'.
466  */
467 static int
468 cfparent_match(struct device *parent, const struct cfparent *cfp)
469 {
470 	struct cfdriver *pcd;
471 	const char * const *cpp;
472 	const char *cp;
473 
474 	/* We don't match root nodes here. */
475 	if (cfp == NULL)
476 		return (0);
477 
478 	pcd = parent->dv_cfdriver;
479 	KASSERT(pcd != NULL);
480 
481 	/*
482 	 * First, ensure this parent has the correct interface
483 	 * attribute.
484 	 */
485 	if (pcd->cd_attrs == NULL)
486 		return (0);	/* no interface attributes -> no children */
487 	for (cpp = pcd->cd_attrs; (cp = *cpp) != NULL; cpp++) {
488 		if (STREQ(cp, cfp->cfp_iattr)) {
489 			/* Match. */
490 			break;
491 		}
492 	}
493 	if (cp == NULL)
494 		return (0);	/* doesn't carry the req'd attribute */
495 
496 	/*
497 	 * If no specific parent device instance was specified (i.e.
498 	 * we're attaching to the attribute only), we're done!
499 	 */
500 	if (cfp->cfp_parent == NULL)
501 		return (1);
502 
503 	/*
504 	 * Check the parent device's name.
505 	 */
506 	if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
507 		return (0);	/* not the same parent */
508 
509 	/*
510 	 * Make sure the unit number matches.
511 	 */
512 	if (cfp->cfp_unit == DVUNIT_ANY ||	/* wildcard */
513 	    cfp->cfp_unit == parent->dv_unit)
514 		return (1);
515 
516 	/* Unit numbers don't match. */
517 	return (0);
518 }
519 
520 /*
521  * Invoke the "match" routine for a cfdata entry on behalf of
522  * an external caller, usually a "submatch" routine.
523  */
524 int
525 config_match(struct device *parent, struct cfdata *cf, void *aux)
526 {
527 	struct cfattach *ca;
528 
529 	ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
530 	if (ca == NULL) {
531 		/* No attachment for this entry, oh well. */
532 		return (0);
533 	}
534 
535 	return ((*ca->ca_match)(parent, cf, aux));
536 }
537 
538 /*
539  * Iterate over all potential children of some device, calling the given
540  * function (default being the child's match function) for each one.
541  * Nonzero returns are matches; the highest value returned is considered
542  * the best match.  Return the `found child' if we got a match, or NULL
543  * otherwise.  The `aux' pointer is simply passed on through.
544  *
545  * Note that this function is designed so that it can be used to apply
546  * an arbitrary function to all potential children (its return value
547  * can be ignored).
548  */
549 struct cfdata *
550 config_search(cfmatch_t fn, struct device *parent, void *aux)
551 {
552 	struct cftable *ct;
553 	struct cfdata *cf;
554 	struct matchinfo m;
555 
556 	KASSERT(config_initialized);
557 
558 	m.fn = fn;
559 	m.parent = parent;
560 	m.aux = aux;
561 	m.match = NULL;
562 	m.pri = 0;
563 
564 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
565 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
566 			/*
567 			 * Skip cf if no longer eligible, otherwise scan
568 			 * through parents for one matching `parent', and
569 			 * try match function.
570 			 */
571 			if (cf->cf_fstate == FSTATE_FOUND)
572 				continue;
573 			if (cf->cf_fstate == FSTATE_DNOTFOUND ||
574 			    cf->cf_fstate == FSTATE_DSTAR)
575 				continue;
576 			if (cfparent_match(parent, cf->cf_pspec))
577 				mapply(&m, cf);
578 		}
579 	}
580 	return (m.match);
581 }
582 
583 /*
584  * Find the given root device.
585  * This is much like config_search, but there is no parent.
586  * Don't bother with multiple cfdata tables; the root node
587  * must always be in the initial table.
588  */
589 struct cfdata *
590 config_rootsearch(cfmatch_t fn, const char *rootname, void *aux)
591 {
592 	struct cfdata *cf;
593 	const short *p;
594 	struct matchinfo m;
595 
596 	m.fn = fn;
597 	m.parent = ROOT;
598 	m.aux = aux;
599 	m.match = NULL;
600 	m.pri = 0;
601 	/*
602 	 * Look at root entries for matching name.  We do not bother
603 	 * with found-state here since only one root should ever be
604 	 * searched (and it must be done first).
605 	 */
606 	for (p = cfroots; *p >= 0; p++) {
607 		cf = &cfdata[*p];
608 		if (strcmp(cf->cf_name, rootname) == 0)
609 			mapply(&m, cf);
610 	}
611 	return (m.match);
612 }
613 
614 static const char * const msgs[3] = { "", " not configured\n", " unsupported\n" };
615 
616 /*
617  * The given `aux' argument describes a device that has been found
618  * on the given parent, but not necessarily configured.  Locate the
619  * configuration data for that device (using the submatch function
620  * provided, or using candidates' cd_match configuration driver
621  * functions) and attach it, and return true.  If the device was
622  * not configured, call the given `print' function and return 0.
623  */
624 struct device *
625 config_found_sm(struct device *parent, void *aux, cfprint_t print,
626     cfmatch_t submatch)
627 {
628 	struct cfdata *cf;
629 
630 	if ((cf = config_search(submatch, parent, aux)) != NULL)
631 		return (config_attach(parent, cf, aux, print));
632 	if (print) {
633 		if (config_do_twiddle)
634 			twiddle();
635 		aprint_normal("%s", msgs[(*print)(aux, parent->dv_xname)]);
636 	}
637 	return (NULL);
638 }
639 
640 /*
641  * As above, but for root devices.
642  */
643 struct device *
644 config_rootfound(const char *rootname, void *aux)
645 {
646 	struct cfdata *cf;
647 
648 	if ((cf = config_rootsearch((cfmatch_t)NULL, rootname, aux)) != NULL)
649 		return (config_attach(ROOT, cf, aux, (cfprint_t)NULL));
650 	aprint_error("root device %s not configured\n", rootname);
651 	return (NULL);
652 }
653 
654 /* just like sprintf(buf, "%d") except that it works from the end */
655 static char *
656 number(char *ep, int n)
657 {
658 
659 	*--ep = 0;
660 	while (n >= 10) {
661 		*--ep = (n % 10) + '0';
662 		n /= 10;
663 	}
664 	*--ep = n + '0';
665 	return (ep);
666 }
667 
668 /*
669  * Expand the size of the cd_devs array if necessary.
670  */
671 void
672 config_makeroom(int n, struct cfdriver *cd)
673 {
674 	int old, new;
675 	void **nsp;
676 
677 	if (n < cd->cd_ndevs)
678 		return;
679 
680 	/*
681 	 * Need to expand the array.
682 	 */
683 	old = cd->cd_ndevs;
684 	if (old == 0)
685 		new = MINALLOCSIZE / sizeof(void *);
686 	else
687 		new = old * 2;
688 	while (new <= n)
689 		new *= 2;
690 	cd->cd_ndevs = new;
691 	nsp = malloc(new * sizeof(void *), M_DEVBUF,
692 	    cold ? M_NOWAIT : M_WAITOK);
693 	if (nsp == NULL)
694 		panic("config_attach: %sing dev array",
695 		    old != 0 ? "expand" : "creat");
696 	memset(nsp + old, 0, (new - old) * sizeof(void *));
697 	if (old != 0) {
698 		memcpy(nsp, cd->cd_devs, old * sizeof(void *));
699 		free(cd->cd_devs, M_DEVBUF);
700 	}
701 	cd->cd_devs = nsp;
702 }
703 
704 /*
705  * Attach a found device.  Allocates memory for device variables.
706  */
707 struct device *
708 config_attach(struct device *parent, struct cfdata *cf, void *aux,
709 	cfprint_t print)
710 {
711 	struct device *dev;
712 	struct cftable *ct;
713 	struct cfdriver *cd;
714 	struct cfattach *ca;
715 	size_t lname, lunit;
716 	const char *xunit;
717 	int myunit;
718 	char num[10];
719 
720 	cd = config_cfdriver_lookup(cf->cf_name);
721 	KASSERT(cd != NULL);
722 
723 	ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
724 	KASSERT(ca != NULL);
725 
726 	if (ca->ca_devsize < sizeof(struct device))
727 		panic("config_attach");
728 
729 #ifndef __BROKEN_CONFIG_UNIT_USAGE
730 	if (cf->cf_fstate == FSTATE_STAR) {
731 		for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
732 			if (cd->cd_devs[myunit] == NULL)
733 				break;
734 		/*
735 		 * myunit is now the unit of the first NULL device pointer,
736 		 * or max(cd->cd_ndevs,cf->cf_unit).
737 		 */
738 	} else {
739 		myunit = cf->cf_unit;
740 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
741 		cf->cf_fstate = FSTATE_FOUND;
742 	}
743 #else
744 	myunit = cf->cf_unit;
745 	if (cf->cf_fstate == FSTATE_STAR)
746 		cf->cf_unit++;
747 	else {
748 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
749 		cf->cf_fstate = FSTATE_FOUND;
750 	}
751 #endif /* ! __BROKEN_CONFIG_UNIT_USAGE */
752 
753 	/* compute length of name and decimal expansion of unit number */
754 	lname = strlen(cd->cd_name);
755 	xunit = number(&num[sizeof(num)], myunit);
756 	lunit = &num[sizeof(num)] - xunit;
757 	if (lname + lunit > sizeof(dev->dv_xname))
758 		panic("config_attach: device name too long");
759 
760 	/* get memory for all device vars */
761 	dev = (struct device *)malloc(ca->ca_devsize, M_DEVBUF,
762 	    cold ? M_NOWAIT : M_WAITOK);
763 	if (!dev)
764 	    panic("config_attach: memory allocation for device softc failed");
765 	memset(dev, 0, ca->ca_devsize);
766 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
767 	dev->dv_class = cd->cd_class;
768 	dev->dv_cfdata = cf;
769 	dev->dv_cfdriver = cd;
770 	dev->dv_cfattach = ca;
771 	dev->dv_unit = myunit;
772 	memcpy(dev->dv_xname, cd->cd_name, lname);
773 	memcpy(dev->dv_xname + lname, xunit, lunit);
774 	dev->dv_parent = parent;
775 	dev->dv_flags = DVF_ACTIVE;	/* always initially active */
776 
777 	if (config_do_twiddle)
778 		twiddle();
779 	else
780 		aprint_naive("Found ");
781 	/*
782 	 * We want the next two printfs for normal, verbose, and quiet,
783 	 * but not silent (in which case, we're twiddling, instead).
784 	 */
785 	if (parent == ROOT) {
786 		aprint_naive("%s (root)", dev->dv_xname);
787 		aprint_normal("%s (root)", dev->dv_xname);
788 	} else {
789 		aprint_naive("%s at %s", dev->dv_xname, parent->dv_xname);
790 		aprint_normal("%s at %s", dev->dv_xname, parent->dv_xname);
791 		if (print)
792 			(void) (*print)(aux, NULL);
793 	}
794 
795 	/* put this device in the devices array */
796 	config_makeroom(dev->dv_unit, cd);
797 	if (cd->cd_devs[dev->dv_unit])
798 		panic("config_attach: duplicate %s", dev->dv_xname);
799 	cd->cd_devs[dev->dv_unit] = dev;
800 
801 	/*
802 	 * Before attaching, clobber any unfound devices that are
803 	 * otherwise identical.
804 	 */
805 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
806 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
807 			if (STREQ(cf->cf_name, cd->cd_name) &&
808 			    cf->cf_unit == dev->dv_unit) {
809 				if (cf->cf_fstate == FSTATE_NOTFOUND)
810 					cf->cf_fstate = FSTATE_FOUND;
811 #ifdef __BROKEN_CONFIG_UNIT_USAGE
812 				/*
813 				 * Bump the unit number on all starred cfdata
814 				 * entries for this device.
815 				 */
816 				if (cf->cf_fstate == FSTATE_STAR)
817 					cf->cf_unit++;
818 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
819 			}
820 		}
821 	}
822 #ifdef __HAVE_DEVICE_REGISTER
823 	device_register(dev, aux);
824 #endif
825 	(*ca->ca_attach)(parent, dev, aux);
826 	config_process_deferred(&deferred_config_queue, dev);
827 	return (dev);
828 }
829 
830 /*
831  * As above, but for pseudo-devices.  Pseudo-devices attached in this
832  * way are silently inserted into the device tree, and their children
833  * attached.
834  *
835  * Note that because pseudo-devices are attached silently, any information
836  * the attach routine wishes to print should be prefixed with the device
837  * name by the attach routine.
838  */
839 struct device *
840 config_attach_pseudo(const char *name, int unit)
841 {
842 	struct device *dev;
843 	struct cfdriver *cd;
844 	struct cfattach *ca;
845 	size_t lname, lunit;
846 	const char *xunit;
847 	int myunit;
848 	char num[10];
849 
850 	cd = config_cfdriver_lookup(name);
851 	if (cd == NULL)
852 		return (NULL);
853 
854 	ca = config_cfattach_lookup_cd(cd, name);
855 	if (ca == NULL)
856 		return (NULL);
857 
858 	if (ca->ca_devsize < sizeof(struct device))
859 		panic("config_attach_pseudo");
860 
861 	if (unit == DVUNIT_ANY) {
862 		for (myunit = 0; myunit < cd->cd_ndevs; myunit++)
863 			if (cd->cd_devs[myunit] == NULL)
864 				break;
865 		/*
866 		 * myunit is now the unit of the first NULL device pointer.
867 		 */
868 	} else {
869 		myunit = unit;
870 		if (myunit < cd->cd_ndevs && cd->cd_devs[myunit] != NULL)
871 			return (NULL);
872 	}
873 
874 	/* compute length of name and decimal expansion of unit number */
875 	lname = strlen(cd->cd_name);
876 	xunit = number(&num[sizeof(num)], myunit);
877 	lunit = &num[sizeof(num)] - xunit;
878 	if (lname + lunit > sizeof(dev->dv_xname))
879 		panic("config_attach_pseudo: device name too long");
880 
881 	/* get memory for all device vars */
882 	dev = (struct device *)malloc(ca->ca_devsize, M_DEVBUF,
883 	    cold ? M_NOWAIT : M_WAITOK);
884 	if (!dev)
885 		panic("config_attach_pseudo: memory allocation for device "
886 		    "softc failed");
887 	memset(dev, 0, ca->ca_devsize);
888 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
889 	dev->dv_class = cd->cd_class;
890 	dev->dv_cfdata = NULL;
891 	dev->dv_cfdriver = cd;
892 	dev->dv_cfattach = ca;
893 	dev->dv_unit = myunit;
894 	memcpy(dev->dv_xname, cd->cd_name, lname);
895 	memcpy(dev->dv_xname + lname, xunit, lunit);
896 	dev->dv_parent = ROOT;
897 	dev->dv_flags = DVF_ACTIVE;	/* always initially active */
898 
899 	/* put this device in the devices array */
900 	config_makeroom(dev->dv_unit, cd);
901 	if (cd->cd_devs[dev->dv_unit])
902 		panic("config_attach_pseudo: duplicate %s", dev->dv_xname);
903 	cd->cd_devs[dev->dv_unit] = dev;
904 
905 #if 0	/* XXXJRT not yet */
906 #ifdef __HAVE_DEVICE_REGISTER
907 	device_register(dev, NULL);	/* like a root node */
908 #endif
909 #endif
910 	(*ca->ca_attach)(ROOT, dev, NULL);
911 	config_process_deferred(&deferred_config_queue, dev);
912 	return (dev);
913 }
914 
915 /*
916  * Detach a device.  Optionally forced (e.g. because of hardware
917  * removal) and quiet.  Returns zero if successful, non-zero
918  * (an error code) otherwise.
919  *
920  * Note that this code wants to be run from a process context, so
921  * that the detach can sleep to allow processes which have a device
922  * open to run and unwind their stacks.
923  */
924 int
925 config_detach(struct device *dev, int flags)
926 {
927 	struct cftable *ct;
928 	struct cfdata *cf;
929 	const struct cfattach *ca;
930 	struct cfdriver *cd;
931 #ifdef DIAGNOSTIC
932 	struct device *d;
933 #endif
934 	int rv = 0, i;
935 
936 #ifdef DIAGNOSTIC
937 	if (dev->dv_cfdata != NULL &&
938 	    dev->dv_cfdata->cf_fstate != FSTATE_FOUND &&
939 	    dev->dv_cfdata->cf_fstate != FSTATE_STAR)
940 		panic("config_detach: bad device fstate");
941 #endif
942 	cd = dev->dv_cfdriver;
943 	KASSERT(cd != NULL);
944 
945 	ca = dev->dv_cfattach;
946 	KASSERT(ca != NULL);
947 
948 	/*
949 	 * Ensure the device is deactivated.  If the device doesn't
950 	 * have an activation entry point, we allow DVF_ACTIVE to
951 	 * remain set.  Otherwise, if DVF_ACTIVE is still set, the
952 	 * device is busy, and the detach fails.
953 	 */
954 	if (ca->ca_activate != NULL)
955 		rv = config_deactivate(dev);
956 
957 	/*
958 	 * Try to detach the device.  If that's not possible, then
959 	 * we either panic() (for the forced but failed case), or
960 	 * return an error.
961 	 */
962 	if (rv == 0) {
963 		if (ca->ca_detach != NULL)
964 			rv = (*ca->ca_detach)(dev, flags);
965 		else
966 			rv = EOPNOTSUPP;
967 	}
968 	if (rv != 0) {
969 		if ((flags & DETACH_FORCE) == 0)
970 			return (rv);
971 		else
972 			panic("config_detach: forced detach of %s failed (%d)",
973 			    dev->dv_xname, rv);
974 	}
975 
976 	/*
977 	 * The device has now been successfully detached.
978 	 */
979 
980 #ifdef DIAGNOSTIC
981 	/*
982 	 * Sanity: If you're successfully detached, you should have no
983 	 * children.  (Note that because children must be attached
984 	 * after parents, we only need to search the latter part of
985 	 * the list.)
986 	 */
987 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
988 	    d = TAILQ_NEXT(d, dv_list)) {
989 		if (d->dv_parent == dev) {
990 			printf("config_detach: detached device %s"
991 			    " has children %s\n", dev->dv_xname, d->dv_xname);
992 			panic("config_detach");
993 		}
994 	}
995 #endif
996 
997 	/*
998 	 * Mark cfdata to show that the unit can be reused, if possible.
999 	 */
1000 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
1001 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1002 			if (STREQ(cf->cf_name, cd->cd_name)) {
1003 				if (cf->cf_fstate == FSTATE_FOUND &&
1004 				    cf->cf_unit == dev->dv_unit)
1005 					cf->cf_fstate = FSTATE_NOTFOUND;
1006 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1007 				/*
1008 				 * Note that we can only re-use a starred
1009 				 * unit number if the unit being detached
1010 				 * had the last assigned unit number.
1011 				 */
1012 				if (cf->cf_fstate == FSTATE_STAR &&
1013 				    cf->cf_unit == dev->dv_unit + 1)
1014 					cf->cf_unit--;
1015 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
1016 			}
1017 		}
1018 	}
1019 
1020 	/*
1021 	 * Unlink from device list.
1022 	 */
1023 	TAILQ_REMOVE(&alldevs, dev, dv_list);
1024 
1025 	/*
1026 	 * Remove from cfdriver's array, tell the world (unless it was
1027 	 * a pseudo-device), and free softc.
1028 	 */
1029 	cd->cd_devs[dev->dv_unit] = NULL;
1030 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
1031 		aprint_normal("%s detached\n", dev->dv_xname);
1032 	free(dev, M_DEVBUF);
1033 
1034 	/*
1035 	 * If the device now has no units in use, deallocate its softc array.
1036 	 */
1037 	for (i = 0; i < cd->cd_ndevs; i++)
1038 		if (cd->cd_devs[i] != NULL)
1039 			break;
1040 	if (i == cd->cd_ndevs) {		/* nothing found; deallocate */
1041 		free(cd->cd_devs, M_DEVBUF);
1042 		cd->cd_devs = NULL;
1043 		cd->cd_ndevs = 0;
1044 	}
1045 
1046 	/*
1047 	 * Return success.
1048 	 */
1049 	return (0);
1050 }
1051 
1052 int
1053 config_activate(struct device *dev)
1054 {
1055 	const struct cfattach *ca = dev->dv_cfattach;
1056 	int rv = 0, oflags = dev->dv_flags;
1057 
1058 	if (ca->ca_activate == NULL)
1059 		return (EOPNOTSUPP);
1060 
1061 	if ((dev->dv_flags & DVF_ACTIVE) == 0) {
1062 		dev->dv_flags |= DVF_ACTIVE;
1063 		rv = (*ca->ca_activate)(dev, DVACT_ACTIVATE);
1064 		if (rv)
1065 			dev->dv_flags = oflags;
1066 	}
1067 	return (rv);
1068 }
1069 
1070 int
1071 config_deactivate(struct device *dev)
1072 {
1073 	const struct cfattach *ca = dev->dv_cfattach;
1074 	int rv = 0, oflags = dev->dv_flags;
1075 
1076 	if (ca->ca_activate == NULL)
1077 		return (EOPNOTSUPP);
1078 
1079 	if (dev->dv_flags & DVF_ACTIVE) {
1080 		dev->dv_flags &= ~DVF_ACTIVE;
1081 		rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
1082 		if (rv)
1083 			dev->dv_flags = oflags;
1084 	}
1085 	return (rv);
1086 }
1087 
1088 /*
1089  * Defer the configuration of the specified device until all
1090  * of its parent's devices have been attached.
1091  */
1092 void
1093 config_defer(struct device *dev, void (*func)(struct device *))
1094 {
1095 	struct deferred_config *dc;
1096 
1097 	if (dev->dv_parent == NULL)
1098 		panic("config_defer: can't defer config of a root device");
1099 
1100 #ifdef DIAGNOSTIC
1101 	for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
1102 	     dc = TAILQ_NEXT(dc, dc_queue)) {
1103 		if (dc->dc_dev == dev)
1104 			panic("config_defer: deferred twice");
1105 	}
1106 #endif
1107 
1108 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
1109 	if (dc == NULL)
1110 		panic("config_defer: unable to allocate callback");
1111 
1112 	dc->dc_dev = dev;
1113 	dc->dc_func = func;
1114 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
1115 	config_pending_incr();
1116 }
1117 
1118 /*
1119  * Defer some autoconfiguration for a device until after interrupts
1120  * are enabled.
1121  */
1122 void
1123 config_interrupts(struct device *dev, void (*func)(struct device *))
1124 {
1125 	struct deferred_config *dc;
1126 
1127 	/*
1128 	 * If interrupts are enabled, callback now.
1129 	 */
1130 	if (cold == 0) {
1131 		(*func)(dev);
1132 		return;
1133 	}
1134 
1135 #ifdef DIAGNOSTIC
1136 	for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
1137 	     dc = TAILQ_NEXT(dc, dc_queue)) {
1138 		if (dc->dc_dev == dev)
1139 			panic("config_interrupts: deferred twice");
1140 	}
1141 #endif
1142 
1143 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
1144 	if (dc == NULL)
1145 		panic("config_interrupts: unable to allocate callback");
1146 
1147 	dc->dc_dev = dev;
1148 	dc->dc_func = func;
1149 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
1150 	config_pending_incr();
1151 }
1152 
1153 /*
1154  * Process a deferred configuration queue.
1155  */
1156 static void
1157 config_process_deferred(struct deferred_config_head *queue,
1158     struct device *parent)
1159 {
1160 	struct deferred_config *dc, *ndc;
1161 
1162 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
1163 		ndc = TAILQ_NEXT(dc, dc_queue);
1164 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
1165 			TAILQ_REMOVE(queue, dc, dc_queue);
1166 			(*dc->dc_func)(dc->dc_dev);
1167 			free(dc, M_DEVBUF);
1168 			config_pending_decr();
1169 		}
1170 	}
1171 }
1172 
1173 /*
1174  * Manipulate the config_pending semaphore.
1175  */
1176 void
1177 config_pending_incr(void)
1178 {
1179 
1180 	config_pending++;
1181 }
1182 
1183 void
1184 config_pending_decr(void)
1185 {
1186 
1187 #ifdef DIAGNOSTIC
1188 	if (config_pending == 0)
1189 		panic("config_pending_decr: config_pending == 0");
1190 #endif
1191 	config_pending--;
1192 	if (config_pending == 0)
1193 		wakeup((void *)&config_pending);
1194 }
1195 
1196 /*
1197  * Register a "finalization" routine.  Finalization routines are
1198  * called iteratively once all real devices have been found during
1199  * autoconfiguration, for as long as any one finalizer has done
1200  * any work.
1201  */
1202 int
1203 config_finalize_register(struct device *dev, int (*fn)(struct device *))
1204 {
1205 	struct finalize_hook *f;
1206 
1207 	/*
1208 	 * If finalization has already been done, invoke the
1209 	 * callback function now.
1210 	 */
1211 	if (config_finalize_done) {
1212 		while ((*fn)(dev) != 0)
1213 			/* loop */ ;
1214 	}
1215 
1216 	/* Ensure this isn't already on the list. */
1217 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
1218 		if (f->f_func == fn && f->f_dev == dev)
1219 			return (EEXIST);
1220 	}
1221 
1222 	f = malloc(sizeof(*f), M_TEMP, M_WAITOK);
1223 	f->f_func = fn;
1224 	f->f_dev = dev;
1225 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
1226 
1227 	return (0);
1228 }
1229 
1230 void
1231 config_finalize(void)
1232 {
1233 	struct finalize_hook *f;
1234 	int rv;
1235 
1236 	/* Run the hooks until none of them does any work. */
1237 	do {
1238 		rv = 0;
1239 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
1240 			rv |= (*f->f_func)(f->f_dev);
1241 	} while (rv != 0);
1242 
1243 	config_finalize_done = 1;
1244 
1245 	/* Now free all the hooks. */
1246 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
1247 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
1248 		free(f, M_TEMP);
1249 	}
1250 }
1251 
1252