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