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