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