]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/savecore/savecore.c
This commit was generated by cvs2svn to compensate for changes in r145510,
[FreeBSD/FreeBSD.git] / sbin / savecore / savecore.c
1 /*-
2  * Copyright (c) 2002 Poul-Henning Kamp
3  * Copyright (c) 2002 Networks Associates Technology, Inc.
4  * All rights reserved.
5  *
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.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
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
21  *    permission.
22  *
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
33  * SUCH DAMAGE.
34  *
35  * Copyright (c) 1986, 1992, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
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. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  */
66
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
69
70 #include <sys/param.h>
71 #include <sys/disk.h>
72 #include <sys/kerneldump.h>
73 #include <sys/param.h>
74 #include <sys/mount.h>
75 #include <sys/stat.h>
76 #include <errno.h>
77 #include <fcntl.h>
78 #include <fstab.h>
79 #include <paths.h>
80 #include <stdarg.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <syslog.h>
85 #include <time.h>
86 #include <unistd.h>
87
88 /* The size of the buffer used for I/O. */
89 #define BUFFERSIZE      (1024*1024)
90
91 #define STATUS_BAD      0
92 #define STATUS_GOOD     1
93 #define STATUS_UNKNOWN  2
94
95 static int checkfor, compress, clear, force, keep, verbose;     /* flags */
96 static int nfound, nsaved, nerr;                        /* statistics */
97
98 extern FILE *zopen(const char *, const char *);
99
100 static void
101 printheader(FILE *f, const struct kerneldumpheader *h, const char *device,
102     int bounds, const int status)
103 {
104         uint64_t dumplen;
105         time_t t;
106         const char *stat_str;
107
108         fprintf(f, "Dump header from device %s\n", device);
109         fprintf(f, "  Architecture: %s\n", h->architecture);
110         fprintf(f, "  Architecture Version: %u\n", h->architectureversion);
111         dumplen = dtoh64(h->dumplength);
112         fprintf(f, "  Dump Length: %lldB (%lld MB)\n", (long long)dumplen,
113             (long long)(dumplen >> 20));
114         fprintf(f, "  Blocksize: %d\n", dtoh32(h->blocksize));
115         t = dtoh64(h->dumptime);
116         fprintf(f, "  Dumptime: %s", ctime(&t));
117         fprintf(f, "  Hostname: %s\n", h->hostname);
118         fprintf(f, "  Magic: %s\n", h->magic);
119         fprintf(f, "  Version String: %s", h->versionstring);
120         fprintf(f, "  Panic String: %s\n", h->panicstring);
121         fprintf(f, "  Dump Parity: %u\n", h->parity);
122         fprintf(f, "  Bounds: %d\n", bounds);
123
124         switch(status) {
125         case STATUS_BAD:
126                 stat_str = "bad";
127                 break;
128         case STATUS_GOOD:
129                 stat_str = "good";
130                 break;
131         default:
132                 stat_str = "unknown";
133         }
134         fprintf(f, "  Dump Status: %s\n", stat_str);
135         fflush(f);
136 }
137
138 static int
139 getbounds(void) {
140         FILE *fp;
141         char buf[6];
142         int ret;
143
144         ret = 0;
145
146         if ((fp = fopen("bounds", "r")) == NULL) {
147                 syslog(LOG_WARNING, "unable to open bounds file, using 0");
148                 goto newfile;
149         }
150
151         if (fgets(buf, sizeof buf, fp) == NULL) {
152                 syslog(LOG_WARNING, "unable to read from bounds, using 0");
153                 fclose(fp);
154                 goto newfile;
155         }
156
157         errno = 0;
158         ret = (int)strtol(buf, NULL, 10);
159         if (ret == 0 && (errno == EINVAL || errno == ERANGE))
160                 syslog(LOG_WARNING, "invalid value found in bounds, using 0");
161
162 newfile:
163
164         if ((fp = fopen("bounds", "w")) == NULL) {
165                 syslog(LOG_WARNING, "unable to write to bounds file: %m");
166                 goto done;
167         }
168
169         if (verbose)
170                 printf("bounds number: %d\n", ret);
171
172         fprintf(fp, "%d\n", (ret + 1));
173         fclose(fp);
174
175 done:
176         return (ret);
177 }
178
179 /*
180  * Check that sufficient space is available on the disk that holds the
181  * save directory.
182  */
183 static int
184 check_space(char *savedir, off_t dumpsize)
185 {
186         FILE *fp;
187         off_t minfree, spacefree, totfree, needed;
188         struct statfs fsbuf;
189         char buf[100], path[MAXPATHLEN];
190
191         if (statfs(savedir, &fsbuf) < 0) {
192                 syslog(LOG_ERR, "%s: %m", savedir);
193                 exit(1);
194         }
195         spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
196         totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
197
198         (void)snprintf(path, sizeof(path), "%s/minfree", savedir);
199         if ((fp = fopen(path, "r")) == NULL)
200                 minfree = 0;
201         else {
202                 if (fgets(buf, sizeof(buf), fp) == NULL)
203                         minfree = 0;
204                 else
205                         minfree = atoi(buf);
206                 (void)fclose(fp);
207         }
208
209         needed = dumpsize / 1024 + 2;   /* 2 for info file */
210         if (((minfree > 0) ? spacefree : totfree) - needed < minfree) {
211                 syslog(LOG_WARNING,
212         "no dump, not enough free space on device (%lld available, need %lld)",
213                     (long long)(minfree > 0 ? spacefree : totfree),
214                     (long long)needed);
215                 return (0);
216         }
217         if (spacefree - needed < 0)
218                 syslog(LOG_WARNING,
219                     "dump performed, but free space threshold crossed");
220         return (1);
221 }
222
223 #define BLOCKSIZE (1<<12)
224 #define BLOCKMASK (~(BLOCKSIZE-1))
225
226 static void
227 DoFile(char *savedir, const char *device)
228 {
229         static char *buf = NULL;
230         struct kerneldumpheader kdhf, kdhl;
231         off_t mediasize, dumpsize, firsthd, lasthd, dmpcnt;
232         FILE *info, *fp;
233         mode_t oumask;
234         int fd, fdinfo, error, wl;
235         int nr, nw, hs, he = 0;
236         int bounds, status;
237         u_int sectorsize;
238
239         bounds = getbounds();
240         dmpcnt = 0;
241         mediasize = 0;
242         status = STATUS_UNKNOWN;
243
244         if (buf == NULL) {
245                 buf = malloc(BUFFERSIZE);
246                 if (buf == NULL) {
247                         syslog(LOG_ERR, "%m");
248                         return;
249                 }
250         }
251
252         if (verbose)
253                 printf("checking for kernel dump on device %s\n", device);
254
255         fd = open(device, O_RDWR);
256         if (fd < 0) {
257                 syslog(LOG_ERR, "%s: %m", device);
258                 return;
259         }
260
261         error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
262         if (!error)
263                 error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
264         if (error) {
265                 syslog(LOG_ERR,
266                     "couldn't find media and/or sector size of %s: %m", device);
267                 goto closefd;
268         }
269
270         if (verbose) {
271                 printf("mediasize = %lld\n", (long long)mediasize);
272                 printf("sectorsize = %u\n", sectorsize);
273         }
274
275         lasthd = mediasize - sectorsize;
276         lseek(fd, lasthd, SEEK_SET);
277         error = read(fd, &kdhl, sizeof kdhl);
278         if (error != sizeof kdhl) {
279                 syslog(LOG_ERR,
280                     "error reading last dump header at offset %lld in %s: %m",
281                     (long long)lasthd, device);
282                 goto closefd;
283         }
284         if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic)) {
285                 if (verbose)
286                         printf("magic mismatch on last dump header on %s\n",
287                             device);
288
289                 status = STATUS_BAD;
290                 if (force == 0)
291                         goto closefd;
292
293                 if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
294                             sizeof kdhl.magic) == 0) {
295                         if (verbose)
296                                 printf("forcing magic on %s\n", device);
297                         memcpy(kdhl.magic, KERNELDUMPMAGIC,
298                             sizeof kdhl.magic);
299                 } else {
300                         syslog(LOG_ERR, "unable to force dump - bad magic");
301                         goto closefd;
302                 }
303         }
304         if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
305                 syslog(LOG_ERR,
306                     "unknown version (%d) in last dump header on %s",
307                     dtoh32(kdhl.version), device);
308
309                 status = STATUS_BAD;
310                 if (force == 0)
311                         goto closefd;
312         }
313
314         nfound++;
315         if (clear)
316                 goto nuke;
317
318         if (kerneldump_parity(&kdhl)) {
319                 syslog(LOG_ERR,
320                     "parity error on last dump header on %s", device);
321                 nerr++;
322                 status = STATUS_BAD;
323                 if (force == 0)
324                         goto closefd;
325         }
326         dumpsize = dtoh64(kdhl.dumplength);
327         firsthd = lasthd - dumpsize - sizeof kdhf;
328         lseek(fd, firsthd, SEEK_SET);
329         error = read(fd, &kdhf, sizeof kdhf);
330         if (error != sizeof kdhf) {
331                 syslog(LOG_ERR,
332                     "error reading first dump header at offset %lld in %s: %m",
333                     (long long)firsthd, device);
334                 nerr++;
335                 goto closefd;
336         }
337
338         if (verbose >= 2) {
339                 printf("First dump headers:\n");
340                 printheader(stdout, &kdhf, device, bounds, -1);
341
342                 printf("\nLast dump headers:\n");
343                 printheader(stdout, &kdhl, device, bounds, -1);
344                 printf("\n");
345         }
346
347         if (memcmp(&kdhl, &kdhf, sizeof kdhl)) {
348                 syslog(LOG_ERR,
349                     "first and last dump headers disagree on %s", device);
350                 nerr++;
351                 status = STATUS_BAD;
352                 if (force == 0)
353                         goto closefd;
354         } else {
355                 status = STATUS_GOOD;
356         }
357
358         if (checkfor) {
359                 printf("A dump exists on %s\n", device);
360                 close(fd);
361                 exit(0);
362         }
363
364         if (kdhl.panicstring[0])
365                 syslog(LOG_ALERT, "reboot after panic: %s", kdhl.panicstring);
366         else
367                 syslog(LOG_ALERT, "reboot");
368
369         if (verbose)
370                 printf("Checking for available free space\n");
371         if (!check_space(savedir, dumpsize)) {
372                 nerr++;
373                 goto closefd;
374         }
375
376         sprintf(buf, "info.%d", bounds);
377
378         /*
379          * Create or overwrite any existing dump header files.
380          */
381         fdinfo = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);
382         if (fdinfo < 0) {
383                 syslog(LOG_ERR, "%s: %m", buf);
384                 nerr++;
385                 goto closefd;
386         }
387         oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
388         if (compress) {
389                 sprintf(buf, "vmcore.%d.gz", bounds);
390                 fp = zopen(buf, "w");
391         } else {
392                 sprintf(buf, "vmcore.%d", bounds);
393                 fp = fopen(buf, "w");
394         }
395         if (fp == NULL) {
396                 syslog(LOG_ERR, "%s: %m", buf);
397                 close(fdinfo);
398                 nerr++;
399                 goto closefd;
400         }
401         (void)umask(oumask);
402
403         info = fdopen(fdinfo, "w");
404
405         if (verbose)
406                 printheader(stdout, &kdhl, device, bounds, status);
407
408         printheader(info, &kdhl, device, bounds, status);
409         fclose(info);
410
411         syslog(LOG_NOTICE, "writing %score to %s",
412             compress ? "compressed " : "", buf);
413
414         while (dumpsize > 0) {
415                 wl = BUFFERSIZE;
416                 if (wl > dumpsize)
417                         wl = dumpsize;
418                 nr = read(fd, buf, wl);
419                 if (nr != wl) {
420                         if (nr == 0)
421                                 syslog(LOG_WARNING,
422                                     "WARNING: EOF on dump device");
423                         else
424                                 syslog(LOG_ERR, "read error on %s: %m", device);
425                         nerr++;
426                         goto closeall;
427                 }
428                 if (compress) {
429                         nw = fwrite(buf, 1, wl, fp);
430                 } else {
431                         for (nw = 0; nw < nr; nw = he) {
432                                 /* find a contiguous block of zeroes */
433                                 for (hs = nw; hs < nr; hs += BLOCKSIZE) {
434                                         for (he = hs; he < nr && buf[he] == 0;
435                                             ++he)
436                                                 /* nothing */ ;
437                                         /* is the hole long enough to matter? */
438                                         if (he >= hs + BLOCKSIZE)
439                                                 break;
440                                 }
441                         
442                                 /* back down to a block boundary */
443                                 he &= BLOCKMASK;
444
445                                 /*
446                                  * 1) Don't go beyond the end of the buffer.
447                                  * 2) If the end of the buffer is less than
448                                  *    BLOCKSIZE bytes away, we're at the end
449                                  *    of the file, so just grab what's left.
450                                  */
451                                 if (hs + BLOCKSIZE > nr)
452                                         hs = he = nr;
453
454                                 /*
455                                  * At this point, we have a partial ordering:
456                                  *     nw <= hs <= he <= nr
457                                  * If hs > nw, buf[nw..hs] contains non-zero data.
458                                  * If he > hs, buf[hs..he] is all zeroes.
459                                  */
460                                 if (hs > nw)
461                                         if (fwrite(buf + nw, hs - nw, 1, fp)
462                                             != 1)
463                                         break;
464                                 if (he > hs)
465                                         if (fseeko(fp, he - hs, SEEK_CUR) == -1)
466                                                 break;
467                         }
468                 }
469                 if (nw != wl) {
470                         syslog(LOG_ERR,
471                             "write error on vmcore.%d file: %m", bounds);
472                         syslog(LOG_WARNING,
473                             "WARNING: vmcore may be incomplete");
474                         nerr++;
475                         goto closeall;
476                 }
477                 if (verbose) {
478                         dmpcnt += wl;
479                         printf("%llu\r", (unsigned long long)dmpcnt);
480                         fflush(stdout);
481                 }
482                 dumpsize -= wl;
483         }
484         if (verbose)
485                 printf("\n");
486
487         if (fclose(fp) < 0) {
488                 syslog(LOG_ERR, "error on vmcore.%d: %m", bounds);
489                 nerr++;
490                 goto closeall;
491         }
492         nsaved++;
493
494         if (verbose)
495                 printf("dump saved\n");
496
497 nuke:
498         if (clear || !keep) {
499                 if (verbose)
500                         printf("clearing dump header\n");
501                 memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic);
502                 lseek(fd, lasthd, SEEK_SET);
503                 error = write(fd, &kdhl, sizeof kdhl);
504                 if (error != sizeof kdhl)
505                         syslog(LOG_ERR,
506                             "error while clearing the dump header: %m");
507         }
508         close(fd);
509         return;
510
511 closeall:
512         fclose(fp);
513
514 closefd:
515         close(fd);
516 }
517
518 static void
519 usage(void)
520 {
521         fprintf(stderr, "%s\n%s\n%s\n",
522             "usage: savecore -c",
523             "       savecore -C [-v] [directory device]",
524             "       savecore [-fkvz] [directory [device ...]]");
525         exit (1);
526 }
527
528 int
529 main(int argc, char **argv)
530 {
531         char *savedir;
532         struct fstab *fsp;
533         int i, ch, error;
534
535         checkfor = compress = clear = force = keep = verbose = 0;
536         nfound = nsaved = nerr = 0;
537
538         openlog("savecore", LOG_PERROR, LOG_DAEMON);
539
540         savedir = strdup(".");
541         if (savedir == NULL) {
542                 syslog(LOG_ERR, "Cannot allocate memory");
543                 exit(1);
544         }
545         while ((ch = getopt(argc, argv, "Ccfkvz")) != -1)
546                 switch(ch) {
547                 case 'C':
548                         checkfor = 1;
549                         break;
550                 case 'c':
551                         clear = 1;
552                         break;
553                 case 'k':
554                         keep = 1;
555                         break;
556                 case 'v':
557                         verbose++;
558                         break;
559                 case 'f':
560                         force = 1;
561                         break;
562                 case 'z':
563                         compress = 1;
564                         break;
565                 case '?':
566                 default:
567                         usage();
568                 }
569         if (checkfor && (clear || force || keep))
570                 usage();
571         argc -= optind;
572         argv += optind;
573         if (argc >= 1) {
574                 error = chdir(argv[0]);
575                 if (error) {
576                         syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
577                         exit(1);
578                 }
579                 savedir = argv[0];
580                 argc--;
581                 argv++;
582         }
583         if (argc == 0) {
584                 for (;;) {
585                         fsp = getfsent();
586                         if (fsp == NULL)
587                                 break;
588                         if (strcmp(fsp->fs_vfstype, "swap") &&
589                             strcmp(fsp->fs_vfstype, "dump"))
590                                 continue;
591                         DoFile(savedir, fsp->fs_spec);
592                 }
593         } else {
594                 for (i = 0; i < argc; i++)
595                         DoFile(savedir, argv[i]);
596         }
597
598         /* Emit minimal output. */
599         if (nfound == 0) {
600                 if (checkfor) {
601                         printf("No dump exists\n");
602                         exit(1);
603                 }
604                 syslog(LOG_WARNING, "no dumps found");
605         }
606         else if (nsaved == 0) {
607                 if (nerr != 0)
608                         syslog(LOG_WARNING, "unsaved dumps found but not saved");
609                 else
610                         syslog(LOG_WARNING, "no unsaved dumps found");
611         }
612
613         return (0);
614 }