2 * Copyright (c) 2002 Poul-Henning Kamp
3 * Copyright (c) 2002 Networks Associates Technology, Inc.
6 * This software was developed for the FreeBSD Project by Poul-Henning Kamp
7 * and NAI Labs, the Security Research Division of Network Associates, Inc.
8 * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9 * DARPA CHATS research program.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior written
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1986, 1992, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
66 #include <sys/param.h>
68 #include <sys/kerneldump.h>
69 #include <sys/mount.h>
87 /* The size of the buffer used for I/O. */
88 #define BUFFERSIZE (1024*1024)
92 #define STATUS_UNKNOWN 2
94 static int checkfor, compress, clear, force, keep, verbose; /* flags */
95 static int nfound, nsaved, nerr; /* statistics */
98 extern FILE *zopen(const char *, const char *);
100 static sig_atomic_t got_siginfo;
101 static void infohandler(int);
104 printheader(xo_handle_t *xo, const struct kerneldumpheader *h,
105 const char *device, int bounds, const int status)
109 const char *stat_str;
112 xo_emit_h(xo, "{Lwc:Dump header from device}{:dump_device/%s}\n",
114 xo_emit_h(xo, "{P: }{Lwc:Architecture}{:architecture/%s}\n",
117 "{P: }{Lwc:Architecture Version}{:architecture_version/%u}\n",
118 dtoh32(h->architectureversion));
119 dumplen = dtoh64(h->dumplength);
120 xo_emit_h(xo, "{P: }{Lwc:Dump Length}{:dump_length_bytes/%lld}\n",
122 xo_emit_h(xo, "{P: }{Lwc:Blocksize}{:blocksize/%d}\n",
123 dtoh32(h->blocksize));
125 t = dtoh64(h->dumptime);
126 xo_emit_h(xo, "{P: }{Lwc:Dumptime}{:dumptime/%s}", ctime(&t));
127 xo_emit_h(xo, "{P: }{Lwc:Hostname}{:hostname/%s}\n", h->hostname);
128 xo_emit_h(xo, "{P: }{Lwc:Magic}{:magic/%s}\n", h->magic);
129 xo_emit_h(xo, "{P: }{Lwc:Version String}{:version_string/%s}",
131 xo_emit_h(xo, "{P: }{Lwc:Panic String}{:panic_string/%s}\n",
133 xo_emit_h(xo, "{P: }{Lwc:Dump Parity}{:dump_parity/%u}\n", h->parity);
134 xo_emit_h(xo, "{P: }{Lwc:Bounds}{:bounds/%d}\n", bounds);
144 stat_str = "unknown";
147 xo_emit_h(xo, "{P: }{Lwc:Dump Status}{:dump_status/%s}\n", stat_str);
160 if ((fp = fopen("bounds", "r")) == NULL) {
162 printf("unable to open bounds file, using 0\n");
166 if (fgets(buf, sizeof buf, fp) == NULL) {
168 syslog(LOG_WARNING, "bounds file is empty, using 0");
170 syslog(LOG_WARNING, "bounds file: %s", strerror(errno));
176 ret = (int)strtol(buf, NULL, 10);
177 if (ret == 0 && (errno == EINVAL || errno == ERANGE))
178 syslog(LOG_WARNING, "invalid value found in bounds, using 0");
184 writebounds(int bounds)
188 if ((fp = fopen("bounds", "w")) == NULL) {
189 syslog(LOG_WARNING, "unable to write to bounds file: %m");
194 printf("bounds number: %d\n", bounds);
196 fprintf(fp, "%d\n", bounds);
201 writekey(const char *keyname, uint8_t *dumpkey, uint32_t dumpkeysize)
205 fd = open(keyname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
207 syslog(LOG_ERR, "Unable to open %s to write the key: %m.",
212 if (write(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
213 syslog(LOG_ERR, "Unable to write the key to %s: %m.", keyname);
223 file_size(const char *path)
227 /* Ignore all errors, those file may not exists. */
228 if (stat(path, &sb) == -1)
234 saved_dump_size(int bounds)
236 static char path[PATH_MAX];
241 (void)snprintf(path, sizeof(path), "info.%d", bounds);
242 dumpsize += file_size(path);
243 (void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
244 dumpsize += file_size(path);
245 (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
246 dumpsize += file_size(path);
247 (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
248 dumpsize += file_size(path);
249 (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
250 dumpsize += file_size(path);
256 saved_dump_remove(int bounds)
258 static char path[PATH_MAX];
260 (void)snprintf(path, sizeof(path), "info.%d", bounds);
262 (void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
264 (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
266 (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
268 (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
273 symlinks_remove(void)
276 (void)unlink("info.last");
277 (void)unlink("key.last");
278 (void)unlink("vmcore.last");
279 (void)unlink("vmcore.last.gz");
280 (void)unlink("vmcore_encrypted.last");
281 (void)unlink("vmcore_encrypted.last.gz");
282 (void)unlink("textdump.tar.last");
283 (void)unlink("textdump.tar.last.gz");
287 * Check that sufficient space is available on the disk that holds the
291 check_space(const char *savedir, off_t dumpsize, int bounds)
294 off_t available, minfree, spacefree, totfree, needed;
298 if (statfs(".", &fsbuf) < 0) {
299 syslog(LOG_ERR, "%s: %m", savedir);
302 spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
303 totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
305 if ((fp = fopen("minfree", "r")) == NULL)
308 if (fgets(buf, sizeof(buf), fp) == NULL)
314 minfree = strtoll(buf, &endp, 10);
315 if (minfree == 0 && errno != 0)
318 while (*endp != '\0' && isspace(*endp))
320 if (*endp != '\0' || minfree < 0)
325 "`minfree` didn't contain a valid size "
326 "(`%s`). Defaulting to 0", buf);
331 available = minfree > 0 ? spacefree - minfree : totfree;
332 needed = dumpsize / 1024 + 2; /* 2 for info file */
333 needed -= saved_dump_size(bounds);
334 if (available < needed) {
336 "no dump: not enough free space on device (need at least "
337 "%jdkB for dump; %jdkB available; %jdkB reserved)",
339 (intmax_t)available + minfree,
343 if (spacefree - needed < 0)
345 "dump performed, but free space threshold crossed");
350 compare_magic(const struct kerneldumpheader *kdh, const char *magic)
353 return (strncmp(kdh->magic, magic, sizeof(kdh->magic)) == 0);
356 #define BLOCKSIZE (1<<12)
357 #define BLOCKMASK (~(BLOCKSIZE-1))
360 DoRegularFile(int fd, bool isencrypted, off_t dumpsize, char *buf,
361 const char *device, const char *filename, FILE *fp)
363 int he, hs, nr, nw, wl;
364 off_t dmpcnt, origsize;
369 while (dumpsize > 0) {
373 nr = read(fd, buf, wl);
377 "WARNING: EOF on dump device");
379 syslog(LOG_ERR, "read error on %s: %m", device);
383 if (compress || isencrypted) {
384 nw = fwrite(buf, 1, wl, fp);
386 for (nw = 0; nw < nr; nw = he) {
387 /* find a contiguous block of zeroes */
388 for (hs = nw; hs < nr; hs += BLOCKSIZE) {
389 for (he = hs; he < nr && buf[he] == 0;
392 /* is the hole long enough to matter? */
393 if (he >= hs + BLOCKSIZE)
397 /* back down to a block boundary */
401 * 1) Don't go beyond the end of the buffer.
402 * 2) If the end of the buffer is less than
403 * BLOCKSIZE bytes away, we're at the end
404 * of the file, so just grab what's left.
406 if (hs + BLOCKSIZE > nr)
410 * At this point, we have a partial ordering:
411 * nw <= hs <= he <= nr
412 * If hs > nw, buf[nw..hs] contains non-zero
413 * data. If he > hs, buf[hs..he] is all zeroes.
416 if (fwrite(buf + nw, hs - nw, 1, fp)
420 if (fseeko(fp, he - hs, SEEK_CUR) == -1)
426 "write error on %s file: %m", filename);
428 "WARNING: vmcore may be incomplete");
434 printf("%llu\r", (unsigned long long)dmpcnt);
439 printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
440 (double)dumpsize / (double)origsize)));
448 * Specialized version of dump-reading logic for use with textdumps, which
449 * are written backwards from the end of the partition, and must be reversed
450 * before being written to the file. Textdumps are small, so do a bit less
451 * work to optimize/sparsify.
454 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
455 const char *device, const char *filename, FILE *fp)
458 off_t dmpcnt, totsize;
463 if ((dumpsize % wl) != 0) {
464 syslog(LOG_ERR, "textdump uneven multiple of 512 on %s",
469 while (dumpsize > 0) {
470 nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
474 "WARNING: EOF on dump device");
476 syslog(LOG_ERR, "read error on %s: %m", device);
480 nw = fwrite(buf, 1, wl, fp);
483 "write error on %s file: %m", filename);
485 "WARNING: textdump may be incomplete");
491 printf("%llu\r", (unsigned long long)dmpcnt);
500 DoFile(const char *savedir, const char *device)
502 xo_handle_t *xostdout, *xoinfo;
503 static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
504 static char keyname[PATH_MAX];
505 static char *buf = NULL;
507 struct kerneldumpheader kdhf, kdhl;
509 off_t mediasize, dumpsize, firsthd, lasthd;
512 int fd, fdinfo, error;
514 u_int sectorsize, xostyle;
516 uint32_t dumpkeysize;
517 bool isencrypted, ret;
519 bounds = getbounds();
522 status = STATUS_UNKNOWN;
524 xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0);
525 if (xostdout == NULL) {
526 syslog(LOG_ERR, "%s: %m", infoname);
530 if (maxdumps > 0 && bounds == maxdumps)
534 buf = malloc(BUFFERSIZE);
536 syslog(LOG_ERR, "%m");
542 printf("checking for kernel dump on device %s\n", device);
544 fd = open(device, (checkfor || keep) ? O_RDONLY : O_RDWR);
546 syslog(LOG_ERR, "%s: %m", device);
550 error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
552 error = ioctl(fd, DIOCGSECTORSIZE, §orsize);
555 "couldn't find media and/or sector size of %s: %m", device);
560 printf("mediasize = %lld bytes\n", (long long)mediasize);
561 printf("sectorsize = %u bytes\n", sectorsize);
564 if (sectorsize < sizeof(kdhl)) {
566 "Sector size is less the kernel dump header %zu",
571 lasthd = mediasize - sectorsize;
572 temp = malloc(sectorsize);
574 syslog(LOG_ERR, "%m");
577 if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
578 read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
580 "error reading last dump header at offset %lld in %s: %m",
581 (long long)lasthd, device);
584 memcpy(&kdhl, temp, sizeof(kdhl));
586 if (compare_magic(&kdhl, TEXTDUMPMAGIC)) {
588 printf("textdump magic on last dump header on %s\n",
591 if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
593 "unknown version (%d) in last dump header on %s",
594 dtoh32(kdhl.version), device);
600 } else if (compare_magic(&kdhl, KERNELDUMPMAGIC)) {
601 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
603 "unknown version (%d) in last dump header on %s",
604 dtoh32(kdhl.version), device);
612 printf("magic mismatch on last dump header on %s\n",
619 if (compare_magic(&kdhl, KERNELDUMPMAGIC_CLEARED)) {
621 printf("forcing magic on %s\n", device);
622 memcpy(kdhl.magic, KERNELDUMPMAGIC,
625 syslog(LOG_ERR, "unable to force dump - bad magic");
628 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
630 "unknown version (%d) in last dump header on %s",
631 dtoh32(kdhl.version), device);
643 if (kerneldump_parity(&kdhl)) {
645 "parity error on last dump header on %s", device);
651 dumpsize = dtoh64(kdhl.dumplength);
652 dumpkeysize = dtoh32(kdhl.dumpkeysize);
653 firsthd = lasthd - dumpsize - sectorsize - dumpkeysize;
654 if (lseek(fd, firsthd, SEEK_SET) != firsthd ||
655 read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
657 "error reading first dump header at offset %lld in %s: %m",
658 (long long)firsthd, device);
662 memcpy(&kdhf, temp, sizeof(kdhf));
665 printf("First dump headers:\n");
666 printheader(xostdout, &kdhf, device, bounds, -1);
668 printf("\nLast dump headers:\n");
669 printheader(xostdout, &kdhl, device, bounds, -1);
673 if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) {
675 "first and last dump headers disagree on %s", device);
681 status = STATUS_GOOD;
685 printf("A dump exists on %s\n", device);
690 if (kdhl.panicstring[0] != '\0')
691 syslog(LOG_ALERT, "reboot after panic: %.*s",
692 (int)sizeof(kdhl.panicstring), kdhl.panicstring);
694 syslog(LOG_ALERT, "reboot");
697 printf("Checking for available free space\n");
699 if (!check_space(savedir, dumpsize, bounds)) {
704 writebounds(bounds + 1);
706 saved_dump_remove(bounds);
708 snprintf(infoname, sizeof(infoname), "info.%d", bounds);
711 * Create or overwrite any existing dump header files.
713 fdinfo = open(infoname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
715 syslog(LOG_ERR, "%s: %m", infoname);
720 oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file. */
721 isencrypted = (dumpkeysize > 0);
723 snprintf(corename, sizeof(corename), "%s.%d.gz",
724 istextdump ? "textdump.tar" :
725 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
726 fp = zopen(corename, "w");
728 snprintf(corename, sizeof(corename), "%s.%d",
729 istextdump ? "textdump.tar" :
730 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
731 fp = fopen(corename, "w");
734 syslog(LOG_ERR, "%s: %m", corename);
741 info = fdopen(fdinfo, "w");
744 syslog(LOG_ERR, "fdopen failed: %m");
749 xostyle = xo_get_style(NULL);
750 xoinfo = xo_create_to_file(info, xostyle, 0);
751 if (xoinfo == NULL) {
752 syslog(LOG_ERR, "%s: %m", infoname);
756 xo_open_container_h(xoinfo, "crashdump");
759 printheader(xostdout, &kdhl, device, bounds, status);
761 printheader(xoinfo, &kdhl, device, bounds, status);
762 xo_close_container_h(xoinfo, "crashdump");
768 dumpkey = calloc(1, dumpkeysize);
769 if (dumpkey == NULL) {
770 syslog(LOG_ERR, "Unable to allocate kernel dump key.");
775 if (read(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
776 syslog(LOG_ERR, "Unable to read kernel dump key: %m.");
781 snprintf(keyname, sizeof(keyname), "key.%d", bounds);
782 ret = writekey(keyname, dumpkey, dumpkeysize);
783 explicit_bzero(dumpkey, dumpkeysize);
790 syslog(LOG_NOTICE, "writing %s%score to %s/%s",
791 isencrypted ? "encrypted " : "", compress ? "compressed " : "",
795 if (DoTextdumpFile(fd, dumpsize, lasthd, buf, device,
799 if (DoRegularFile(fd, isencrypted, dumpsize, buf, device,
807 if (fclose(fp) < 0) {
808 syslog(LOG_ERR, "error on %s: %m", corename);
814 if (symlink(infoname, "info.last") == -1) {
815 syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
816 savedir, "info.last");
819 if (symlink(keyname, "key.last") == -1) {
821 "unable to create symlink %s/%s: %m", savedir,
826 snprintf(linkname, sizeof(linkname), "%s.last.gz",
827 istextdump ? "textdump.tar" :
828 (isencrypted ? "vmcore_encrypted" : "vmcore"));
830 snprintf(linkname, sizeof(linkname), "%s.last",
831 istextdump ? "textdump.tar" :
832 (isencrypted ? "vmcore_encrypted" : "vmcore"));
834 if (symlink(corename, linkname) == -1) {
835 syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
842 printf("dump saved\n");
847 printf("clearing dump header\n");
848 memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic));
849 memcpy(temp, &kdhl, sizeof(kdhl));
850 if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
851 write(fd, temp, sectorsize) != (ssize_t)sectorsize)
853 "error while clearing the dump header: %m");
855 xo_close_container_h(xostdout, "crashdump");
856 xo_finish_h(xostdout);
874 xo_error("%s\n%s\n%s\n",
875 "usage: savecore -c [-v] [device ...]",
876 " savecore -C [-v] [device ...]",
877 " savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
882 main(int argc, char **argv)
884 const char *savedir = ".";
888 checkfor = compress = clear = force = keep = verbose = 0;
889 nfound = nsaved = nerr = 0;
891 openlog("savecore", LOG_PERROR, LOG_DAEMON);
892 signal(SIGINFO, infohandler);
894 argc = xo_parse_args(argc, argv);
898 while ((ch = getopt(argc, argv, "Ccfkm:vz")) != -1)
913 maxdumps = atoi(optarg);
915 syslog(LOG_ERR, "Invalid maxdump value");
929 if (checkfor && (clear || force || keep))
931 if (clear && (compress || keep))
933 if (maxdumps > 0 && (checkfor || clear))
937 if (argc >= 1 && !checkfor && !clear) {
938 error = chdir(argv[0]);
940 syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
952 if (strcmp(fsp->fs_vfstype, "swap") &&
953 strcmp(fsp->fs_vfstype, "dump"))
955 DoFile(savedir, fsp->fs_spec);
959 for (i = 0; i < argc; i++)
960 DoFile(savedir, argv[i]);
963 /* Emit minimal output. */
967 printf("No dump exists\n");
971 syslog(LOG_WARNING, "no dumps found");
972 } else if (nsaved == 0) {
976 "unsaved dumps found but not saved");
979 syslog(LOG_WARNING, "no unsaved dumps found");
986 infohandler(int sig __unused)