Home | History | Annotate | Line # | Download | only in config
main.c revision 1.45
      1 /*	$NetBSD: main.c,v 1.45 2012/03/11 08:21:53 dholland Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This software was developed by the Computer Systems Engineering group
      8  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
      9  * contributed to Berkeley.
     10  *
     11  * All advertising materials mentioning features or use of this software
     12  * must display the following acknowledgement:
     13  *	This product includes software developed by the University of
     14  *	California, Lawrence Berkeley Laboratories.
     15  *
     16  * Redistribution and use in source and binary forms, with or without
     17  * modification, are permitted provided that the following conditions
     18  * are met:
     19  * 1. Redistributions of source code must retain the above copyright
     20  *    notice, this list of conditions and the following disclaimer.
     21  * 2. Redistributions in binary form must reproduce the above copyright
     22  *    notice, this list of conditions and the following disclaimer in the
     23  *    documentation and/or other materials provided with the distribution.
     24  * 3. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  *	from: @(#)main.c	8.1 (Berkeley) 6/6/93
     41  */
     42 
     43 #if HAVE_NBTOOL_CONFIG_H
     44 #include "nbtool_config.h"
     45 #endif
     46 
     47 #ifndef MAKE_BOOTSTRAP
     48 #include <sys/cdefs.h>
     49 #define	COPYRIGHT(x)	__COPYRIGHT(x)
     50 #else
     51 #define	COPYRIGHT(x)	static const char copyright[] = x
     52 #endif
     53 
     54 #ifndef lint
     55 COPYRIGHT("@(#) Copyright (c) 1992, 1993\
     56  The Regents of the University of California.  All rights reserved.");
     57 #endif /* not lint */
     58 
     59 #include <sys/types.h>
     60 #include <sys/stat.h>
     61 #include <sys/param.h>
     62 #include <sys/mman.h>
     63 #include <paths.h>
     64 #include <ctype.h>
     65 #include <err.h>
     66 #include <errno.h>
     67 #include <fcntl.h>
     68 #include <limits.h>
     69 #include <stdio.h>
     70 #include <stdlib.h>
     71 #include <string.h>
     72 #include <unistd.h>
     73 #include <vis.h>
     74 #include <util.h>
     75 
     76 #include "defs.h"
     77 #include "sem.h"
     78 
     79 #ifndef LINE_MAX
     80 #define LINE_MAX 1024
     81 #endif
     82 
     83 int	vflag;				/* verbose output */
     84 int	Pflag;				/* pack locators */
     85 int	Lflag;				/* lint config generation */
     86 
     87 int	yyparse(void);
     88 
     89 #ifndef MAKE_BOOTSTRAP
     90 extern int yydebug;
     91 #endif
     92 
     93 static struct hashtab *obsopttab;
     94 static struct hashtab *mkopttab;
     95 static struct nvlist **nextopt;
     96 static struct nvlist **nextmkopt;
     97 static struct nvlist **nextappmkopt;
     98 static struct nvlist **nextcndmkopt;
     99 static struct nvlist **nextfsopt;
    100 
    101 static	void	usage(void) __dead;
    102 static	void	dependopts(void);
    103 static	void	do_depend(struct nvlist *);
    104 static	void	stop(void);
    105 static	int	do_option(struct hashtab *, struct nvlist ***,
    106 		    const char *, const char *, const char *);
    107 static	int	undo_option(struct hashtab *, struct nvlist **,
    108 		    struct nvlist ***, const char *, const char *);
    109 static	int	crosscheck(void);
    110 static	int	badstar(void);
    111 	int	main(int, char **);
    112 static	int	mksymlinks(void);
    113 static	int	mkident(void);
    114 static	int	devbase_has_dead_instances(const char *, void *, void *);
    115 static	int	devbase_has_any_instance(struct devbase *, int, int, int);
    116 static	int	check_dead_devi(const char *, void *, void *);
    117 static	void	kill_orphans(void);
    118 static	void	do_kill_orphans(struct devbase *, struct attr *,
    119     struct devbase *, int);
    120 static	int	kill_orphans_cb(const char *, void *, void *);
    121 static	int	cfcrosscheck(struct config *, const char *, struct nvlist *);
    122 void	defopt(struct hashtab *ht, const char *fname,
    123 	     struct nvlist *opts, struct nvlist *deps, int obs);
    124 
    125 #define LOGCONFIG_LARGE "INCLUDE_CONFIG_FILE"
    126 #define LOGCONFIG_SMALL "INCLUDE_JUST_CONFIG"
    127 
    128 static	void	logconfig_start(void);
    129 static	void	logconfig_end(void);
    130 static	FILE	*cfg;
    131 static	time_t	cfgtime;
    132 
    133 static	int	is_elf(const char *);
    134 static	int	extract_config(const char *, const char *, int);
    135 
    136 int badfilename(const char *fname);
    137 
    138 const char *progname;
    139 
    140 int
    141 main(int argc, char **argv)
    142 {
    143 	char *p, cname[PATH_MAX];
    144 	const char *last_component;
    145 	int pflag, xflag, ch, removeit;
    146 
    147 	setprogname(argv[0]);
    148 
    149 	pflag = 0;
    150 	xflag = 0;
    151 	while ((ch = getopt(argc, argv, "DLPgpvb:s:x")) != -1) {
    152 		switch (ch) {
    153 
    154 #ifndef MAKE_BOOTSTRAP
    155 		case 'D':
    156 			yydebug = 1;
    157 			break;
    158 #endif
    159 
    160 		case 'L':
    161 			Lflag = 1;
    162 			break;
    163 
    164 		case 'P':
    165 			Pflag = 1;
    166 			break;
    167 
    168 		case 'g':
    169 			/*
    170 			 * In addition to DEBUG, you probably wanted to
    171 			 * set "options KGDB" and maybe others.  We could
    172 			 * do that for you, but you really should just
    173 			 * put them in the config file.
    174 			 */
    175 			warnx("-g is obsolete (use makeoptions DEBUG=\"-g\")");
    176 			usage();
    177 			/*NOTREACHED*/
    178 
    179 		case 'p':
    180 			/*
    181 			 * Essentially the same as makeoptions PROF="-pg",
    182 			 * but also changes the path from ../../compile/FOO
    183 			 * to ../../compile/FOO.PROF; i.e., compile a
    184 			 * profiling kernel based on a typical "regular"
    185 			 * kernel.
    186 			 *
    187 			 * Note that if you always want profiling, you
    188 			 * can (and should) use a "makeoptions" line.
    189 			 */
    190 			pflag = 1;
    191 			break;
    192 
    193 		case 'v':
    194 			vflag = 1;
    195 			break;
    196 
    197 		case 'b':
    198 			builddir = optarg;
    199 			break;
    200 
    201 		case 's':
    202 			srcdir = optarg;
    203 			break;
    204 
    205 		case 'x':
    206 			xflag = 1;
    207 			break;
    208 
    209 		case '?':
    210 		default:
    211 			usage();
    212 		}
    213 	}
    214 
    215 	if (xflag && optind != 2) {
    216 		errx(EXIT_FAILURE, "-x must be used alone");
    217 	}
    218 
    219 	argc -= optind;
    220 	argv += optind;
    221 	if (argc > 1) {
    222 		usage();
    223 	}
    224 
    225 	if (Lflag && (builddir != NULL || Pflag || pflag))
    226 		errx(EXIT_FAILURE, "-L can only be used with -s and -v");
    227 
    228 	if (xflag) {
    229 #ifdef __NetBSD__
    230 		conffile = (argc == 1) ? argv[0] : _PATH_UNIX;
    231 #else
    232 		if (argc == 0)
    233 			errx(EXIT_FAILURE, "no kernel supplied");
    234 #endif
    235 		if (!is_elf(conffile))
    236 			errx(EXIT_FAILURE, "%s: not a binary kernel",
    237 			    conffile);
    238 		if (!extract_config(conffile, "stdout", STDOUT_FILENO))
    239 			errx(EXIT_FAILURE, "%s does not contain embedded "
    240 			    "configuration data", conffile);
    241 		exit(0);
    242 	}
    243 
    244 	conffile = (argc == 1) ? argv[0] : "CONFIG";
    245 	if (firstfile(conffile)) {
    246 		err(EXIT_FAILURE, "Cannot read `%s'", conffile);
    247 		exit(2);
    248 	}
    249 
    250 	/*
    251 	 * Init variables.
    252 	 */
    253 	minmaxusers = 1;
    254 	maxmaxusers = 10000;
    255 	initintern();
    256 	initfiles();
    257 	initsem();
    258 	ident = NULL;
    259 	devbasetab = ht_new();
    260 	devroottab = ht_new();
    261 	devatab = ht_new();
    262 	devitab = ht_new();
    263 	deaddevitab = ht_new();
    264 	selecttab = ht_new();
    265 	needcnttab = ht_new();
    266 	opttab = ht_new();
    267 	mkopttab = ht_new();
    268 	fsopttab = ht_new();
    269 	deffstab = ht_new();
    270 	defopttab = ht_new();
    271 	defparamtab = ht_new();
    272 	defoptlint = ht_new();
    273 	defflagtab = ht_new();
    274 	optfiletab = ht_new();
    275 	obsopttab = ht_new();
    276 	bdevmtab = ht_new();
    277 	maxbdevm = 0;
    278 	cdevmtab = ht_new();
    279 	maxcdevm = 0;
    280 	nextopt = &options;
    281 	nextmkopt = &mkoptions;
    282 	nextappmkopt = &appmkoptions;
    283 	nextcndmkopt = &condmkoptions;
    284 	nextfsopt = &fsoptions;
    285 
    286 	/*
    287 	 * Handle profiling (must do this before we try to create any
    288 	 * files).
    289 	 */
    290 	last_component = strrchr(conffile, '/');
    291 	last_component = (last_component) ? last_component + 1 : conffile;
    292 	if (pflag) {
    293 		p = emalloc(strlen(last_component) + 17);
    294 		(void)sprintf(p, "../compile/%s.PROF", last_component);
    295 		(void)addmkoption(intern("PROF"), "-pg");
    296 		(void)addoption(intern("GPROF"), NULL);
    297 	} else {
    298 		p = emalloc(strlen(last_component) + 13);
    299 		(void)sprintf(p, "../compile/%s", last_component);
    300 	}
    301 	defbuilddir = (argc == 0) ? "." : p;
    302 
    303 	if (Lflag) {
    304 		char resolvedname[MAXPATHLEN];
    305 
    306 		if (realpath(conffile, resolvedname) == NULL)
    307 			err(EXIT_FAILURE, "realpath(%s)", conffile);
    308 
    309 		if (yyparse())
    310 			stop();
    311 
    312 		printf("include \"%s\"\n", resolvedname);
    313 
    314 		emit_params();
    315 		emit_options();
    316 		emit_instances();
    317 
    318 		exit(EXIT_SUCCESS);
    319 	}
    320 
    321 	removeit = 0;
    322 	if (is_elf(conffile)) {
    323 		const char *tmpdir;
    324 		int cfd;
    325 
    326 		if (builddir == NULL)
    327 			errx(EXIT_FAILURE, "Build directory must be specified "
    328 			    "with binary kernels");
    329 
    330 		/* Open temporary configuration file */
    331 		tmpdir = getenv("TMPDIR");
    332 		if (tmpdir == NULL)
    333 			tmpdir = _PATH_TMP;
    334 		snprintf(cname, sizeof(cname), "%s/config.tmp.XXXXXX", tmpdir);
    335 		cfd = mkstemp(cname);
    336 		if (cfd == -1)
    337 			err(EXIT_FAILURE, "Cannot create `%s'", cname);
    338 
    339 		printf("Using configuration data embedded in kernel...\n");
    340 		if (!extract_config(conffile, cname, cfd)) {
    341 			unlink(cname);
    342 			errx(EXIT_FAILURE, "%s does not contain embedded "
    343 			    "configuration data", conffile);
    344 		}
    345 
    346 		removeit = 1;
    347 		close(cfd);
    348 		firstfile(cname);
    349 	}
    350 
    351 	 /*
    352 	  * Log config file.  We don't know until yyparse() if we're
    353 	  * going to need config_file.h (i.e. if we're doing ioconf-only
    354 	  * or not).  Just start creating the file, and when we know
    355 	  * later, we'll just keep or discard our work here.
    356 	  */
    357 	logconfig_start();
    358 
    359 	/*
    360 	 * Parse config file (including machine definitions).
    361 	 */
    362 	if (yyparse())
    363 		stop();
    364 
    365 	if (ioconfname && cfg)
    366 		fclose(cfg);
    367 	else
    368 		logconfig_end();
    369 
    370 	if (removeit)
    371 		unlink(cname);
    372 
    373 	/*
    374 	 * Detect and properly ignore orphaned devices
    375 	 */
    376 	kill_orphans();
    377 
    378 	/*
    379 	 * Select devices and pseudo devices and their attributes
    380 	 */
    381 	if (fixdevis())
    382 		stop();
    383 
    384 	/*
    385 	 * If working on an ioconf-only config, process here and exit
    386 	 */
    387 	if (ioconfname) {
    388 		pack();
    389 		mkioconf();
    390 		emitlocs();
    391 		emitioconfh();
    392 		return 0;
    393 	}
    394 
    395 	/*
    396 	 * Deal with option dependencies.
    397 	 */
    398 	dependopts();
    399 
    400 	/*
    401 	 * Fix (as in `set firmly in place') files.
    402 	 */
    403 	if (fixfiles())
    404 		stop();
    405 
    406 	/*
    407 	 * Fix objects and libraries.
    408 	 */
    409 	if (fixobjects())
    410 		stop();
    411 
    412 	/*
    413 	 * Fix device-majors.
    414 	 */
    415 	if (fixdevsw())
    416 		stop();
    417 
    418 	/*
    419 	 * Perform cross-checking.
    420 	 */
    421 	if (maxusers == 0) {
    422 		if (defmaxusers) {
    423 			(void)printf("maxusers not specified; %d assumed\n",
    424 			    defmaxusers);
    425 			maxusers = defmaxusers;
    426 		} else {
    427 			warnx("need \"maxusers\" line");
    428 			errors++;
    429 		}
    430 	}
    431 	if (crosscheck() || errors)
    432 		stop();
    433 
    434 	/*
    435 	 * Squeeze things down and finish cross-checks (STAR checks must
    436 	 * run after packing).
    437 	 */
    438 	pack();
    439 	if (badstar())
    440 		stop();
    441 
    442 	/*
    443 	 * Ready to go.  Build all the various files.
    444 	 */
    445 	if (mksymlinks() || mkmakefile() || mkheaders() || mkswap() ||
    446 	    mkioconf() || (do_devsw ? mkdevsw() : 0) || mkident() || errors)
    447 		stop();
    448 	(void)printf("Build directory is %s\n", builddir);
    449 	(void)printf("Don't forget to run \"make depend\"\n");
    450 	return 0;
    451 }
    452 
    453 static void
    454 usage(void)
    455 {
    456 	(void)fprintf(stderr, "Usage: %s [-Ppv] [-s srcdir] [-b builddir] "
    457 	    "[config-file]\n\t%s -x [kernel-file]\n"
    458 	    "\t%s -L [-v] [-s srcdir] [config-file]\n",
    459 	    getprogname(), getprogname(), getprogname());
    460 	exit(1);
    461 }
    462 
    463 /*
    464  * Set any options that are implied by other options.
    465  */
    466 static void
    467 dependopts(void)
    468 {
    469 	struct nvlist *nv, *opt;
    470 
    471 	for (nv = options; nv != NULL; nv = nv->nv_next) {
    472 		if ((opt = find_declared_option(nv->nv_name)) != NULL) {
    473 			for (opt = opt->nv_ptr; opt != NULL;
    474 			    opt = opt->nv_next) {
    475 				do_depend(opt);
    476 			}
    477 		}
    478 	}
    479 
    480 	for (nv = fsoptions; nv != NULL; nv = nv->nv_next) {
    481 		if ((opt = find_declared_option(nv->nv_name)) != NULL) {
    482 			for (opt = opt->nv_ptr; opt != NULL;
    483 			    opt = opt->nv_next) {
    484 				do_depend(opt);
    485 			}
    486 		}
    487 	}
    488 }
    489 
    490 static void
    491 do_depend(struct nvlist *nv)
    492 {
    493 	struct nvlist *nextnv;
    494 	struct attr *a;
    495 
    496 	if (nv != NULL && (nv->nv_flags & NV_DEPENDED) == 0) {
    497 		nv->nv_flags |= NV_DEPENDED;
    498 		/*
    499 		 * If the dependency is an attribute, then just add
    500 		 * it to the selecttab.
    501 		 */
    502 		if ((a = ht_lookup(attrtab, nv->nv_name)) != NULL) {
    503 			if (a->a_iattr)
    504 				panic("do_depend(%s): dep `%s' is an iattr",
    505 				    nv->nv_name, a->a_name);
    506 			expandattr(a, selectattr);
    507 		} else {
    508 			if (ht_lookup(opttab, nv->nv_name) == NULL)
    509 				addoption(nv->nv_name, NULL);
    510 			if ((nextnv =
    511 			     find_declared_option(nv->nv_name)) != NULL)
    512 				do_depend(nextnv->nv_ptr);
    513 		}
    514 	}
    515 }
    516 
    517 static int
    518 recreate(const char *p, const char *q)
    519 {
    520 	int ret;
    521 
    522 	if ((ret = unlink(q)) == -1 && errno != ENOENT)
    523 		warn("unlink(%s)\n", q);
    524 	if ((ret = symlink(p, q)) == -1)
    525 		warn("symlink(%s -> %s)", q, p);
    526 	return ret;
    527 }
    528 
    529 /*
    530  * Make a symlink for "machine" so that "#include <machine/foo.h>" works,
    531  * and for the machine's CPU architecture, so that works as well.
    532  */
    533 static int
    534 mksymlinks(void)
    535 {
    536 	int ret;
    537 	char *p, buf[MAXPATHLEN];
    538 	const char *q;
    539 	struct nvlist *nv;
    540 
    541 	snprintf(buf, sizeof(buf), "arch/%s/include", machine);
    542 	p = sourcepath(buf);
    543 	ret = recreate(p, "machine");
    544 	ret = recreate(p, machine);
    545 	free(p);
    546 
    547 	if (machinearch != NULL) {
    548 		snprintf(buf, sizeof(buf), "arch/%s/include", machinearch);
    549 		p = sourcepath(buf);
    550 		q = machinearch;
    551 	} else {
    552 		p = estrdup("machine");
    553 		q = machine;
    554 	}
    555 
    556 	ret = recreate(p, q);
    557 	free(p);
    558 
    559 	for (nv = machinesubarches; nv != NULL; nv = nv->nv_next) {
    560 		q = nv->nv_name;
    561 		snprintf(buf, sizeof(buf), "arch/%s/include", q);
    562 		p = sourcepath(buf);
    563 		ret = recreate(p, q);
    564 		free(p);
    565 	}
    566 
    567 	return (ret);
    568 }
    569 
    570 static __dead void
    571 stop(void)
    572 {
    573 	(void)fprintf(stderr, "*** Stop.\n");
    574 	exit(1);
    575 }
    576 
    577 static void
    578 add_dependencies(struct nvlist *nv, struct nvlist *deps)
    579 {
    580 	struct nvlist *dep;
    581 	struct attr *a;
    582 
    583 	/* Use nv_ptr to link any other options that are implied. */
    584 	nv->nv_ptr = deps;
    585 	for (dep = deps; dep != NULL; dep = dep->nv_next) {
    586 		/*
    587 		 * If the dependency is an attribute, it must not
    588 		 * be an interface attribute.  Otherwise, it must
    589 		 * be a previously declared option.
    590 		 */
    591 		if ((a = ht_lookup(attrtab, dep->nv_name)) != NULL) {
    592 			if (a->a_iattr)
    593 				cfgerror("option `%s' dependency `%s' "
    594 				    "is an interface attribute",
    595 				    nv->nv_name, a->a_name);
    596 		} else if (OPT_OBSOLETE(dep->nv_name)) {
    597 			cfgerror("option `%s' dependency `%s' "
    598 			    "is obsolete", nv->nv_name, dep->nv_name);
    599 		} else if (find_declared_option(dep->nv_name) == NULL) {
    600 			cfgerror("option `%s' dependency `%s' "
    601 			    "is an unknown option",
    602 			    nv->nv_name, dep->nv_name);
    603 		}
    604 	}
    605 }
    606 
    607 /*
    608  * Define one or more file systems.
    609  */
    610 void
    611 deffilesystem(struct nvlist *fses, struct nvlist *deps)
    612 {
    613 	struct nvlist *nv;
    614 
    615 	/*
    616 	 * Mark these options as ones to skip when creating the Makefile.
    617 	 */
    618 	for (nv = fses; nv != NULL; nv = nv->nv_next) {
    619 		if (DEFINED_OPTION(nv->nv_name)) {
    620 			cfgerror("file system or option `%s' already defined",
    621 			    nv->nv_name);
    622 			return;
    623 		}
    624 
    625 		/*
    626 		 * Also mark it as a valid file system, which may be
    627 		 * used in "file-system" directives in the config
    628 		 * file.
    629 		 */
    630 		if (ht_insert(deffstab, nv->nv_name, nv))
    631 			panic("file system `%s' already in table?!",
    632 			    nv->nv_name);
    633 
    634 		add_dependencies(nv, deps);
    635 	}
    636 }
    637 
    638 /*
    639  * Sanity check a file name.
    640  */
    641 int
    642 badfilename(const char *fname)
    643 {
    644 	const char *n;
    645 
    646 	/*
    647 	 * We're putting multiple options into one file.  Sanity
    648 	 * check the file name.
    649 	 */
    650 	if (strchr(fname, '/') != NULL) {
    651 		cfgerror("option file name contains a `/'");
    652 		return 1;
    653 	}
    654 	if ((n = strrchr(fname, '.')) == NULL || strcmp(n, ".h") != 0) {
    655 		cfgerror("option file name does not end in `.h'");
    656 		return 1;
    657 	}
    658 	return 0;
    659 }
    660 
    661 
    662 /*
    663  * Search for a defined option (defopt, filesystem, etc), and if found,
    664  * return the option's struct nvlist.
    665  */
    666 struct nvlist *
    667 find_declared_option(const char *name)
    668 {
    669 	struct nvlist *option = NULL;
    670 
    671 	if ((option = ht_lookup(defopttab, name)) != NULL ||
    672 	    (option = ht_lookup(defparamtab, name)) != NULL ||
    673 	    (option = ht_lookup(defflagtab, name)) != NULL ||
    674 	    (option = ht_lookup(deffstab, name)) != NULL) {
    675 		return (option);
    676 	}
    677 
    678 	return (NULL);
    679 }
    680 
    681 
    682 /*
    683  * Define one or more standard options.  If an option file name is specified,
    684  * place all options in one file with the specified name.  Otherwise, create
    685  * an option file for each option.
    686  * record the option information in the specified table.
    687  */
    688 void
    689 defopt(struct hashtab *ht, const char *fname, struct nvlist *opts,
    690        struct nvlist *deps, int obs)
    691 {
    692 	struct nvlist *nv, *nextnv, *oldnv;
    693 	const char *name;
    694 	char buf[500];
    695 
    696 	if (fname != NULL && badfilename(fname)) {
    697 		return;
    698 	}
    699 
    700 	/*
    701 	 * Mark these options as ones to skip when creating the Makefile.
    702 	 */
    703 	for (nv = opts; nv != NULL; nv = nextnv) {
    704 		nextnv = nv->nv_next;
    705 
    706 		if (*(nv->nv_name) == '\0') {
    707 			if (nextnv == NULL)
    708 				panic("invalid option chain");
    709 			/*
    710 			 * If an entry already exists, then we are about to
    711 			 * complain, so no worry.
    712 			 */
    713 			(void) ht_insert(defoptlint, nextnv->nv_name,
    714 			    nv);
    715 			nv = nextnv;
    716 			nextnv = nextnv->nv_next;
    717 		}
    718 
    719 		/* An option name can be declared at most once. */
    720 		if (DEFINED_OPTION(nv->nv_name)) {
    721 			cfgerror("file system or option `%s' already defined",
    722 			    nv->nv_name);
    723 			return;
    724 		}
    725 
    726 		if (ht_insert(ht, nv->nv_name, nv)) {
    727 			cfgerror("file system or option `%s' already defined",
    728 			    nv->nv_name);
    729 			return;
    730 		}
    731 
    732 		if (fname == NULL) {
    733 			/*
    734 			 * Each option will be going into its own file.
    735 			 * Convert the option name to lower case.  This
    736 			 * lower case name will be used as the option
    737 			 * file name.
    738 			 */
    739 			(void) snprintf(buf, sizeof(buf), "opt_%s.h",
    740 			    strtolower(nv->nv_name));
    741 			name = intern(buf);
    742 		} else {
    743 			name = fname;
    744 		}
    745 
    746 		add_dependencies(nv, deps);
    747 
    748 		/*
    749 		 * Remove this option from the parameter list before adding
    750 		 * it to the list associated with this option file.
    751 		 */
    752 		nv->nv_next = NULL;
    753 
    754 		/*
    755 		 * Flag as obsolete, if requested.
    756 		 */
    757 		if (obs) {
    758 			nv->nv_flags |= NV_OBSOLETE;
    759 			(void)ht_insert(obsopttab, nv->nv_name, nv);
    760 		}
    761 
    762 		/*
    763 		 * Add this option file if we haven't seen it yet.
    764 		 * Otherwise, append to the list of options already
    765 		 * associated with this file.
    766 		 */
    767 		if ((oldnv = ht_lookup(optfiletab, name)) == NULL) {
    768 			(void)ht_insert(optfiletab, name, nv);
    769 		} else {
    770 			while (oldnv->nv_next != NULL)
    771 				oldnv = oldnv->nv_next;
    772 			oldnv->nv_next = nv;
    773 		}
    774 	}
    775 }
    776 
    777 /*
    778  * Define one or more standard options.  If an option file name is specified,
    779  * place all options in one file with the specified name.  Otherwise, create
    780  * an option file for each option.
    781  */
    782 void
    783 defoption(const char *fname, struct nvlist *opts, struct nvlist *deps)
    784 {
    785 
    786 	cfgwarn("The use of `defopt' is deprecated");
    787 	defopt(defopttab, fname, opts, deps, 0);
    788 }
    789 
    790 
    791 /*
    792  * Define an option for which a value is required.
    793  */
    794 void
    795 defparam(const char *fname, struct nvlist *opts, struct nvlist *deps, int obs)
    796 {
    797 
    798 	defopt(defparamtab, fname, opts, deps, obs);
    799 }
    800 
    801 /*
    802  * Define an option which must not have a value, and which
    803  * emits a "needs-flag" style output.
    804  */
    805 void
    806 defflag(const char *fname, struct nvlist *opts, struct nvlist *deps, int obs)
    807 {
    808 
    809 	defopt(defflagtab, fname, opts, deps, obs);
    810 }
    811 
    812 
    813 /*
    814  * Add an option from "options FOO".  Note that this selects things that
    815  * are "optional foo".
    816  */
    817 void
    818 addoption(const char *name, const char *value)
    819 {
    820 	const char *n;
    821 	int is_fs, is_param, is_flag, is_undecl, is_obs;
    822 
    823 	/*
    824 	 * Figure out how this option was declared (if at all.)
    825 	 * XXX should use "params" and "flags" in config.
    826 	 * XXX crying out for a type field in a unified hashtab.
    827 	 */
    828 	is_fs = OPT_FSOPT(name);
    829 	is_param = OPT_DEFPARAM(name);
    830 	is_flag =  OPT_DEFFLAG(name);
    831 	is_obs = OPT_OBSOLETE(name);
    832 	is_undecl = !DEFINED_OPTION(name);
    833 
    834 	/* Warn and pretend the user had not selected the option  */
    835 	if (is_obs) {
    836 		cfgwarn("obsolete option `%s' will be ignored", name);
    837 		return;
    838 	}
    839 
    840 	/* Make sure this is not a defined file system. */
    841 	if (is_fs) {
    842 		cfgerror("`%s' is a defined file system", name);
    843 		return;
    844 	}
    845 	/* A defparam must have a value */
    846 	if (is_param && value == NULL) {
    847 		cfgerror("option `%s' must have a value", name);
    848 		return;
    849 	}
    850 	/* A defflag must not have a value */
    851 	if (is_flag && value != NULL) {
    852 		cfgerror("option `%s' must not have a value", name);
    853 		return;
    854 	}
    855 
    856 	if (is_undecl && vflag) {
    857 		cfgwarn("undeclared option `%s' added to IDENT", name);
    858 	}
    859 
    860 	if (do_option(opttab, &nextopt, name, value, "options"))
    861 		return;
    862 
    863 	/* make lowercase, then add to select table */
    864 	n = strtolower(name);
    865 	(void)ht_insert(selecttab, n, (void *)__UNCONST(n));
    866 }
    867 
    868 void
    869 deloption(const char *name)
    870 {
    871 
    872 	if (undo_option(opttab, &options, &nextopt, name, "options"))
    873 		return;
    874 	if (undo_option(selecttab, NULL, NULL, strtolower(name), "options"))
    875 		return;
    876 }
    877 
    878 /*
    879  * Add a file system option.  This routine simply inserts the name into
    880  * a list of valid file systems, which is used to validate the root
    881  * file system type.  The name is then treated like a standard option.
    882  */
    883 void
    884 addfsoption(const char *name)
    885 {
    886 	const char *n;
    887 
    888 	/* Make sure this is a defined file system. */
    889 	if (!OPT_FSOPT(name)) {
    890 		cfgerror("`%s' is not a defined file system", name);
    891 		return;
    892 	}
    893 
    894 	/*
    895 	 * Convert to lower case.  This will be used in the select
    896 	 * table, to verify root file systems.
    897 	 */
    898 	n = strtolower(name);
    899 
    900 	if (do_option(fsopttab, &nextfsopt, name, n, "file-system"))
    901 		return;
    902 
    903 	/* Add to select table. */
    904 	(void)ht_insert(selecttab, n, __UNCONST(n));
    905 }
    906 
    907 void
    908 delfsoption(const char *name)
    909 {
    910 	const char *n;
    911 
    912 	n = strtolower(name);
    913 	if (undo_option(fsopttab, &fsoptions, &nextfsopt, name, "file-system"))
    914 		return;
    915 	if (undo_option(selecttab, NULL, NULL, n, "file-system"))
    916 		return;
    917 }
    918 
    919 /*
    920  * Add a "make" option.
    921  */
    922 void
    923 addmkoption(const char *name, const char *value)
    924 {
    925 
    926 	(void)do_option(mkopttab, &nextmkopt, name, value, "makeoptions");
    927 }
    928 
    929 void
    930 delmkoption(const char *name)
    931 {
    932 
    933 	(void)undo_option(mkopttab, &mkoptions, &nextmkopt, name,
    934 	    "makeoptions");
    935 }
    936 
    937 /*
    938  * Add an appending "make" option.
    939  */
    940 void
    941 appendmkoption(const char *name, const char *value)
    942 {
    943 	struct nvlist *nv;
    944 
    945 	nv = newnv(name, value, NULL, 0, NULL);
    946 	*nextappmkopt = nv;
    947 	nextappmkopt = &nv->nv_next;
    948 }
    949 
    950 /*
    951  * Add a conditional appending "make" option.
    952  */
    953 void
    954 appendcondmkoption(struct condexpr *cond, const char *name, const char *value)
    955 {
    956 	struct nvlist *nv;
    957 
    958 	nv = newnv(name, value, cond, 0, NULL);
    959 	*nextcndmkopt = nv;
    960 	nextcndmkopt = &nv->nv_next;
    961 }
    962 
    963 /*
    964  * Add a name=value pair to an option list.  The value may be NULL.
    965  */
    966 static int
    967 do_option(struct hashtab *ht, struct nvlist ***nppp, const char *name,
    968 	  const char *value, const char *type)
    969 {
    970 	struct nvlist *nv;
    971 
    972 	/* assume it will work */
    973 	nv = newnv(name, value, NULL, 0, NULL);
    974 	if (ht_insert(ht, name, nv) == 0) {
    975 		**nppp = nv;
    976 		*nppp = &nv->nv_next;
    977 		return (0);
    978 	}
    979 
    980 	/* oops, already got that option */
    981 	nvfree(nv);
    982 	if ((nv = ht_lookup(ht, name)) == NULL)
    983 		panic("do_option");
    984 	if (nv->nv_str != NULL && !OPT_FSOPT(name))
    985 		cfgerror("already have %s `%s=%s'", type, name, nv->nv_str);
    986 	else
    987 		cfgerror("already have %s `%s'", type, name);
    988 	return (1);
    989 }
    990 
    991 /*
    992  * Remove a name from a hash table,
    993  * and optionally, a name=value pair from an option list.
    994  */
    995 static int
    996 undo_option(struct hashtab *ht, struct nvlist **npp,
    997     struct nvlist ***next, const char *name, const char *type)
    998 {
    999 	struct nvlist *nv;
   1000 
   1001 	if (ht_remove(ht, name)) {
   1002 		cfgerror("%s `%s' is not defined", type, name);
   1003 		return (1);
   1004 	}
   1005 	if (npp == NULL)
   1006 		return (0);
   1007 
   1008 	for ( ; *npp != NULL; npp = &(*npp)->nv_next) {
   1009 		if ((*npp)->nv_name != name)
   1010 			continue;
   1011 		if (next != NULL && *next == &(*npp)->nv_next)
   1012 			*next = npp;
   1013 		nv = (*npp)->nv_next;
   1014 		nvfree(*npp);
   1015 		*npp = nv;
   1016 		return (0);
   1017 	}
   1018 	panic("%s `%s' is not defined in nvlist", type, name);
   1019 	return (1);
   1020 }
   1021 
   1022 /*
   1023  * Return true if there is at least one instance of the given unit
   1024  * on the given device attachment (or any units, if unit == WILD).
   1025  */
   1026 int
   1027 deva_has_instances(struct deva *deva, int unit)
   1028 {
   1029 	struct devi *i;
   1030 
   1031 	/*
   1032 	 * EHAMMERTOOBIG: we shouldn't check i_pseudoroot here.
   1033 	 * What we want by this check is them to appear non-present
   1034 	 * except for purposes of other devices being able to attach
   1035 	 * to them.
   1036 	 */
   1037 	for (i = deva->d_ihead; i != NULL; i = i->i_asame)
   1038 		if (i->i_active == DEVI_ACTIVE && i->i_pseudoroot == 0 &&
   1039 		    (unit == WILD || unit == i->i_unit || i->i_unit == STAR))
   1040 			return (1);
   1041 	return (0);
   1042 }
   1043 
   1044 /*
   1045  * Return true if there is at least one instance of the given unit
   1046  * on the given base (or any units, if unit == WILD).
   1047  */
   1048 int
   1049 devbase_has_instances(struct devbase *dev, int unit)
   1050 {
   1051 	struct deva *da;
   1052 
   1053 	/*
   1054 	 * Pseudo-devices are a little special.  We consider them
   1055 	 * to have instances only if they are both:
   1056 	 *
   1057 	 *	1. Included in this kernel configuration.
   1058 	 *
   1059 	 *	2. Be declared "defpseudodev".
   1060 	 */
   1061 	if (dev->d_ispseudo) {
   1062 		return ((ht_lookup(devitab, dev->d_name) != NULL)
   1063 			&& (dev->d_ispseudo > 1));
   1064 	}
   1065 
   1066 	for (da = dev->d_ahead; da != NULL; da = da->d_bsame)
   1067 		if (deva_has_instances(da, unit))
   1068 			return (1);
   1069 	return (0);
   1070 }
   1071 
   1072 static int
   1073 cfcrosscheck(struct config *cf, const char *what, struct nvlist *nv)
   1074 {
   1075 	struct devbase *dev;
   1076 	struct devi *pd;
   1077 	int errs, devunit;
   1078 
   1079 	if (maxpartitions <= 0)
   1080 		panic("cfcrosscheck");
   1081 
   1082 	for (errs = 0; nv != NULL; nv = nv->nv_next) {
   1083 		if (nv->nv_name == NULL)
   1084 			continue;
   1085 		dev = ht_lookup(devbasetab, nv->nv_name);
   1086 		if (dev == NULL)
   1087 			panic("cfcrosscheck(%s)", nv->nv_name);
   1088 		if (has_attr(dev->d_attrs, s_ifnet))
   1089 			devunit = nv->nv_ifunit;	/* XXX XXX XXX */
   1090 		else
   1091 			devunit = (int)(minor(nv->nv_num) / maxpartitions);
   1092 		if (devbase_has_instances(dev, devunit))
   1093 			continue;
   1094 		if (devbase_has_instances(dev, STAR) &&
   1095 		    devunit >= dev->d_umax)
   1096 			continue;
   1097 		TAILQ_FOREACH(pd, &allpseudo, i_next) {
   1098 			if (pd->i_base == dev && devunit < dev->d_umax &&
   1099 			    devunit >= 0)
   1100 				goto loop;
   1101 		}
   1102 		(void)fprintf(stderr,
   1103 		    "%s:%d: %s says %s on %s, but there's no %s\n",
   1104 		    conffile, cf->cf_lineno,
   1105 		    cf->cf_name, what, nv->nv_str, nv->nv_str);
   1106 		errs++;
   1107  loop:
   1108 		;
   1109 	}
   1110 	return (errs);
   1111 }
   1112 
   1113 /*
   1114  * Cross-check the configuration: make sure that each target device
   1115  * or attribute (`at foo[0*?]') names at least one real device.  Also
   1116  * see that the root and dump devices for all configurations are there.
   1117  */
   1118 int
   1119 crosscheck(void)
   1120 {
   1121 	struct config *cf;
   1122 	int errs;
   1123 
   1124 	errs = 0;
   1125 	if (TAILQ_EMPTY(&allcf)) {
   1126 		warnx("%s has no configurations!", conffile);
   1127 		errs++;
   1128 	}
   1129 	TAILQ_FOREACH(cf, &allcf, cf_next) {
   1130 		if (cf->cf_root != NULL) {	/* i.e., not root on ? */
   1131 			errs += cfcrosscheck(cf, "root", cf->cf_root);
   1132 			errs += cfcrosscheck(cf, "dumps", cf->cf_dump);
   1133 		}
   1134 	}
   1135 	return (errs);
   1136 }
   1137 
   1138 /*
   1139  * Check to see if there is a *'d unit with a needs-count file.
   1140  */
   1141 int
   1142 badstar(void)
   1143 {
   1144 	struct devbase *d;
   1145 	struct deva *da;
   1146 	struct devi *i;
   1147 	int errs, n;
   1148 
   1149 	errs = 0;
   1150 	TAILQ_FOREACH(d, &allbases, d_next) {
   1151 		for (da = d->d_ahead; da != NULL; da = da->d_bsame)
   1152 			for (i = da->d_ihead; i != NULL; i = i->i_asame) {
   1153 				if (i->i_unit == STAR)
   1154 					goto aybabtu;
   1155 			}
   1156 		continue;
   1157  aybabtu:
   1158 		if (ht_lookup(needcnttab, d->d_name)) {
   1159 			warnx("%s's cannot be *'d until its driver is fixed",
   1160 			    d->d_name);
   1161 			errs++;
   1162 			continue;
   1163 		}
   1164 		for (n = 0; i != NULL; i = i->i_alias)
   1165 			if (!i->i_collapsed)
   1166 				n++;
   1167 		if (n < 1)
   1168 			panic("badstar() n<1");
   1169 	}
   1170 	return (errs);
   1171 }
   1172 
   1173 /*
   1174  * Verify/create builddir if necessary, change to it, and verify srcdir.
   1175  * This will be called when we see the first include.
   1176  */
   1177 void
   1178 setupdirs(void)
   1179 {
   1180 	struct stat st;
   1181 
   1182 	/* srcdir must be specified if builddir is not specified or if
   1183 	 * no configuration filename was specified. */
   1184 	if ((builddir || strcmp(defbuilddir, ".") == 0) && !srcdir) {
   1185 		cfgerror("source directory must be specified");
   1186 		exit(1);
   1187 	}
   1188 
   1189 	if (Lflag) {
   1190 		if (srcdir == NULL)
   1191 			srcdir = "../../..";
   1192 		return;
   1193 	}
   1194 
   1195 	if (srcdir == NULL)
   1196 		srcdir = "../../../..";
   1197 	if (builddir == NULL)
   1198 		builddir = defbuilddir;
   1199 
   1200 	if (stat(builddir, &st) == -1) {
   1201 		if (mkdir(builddir, 0777) == -1)
   1202 			errx(EXIT_FAILURE, "cannot create %s", builddir);
   1203 	} else if (!S_ISDIR(st.st_mode))
   1204 		errx(EXIT_FAILURE, "%s is not a directory", builddir);
   1205 	if (chdir(builddir) == -1)
   1206 		err(EXIT_FAILURE, "cannot change to %s", builddir);
   1207 	if (stat(srcdir, &st) == -1)
   1208 		err(EXIT_FAILURE, "cannot stat %s", srcdir);
   1209 	if (!S_ISDIR(st.st_mode))
   1210 		errx(EXIT_FAILURE, "%s is not a directory", srcdir);
   1211 }
   1212 
   1213 /*
   1214  * Write identifier from "ident" directive into file, for
   1215  * newvers.sh to pick it up.
   1216  */
   1217 int
   1218 mkident(void)
   1219 {
   1220 	FILE *fp;
   1221 	int error = 0;
   1222 
   1223 	(void)unlink("ident");
   1224 
   1225 	if (ident == NULL)
   1226 		return (0);
   1227 
   1228 	if ((fp = fopen("ident", "w")) == NULL) {
   1229 		warn("cannot write ident");
   1230 		return (1);
   1231 	}
   1232 	if (vflag)
   1233 		(void)printf("using ident '%s'\n", ident);
   1234 	fprintf(fp, "%s\n", ident);
   1235 	fflush(fp);
   1236 	if (ferror(fp))
   1237 		error = 1;
   1238 	(void)fclose(fp);
   1239 
   1240 	return error;
   1241 }
   1242 
   1243 void
   1244 logconfig_start(void)
   1245 {
   1246 	extern FILE *yyin;
   1247 	char line[1024];
   1248 	const char *tmpdir;
   1249 	struct stat st;
   1250 	int fd;
   1251 
   1252 	if (yyin == NULL || fstat(fileno(yyin), &st) == -1)
   1253 		return;
   1254 	cfgtime = st.st_mtime;
   1255 
   1256 	tmpdir = getenv("TMPDIR");
   1257 	if (tmpdir == NULL)
   1258 		tmpdir = _PATH_TMP;
   1259 	(void)snprintf(line, sizeof(line), "%s/config.tmp.XXXXXX", tmpdir);
   1260 	if ((fd = mkstemp(line)) == -1 ||
   1261 	    (cfg = fdopen(fd, "r+")) == NULL) {
   1262 		if (fd != -1) {
   1263 			(void)unlink(line);
   1264 			(void)close(fd);
   1265 		}
   1266 		cfg = NULL;
   1267 		return;
   1268 	}
   1269 	(void)unlink(line);
   1270 
   1271 	(void)fprintf(cfg, "#include <sys/cdefs.h>\n\n");
   1272 	(void)fprintf(cfg, "#include \"opt_config.h\"\n");
   1273 	(void)fprintf(cfg, "\n");
   1274 	(void)fprintf(cfg, "/*\n");
   1275 	(void)fprintf(cfg, " * Add either (or both) of\n");
   1276 	(void)fprintf(cfg, " *\n");
   1277 	(void)fprintf(cfg, " *\toptions %s\n", LOGCONFIG_LARGE);
   1278 	(void)fprintf(cfg, " *\toptions %s\n", LOGCONFIG_SMALL);
   1279 	(void)fprintf(cfg, " *\n");
   1280 	(void)fprintf(cfg,
   1281 	    " * to your kernel config file to embed it in the resulting\n");
   1282 	(void)fprintf(cfg,
   1283 	    " * kernel.  The latter option does not include files that are\n");
   1284 	(void)fprintf(cfg,
   1285 	    " * included (recursively) by your config file.  The embedded\n");
   1286 	(void)fprintf(cfg,
   1287 	    " * data be extracted by using the command:\n");
   1288 	(void)fprintf(cfg, " *\n");
   1289 	(void)fprintf(cfg,
   1290 	    " *\tstrings netbsd | sed -n 's/^_CFG_//p' | unvis\n");
   1291 	(void)fprintf(cfg, " */\n");
   1292 	(void)fprintf(cfg, "\n");
   1293 	(void)fprintf(cfg, "#ifdef CONFIG_FILE\n");
   1294 	(void)fprintf(cfg, "#if defined(%s) || defined(%s)\n\n",
   1295 	    LOGCONFIG_LARGE, LOGCONFIG_SMALL);
   1296 	(void)fprintf(cfg, "static const char config[] __used =\n\n");
   1297 
   1298 	(void)fprintf(cfg, "#ifdef %s\n\n", LOGCONFIG_LARGE);
   1299 	(void)fprintf(cfg, "\"_CFG_### START CONFIG FILE \\\"%s\\\"\\n\"\n\n",
   1300 	    conffile);
   1301 	(void)fprintf(cfg, "#endif /* %s */\n\n", LOGCONFIG_LARGE);
   1302 
   1303 	logconfig_include(yyin, NULL);
   1304 
   1305 	(void)fprintf(cfg, "#ifdef %s\n\n", LOGCONFIG_LARGE);
   1306 	(void)fprintf(cfg, "\"_CFG_### END CONFIG FILE \\\"%s\\\"\\n\"\n",
   1307 	    conffile);
   1308 
   1309 	rewind(yyin);
   1310 }
   1311 
   1312 void
   1313 logconfig_include(FILE *cf, const char *filename)
   1314 {
   1315 	char line[1024], in[2048], *out;
   1316 	struct stat st;
   1317 	int missingeol;
   1318 
   1319 	if (!cfg)
   1320 		return;
   1321 
   1322 	missingeol = 0;
   1323 	if (fstat(fileno(cf), &st) == -1)
   1324 		return;
   1325 	if (cfgtime < st.st_mtime)
   1326 		cfgtime = st.st_mtime;
   1327 
   1328 	if (filename)
   1329 		(void)fprintf(cfg,
   1330 		    "\"_CFG_### (included from \\\"%s\\\")\\n\"\n",
   1331 		    filename);
   1332 	while (fgets(line, sizeof(line), cf) != NULL) {
   1333 		missingeol = 1;
   1334 		(void)fprintf(cfg, "\"_CFG_");
   1335 		if (filename)
   1336 			(void)fprintf(cfg, "###> ");
   1337 		strvis(in, line, VIS_TAB);
   1338 		for (out = in; *out; out++)
   1339 			switch (*out) {
   1340 			case '\n':
   1341 				(void)fprintf(cfg, "\\n\"\n");
   1342 				missingeol = 0;
   1343 				break;
   1344 			case '"': case '\\':
   1345 				(void)fputc('\\', cfg);
   1346 				/* FALLTHROUGH */
   1347 			default:
   1348 				(void)fputc(*out, cfg);
   1349 				break;
   1350 			}
   1351 	}
   1352 	if (missingeol) {
   1353 		(void)fprintf(cfg, "\\n\"\n");
   1354 		warnx("%s: newline missing at EOF",
   1355 		    filename != NULL ? filename : conffile);
   1356 	}
   1357 	if (filename)
   1358 		(void)fprintf(cfg, "\"_CFG_### (end include \\\"%s\\\")\\n\"\n",
   1359 		    filename);
   1360 
   1361 	rewind(cf);
   1362 }
   1363 
   1364 void
   1365 logconfig_end(void)
   1366 {
   1367 	char line[1024];
   1368 	FILE *fp;
   1369 	struct stat st;
   1370 
   1371 	if (!cfg)
   1372 		return;
   1373 
   1374 	(void)fprintf(cfg, "#endif /* %s */\n", LOGCONFIG_LARGE);
   1375 	(void)fprintf(cfg, ";\n");
   1376 	(void)fprintf(cfg, "#endif /* %s || %s */\n",
   1377 	    LOGCONFIG_LARGE, LOGCONFIG_SMALL);
   1378 	(void)fprintf(cfg, "#endif /* CONFIG_FILE */\n");
   1379 	fflush(cfg);
   1380 	if (ferror(cfg))
   1381 		err(EXIT_FAILURE, "write to temporary file for config.h failed");
   1382 	rewind(cfg);
   1383 
   1384 	if (stat("config_file.h", &st) != -1) {
   1385 		if (cfgtime < st.st_mtime) {
   1386 			fclose(cfg);
   1387 			return;
   1388 		}
   1389 	}
   1390 
   1391 	fp = fopen("config_file.h", "w");
   1392 	if (!fp)
   1393 		err(EXIT_FAILURE, "cannot open \"config.h\"");
   1394 
   1395 	while (fgets(line, sizeof(line), cfg) != NULL)
   1396 		fputs(line, fp);
   1397 	fflush(fp);
   1398 	if (ferror(fp))
   1399 		err(EXIT_FAILURE, "write to \"config.h\" failed");
   1400 	fclose(fp);
   1401 	fclose(cfg);
   1402 }
   1403 
   1404 const char *
   1405 strtolower(const char *name)
   1406 {
   1407 	const char *n;
   1408 	char *p, low[500];
   1409 	unsigned char c;
   1410 
   1411 	for (n = name, p = low; (c = *n) != '\0'; n++)
   1412 		*p++ = isupper(c) ? tolower(c) : c;
   1413 	*p = 0;
   1414 	return (intern(low));
   1415 }
   1416 
   1417 static int
   1418 is_elf(const char *file)
   1419 {
   1420 	int kernel;
   1421 	char hdr[4];
   1422 
   1423 	kernel = open(file, O_RDONLY);
   1424 	if (kernel == -1)
   1425 		err(EXIT_FAILURE, "cannot open %s", file);
   1426 	if (read(kernel, hdr, 4) != 4)
   1427 		err(EXIT_FAILURE, "Cannot read from %s", file);
   1428 	(void)close(kernel);
   1429 
   1430 	return memcmp("\177ELF", hdr, 4) == 0 ? 1 : 0;
   1431 }
   1432 
   1433 static int
   1434 extract_config(const char *kname, const char *cname, int cfd)
   1435 {
   1436 	char *ptr;
   1437 	int found, kfd, i;
   1438 	struct stat st;
   1439 
   1440 	found = 0;
   1441 
   1442 	/* mmap(2) binary kernel */
   1443 	kfd = open(conffile, O_RDONLY);
   1444 	if (kfd == -1)
   1445 		err(EXIT_FAILURE, "cannot open %s", kname);
   1446 	if (fstat(kfd, &st) == -1)
   1447 		err(EXIT_FAILURE, "cannot stat %s", kname);
   1448 	ptr = mmap(0, st.st_size, PROT_READ, MAP_FILE | MAP_SHARED,
   1449 	    kfd, 0);
   1450 	if (ptr == MAP_FAILED)
   1451 		err(EXIT_FAILURE, "cannot mmap %s", kname);
   1452 
   1453 	/* Scan mmap(2)'ed region, extracting kernel configuration */
   1454 	for (i = 0; i < st.st_size; i++) {
   1455 		if ((*ptr == '_') && (st.st_size - i > 5) && memcmp(ptr,
   1456 		    "_CFG_", 5) == 0) {
   1457 			/* Line found */
   1458 			char *oldptr, line[LINE_MAX + 1], uline[LINE_MAX + 1];
   1459 			int j;
   1460 
   1461 			found = 1;
   1462 
   1463 			oldptr = (ptr += 5);
   1464 			while (*ptr != '\n' && *ptr != '\0')
   1465 				ptr++;
   1466 			if (ptr - oldptr > LINE_MAX)
   1467 				errx(EXIT_FAILURE, "line too long");
   1468 			i += ptr - oldptr + 5;
   1469 			(void)memcpy(line, oldptr, (size_t)(ptr - oldptr));
   1470 			line[ptr - oldptr] = '\0';
   1471 			j = strunvis(uline, line);
   1472 			if (j == -1)
   1473 				errx(EXIT_FAILURE, "unvis: invalid "
   1474 				    "encoded sequence");
   1475 			uline[j] = '\n';
   1476 			if (write(cfd, uline, (size_t)j + 1) == -1)
   1477 				err(EXIT_FAILURE, "cannot write to %s", cname);
   1478 		} else
   1479 			ptr++;
   1480 	}
   1481 
   1482 	(void)close(kfd);
   1483 
   1484 	return found;
   1485 }
   1486 
   1487 struct dhdi_params {
   1488 	struct devbase *d;
   1489 	int unit;
   1490 	int level;
   1491 };
   1492 
   1493 static int
   1494 devbase_has_dead_instances(const char *key, void *value, void *aux)
   1495 {
   1496 	struct devi *i;
   1497 	struct dhdi_params *dhdi = aux;
   1498 
   1499 	for (i = value; i != NULL; i = i->i_alias)
   1500 		if (i->i_base == dhdi->d &&
   1501 		    (dhdi->unit == WILD || dhdi->unit == i->i_unit ||
   1502 		     i->i_unit == STAR) &&
   1503 		    i->i_level >= dhdi->level)
   1504 			return 1;
   1505 	return 0;
   1506 }
   1507 
   1508 /*
   1509  * This is almost the same as devbase_has_instances, except it
   1510  * may have special considerations regarding ignored instances.
   1511  */
   1512 
   1513 static int
   1514 devbase_has_any_instance(struct devbase *dev, int unit, int state, int level)
   1515 {
   1516 	struct deva *da;
   1517 	struct devi *i;
   1518 
   1519 	if (dev->d_ispseudo) {
   1520 		if (dev->d_ihead != NULL)
   1521 			return 1;
   1522 		else if (state != DEVI_IGNORED)
   1523 			return 0;
   1524 		if ((i = ht_lookup(deaddevitab, dev->d_name)) == NULL)
   1525 			return 0;
   1526 		return (i->i_level >= level);
   1527 	}
   1528 
   1529 	for (da = dev->d_ahead; da != NULL; da = da->d_bsame)
   1530 		for (i = da->d_ihead; i != NULL; i = i->i_asame)
   1531 			if ((i->i_active == DEVI_ACTIVE ||
   1532 			     i->i_active == state) &&
   1533 			    (unit == WILD || unit == i->i_unit ||
   1534 			     i->i_unit == STAR))
   1535 				return 1;
   1536 
   1537 	if (state == DEVI_IGNORED) {
   1538 		struct dhdi_params dhdi = { dev, unit, level };
   1539 		/* also check dead devices */
   1540 		return ht_enumerate(deaddevitab, devbase_has_dead_instances,
   1541 		    &dhdi);
   1542 	}
   1543 
   1544 	return 0;
   1545 }
   1546 
   1547 /*
   1548  * check_dead_devi(), used with ht_enumerate, checks if any of the removed
   1549  * device instances would have been a valid instance considering the devbase,
   1550  * the parent device and the interface attribute.
   1551  *
   1552  * In other words, for a non-active device, it checks if children would be
   1553  * actual orphans or the result of a negative statement in the config file.
   1554  */
   1555 
   1556 struct cdd_params {
   1557 	struct devbase *d;
   1558 	struct attr *at;
   1559 	struct devbase *parent;
   1560 };
   1561 
   1562 static int
   1563 check_dead_devi(const char *key, void *value, void *aux)
   1564 {
   1565 	struct cdd_params *cdd = aux;
   1566 	struct devi *i = value;
   1567 	struct pspec *p;
   1568 
   1569 	if (i->i_base != cdd->d)
   1570 		return 0;
   1571 
   1572 	for (; i != NULL; i = i->i_alias) {
   1573 		p = i->i_pspec;
   1574 		if ((p == NULL && cdd->at == NULL) ||
   1575 		    (p != NULL && p->p_iattr == cdd->at &&
   1576 		     (p->p_atdev == NULL || p->p_atdev == cdd->parent))) {
   1577 			if (p != NULL &&
   1578 			    !devbase_has_any_instance(cdd->parent, p->p_atunit,
   1579 			    DEVI_IGNORED, i->i_level))
   1580 				return 0;
   1581 			else
   1582 				return 1;
   1583 		}
   1584 	}
   1585 	return 0;
   1586 }
   1587 
   1588 static void
   1589 do_kill_orphans(struct devbase *d, struct attr *at, struct devbase *parent,
   1590     int state)
   1591 {
   1592 	struct nvlist *nv1;
   1593 	struct attrlist *al;
   1594 	struct attr *a;
   1595 	struct devi *i, *j = NULL;
   1596 	struct pspec *p;
   1597 	int active = 0;
   1598 
   1599 	/*
   1600 	 * A pseudo-device will always attach at root, and if it has an
   1601 	 * instance (it cannot have more than one), it is enough to consider
   1602 	 * it active, as there is no real attachment.
   1603 	 *
   1604 	 * A pseudo device can never be marked DEVI_IGNORED.
   1605 	 */
   1606 	if (d->d_ispseudo) {
   1607 		if (d->d_ihead != NULL)
   1608 			d->d_ihead->i_active = active = DEVI_ACTIVE;
   1609 		else {
   1610 			if (ht_lookup(deaddevitab, d->d_name) != NULL)
   1611 				active = DEVI_IGNORED;
   1612 			else
   1613 				return;
   1614 		}
   1615 	} else {
   1616 		int seen = 0;
   1617 
   1618 		for (i = d->d_ihead; i != NULL; i = i->i_bsame) {
   1619 			for (j = i; j != NULL; j = j->i_alias) {
   1620 				p = j->i_pspec;
   1621 				if ((p == NULL && at == NULL) ||
   1622 				    (p != NULL && p->p_iattr == at &&
   1623 				    (p->p_atdev == NULL ||
   1624 				    p->p_atdev == parent))) {
   1625 					if (p != NULL &&
   1626 					    !devbase_has_any_instance(parent,
   1627 					      p->p_atunit, state, j->i_level))
   1628 						continue;
   1629 					/*
   1630 					 * There are Fry-like devices which can
   1631 					 * be their own grand-parent (or even
   1632 					 * parent, like uhub).  We don't want
   1633 					 * to loop, so if we've already reached
   1634 					 * an instance for one reason or
   1635 					 * another, stop there.
   1636 					 */
   1637 					if (j->i_active == DEVI_ACTIVE ||
   1638 					    j->i_active == state) {
   1639 						/*
   1640 						 * Device has already been
   1641 						 * seen.  However it might
   1642 						 * have siblings who still
   1643 						 * have to be activated or
   1644 						 * orphaned.
   1645 						 */
   1646 						seen = 1;
   1647 						continue;
   1648 					}
   1649 					j->i_active = active = state;
   1650 					if (p != NULL)
   1651 						p->p_active = state;
   1652 				}
   1653 			}
   1654 		}
   1655 		/*
   1656 		 * If we've been there but have made no change, stop.
   1657 		 */
   1658 		if (seen && !active)
   1659 			return;
   1660 		if (!active) {
   1661 			struct cdd_params cdd = { d, at, parent };
   1662 			/* Look for a matching dead devi */
   1663 			if (ht_enumerate(deaddevitab, check_dead_devi, &cdd) &&
   1664 			    d != parent)
   1665 				/*
   1666 				 * That device had its instances removed.
   1667 				 * Continue the loop marking descendants
   1668 				 * with DEVI_IGNORED instead of DEVI_ACTIVE.
   1669 				 *
   1670 				 * There is one special case for devices that
   1671 				 * are their own parent:  if that instance is
   1672 				 * removed (e.g., no uhub* at uhub?), we don't
   1673 				 * have to continue looping.
   1674 				 */
   1675 				active = DEVI_IGNORED;
   1676 			else
   1677 				return;
   1678 		}
   1679 	}
   1680 
   1681 	for (al = d->d_attrs; al != NULL; al = al->al_next) {
   1682 		a = al->al_this;
   1683 		for (nv1 = a->a_devs; nv1 != NULL; nv1 = nv1->nv_next)
   1684 			do_kill_orphans(nv1->nv_ptr, a, d, active);
   1685 	}
   1686 }
   1687 
   1688 static int
   1689 /*ARGSUSED*/
   1690 kill_orphans_cb(const char *key, void *value, void *aux)
   1691 {
   1692 	do_kill_orphans((struct devbase *)value, NULL, NULL, DEVI_ACTIVE);
   1693 	return 0;
   1694 }
   1695 
   1696 static void
   1697 kill_orphans(void)
   1698 {
   1699 	ht_enumerate(devroottab, kill_orphans_cb, NULL);
   1700 }
   1701