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