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