2 * Copyright (c) 1986, 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#) Copyright (c) 1986, 1992, 1993 The Regents of the University of California. All rights reserved.
34 * @(#)savecore.c 8.3 (Berkeley) 1/2/94
35 * $FreeBSD: src/sbin/savecore/savecore.c,v 1.28.2.14 2005/01/05 09:14:34 maxim Exp $
36 * $DragonFly: src/sbin/savecore/savecore.c,v 1.12 2006/03/25 07:46:58 dillon Exp $
39 #define _KERNEL_STRUCTURES
41 #include <sys/param.h>
43 #undef _KERNEL_STRUCTURES
46 #include <sys/mount.h>
47 #include <sys/syslog.h>
48 #include <sys/sysctl.h>
51 #include <vm/vm_param.h>
64 extern FILE *zopen(const char *fname, const char *mode);
67 #define ok(number) ((number) - kernbase)
70 struct nlist current_nl[] = { /* Namelist for currently running system. */
72 { "_dumplo", 0, 0, 0, 0 },
74 { "_time_second", 0, 0, 0, 0 },
76 { "_dumpsize", 0, 0, 0, 0 },
78 { "_version", 0, 0, 0, 0 },
80 { "_panicstr", 0, 0, 0, 0 },
82 { "_dumpmag", 0, 0, 0, 0 },
84 { "_kernbase", 0, 0, 0, 0 },
86 { "_Maxmem", 0, 0, 0, 0 },
89 int cursyms[] = { X_DUMPLO, X_VERSION, X_DUMPMAG, -1 };
90 int dumpsyms[] = { X_TIME, X_DUMPSIZE, X_VERSION, X_PANICSTR, X_DUMPMAG, -1 };
92 struct nlist dump_nl[] = { /* Name list for dumped system. */
93 { "_dumplo", 0, 0, 0, 0 }, /* Entries MUST be the same as */
94 { "_time_second", 0, 0, 0, 0 }, /* those in current_nl[]. */
95 { "_dumpsize", 0, 0, 0, 0 },
96 { "_version", 0, 0, 0, 0 },
97 { "_panicstr", 0, 0, 0, 0 },
98 { "_dumpmag", 0, 0, 0, 0 },
99 { "_kernbase", 0, 0, 0, 0 },
100 { "_Maxmem", 0, 0, 0, 0 },
104 /* Types match kernel declarations. */
105 u_long dumpmag; /* magic number in dump */
107 /* Based on kernel variables, but with more convenient types. */
108 off_t dumplo; /* where dump starts on dumpdev */
109 off_t dumpsize; /* amount of memory dumped */
111 char *kernel; /* user-specified kernel */
112 char *savedir; /* directory to save dumps in */
113 char ddname[MAXPATHLEN]; /* name of dump device */
114 dev_t dumpdev; /* dump device */
115 int dumpfd; /* read/write descriptor on char dev */
116 time_t now; /* current date */
117 char panic_mesg[1024]; /* panic message */
118 int panicstr; /* flag: dump was caused by panic */
119 char vers[1024]; /* version of kernel that crashed */
120 char *physmem; /* physmem value used with dumped session */
121 long dkdumplo; /* directly specified kernel dumplo value */
124 u_long kernbase; /* offset of kvm to core file */
127 static int clear, compress, force, verbose, directdumplo; /* flags */
128 static int keep; /* keep dump on device */
130 static void check_kmem(void);
131 static int check_space(void);
132 static void clear_dump(void);
133 static void DumpRead(int fd, void *bp, int size, off_t off, int flag);
134 static void DumpWrite(int fd, void *bp, int size, off_t off, int flag);
135 static int dump_exists(void);
136 static void find_dev(dev_t);
137 static int get_crashtime(void);
138 static void get_dumpsize(void);
139 static void kmem_setup(void);
140 static void Lseek(int, off_t, int);
141 static int Open(const char *, int rw);
142 static int Read(int, void *, int);
143 static void save_core(void);
144 static void usage(void);
145 static int verify_dev(char *, dev_t);
146 static void Write(int, void *, int);
147 static void kdumplo_adjust(char *cp, int kmem, long *kdumplop);
150 main(int argc, char **argv)
155 openlog("savecore", LOG_PERROR, LOG_DAEMON);
157 while ((ch = getopt(argc, argv, "cdfkN:vzP:B:")) != -1)
162 case 'd': /* Not documented. */
183 dkdumplo = strtol(optarg, &ep, 10);
185 errx(1, "invalid offset: '%s'", optarg);
195 if (argc != 1 && argc != 2)
210 if (!dump_exists() && !force)
216 syslog(LOG_ALERT, "reboot after panic: %s", panic_mesg);
218 syslog(LOG_ALERT, "reboot");
222 if ((!get_crashtime() || !check_space()) && !force)
237 const char *dump_sys;
239 long kdumplo; /* block number where dump starts on dumpdev */
243 * Some names we need for the currently running system, others for
244 * the system that was running when the dump was made. The values
245 * obtained from the current system are used to look for things in
246 * /dev/kmem that cannot be found in the dump_sys namelist, but are
247 * presumed to be the same (since the disk partitions are probably
250 if ((nlist(getbootfile(), current_nl)) == -1)
251 syslog(LOG_ERR, "%s: nlist: %m", getbootfile());
252 for (i = 0; cursyms[i] != -1; i++)
253 if (current_nl[cursyms[i]].n_value == 0) {
254 syslog(LOG_ERR, "%s: %s not in namelist",
255 getbootfile(), current_nl[cursyms[i]].n_name);
259 dump_sys = kernel ? kernel : getbootfile();
260 if ((nlist(dump_sys, dump_nl)) == -1)
261 syslog(LOG_ERR, "%s: nlist: %m", dump_sys);
262 for (i = 0; dumpsyms[i] != -1; i++)
263 if (dump_nl[dumpsyms[i]].n_value == 0) {
264 syslog(LOG_ERR, "%s: %s not in namelist",
265 dump_sys, dump_nl[dumpsyms[i]].n_name);
270 if (dump_nl[X_KERNBASE].n_value != 0)
271 kernbase = dump_nl[X_KERNBASE].n_value;
276 len = sizeof dumpdev;
277 if (sysctlbyname("kern.dumpdev", &dumpdev, &len, NULL, 0) == -1) {
278 syslog(LOG_ERR, "sysctl: kern.dumpdev: %m");
281 if (dumpdev == NODEV) {
282 syslog(LOG_WARNING, "no core dump (no dumpdev)");
286 kmem = Open(_PATH_KMEM, O_RDONLY);
290 Lseek(kmem, (off_t)current_nl[X_DUMPLO].n_value, L_SET);
291 Read(kmem, &kdumplo, sizeof(kdumplo));
293 kdumplo_adjust(physmem, kmem, &kdumplo);
295 dumplo = (off_t)kdumplo * DEV_BSIZE;
297 printf("dumplo = %lld (%ld * %d)\n",
298 (long long)dumplo, kdumplo, DEV_BSIZE);
299 Lseek(kmem, (off_t)current_nl[X_DUMPMAG].n_value, L_SET);
300 Read(kmem, &dumpmag, sizeof(dumpmag));
302 dumpfd = Open(ddname, O_RDWR);
306 lseek(kmem, (off_t)current_nl[X_VERSION].n_value, SEEK_SET);
307 Read(kmem, vers, sizeof(vers));
308 vers[sizeof(vers) - 1] = '\0';
309 p = strchr(vers, '\n');
313 /* Don't fclose(fp), we use kmem later. */
319 char core_vers[1024], *p;
321 DumpRead(dumpfd, core_vers, sizeof(core_vers),
322 (off_t)(dumplo + ok(dump_nl[X_VERSION].n_value)), L_SET);
323 core_vers[sizeof(core_vers) - 1] = '\0';
324 p = strchr(core_vers, '\n');
327 if (strcmp(vers, core_vers) && kernel == 0)
329 "warning: %s version mismatch:\n\t\"%s\"\nand\t\"%s\"\n",
330 getbootfile(), vers, core_vers);
331 DumpRead(dumpfd, &panicstr, sizeof(panicstr),
332 (off_t)(dumplo + ok(dump_nl[X_PANICSTR].n_value)), L_SET);
334 DumpRead(dumpfd, panic_mesg, sizeof(panic_mesg),
335 (off_t)(dumplo + ok(panicstr)), L_SET);
340 * Clear the magic number in the dump header.
348 DumpWrite(dumpfd, &newdumpmag, sizeof(newdumpmag),
349 (off_t)(dumplo + ok(dump_nl[X_DUMPMAG].n_value)), L_SET);
354 * Check if a dump exists by looking for a magic number in the dump
362 DumpRead(dumpfd, &newdumpmag, sizeof(newdumpmag),
363 (off_t)(dumplo + ok(dump_nl[X_DUMPMAG].n_value)), L_SET);
364 if (newdumpmag != dumpmag) {
366 syslog(LOG_WARNING, "magic number mismatch (%lx != %lx)",
367 newdumpmag, dumpmag);
368 syslog(LOG_WARNING, "no core dump");
374 char buf[1024 * 1024];
375 #define BLOCKSIZE (1<<12)
376 #define BLOCKMASK (~(BLOCKSIZE-1))
379 * Save the core dump.
385 int bounds, ifd, nr, nw;
386 int hs, he = 0; /* start and end of hole */
387 char path[MAXPATHLEN];
391 * Get the current number and update the bounds file. Do the update
392 * now, because may fail later and don't want to overwrite anything.
394 snprintf(path, sizeof(path), "%s/bounds", savedir);
395 if ((fp = fopen(path, "r")) == NULL)
397 if (fgets(buf, sizeof(buf), fp) == NULL) {
399 err1: syslog(LOG_WARNING, "%s: %m", path);
405 if ((fp = fopen(path, "w")) == NULL)
406 syslog(LOG_ERR, "%s: %m", path);
408 fprintf(fp, "%d\n", bounds + 1);
412 /* Create the core file. */
413 oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
414 snprintf(path, sizeof(path), "%s/vmcore.%d%s",
415 savedir, bounds, compress ? ".gz" : "");
417 fp = zopen(path, "w");
419 fp = fopen(path, "w");
421 syslog(LOG_ERR, "%s: %m", path);
426 /* Seek to the start of the core. */
427 Lseek(dumpfd, (off_t)dumplo, L_SET);
429 /* Copy the core file. */
430 syslog(LOG_NOTICE, "writing %score to %s",
431 compress ? "compressed " : "", path);
432 for (; dumpsize > 0; dumpsize -= nr) {
433 printf("%6ldK\r", (long)(dumpsize / 1024));
435 nr = read(dumpfd, buf, MIN(dumpsize, sizeof(buf)));
439 "WARNING: EOF on dump device");
441 syslog(LOG_ERR, "%s: %m", ddname);
445 nw = fwrite(buf, 1, nr, fp);
447 for (nw = 0; nw < nr; nw = he) {
448 /* find a contiguous block of zeroes */
449 for (hs = nw; hs < nr; hs += BLOCKSIZE) {
450 for (he = hs; he < nr && buf[he] == 0; ++he)
453 /* is the hole long enough to matter? */
454 if (he >= hs + BLOCKSIZE)
458 /* back down to a block boundary */
462 * 1) Don't go beyond the end of the buffer.
463 * 2) If the end of the buffer is less than
464 * BLOCKSIZE bytes away, we're at the end
465 * of the file, so just grab what's left.
467 if (hs + BLOCKSIZE > nr)
471 * At this point, we have a partial ordering:
472 * nw <= hs <= he <= nr
473 * If hs > nw, buf[nw..hs] contains non-zero data.
474 * If he > hs, buf[hs..he] is all zeroes.
477 if (fwrite(buf + nw, hs - nw, 1, fp) != 1)
480 if (fseeko(fp, he - hs, SEEK_CUR) == -1)
485 syslog(LOG_ERR, "%s: %m", path);
486 err2: syslog(LOG_WARNING,
487 "WARNING: vmcore may be incomplete");
495 /* Copy the kernel. */
496 ifd = Open(kernel ? kernel : getbootfile(), O_RDONLY);
497 snprintf(path, sizeof(path), "%s/kernel.%d%s",
498 savedir, bounds, compress ? ".gz" : "");
500 fp = zopen(path, "w");
502 fp = fopen(path, "w");
504 syslog(LOG_ERR, "%s: %m", path);
507 syslog(LOG_NOTICE, "writing %skernel to %s",
508 compress ? "compressed " : "", path);
509 while ((nr = read(ifd, buf, sizeof(buf))) > 0) {
510 nw = fwrite(buf, 1, nr, fp);
512 syslog(LOG_ERR, "%s: %m", path);
514 "WARNING: kernel may be incomplete");
519 syslog(LOG_ERR, "%s: %m", kernel ? kernel : getbootfile());
521 "WARNING: kernel may be incomplete");
529 * Verify that the specified device node exists and matches the
533 verify_dev(char *name, dev_t dev)
537 if (lstat(name, &sb) == -1)
539 if (!S_ISCHR(sb.st_mode) || sb.st_rdev != dev)
545 * Find the dump device.
547 * 1) try devname(3); see if it returns something sensible
548 * 2) scan /dev for the desired node
549 * 3) as a last resort, try to create the node we need
558 strcpy(ddname, _PATH_DEV);
559 dnp = ddname + sizeof _PATH_DEV - 1;
560 if ((dn = devname(dev, S_IFCHR)) != NULL) {
562 if (verify_dev(ddname, dev) == 0)
565 if ((d = opendir(_PATH_DEV)) != NULL) {
566 while ((ent = readdir(d))) {
567 strcpy(dnp, ent->d_name);
568 if (verify_dev(ddname, dev) == 0) {
576 if (mknod(ddname, S_IFCHR|S_IRUSR|S_IWUSR, dev) == 0)
578 syslog(LOG_ERR, "can't find device %d/%#x", major(dev), minor(dev));
583 * Extract the date and time of the crash from the dump header, and
584 * make sure it looks sane (within one week of current date and time).
589 time_t dumptime; /* Time the dump was taken. */
591 DumpRead(dumpfd, &dumptime, sizeof(dumptime),
592 (off_t)(dumplo + ok(dump_nl[X_TIME].n_value)), L_SET);
595 syslog(LOG_ERR, "dump time is zero");
598 printf("savecore: system went down at %s", ctime(&dumptime));
599 #define LEEWAY (7 * 86400)
600 if (dumptime < now - LEEWAY || dumptime > now + LEEWAY) {
601 printf("dump time is unreasonable\n");
608 * Extract the size of the dump from the dump header.
613 int kdumpsize; /* Number of pages in dump. */
615 /* Read the dump size. */
616 DumpRead(dumpfd, &kdumpsize, sizeof(kdumpsize),
617 (off_t)(dumplo + ok(dump_nl[X_DUMPSIZE].n_value)), L_SET);
618 dumpsize = (off_t)kdumpsize * getpagesize();
622 * Check that sufficient space is available on the disk that holds the
630 off_t minfree, spacefree, totfree, kernelsize, needed;
633 char mybuf[100], path[MAXPATHLEN];
635 tkernel = kernel ? kernel : getbootfile();
636 if (stat(tkernel, &st) < 0) {
637 syslog(LOG_ERR, "%s: %m", tkernel);
640 kernelsize = st.st_blocks * S_BLKSIZE;
642 if (statfs(savedir, &fsbuf) < 0) {
643 syslog(LOG_ERR, "%s: %m", savedir);
646 spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
647 totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
649 snprintf(path, sizeof(path), "%s/minfree", savedir);
650 if ((fp = fopen(path, "r")) == NULL)
653 if (fgets(mybuf, sizeof(mybuf), fp) == NULL)
656 minfree = atoi(mybuf);
660 needed = (dumpsize + kernelsize) / 1024;
661 if (((minfree > 0) ? spacefree : totfree) - needed < minfree) {
663 "no dump, not enough free space on device (%lld available, need %lld)",
664 (long long)(minfree > 0 ? spacefree : totfree),
668 if (spacefree - needed < 0)
670 "dump performed, but free space threshold crossed");
675 Open(const char *name, int rw)
679 if ((fd = open(name, rw, 0)) < 0) {
680 syslog(LOG_ERR, "%s: %m", name);
687 Read(int fd, void *bp, int size)
691 nr = read(fd, bp, size);
693 syslog(LOG_ERR, "read: %m");
700 Lseek(int fd, off_t off, int flag)
704 ret = lseek(fd, off, flag);
706 syslog(LOG_ERR, "lseek: %m");
712 * DumpWrite and DumpRead block io requests to the * dump device.
714 #define DUMPBUFSIZE 8192
716 DumpWrite(int fd, void *bp, int size, off_t off, int flag)
718 unsigned char mybuf[DUMPBUFSIZE], *p, *q;
723 syslog(LOG_ERR, "lseek: not LSET");
728 pos = off & ~(DUMPBUFSIZE - 1);
729 Lseek(fd, pos, flag);
730 Read(fd, mybuf, sizeof(mybuf));
731 j = off & (DUMPBUFSIZE - 1);
734 if (i > DUMPBUFSIZE - j)
737 Lseek(fd, pos, flag);
738 Write(fd, mybuf, sizeof(mybuf));
746 DumpRead(int fd, void *bp, int size, off_t off, int flag)
748 unsigned char mybuf[DUMPBUFSIZE], *p, *q;
753 syslog(LOG_ERR, "lseek: not LSET");
758 pos = off & ~(DUMPBUFSIZE - 1);
759 Lseek(fd, pos, flag);
760 Read(fd, mybuf, sizeof(mybuf));
761 j = off & (DUMPBUFSIZE - 1);
764 if (i > DUMPBUFSIZE - j)
774 Write(int fd, void *bp, int size)
778 if ((n = write(fd, bp, size)) < size) {
779 syslog(LOG_ERR, "write: %m");
785 kdumplo_adjust(char *cp, int kmem, long *kdumplop)
787 uint64_t AllowMem, sanity, Maxmem, CurrMaxmem;
790 /* based on getmemsize() in i386/i386/machdep.c */
791 sanity = AllowMem = strtouq(cp, &ep, 0);
792 if ((ep != cp) && (*ep != 0)) {
807 if (AllowMem < sanity)
811 errx(1, "invalid memory size: '%s'\n", cp);
813 Maxmem = atop(AllowMem);
815 Lseek(kmem, (off_t)current_nl[X_MAXMEM].n_value, L_SET);
816 Read(kmem, &CurrMaxmem, sizeof(CurrMaxmem));
818 /* based on setdumpdev() in kern_shutdown.c */
819 *kdumplop += CurrMaxmem * (PAGE_SIZE / DEV_BSIZE);
820 *kdumplop -= Maxmem * (PAGE_SIZE / DEV_BSIZE);
827 "usage: savecore [-cfkvz] [-N system] [-P physmem|-B blkno] directory");