Home | History | Annotate | Line # | Download | only in savecore
savecore.c revision 1.66
      1 /*	$NetBSD: savecore.c,v 1.66 2006/03/17 01:45:51 hubertf Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1986, 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1986, 1992, 1993\n\
     35 	The Regents of the University of California.  All rights reserved.\n");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)savecore.c	8.5 (Berkeley) 4/28/95";
     41 #else
     42 __RCSID("$NetBSD: savecore.c,v 1.66 2006/03/17 01:45:51 hubertf Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 #include <sys/param.h>
     47 #include <sys/mount.h>
     48 #include <sys/msgbuf.h>
     49 #include <sys/syslog.h>
     50 #include <sys/time.h>
     51 
     52 #include <dirent.h>
     53 #include <errno.h>
     54 #include <fcntl.h>
     55 #include <nlist.h>
     56 #include <paths.h>
     57 #include <stddef.h>
     58 #include <stdio.h>
     59 #include <stdlib.h>
     60 #include <string.h>
     61 #include <time.h>
     62 #include <tzfile.h>
     63 #include <unistd.h>
     64 #include <util.h>
     65 #include <limits.h>
     66 #include <kvm.h>
     67 
     68 extern FILE *zopen(const char *fname, const char *mode);
     69 
     70 #define	KREAD(kd, addr, p)\
     71 	(kvm_read(kd, addr, (char *)(p), sizeof(*(p))) != sizeof(*(p)))
     72 
     73 struct nlist current_nl[] = {	/* Namelist for currently running system. */
     74 #define	X_DUMPDEV	0
     75 	{ "_dumpdev" },
     76 #define	X_DUMPLO	1
     77 	{ "_dumplo" },
     78 #define	X_TIME		2
     79 	{ "_time" },
     80 #define	X_DUMPSIZE	3
     81 	{ "_dumpsize" },
     82 #define	X_VERSION	4
     83 	{ "_version" },
     84 #define	X_DUMPMAG	5
     85 	{ "_dumpmag" },
     86 #define	X_PANICSTR	6
     87 	{ "_panicstr" },
     88 #define	X_PANICSTART	7
     89 	{ "_panicstart" },
     90 #define	X_PANICEND	8
     91 	{ "_panicend" },
     92 #define	X_MSGBUF	9
     93 	{ "_msgbufp" },
     94 	{ NULL },
     95 };
     96 int cursyms[] = { X_DUMPDEV, X_DUMPLO, X_VERSION, X_DUMPMAG, -1 };
     97 int dumpsyms[] = { X_TIME, X_DUMPSIZE, X_VERSION, X_PANICSTR, X_DUMPMAG, -1 };
     98 
     99 struct nlist dump_nl[] = {	/* Name list for dumped system. */
    100 	{ "_dumpdev" },		/* Entries MUST be the same as */
    101 	{ "_dumplo" },		/*	those in current_nl[].  */
    102 	{ "_time" },
    103 	{ "_dumpsize" },
    104 	{ "_version" },
    105 	{ "_dumpmag" },
    106 	{ "_panicstr" },
    107 	{ "_panicstart" },
    108 	{ "_panicend" },
    109 	{ "_msgbufp" },
    110 	{ NULL },
    111 };
    112 
    113 /* Types match kernel declarations. */
    114 off_t	dumplo;				/* where dump starts on dumpdev */
    115 u_int32_t dumpmag;			/* magic number in dump */
    116 int	dumpsize;			/* amount of memory dumped */
    117 off_t dumpbytes;			/* in bytes */
    118 
    119 const char	*kernel;		/* name of used kernel */
    120 char	*dirname;			/* directory to save dumps in */
    121 char	*ddname;			/* name of dump device */
    122 dev_t	dumpdev;			/* dump device */
    123 int	dumpfd;				/* read/write descriptor on block dev */
    124 kvm_t	*kd_dump;			/* kvm descriptor on block dev	*/
    125 time_t	now;				/* current date */
    126 char	panic_mesg[1024];
    127 long	panicstr;
    128 char	vers[1024];
    129 char	gzmode[3];
    130 
    131 static int	clear, compress, force, verbose;	/* flags */
    132 
    133 void	check_kmem(void);
    134 int	check_space(void);
    135 void	clear_dump(void);
    136 int	Create(char *, int);
    137 int	dump_exists(void);
    138 char	*find_dev(dev_t, int);
    139 int	get_crashtime(void);
    140 void	kmem_setup(void);
    141 void	Lseek(int, off_t, int);
    142 int	main(int, char *[]);
    143 int	Open(const char *, int rw);
    144 char	*rawname(char *s);
    145 void	save_core(void);
    146 void	usage(void);
    147 void	Write(int, void *, int);
    148 
    149 int
    150 main(int argc, char *argv[])
    151 {
    152 	int ch, level, testonly;
    153 	char *ep;
    154 
    155 	dirname = NULL;
    156 	kernel = NULL;
    157 	level = 1;		/* default to fastest gzip compression */
    158 	testonly = 0;
    159 	gzmode[0] = 'w';
    160 
    161 	openlog("savecore", LOG_PERROR, LOG_DAEMON);
    162 
    163 	while ((ch = getopt(argc, argv, "cdfnN:vzZ:")) != -1)
    164 		switch(ch) {
    165 		case 'c':
    166 			clear = 1;
    167 			break;
    168 		case 'd':		/* Not documented. */
    169 		case 'v':
    170 			verbose = 1;
    171 			break;
    172 		case 'f':
    173 			force = 1;
    174 			break;
    175 		case 'n':
    176 			testonly = 1;
    177 			break;
    178 		case 'N':
    179 			kernel = optarg;
    180 			break;
    181 		case 'z':
    182 			compress = 1;
    183 			break;
    184 		case 'Z':
    185 			level = (int)strtol(optarg, &ep, 10);
    186 			if (level < 0 || level > 9) {
    187 				(void)syslog(LOG_ERR, "invalid compression %s",
    188 				    optarg);
    189 				usage();
    190 			}
    191 			break;
    192 		case '?':
    193 		default:
    194 			usage();
    195 		}
    196 	argc -= optind;
    197 	argv += optind;
    198 
    199 	if (argc != ((clear || testonly) ? 0 : 1))
    200 		usage();
    201 
    202 	gzmode[1] = level + '0';
    203 	if (!clear)
    204 		dirname = argv[0];
    205 
    206 	if (kernel == NULL) {
    207 		kernel = getbootfile();
    208 	}
    209 
    210 	(void)time(&now);
    211 	kmem_setup();
    212 
    213 	if (clear && !testonly) {
    214 		clear_dump();
    215 		exit(0);
    216 	}
    217 
    218 	if (!dump_exists() && !force)
    219 		exit(1);
    220 
    221 	if (testonly)
    222 		/* If -n was passed and there was a dump, exit at level 0 */
    223 		exit(0);
    224 
    225 	check_kmem();
    226 
    227 	if (panicstr)
    228 		syslog(LOG_ALERT, "reboot after panic: %s", panic_mesg);
    229 	else
    230 		syslog(LOG_ALERT, "reboot");
    231 
    232 	if ((!get_crashtime() || !check_space()) && !force)
    233 		exit(1);
    234 
    235 	save_core();
    236 
    237 	clear_dump();
    238 	exit(0);
    239 }
    240 
    241 void
    242 kmem_setup(void)
    243 {
    244 	kvm_t *kd_kern;
    245 	char errbuf[_POSIX2_LINE_MAX];
    246 	int i, hdrsz;
    247 
    248 	/*
    249 	 * Some names we need for the currently running system, others for
    250 	 * the system that was running when the dump was made.  The values
    251 	 * obtained from the current system are used to look for things in
    252 	 * /dev/kmem that cannot be found in the kernel namelist, but are
    253 	 * presumed to be the same (since the disk partitions are probably
    254 	 * the same!)
    255 	 */
    256 	kd_kern = kvm_openfiles(kernel, NULL, NULL, O_RDONLY, errbuf);
    257 	if (kd_kern == NULL) {
    258 		syslog(LOG_ERR, "%s: kvm_openfiles: %s", kernel, errbuf);
    259 		exit(1);
    260 	}
    261 	if (kvm_nlist(kd_kern, current_nl) == -1)
    262 		syslog(LOG_ERR, "%s: kvm_nlist: %s", kernel,
    263 		    kvm_geterr(kd_kern));
    264 
    265 	for (i = 0; cursyms[i] != -1; i++)
    266 		if (current_nl[cursyms[i]].n_value == 0) {
    267 			syslog(LOG_ERR, "%s: %s not in namelist",
    268 			    kernel, current_nl[cursyms[i]].n_name);
    269 			exit(1);
    270 		}
    271 
    272 	if (KREAD(kd_kern, current_nl[X_DUMPDEV].n_value, &dumpdev) != 0) {
    273 		if (verbose)
    274 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_kern));
    275 		exit(1);
    276 	}
    277 	if (dumpdev == NODEV) {
    278 		syslog(LOG_WARNING, "no core dump (no dumpdev)");
    279 		exit(1);
    280 	}
    281 	{
    282 	    long l_dumplo;
    283 
    284 	    if (KREAD(kd_kern, current_nl[X_DUMPLO].n_value, &l_dumplo) != 0) {
    285 		    if (verbose)
    286 			syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_kern));
    287 		    exit(1);
    288 	    }
    289 	    if (l_dumplo == -1) {
    290 		syslog(LOG_WARNING, "no core dump (invalid dumplo)");
    291 		exit(1);
    292 	    }
    293 	    dumplo = DEV_BSIZE * (off_t) l_dumplo;
    294 	}
    295 
    296 	if (verbose)
    297 		(void)printf("dumplo = %lld (%ld * %ld)\n",
    298 		    (long long)dumplo, (long)(dumplo / DEV_BSIZE), (long)DEV_BSIZE);
    299 	if (KREAD(kd_kern, current_nl[X_DUMPMAG].n_value, &dumpmag) != 0) {
    300 		if (verbose)
    301 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_kern));
    302 		exit(1);
    303 	}
    304 
    305 	(void)kvm_read(kd_kern, current_nl[X_VERSION].n_value, vers,
    306 	    sizeof(vers));
    307 	vers[sizeof(vers) - 1] = '\0';
    308 
    309 	ddname = find_dev(dumpdev, S_IFBLK);
    310 	dumpfd = Open(ddname, O_RDWR);
    311 
    312 	kd_dump = kvm_openfiles(kernel, ddname, NULL, O_RDWR, errbuf);
    313 	if (kd_dump == NULL) {
    314 		syslog(LOG_ERR, "%s: kvm_openfiles: %s", kernel, errbuf);
    315 		exit(1);
    316 	}
    317 
    318 	if (kvm_nlist(kd_dump, dump_nl) == -1)
    319 		syslog(LOG_ERR, "%s: kvm_nlist: %s", kernel,
    320 		    kvm_geterr(kd_dump));
    321 
    322 	for (i = 0; dumpsyms[i] != -1; i++)
    323 		if (dump_nl[dumpsyms[i]].n_value == 0) {
    324 			syslog(LOG_ERR, "%s: %s not in namelist",
    325 			    kernel, dump_nl[dumpsyms[i]].n_name);
    326 			exit(1);
    327 		}
    328 	hdrsz = kvm_dump_mkheader(kd_dump, dumplo);
    329 
    330 	/*
    331 	 * If 'hdrsz' == 0, kvm_dump_mkheader() failed on the magic-number
    332 	 * checks, ergo no dump is present...
    333 	 */
    334 	if (hdrsz == 0) {
    335 		syslog(LOG_WARNING, "no core dump");
    336 		exit(1);
    337 	}
    338 	if (hdrsz == -1) {
    339 		syslog(LOG_ERR, "%s: kvm_dump_mkheader: %s", kernel,
    340 		    kvm_geterr(kd_dump));
    341 		exit(1);
    342 	}
    343 	dumplo += hdrsz;
    344 	kvm_close(kd_kern);
    345 }
    346 
    347 void
    348 check_kmem(void)
    349 {
    350 	char *cp, *bufdata;
    351 	struct kern_msgbuf msgbuf, *bufp;
    352 	long panicloc, panicstart, panicend;
    353 	char core_vers[1024];
    354 
    355 	(void)kvm_read(kd_dump, dump_nl[X_VERSION].n_value, core_vers,
    356 	    sizeof(core_vers));
    357 	core_vers[sizeof(core_vers) - 1] = '\0';
    358 
    359 	if (strcmp(vers, core_vers) != 0)
    360 		syslog(LOG_WARNING,
    361 		    "warning: %s version mismatch:\n\t%s\nand\t%s\n",
    362 		    kernel, vers, core_vers);
    363 
    364 	panicstart = panicend = 0;
    365 	if (KREAD(kd_dump, dump_nl[X_PANICSTART].n_value, &panicstart) != 0) {
    366 		if (verbose)
    367 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    368 		goto nomsguf;
    369 	}
    370 	if (KREAD(kd_dump, dump_nl[X_PANICEND].n_value, &panicend) != 0) {
    371 		if (verbose)
    372 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    373 		goto nomsguf;
    374 	}
    375 	if (panicstart != 0 && panicend != 0) {
    376 		if (KREAD(kd_dump, dump_nl[X_MSGBUF].n_value, &bufp)) {
    377 			if (verbose)
    378 				syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    379 			goto nomsguf;
    380 		}
    381 		if (kvm_read(kd_dump, (long)bufp, &msgbuf,
    382 		    offsetof(struct kern_msgbuf, msg_bufc)) !=
    383 		    offsetof(struct kern_msgbuf, msg_bufc)) {
    384 			if (verbose)
    385 				syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    386 			goto nomsguf;
    387 		}
    388 		if (msgbuf.msg_magic != MSG_MAGIC) {
    389 			if (verbose)
    390 				syslog(LOG_WARNING, "msgbuf magic incorrect");
    391 			goto nomsguf;
    392 		}
    393 		bufdata = malloc(msgbuf.msg_bufs);
    394 		if (bufdata == NULL) {
    395 			if (verbose)
    396 				syslog(LOG_WARNING, "couldn't allocate space for msgbuf data");
    397 			goto nomsguf;
    398 		}
    399 		if (kvm_read(kd_dump, (long)&bufp->msg_bufc, bufdata,
    400 		    msgbuf.msg_bufs) != msgbuf.msg_bufs) {
    401 			if (verbose)
    402 				syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    403 			free(bufdata);
    404 			goto nomsguf;
    405 		}
    406 		cp = panic_mesg;
    407 		while (panicstart != panicend && cp < &panic_mesg[sizeof(panic_mesg)-1]) {
    408 			*cp++ = bufdata[panicstart];
    409 			panicstart++;
    410 			if (panicstart >= msgbuf.msg_bufs)
    411 				panicstart = 0;
    412 		}
    413 		/* Don't end in a new-line */
    414 		cp = &panic_mesg[strlen(panic_mesg)] - 1;
    415 		if (*cp == '\n')
    416 			*cp = '\0';
    417 		panic_mesg[sizeof(panic_mesg) - 1] = '\0';
    418 		free(bufdata);
    419 
    420 		panicstr = 1;	/* anything not zero */
    421 		return;
    422 	}
    423 nomsguf:
    424 	if (KREAD(kd_dump, dump_nl[X_PANICSTR].n_value, &panicstr) != 0) {
    425 		if (verbose)
    426 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    427 		return;
    428 	}
    429 	if (panicstr) {
    430 		cp = panic_mesg;
    431 		panicloc = panicstr;
    432 		do {
    433 			if (KREAD(kd_dump, panicloc, cp) != 0) {
    434 				if (verbose)
    435 				    syslog(LOG_WARNING, "kvm_read: %s",
    436 					kvm_geterr(kd_dump));
    437 				break;
    438 			}
    439 			panicloc++;
    440 		} while (*cp++ && cp < &panic_mesg[sizeof(panic_mesg)-1]);
    441 		panic_mesg[sizeof(panic_mesg) - 1] = '\0';
    442 	}
    443 }
    444 
    445 int
    446 dump_exists(void)
    447 {
    448 	u_int32_t newdumpmag;
    449 
    450 	if (KREAD(kd_dump, dump_nl[X_DUMPMAG].n_value, &newdumpmag) != 0) {
    451 		if (verbose)
    452 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    453 		return (0);
    454 	}
    455 
    456 	/* Read the dump size. */
    457 	if (KREAD(kd_dump, dump_nl[X_DUMPSIZE].n_value, &dumpsize) != 0) {
    458 		if (verbose)
    459 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    460 		return (0);
    461 	}
    462 	dumpbytes = (off_t)dumpsize * getpagesize();
    463 
    464 	/*
    465 	 * Return zero if core dump doesn't seem to be there, and note
    466 	 * it for syslog.  This check and return happens after the dump size
    467 	 * is read, so dumpsize is whether or not the core is valid (for -f).
    468 	 */
    469 	if (newdumpmag != dumpmag) {
    470 		if (verbose)
    471 			syslog(LOG_WARNING,
    472 			    "magic number mismatch (0x%x != 0x%x)",
    473 			    newdumpmag, dumpmag);
    474 		syslog(LOG_WARNING, "no core dump");
    475 		return (0);
    476 	}
    477 	return (1);
    478 }
    479 
    480 void
    481 clear_dump(void)
    482 {
    483 	if (kvm_dump_inval(kd_dump) == -1)
    484 		syslog(LOG_ERR, "%s: kvm_clear_dump: %s", ddname,
    485 		    kvm_geterr(kd_dump));
    486 
    487 }
    488 
    489 char buf[1024 * 1024];
    490 
    491 void
    492 save_core(void)
    493 {
    494 	FILE *fp;
    495 	int bounds, ifd, nr, nw, ofd;
    496 	char *rawp, path[MAXPATHLEN];
    497 
    498 	ofd = -1;
    499 	/*
    500 	 * Get the current number and update the bounds file.  Do the update
    501 	 * now, because may fail later and don't want to overwrite anything.
    502 	 */
    503 	umask(066);
    504 	(void)snprintf(path, sizeof(path), "%s/bounds", dirname);
    505 	if ((fp = fopen(path, "r")) == NULL)
    506 		goto err1;
    507 	if (fgets(buf, sizeof(buf), fp) == NULL) {
    508 		if (ferror(fp))
    509 err1:			syslog(LOG_WARNING, "%s: %m", path);
    510 		bounds = 0;
    511 	} else
    512 		bounds = atoi(buf);
    513 	if (fp != NULL)
    514 		(void)fclose(fp);
    515 	if ((fp = fopen(path, "w")) == NULL)
    516 		syslog(LOG_ERR, "%s: %m", path);
    517 	else {
    518 		(void)fprintf(fp, "%d\n", bounds + 1);
    519 		(void)fclose(fp);
    520 	}
    521 
    522 	/* Create the core file. */
    523 	(void)snprintf(path, sizeof(path), "%s/netbsd.%d.core%s",
    524 	    dirname, bounds, compress ? ".gz" : "");
    525 	if (compress) {
    526 		if ((fp = zopen(path, gzmode)) == NULL) {
    527 			syslog(LOG_ERR, "%s: %m", path);
    528 			exit(1);
    529 		}
    530 	} else {
    531 		ofd = Create(path, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    532 		fp  = fdopen(ofd, "w");
    533 		if (fp == NULL) {
    534 			syslog(LOG_ERR, "%s: fdopen: %m", path);
    535 			exit(1);
    536 		}
    537 	}
    538 
    539 	/* Open the raw device. */
    540 	rawp = rawname(ddname);
    541 	if ((ifd = open(rawp, O_RDONLY)) == -1) {
    542 		syslog(LOG_WARNING, "%s: %m; using block device", rawp);
    543 		ifd = dumpfd;
    544 	}
    545 
    546 	/* Seek to the start of the core. */
    547 	Lseek(ifd, dumplo, SEEK_SET);
    548 
    549 	if (kvm_dump_wrtheader(kd_dump, fp, (int32_t)dumpbytes) == -1) {
    550 		syslog(LOG_ERR, "kvm_dump_wrtheader: %s : %s", path,
    551 		    kvm_geterr(kd_dump));
    552 		exit(1);
    553 	}
    554 
    555 	/* Copy the core file. */
    556 	syslog(LOG_NOTICE, "writing %score to %s",
    557 	    compress ? "compressed " : "", path);
    558 	for (; dumpbytes > (off_t)0; dumpbytes -= (off_t)nr) {
    559 		char nbuf[7];
    560 		humanize_number(nbuf, 7, dumpbytes, "", HN_AUTOSCALE, 0);
    561 		(void)printf("%7s\r", nbuf);
    562 		(void)fflush(stdout);
    563 		nr = read(ifd, buf, MIN(dumpbytes, sizeof(buf)));
    564 		if (nr <= 0) {
    565 			if (nr == 0)
    566 				syslog(LOG_WARNING,
    567 				    "WARNING: EOF on dump device");
    568 			else
    569 				syslog(LOG_ERR, "%s: %m", rawp);
    570 			goto err2;
    571 		}
    572 		nw = fwrite(buf, 1, nr, fp);
    573 		if (nw != nr) {
    574 			syslog(LOG_ERR, "%s: %s",
    575 			    path, strerror(nw == 0 ? EIO : errno));
    576 err2:			syslog(LOG_WARNING,
    577 			    "WARNING: core may be incomplete");
    578 			(void)printf("\n");
    579 			exit(1);
    580 		}
    581 	}
    582 	(void)close(ifd);
    583 	(void)fclose(fp);
    584 
    585 	/* Copy the kernel. */
    586 	ifd = Open(kernel, O_RDONLY);
    587 	(void)snprintf(path, sizeof(path), "%s/netbsd.%d%s",
    588 	    dirname, bounds, compress ? ".gz" : "");
    589 	if (compress) {
    590 		if ((fp = zopen(path, gzmode)) == NULL) {
    591 			syslog(LOG_ERR, "%s: %m", path);
    592 			exit(1);
    593 		}
    594 	} else
    595 		ofd = Create(path, S_IRUSR | S_IWUSR);
    596 	syslog(LOG_NOTICE, "writing %skernel to %s",
    597 	    compress ? "compressed " : "", path);
    598 	while ((nr = read(ifd, buf, sizeof(buf))) > 0) {
    599 		if (compress)
    600 			nw = fwrite(buf, 1, nr, fp);
    601 		else
    602 			nw = write(ofd, buf, nr);
    603 		if (nw != nr) {
    604 			syslog(LOG_ERR, "%s: %s",
    605 			    path, strerror(nw == 0 ? EIO : errno));
    606 			syslog(LOG_WARNING,
    607 			    "WARNING: kernel may be incomplete");
    608 			exit(1);
    609 		}
    610 	}
    611 	if (nr < 0) {
    612 		syslog(LOG_ERR, "%s: %m", kernel);
    613 		syslog(LOG_WARNING, "WARNING: kernel may be incomplete");
    614 		exit(1);
    615 	}
    616 	if (compress)
    617 		(void)fclose(fp);
    618 	else
    619 		(void)close(ofd);
    620 }
    621 
    622 char *
    623 find_dev(dev_t dev, int type)
    624 {
    625 	DIR *dfd;
    626 	struct dirent *dir;
    627 	struct stat sb;
    628 	char *dp, device[MAXPATHLEN + 1], *p;
    629 	size_t l;
    630 
    631 	if ((dfd = opendir(_PATH_DEV)) == NULL) {
    632 		syslog(LOG_ERR, "%s: %m", _PATH_DEV);
    633 		exit(1);
    634 	}
    635 	strlcpy(device, _PATH_DEV, sizeof(device));
    636 	p = &device[strlen(device)];
    637 	l = sizeof(device) - strlen(device);
    638 	while ((dir = readdir(dfd))) {
    639 		strlcpy(p, dir->d_name, l);
    640 		if (lstat(device, &sb)) {
    641 			syslog(LOG_ERR, "%s: %m", device);
    642 			continue;
    643 		}
    644 		if ((sb.st_mode & S_IFMT) != type)
    645 			continue;
    646 		if (dev == sb.st_rdev) {
    647 			closedir(dfd);
    648 			if ((dp = strdup(device)) == NULL) {
    649 				syslog(LOG_ERR, "%m");
    650 				exit(1);
    651 			}
    652 			return (dp);
    653 		}
    654 	}
    655 	closedir(dfd);
    656 	syslog(LOG_ERR, "can't find device %d/%d", major(dev), minor(dev));
    657 	exit(1);
    658 }
    659 
    660 char *
    661 rawname(char *s)
    662 {
    663 	char *sl;
    664 	char name[MAXPATHLEN];
    665 
    666 	if ((sl = strrchr(s, '/')) == NULL || sl[1] == '0') {
    667 		syslog(LOG_ERR,
    668 		    "can't make raw dump device name from %s", s);
    669 		return (s);
    670 	}
    671 	(void)snprintf(name, sizeof(name), "%.*s/r%s", (int)(sl - s), s,
    672 	    sl + 1);
    673 	if ((sl = strdup(name)) == NULL) {
    674 		syslog(LOG_ERR, "%m");
    675 		exit(1);
    676 	}
    677 	return (sl);
    678 }
    679 
    680 int
    681 get_crashtime(void)
    682 {
    683 	struct timeval dtime;
    684 	time_t dumptime;			/* Time the dump was taken. */
    685 
    686 	if (KREAD(kd_dump, dump_nl[X_TIME].n_value, &dtime) != 0) {
    687 		if (verbose)
    688 		    syslog(LOG_WARNING, "kvm_read: %s", kvm_geterr(kd_dump));
    689 		return (0);
    690 	}
    691 	dumptime = dtime.tv_sec;
    692 	if (dumptime == 0) {
    693 		if (verbose)
    694 			syslog(LOG_ERR, "dump time is zero");
    695 		return (0);
    696 	}
    697 	(void)printf("savecore: system went down at %s", ctime(&dumptime));
    698 #define	LEEWAY	(60 * SECSPERDAY)
    699 	if (dumptime < now - LEEWAY || dumptime > now + LEEWAY) {
    700 		(void)printf("dump time is unreasonable\n");
    701 		return (0);
    702 	}
    703 	return (1);
    704 }
    705 
    706 int
    707 check_space(void)
    708 {
    709 	FILE *fp;
    710 	off_t minfree, spacefree, kernelsize, needed;
    711 	struct stat st;
    712 	struct statvfs fsbuf;
    713 	char mbuf[100], path[MAXPATHLEN];
    714 
    715 #ifdef __GNUC__
    716 	(void) &minfree;
    717 #endif
    718 
    719 	if (stat(kernel, &st) < 0) {
    720 		syslog(LOG_ERR, "%s: %m", kernel);
    721 		exit(1);
    722 	}
    723 	kernelsize = st.st_blocks * S_BLKSIZE;
    724 	if (statvfs(dirname, &fsbuf) < 0) {
    725 		syslog(LOG_ERR, "%s: %m", dirname);
    726 		exit(1);
    727 	}
    728 	spacefree = fsbuf.f_bavail;
    729 	spacefree *= fsbuf.f_frsize;
    730 	spacefree /= 1024;
    731 
    732 	(void)snprintf(path, sizeof(path), "%s/minfree", dirname);
    733 	if ((fp = fopen(path, "r")) == NULL)
    734 		minfree = 0;
    735 	else {
    736 		if (fgets(mbuf, sizeof(mbuf), fp) == NULL)
    737 			minfree = 0;
    738 		else
    739 			minfree = atoi(mbuf);
    740 		(void)fclose(fp);
    741 	}
    742 
    743 	needed = (dumpbytes + kernelsize) / 1024;
    744  	if (minfree > 0 && spacefree - needed < minfree) {
    745 		syslog(LOG_WARNING,
    746 		    "no dump, not enough free space in %s", dirname);
    747 		return (0);
    748 	}
    749 	if (spacefree - needed < minfree)
    750 		syslog(LOG_WARNING,
    751 		    "dump performed, but free space threshold crossed");
    752 	return (1);
    753 }
    754 
    755 int
    756 Open(const char *name, int rw)
    757 {
    758 	int fd;
    759 
    760 	if ((fd = open(name, rw, 0)) < 0) {
    761 		syslog(LOG_ERR, "%s: %m", name);
    762 		exit(1);
    763 	}
    764 	return (fd);
    765 }
    766 
    767 void
    768 Lseek(int fd, off_t off, int flag)
    769 {
    770 	off_t ret;
    771 
    772 	ret = lseek(fd, off, flag);
    773 	if (ret == -1) {
    774 		syslog(LOG_ERR, "lseek: %m");
    775 		exit(1);
    776 	}
    777 }
    778 
    779 int
    780 Create(char *file, int mode)
    781 {
    782 	int fd;
    783 
    784 	fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, mode);
    785 	if (fd < 0) {
    786 		syslog(LOG_ERR, "%s: %m", file);
    787 		exit(1);
    788 	}
    789 	return (fd);
    790 }
    791 
    792 void
    793 Write(int fd, void *bp, int size)
    794 {
    795 	int n;
    796 
    797 	if ((n = write(fd, bp, size)) < size) {
    798 		syslog(LOG_ERR, "write: %s", strerror(n == -1 ? errno : EIO));
    799 		exit(1);
    800 	}
    801 }
    802 
    803 void
    804 usage(void)
    805 {
    806 	(void)syslog(LOG_ERR,
    807 	    "usage: savecore [-cfnvz] [-N system] [-Z level] directory");
    808 	exit(1);
    809 }
    810