Home | History | Annotate | Line # | Download | only in config
main.c revision 1.55
      1 /*	$NetBSD: main.c,v 1.55 2014/10/09 06:45:31 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 }
    960 
    961 void
    962 deloption(const char *name)
    963 {
    964 
    965 	if (undo_option(opttab, &options, &nextopt, name, "options"))
    966 		return;
    967 	if (undo_option(selecttab, NULL, NULL, strtolower(name), "options"))
    968 		return;
    969 }
    970 
    971 /*
    972  * Add a file system option.  This routine simply inserts the name into
    973  * a list of valid file systems, which is used to validate the root
    974  * file system type.  The name is then treated like a standard option.
    975  */
    976 void
    977 addfsoption(const char *name)
    978 {
    979 	const char *n;
    980 
    981 	/* Make sure this is a defined file system. */
    982 	if (!OPT_FSOPT(name)) {
    983 		cfgerror("`%s' is not a defined file system", name);
    984 		return;
    985 	}
    986 
    987 	/*
    988 	 * Convert to lower case.  This will be used in the select
    989 	 * table, to verify root file systems.
    990 	 */
    991 	n = strtolower(name);
    992 
    993 	if (do_option(fsopttab, &nextfsopt, name, n, "file-system"))
    994 		return;
    995 
    996 	/* Add to select table. */
    997 	(void)ht_insert(selecttab, n, __UNCONST(n));
    998 }
    999 
   1000 void
   1001 delfsoption(const char *name)
   1002 {
   1003 	const char *n;
   1004 
   1005 	n = strtolower(name);
   1006 	if (undo_option(fsopttab, &fsoptions, &nextfsopt, name, "file-system"))
   1007 		return;
   1008 	if (undo_option(selecttab, NULL, NULL, n, "file-system"))
   1009 		return;
   1010 }
   1011 
   1012 /*
   1013  * Add a "make" option.
   1014  */
   1015 void
   1016 addmkoption(const char *name, const char *value)
   1017 {
   1018 
   1019 	(void)do_option(mkopttab, &nextmkopt, name, value, "makeoptions");
   1020 }
   1021 
   1022 void
   1023 delmkoption(const char *name)
   1024 {
   1025 
   1026 	(void)undo_option(mkopttab, &mkoptions, &nextmkopt, name,
   1027 	    "makeoptions");
   1028 }
   1029 
   1030 /*
   1031  * Add an appending "make" option.
   1032  */
   1033 void
   1034 appendmkoption(const char *name, const char *value)
   1035 {
   1036 	struct nvlist *nv;
   1037 
   1038 	nv = newnv(name, value, NULL, 0, NULL);
   1039 	*nextappmkopt = nv;
   1040 	nextappmkopt = &nv->nv_next;
   1041 }
   1042 
   1043 /*
   1044  * Add a conditional appending "make" option.
   1045  */
   1046 void
   1047 appendcondmkoption(struct condexpr *cond, const char *name, const char *value)
   1048 {
   1049 	struct nvlist *nv;
   1050 
   1051 	nv = newnv(name, value, cond, 0, NULL);
   1052 	*nextcndmkopt = nv;
   1053 	nextcndmkopt = &nv->nv_next;
   1054 }
   1055 
   1056 /*
   1057  * Add a name=value pair to an option list.  The value may be NULL.
   1058  */
   1059 static int
   1060 do_option(struct hashtab *ht, struct nvlist ***nppp, const char *name,
   1061 	  const char *value, const char *type)
   1062 {
   1063 	struct nvlist *nv;
   1064 
   1065 	/* assume it will work */
   1066 	nv = newnv(name, value, NULL, 0, NULL);
   1067 	if (ht_insert(ht, name, nv) == 0) {
   1068 		**nppp = nv;
   1069 		*nppp = &nv->nv_next;
   1070 		return (0);
   1071 	}
   1072 
   1073 	/* oops, already got that option */
   1074 	nvfree(nv);
   1075 	if ((nv = ht_lookup(ht, name)) == NULL)
   1076 		panic("do_option");
   1077 	if (nv->nv_str != NULL && !OPT_FSOPT(name))
   1078 		cfgerror("already have %s `%s=%s'", type, name, nv->nv_str);
   1079 	else
   1080 		cfgerror("already have %s `%s'", type, name);
   1081 	return (1);
   1082 }
   1083 
   1084 /*
   1085  * Remove a name from a hash table,
   1086  * and optionally, a name=value pair from an option list.
   1087  */
   1088 static int
   1089 undo_option(struct hashtab *ht, struct nvlist **npp,
   1090     struct nvlist ***next, const char *name, const char *type)
   1091 {
   1092 	struct nvlist *nv;
   1093 
   1094 	if (ht_remove(ht, name)) {
   1095 		/*
   1096 		 * -U command line option removals are always silent
   1097 		 */
   1098 		if (!handling_cmdlineopts)
   1099 			cfgwarn("%s `%s' is not defined", type, name);
   1100 		return (1);
   1101 	}
   1102 	if (npp == NULL)
   1103 		return (0);
   1104 
   1105 	for ( ; *npp != NULL; npp = &(*npp)->nv_next) {
   1106 		if ((*npp)->nv_name != name)
   1107 			continue;
   1108 		if (next != NULL && *next == &(*npp)->nv_next)
   1109 			*next = npp;
   1110 		nv = (*npp)->nv_next;
   1111 		nvfree(*npp);
   1112 		*npp = nv;
   1113 		return (0);
   1114 	}
   1115 	panic("%s `%s' is not defined in nvlist", type, name);
   1116 	return (1);
   1117 }
   1118 
   1119 /*
   1120  * Return true if there is at least one instance of the given unit
   1121  * on the given device attachment (or any units, if unit == WILD).
   1122  */
   1123 int
   1124 deva_has_instances(struct deva *deva, int unit)
   1125 {
   1126 	struct devi *i;
   1127 
   1128 	/*
   1129 	 * EHAMMERTOOBIG: we shouldn't check i_pseudoroot here.
   1130 	 * What we want by this check is them to appear non-present
   1131 	 * except for purposes of other devices being able to attach
   1132 	 * to them.
   1133 	 */
   1134 	for (i = deva->d_ihead; i != NULL; i = i->i_asame)
   1135 		if (i->i_active == DEVI_ACTIVE && i->i_pseudoroot == 0 &&
   1136 		    (unit == WILD || unit == i->i_unit || i->i_unit == STAR))
   1137 			return (1);
   1138 	return (0);
   1139 }
   1140 
   1141 /*
   1142  * Return true if there is at least one instance of the given unit
   1143  * on the given base (or any units, if unit == WILD).
   1144  */
   1145 int
   1146 devbase_has_instances(struct devbase *dev, int unit)
   1147 {
   1148 	struct deva *da;
   1149 
   1150 	/*
   1151 	 * Pseudo-devices are a little special.  We consider them
   1152 	 * to have instances only if they are both:
   1153 	 *
   1154 	 *	1. Included in this kernel configuration.
   1155 	 *
   1156 	 *	2. Be declared "defpseudodev".
   1157 	 */
   1158 	if (dev->d_ispseudo) {
   1159 		return ((ht_lookup(devitab, dev->d_name) != NULL)
   1160 			&& (dev->d_ispseudo > 1));
   1161 	}
   1162 
   1163 	for (da = dev->d_ahead; da != NULL; da = da->d_bsame)
   1164 		if (deva_has_instances(da, unit))
   1165 			return (1);
   1166 	return (0);
   1167 }
   1168 
   1169 static int
   1170 cfcrosscheck(struct config *cf, const char *what, struct nvlist *nv)
   1171 {
   1172 	struct devbase *dev;
   1173 	struct devi *pd;
   1174 	int errs, devunit;
   1175 
   1176 	if (maxpartitions <= 0)
   1177 		panic("cfcrosscheck");
   1178 
   1179 	for (errs = 0; nv != NULL; nv = nv->nv_next) {
   1180 		if (nv->nv_name == NULL)
   1181 			continue;
   1182 		dev = ht_lookup(devbasetab, nv->nv_name);
   1183 		if (dev == NULL)
   1184 			panic("cfcrosscheck(%s)", nv->nv_name);
   1185 		if (has_attr(dev->d_attrs, s_ifnet))
   1186 			devunit = nv->nv_ifunit;	/* XXX XXX XXX */
   1187 		else
   1188 			devunit = (int)(minor(nv->nv_num) / maxpartitions);
   1189 		if (devbase_has_instances(dev, devunit))
   1190 			continue;
   1191 		if (devbase_has_instances(dev, STAR) &&
   1192 		    devunit >= dev->d_umax)
   1193 			continue;
   1194 		TAILQ_FOREACH(pd, &allpseudo, i_next) {
   1195 			if (pd->i_base == dev && devunit < dev->d_umax &&
   1196 			    devunit >= 0)
   1197 				goto loop;
   1198 		}
   1199 		(void)fprintf(stderr,
   1200 		    "%s:%d: %s says %s on %s, but there's no %s\n",
   1201 		    conffile, cf->cf_lineno,
   1202 		    cf->cf_name, what, nv->nv_str, nv->nv_str);
   1203 		errs++;
   1204  loop:
   1205 		;
   1206 	}
   1207 	return (errs);
   1208 }
   1209 
   1210 /*
   1211  * Cross-check the configuration: make sure that each target device
   1212  * or attribute (`at foo[0*?]') names at least one real device.  Also
   1213  * see that the root and dump devices for all configurations are there.
   1214  */
   1215 int
   1216 crosscheck(void)
   1217 {
   1218 	struct config *cf;
   1219 	int errs;
   1220 
   1221 	errs = 0;
   1222 	if (TAILQ_EMPTY(&allcf)) {
   1223 		warnx("%s has no configurations!", conffile);
   1224 		errs++;
   1225 	}
   1226 	TAILQ_FOREACH(cf, &allcf, cf_next) {
   1227 		if (cf->cf_root != NULL) {	/* i.e., not root on ? */
   1228 			errs += cfcrosscheck(cf, "root", cf->cf_root);
   1229 			errs += cfcrosscheck(cf, "dumps", cf->cf_dump);
   1230 		}
   1231 	}
   1232 	return (errs);
   1233 }
   1234 
   1235 /*
   1236  * Check to see if there is a *'d unit with a needs-count file.
   1237  */
   1238 int
   1239 badstar(void)
   1240 {
   1241 	struct devbase *d;
   1242 	struct deva *da;
   1243 	struct devi *i;
   1244 	int errs, n;
   1245 
   1246 	errs = 0;
   1247 	TAILQ_FOREACH(d, &allbases, d_next) {
   1248 		for (da = d->d_ahead; da != NULL; da = da->d_bsame)
   1249 			for (i = da->d_ihead; i != NULL; i = i->i_asame) {
   1250 				if (i->i_unit == STAR)
   1251 					goto aybabtu;
   1252 			}
   1253 		continue;
   1254  aybabtu:
   1255 		if (ht_lookup(needcnttab, d->d_name)) {
   1256 			warnx("%s's cannot be *'d until its driver is fixed",
   1257 			    d->d_name);
   1258 			errs++;
   1259 			continue;
   1260 		}
   1261 		for (n = 0; i != NULL; i = i->i_alias)
   1262 			if (!i->i_collapsed)
   1263 				n++;
   1264 		if (n < 1)
   1265 			panic("badstar() n<1");
   1266 	}
   1267 	return (errs);
   1268 }
   1269 
   1270 /*
   1271  * Verify/create builddir if necessary, change to it, and verify srcdir.
   1272  * This will be called when we see the first include.
   1273  */
   1274 void
   1275 setupdirs(void)
   1276 {
   1277 	struct stat st;
   1278 
   1279 	/* srcdir must be specified if builddir is not specified or if
   1280 	 * no configuration filename was specified. */
   1281 	if ((builddir || strcmp(defbuilddir, ".") == 0) && !srcdir) {
   1282 		cfgerror("source directory must be specified");
   1283 		exit(1);
   1284 	}
   1285 
   1286 	if (Lflag) {
   1287 		if (srcdir == NULL)
   1288 			srcdir = "../../..";
   1289 		return;
   1290 	}
   1291 
   1292 	if (srcdir == NULL)
   1293 		srcdir = "../../../..";
   1294 	if (builddir == NULL)
   1295 		builddir = defbuilddir;
   1296 
   1297 	if (stat(builddir, &st) == -1) {
   1298 		if (mkdir(builddir, 0777) == -1)
   1299 			errx(EXIT_FAILURE, "cannot create %s", builddir);
   1300 	} else if (!S_ISDIR(st.st_mode))
   1301 		errx(EXIT_FAILURE, "%s is not a directory", builddir);
   1302 	if (chdir(builddir) == -1)
   1303 		err(EXIT_FAILURE, "cannot change to %s", builddir);
   1304 	if (stat(srcdir, &st) == -1)
   1305 		err(EXIT_FAILURE, "cannot stat %s", srcdir);
   1306 	if (!S_ISDIR(st.st_mode))
   1307 		errx(EXIT_FAILURE, "%s is not a directory", srcdir);
   1308 }
   1309 
   1310 /*
   1311  * Write identifier from "ident" directive into file, for
   1312  * newvers.sh to pick it up.
   1313  */
   1314 int
   1315 mkident(void)
   1316 {
   1317 	FILE *fp;
   1318 	int error = 0;
   1319 
   1320 	(void)unlink("ident");
   1321 
   1322 	if (ident == NULL)
   1323 		return (0);
   1324 
   1325 	if ((fp = fopen("ident", "w")) == NULL) {
   1326 		warn("cannot write ident");
   1327 		return (1);
   1328 	}
   1329 	if (vflag)
   1330 		(void)printf("using ident '%s'\n", ident);
   1331 	fprintf(fp, "%s\n", ident);
   1332 	fflush(fp);
   1333 	if (ferror(fp))
   1334 		error = 1;
   1335 	(void)fclose(fp);
   1336 
   1337 	return error;
   1338 }
   1339 
   1340 void
   1341 logconfig_start(void)
   1342 {
   1343 	extern FILE *yyin;
   1344 	char line[1024];
   1345 	const char *tmpdir;
   1346 	struct stat st;
   1347 	int fd;
   1348 
   1349 	if (yyin == NULL || fstat(fileno(yyin), &st) == -1)
   1350 		return;
   1351 	cfgtime = st.st_mtime;
   1352 
   1353 	tmpdir = getenv("TMPDIR");
   1354 	if (tmpdir == NULL)
   1355 		tmpdir = _PATH_TMP;
   1356 	(void)snprintf(line, sizeof(line), "%s/config.tmp.XXXXXX", tmpdir);
   1357 	if ((fd = mkstemp(line)) == -1 ||
   1358 	    (cfg = fdopen(fd, "r+")) == NULL) {
   1359 		if (fd != -1) {
   1360 			(void)unlink(line);
   1361 			(void)close(fd);
   1362 		}
   1363 		cfg = NULL;
   1364 		return;
   1365 	}
   1366 	(void)unlink(line);
   1367 
   1368 	(void)fprintf(cfg, "#include <sys/cdefs.h>\n\n");
   1369 	(void)fprintf(cfg, "#include \"opt_config.h\"\n");
   1370 	(void)fprintf(cfg, "\n");
   1371 	(void)fprintf(cfg, "/*\n");
   1372 	(void)fprintf(cfg, " * Add either (or both) of\n");
   1373 	(void)fprintf(cfg, " *\n");
   1374 	(void)fprintf(cfg, " *\toptions %s\n", LOGCONFIG_LARGE);
   1375 	(void)fprintf(cfg, " *\toptions %s\n", LOGCONFIG_SMALL);
   1376 	(void)fprintf(cfg, " *\n");
   1377 	(void)fprintf(cfg,
   1378 	    " * to your kernel config file to embed it in the resulting\n");
   1379 	(void)fprintf(cfg,
   1380 	    " * kernel.  The latter option does not include files that are\n");
   1381 	(void)fprintf(cfg,
   1382 	    " * included (recursively) by your config file.  The embedded\n");
   1383 	(void)fprintf(cfg,
   1384 	    " * data be extracted by using the command:\n");
   1385 	(void)fprintf(cfg, " *\n");
   1386 	(void)fprintf(cfg,
   1387 	    " *\tstrings netbsd | sed -n 's/^_CFG_//p' | unvis\n");
   1388 	(void)fprintf(cfg, " */\n");
   1389 	(void)fprintf(cfg, "\n");
   1390 	(void)fprintf(cfg, "#ifdef CONFIG_FILE\n");
   1391 	(void)fprintf(cfg, "#if defined(%s) || defined(%s)\n\n",
   1392 	    LOGCONFIG_LARGE, LOGCONFIG_SMALL);
   1393 	(void)fprintf(cfg, "static const char config[] __used =\n\n");
   1394 
   1395 	(void)fprintf(cfg, "#ifdef %s\n\n", LOGCONFIG_LARGE);
   1396 	(void)fprintf(cfg, "\"_CFG_### START CONFIG FILE \\\"%s\\\"\\n\"\n\n",
   1397 	    conffile);
   1398 	(void)fprintf(cfg, "#endif /* %s */\n\n", LOGCONFIG_LARGE);
   1399 
   1400 	logconfig_include(yyin, NULL);
   1401 
   1402 	(void)fprintf(cfg, "#ifdef %s\n\n", LOGCONFIG_LARGE);
   1403 	(void)fprintf(cfg, "\"_CFG_### END CONFIG FILE \\\"%s\\\"\\n\"\n",
   1404 	    conffile);
   1405 
   1406 	rewind(yyin);
   1407 }
   1408 
   1409 void
   1410 logconfig_include(FILE *cf, const char *filename)
   1411 {
   1412 	char line[1024], in[2048], *out;
   1413 	struct stat st;
   1414 	int missingeol;
   1415 
   1416 	if (!cfg)
   1417 		return;
   1418 
   1419 	missingeol = 0;
   1420 	if (fstat(fileno(cf), &st) == -1)
   1421 		return;
   1422 	if (cfgtime < st.st_mtime)
   1423 		cfgtime = st.st_mtime;
   1424 
   1425 	if (filename)
   1426 		(void)fprintf(cfg,
   1427 		    "\"_CFG_### (included from \\\"%s\\\")\\n\"\n",
   1428 		    filename);
   1429 	while (fgets(line, sizeof(line), cf) != NULL) {
   1430 		missingeol = 1;
   1431 		(void)fprintf(cfg, "\"_CFG_");
   1432 		if (filename)
   1433 			(void)fprintf(cfg, "###> ");
   1434 		strvis(in, line, VIS_TAB);
   1435 		for (out = in; *out; out++)
   1436 			switch (*out) {
   1437 			case '\n':
   1438 				(void)fprintf(cfg, "\\n\"\n");
   1439 				missingeol = 0;
   1440 				break;
   1441 			case '"': case '\\':
   1442 				(void)fputc('\\', cfg);
   1443 				/* FALLTHROUGH */
   1444 			default:
   1445 				(void)fputc(*out, cfg);
   1446 				break;
   1447 			}
   1448 	}
   1449 	if (missingeol) {
   1450 		(void)fprintf(cfg, "\\n\"\n");
   1451 		warnx("%s: newline missing at EOF",
   1452 		    filename != NULL ? filename : conffile);
   1453 	}
   1454 	if (filename)
   1455 		(void)fprintf(cfg, "\"_CFG_### (end include \\\"%s\\\")\\n\"\n",
   1456 		    filename);
   1457 
   1458 	rewind(cf);
   1459 }
   1460 
   1461 void
   1462 logconfig_end(void)
   1463 {
   1464 	char line[1024];
   1465 	FILE *fp;
   1466 	struct stat st;
   1467 
   1468 	if (!cfg)
   1469 		return;
   1470 
   1471 	(void)fprintf(cfg, "#endif /* %s */\n", LOGCONFIG_LARGE);
   1472 	(void)fprintf(cfg, ";\n");
   1473 	(void)fprintf(cfg, "#endif /* %s || %s */\n",
   1474 	    LOGCONFIG_LARGE, LOGCONFIG_SMALL);
   1475 	(void)fprintf(cfg, "#endif /* CONFIG_FILE */\n");
   1476 	fflush(cfg);
   1477 	if (ferror(cfg))
   1478 		err(EXIT_FAILURE, "write to temporary file for config.h failed");
   1479 	rewind(cfg);
   1480 
   1481 	if (stat("config_file.h", &st) != -1) {
   1482 		if (cfgtime < st.st_mtime) {
   1483 			fclose(cfg);
   1484 			return;
   1485 		}
   1486 	}
   1487 
   1488 	fp = fopen("config_file.h", "w");
   1489 	if (!fp)
   1490 		err(EXIT_FAILURE, "cannot open \"config.h\"");
   1491 
   1492 	while (fgets(line, sizeof(line), cfg) != NULL)
   1493 		fputs(line, fp);
   1494 	fflush(fp);
   1495 	if (ferror(fp))
   1496 		err(EXIT_FAILURE, "write to \"config.h\" failed");
   1497 	fclose(fp);
   1498 	fclose(cfg);
   1499 }
   1500 
   1501 const char *
   1502 strtolower(const char *name)
   1503 {
   1504 	const char *n;
   1505 	char *p, low[500];
   1506 	unsigned char c;
   1507 
   1508 	for (n = name, p = low; (c = *n) != '\0'; n++)
   1509 		*p++ = isupper(c) ? tolower(c) : c;
   1510 	*p = 0;
   1511 	return (intern(low));
   1512 }
   1513 
   1514 static int
   1515 is_elf(const char *file)
   1516 {
   1517 	int kernel;
   1518 	char hdr[4];
   1519 
   1520 	kernel = open(file, O_RDONLY);
   1521 	if (kernel == -1)
   1522 		err(EXIT_FAILURE, "cannot open %s", file);
   1523 	if (read(kernel, hdr, 4) != 4)
   1524 		err(EXIT_FAILURE, "Cannot read from %s", file);
   1525 	(void)close(kernel);
   1526 
   1527 	return memcmp("\177ELF", hdr, 4) == 0 ? 1 : 0;
   1528 }
   1529 
   1530 static int
   1531 extract_config(const char *kname, const char *cname, int cfd)
   1532 {
   1533 	char *ptr;
   1534 	int found, kfd, i;
   1535 	struct stat st;
   1536 
   1537 	found = 0;
   1538 
   1539 	/* mmap(2) binary kernel */
   1540 	kfd = open(conffile, O_RDONLY);
   1541 	if (kfd == -1)
   1542 		err(EXIT_FAILURE, "cannot open %s", kname);
   1543 	if (fstat(kfd, &st) == -1)
   1544 		err(EXIT_FAILURE, "cannot stat %s", kname);
   1545 	ptr = mmap(0, st.st_size, PROT_READ, MAP_FILE | MAP_SHARED,
   1546 	    kfd, 0);
   1547 	if (ptr == MAP_FAILED)
   1548 		err(EXIT_FAILURE, "cannot mmap %s", kname);
   1549 
   1550 	/* Scan mmap(2)'ed region, extracting kernel configuration */
   1551 	for (i = 0; i < st.st_size; i++) {
   1552 		if ((*ptr == '_') && (st.st_size - i > 5) && memcmp(ptr,
   1553 		    "_CFG_", 5) == 0) {
   1554 			/* Line found */
   1555 			char *oldptr, line[LINE_MAX + 1], uline[LINE_MAX + 1];
   1556 			int j;
   1557 
   1558 			found = 1;
   1559 
   1560 			oldptr = (ptr += 5);
   1561 			while (*ptr != '\n' && *ptr != '\0')
   1562 				ptr++;
   1563 			if (ptr - oldptr > LINE_MAX)
   1564 				errx(EXIT_FAILURE, "line too long");
   1565 			i += ptr - oldptr + 5;
   1566 			(void)memcpy(line, oldptr, (size_t)(ptr - oldptr));
   1567 			line[ptr - oldptr] = '\0';
   1568 			j = strunvis(uline, line);
   1569 			if (j == -1)
   1570 				errx(EXIT_FAILURE, "unvis: invalid "
   1571 				    "encoded sequence");
   1572 			uline[j] = '\n';
   1573 			if (write(cfd, uline, (size_t)j + 1) == -1)
   1574 				err(EXIT_FAILURE, "cannot write to %s", cname);
   1575 		} else
   1576 			ptr++;
   1577 	}
   1578 
   1579 	(void)close(kfd);
   1580 
   1581 	return found;
   1582 }
   1583 
   1584 struct dhdi_params {
   1585 	struct devbase *d;
   1586 	int unit;
   1587 	int level;
   1588 };
   1589 
   1590 static int
   1591 devbase_has_dead_instances(const char *key, void *value, void *aux)
   1592 {
   1593 	struct devi *i;
   1594 	struct dhdi_params *dhdi = aux;
   1595 
   1596 	for (i = value; i != NULL; i = i->i_alias)
   1597 		if (i->i_base == dhdi->d &&
   1598 		    (dhdi->unit == WILD || dhdi->unit == i->i_unit ||
   1599 		     i->i_unit == STAR) &&
   1600 		    i->i_level >= dhdi->level)
   1601 			return 1;
   1602 	return 0;
   1603 }
   1604 
   1605 /*
   1606  * This is almost the same as devbase_has_instances, except it
   1607  * may have special considerations regarding ignored instances.
   1608  */
   1609 
   1610 static int
   1611 devbase_has_any_instance(struct devbase *dev, int unit, int state, int level)
   1612 {
   1613 	struct deva *da;
   1614 	struct devi *i;
   1615 
   1616 	if (dev->d_ispseudo) {
   1617 		if (dev->d_ihead != NULL)
   1618 			return 1;
   1619 		else if (state != DEVI_IGNORED)
   1620 			return 0;
   1621 		if ((i = ht_lookup(deaddevitab, dev->d_name)) == NULL)
   1622 			return 0;
   1623 		return (i->i_level >= level);
   1624 	}
   1625 
   1626 	for (da = dev->d_ahead; da != NULL; da = da->d_bsame)
   1627 		for (i = da->d_ihead; i != NULL; i = i->i_asame)
   1628 			if ((i->i_active == DEVI_ACTIVE ||
   1629 			     i->i_active == state) &&
   1630 			    (unit == WILD || unit == i->i_unit ||
   1631 			     i->i_unit == STAR))
   1632 				return 1;
   1633 
   1634 	if (state == DEVI_IGNORED) {
   1635 		struct dhdi_params dhdi = { dev, unit, level };
   1636 		/* also check dead devices */
   1637 		return ht_enumerate(deaddevitab, devbase_has_dead_instances,
   1638 		    &dhdi);
   1639 	}
   1640 
   1641 	return 0;
   1642 }
   1643 
   1644 /*
   1645  * check_dead_devi(), used with ht_enumerate, checks if any of the removed
   1646  * device instances would have been a valid instance considering the devbase,
   1647  * the parent device and the interface attribute.
   1648  *
   1649  * In other words, for a non-active device, it checks if children would be
   1650  * actual orphans or the result of a negative statement in the config file.
   1651  */
   1652 
   1653 struct cdd_params {
   1654 	struct devbase *d;
   1655 	struct attr *at;
   1656 	struct devbase *parent;
   1657 };
   1658 
   1659 static int
   1660 check_dead_devi(const char *key, void *value, void *aux)
   1661 {
   1662 	struct cdd_params *cdd = aux;
   1663 	struct devi *i = value;
   1664 	struct pspec *p;
   1665 
   1666 	if (i->i_base != cdd->d)
   1667 		return 0;
   1668 
   1669 	for (; i != NULL; i = i->i_alias) {
   1670 		p = i->i_pspec;
   1671 		if ((p == NULL && cdd->at == NULL) ||
   1672 		    (p != NULL && p->p_iattr == cdd->at &&
   1673 		     (p->p_atdev == NULL || p->p_atdev == cdd->parent))) {
   1674 			if (p != NULL &&
   1675 			    !devbase_has_any_instance(cdd->parent, p->p_atunit,
   1676 			    DEVI_IGNORED, i->i_level))
   1677 				return 0;
   1678 			else
   1679 				return 1;
   1680 		}
   1681 	}
   1682 	return 0;
   1683 }
   1684 
   1685 static void
   1686 do_kill_orphans(struct devbase *d, struct attr *at, struct devbase *parent,
   1687     int state)
   1688 {
   1689 	struct nvlist *nv1;
   1690 	struct attrlist *al;
   1691 	struct attr *a;
   1692 	struct devi *i, *j = NULL;
   1693 	struct pspec *p;
   1694 	int active = 0;
   1695 
   1696 	/*
   1697 	 * A pseudo-device will always attach at root, and if it has an
   1698 	 * instance (it cannot have more than one), it is enough to consider
   1699 	 * it active, as there is no real attachment.
   1700 	 *
   1701 	 * A pseudo device can never be marked DEVI_IGNORED.
   1702 	 */
   1703 	if (d->d_ispseudo) {
   1704 		if (d->d_ihead != NULL)
   1705 			d->d_ihead->i_active = active = DEVI_ACTIVE;
   1706 		else {
   1707 			if (ht_lookup(deaddevitab, d->d_name) != NULL)
   1708 				active = DEVI_IGNORED;
   1709 			else
   1710 				return;
   1711 		}
   1712 	} else {
   1713 		int seen = 0;
   1714 
   1715 		for (i = d->d_ihead; i != NULL; i = i->i_bsame) {
   1716 			for (j = i; j != NULL; j = j->i_alias) {
   1717 				p = j->i_pspec;
   1718 				if ((p == NULL && at == NULL) ||
   1719 				    (p != NULL && p->p_iattr == at &&
   1720 				    (p->p_atdev == NULL ||
   1721 				    p->p_atdev == parent))) {
   1722 					if (p != NULL &&
   1723 					    !devbase_has_any_instance(parent,
   1724 					      p->p_atunit, state, j->i_level))
   1725 						continue;
   1726 					/*
   1727 					 * There are Fry-like devices which can
   1728 					 * be their own grand-parent (or even
   1729 					 * parent, like uhub).  We don't want
   1730 					 * to loop, so if we've already reached
   1731 					 * an instance for one reason or
   1732 					 * another, stop there.
   1733 					 */
   1734 					if (j->i_active == DEVI_ACTIVE ||
   1735 					    j->i_active == state) {
   1736 						/*
   1737 						 * Device has already been
   1738 						 * seen.  However it might
   1739 						 * have siblings who still
   1740 						 * have to be activated or
   1741 						 * orphaned.
   1742 						 */
   1743 						seen = 1;
   1744 						continue;
   1745 					}
   1746 					j->i_active = active = state;
   1747 					if (p != NULL)
   1748 						p->p_active = state;
   1749 				}
   1750 			}
   1751 		}
   1752 		/*
   1753 		 * If we've been there but have made no change, stop.
   1754 		 */
   1755 		if (seen && !active)
   1756 			return;
   1757 		if (!active) {
   1758 			struct cdd_params cdd = { d, at, parent };
   1759 			/* Look for a matching dead devi */
   1760 			if (ht_enumerate(deaddevitab, check_dead_devi, &cdd) &&
   1761 			    d != parent)
   1762 				/*
   1763 				 * That device had its instances removed.
   1764 				 * Continue the loop marking descendants
   1765 				 * with DEVI_IGNORED instead of DEVI_ACTIVE.
   1766 				 *
   1767 				 * There is one special case for devices that
   1768 				 * are their own parent:  if that instance is
   1769 				 * removed (e.g., no uhub* at uhub?), we don't
   1770 				 * have to continue looping.
   1771 				 */
   1772 				active = DEVI_IGNORED;
   1773 			else
   1774 				return;
   1775 		}
   1776 	}
   1777 
   1778 	for (al = d->d_attrs; al != NULL; al = al->al_next) {
   1779 		a = al->al_this;
   1780 		for (nv1 = a->a_devs; nv1 != NULL; nv1 = nv1->nv_next)
   1781 			do_kill_orphans(nv1->nv_ptr, a, d, active);
   1782 	}
   1783 }
   1784 
   1785 static int
   1786 /*ARGSUSED*/
   1787 kill_orphans_cb(const char *key, void *value, void *aux)
   1788 {
   1789 	do_kill_orphans((struct devbase *)value, NULL, NULL, DEVI_ACTIVE);
   1790 	return 0;
   1791 }
   1792 
   1793 static void
   1794 kill_orphans(void)
   1795 {
   1796 	ht_enumerate(devroottab, kill_orphans_cb, NULL);
   1797 }
   1798 
   1799 static void
   1800 add_makeopt(const char *opt)
   1801 {
   1802 	struct nvlist *p;
   1803 	char *buf = estrdup(opt);
   1804 	char *eq = strchr(buf, '=');
   1805 
   1806 	if (!eq)
   1807 		errx(EXIT_FAILURE, "-D %s is not in var=value format", opt);
   1808 
   1809 	*eq = 0;
   1810 	p = newnv(estrdup(buf), estrdup(eq+1), NULL, 0, NULL);
   1811 	free(buf);
   1812 	p->nv_next = cmdlinedefs;
   1813 	cmdlinedefs = p;
   1814 }
   1815 
   1816 static void
   1817 remove_makeopt(const char *opt)
   1818 {
   1819 	struct nvlist *p;
   1820 
   1821 	p = newnv(estrdup(opt), NULL, NULL, 0, NULL);
   1822 	p->nv_next = cmdlineundefs;
   1823 	cmdlineundefs = p;
   1824 }
   1825 
   1826 static void
   1827 handle_cmdline_makeoptions(void)
   1828 {
   1829 	struct nvlist *p, *n;
   1830 
   1831 	handling_cmdlineopts = 1;
   1832 	for (p = cmdlineundefs; p; p = n) {
   1833 		n = p->nv_next;
   1834 		delmkoption(intern(p->nv_name));
   1835 		free(__UNCONST(p->nv_name));
   1836 		nvfree(p);
   1837 	}
   1838 	for (p = cmdlinedefs; p; p = n) {
   1839 		const char *name = intern(p->nv_name);
   1840 
   1841 		n = p->nv_next;
   1842 		delmkoption(name);
   1843 		addmkoption(name, intern(p->nv_str));
   1844 		free(__UNCONST(p->nv_name));
   1845 		free(__UNCONST(p->nv_str));
   1846 
   1847 		nvfree(p);
   1848 	}
   1849 	handling_cmdlineopts = 0;
   1850 }
   1851