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