]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_shutdown.c
Add support for compressed kernel dumps.
[FreeBSD/FreeBSD.git] / sys / kern / kern_shutdown.c
1 /*-
2  * Copyright (c) 1986, 1988, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)kern_shutdown.c     8.3 (Berkeley) 1/21/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_ddb.h"
41 #include "opt_ekcd.h"
42 #include "opt_gzio.h"
43 #include "opt_kdb.h"
44 #include "opt_panic.h"
45 #include "opt_sched.h"
46 #include "opt_watchdog.h"
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/bio.h>
51 #include <sys/buf.h>
52 #include <sys/conf.h>
53 #include <sys/cons.h>
54 #include <sys/eventhandler.h>
55 #include <sys/filedesc.h>
56 #include <sys/gzio.h>
57 #include <sys/jail.h>
58 #include <sys/kdb.h>
59 #include <sys/kernel.h>
60 #include <sys/kerneldump.h>
61 #include <sys/kthread.h>
62 #include <sys/ktr.h>
63 #include <sys/malloc.h>
64 #include <sys/mount.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/reboot.h>
68 #include <sys/resourcevar.h>
69 #include <sys/rwlock.h>
70 #include <sys/sched.h>
71 #include <sys/smp.h>
72 #include <sys/sysctl.h>
73 #include <sys/sysproto.h>
74 #include <sys/vnode.h>
75 #include <sys/watchdog.h>
76
77 #include <crypto/rijndael/rijndael-api-fst.h>
78 #include <crypto/sha2/sha256.h>
79
80 #include <ddb/ddb.h>
81
82 #include <machine/cpu.h>
83 #include <machine/dump.h>
84 #include <machine/pcb.h>
85 #include <machine/smp.h>
86
87 #include <security/mac/mac_framework.h>
88
89 #include <vm/vm.h>
90 #include <vm/vm_object.h>
91 #include <vm/vm_page.h>
92 #include <vm/vm_pager.h>
93 #include <vm/swap_pager.h>
94
95 #include <sys/signalvar.h>
96
97 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
98
99 #ifndef PANIC_REBOOT_WAIT_TIME
100 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
101 #endif
102 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
103 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
104     &panic_reboot_wait_time, 0,
105     "Seconds to wait before rebooting after a panic");
106
107 /*
108  * Note that stdarg.h and the ANSI style va_start macro is used for both
109  * ANSI and traditional C compilers.
110  */
111 #include <machine/stdarg.h>
112
113 #ifdef KDB
114 #ifdef KDB_UNATTENDED
115 int debugger_on_panic = 0;
116 #else
117 int debugger_on_panic = 1;
118 #endif
119 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
120     CTLFLAG_RWTUN | CTLFLAG_SECURE,
121     &debugger_on_panic, 0, "Run debugger on kernel panic");
122
123 #ifdef KDB_TRACE
124 static int trace_on_panic = 1;
125 #else
126 static int trace_on_panic = 0;
127 #endif
128 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
129     CTLFLAG_RWTUN | CTLFLAG_SECURE,
130     &trace_on_panic, 0, "Print stack trace on kernel panic");
131 #endif /* KDB */
132
133 static int sync_on_panic = 0;
134 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
135         &sync_on_panic, 0, "Do a sync before rebooting from a panic");
136
137 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
138     "Shutdown environment");
139
140 #ifndef DIAGNOSTIC
141 static int show_busybufs;
142 #else
143 static int show_busybufs = 1;
144 #endif
145 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
146         &show_busybufs, 0, "");
147
148 int suspend_blocked = 0;
149 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
150         &suspend_blocked, 0, "Block suspend due to a pending shutdown");
151
152 #ifdef EKCD
153 FEATURE(ekcd, "Encrypted kernel crash dumps support");
154
155 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
156
157 struct kerneldumpcrypto {
158         uint8_t                 kdc_encryption;
159         uint8_t                 kdc_iv[KERNELDUMP_IV_MAX_SIZE];
160         keyInstance             kdc_ki;
161         cipherInstance          kdc_ci;
162         uint32_t                kdc_dumpkeysize;
163         struct kerneldumpkey    kdc_dumpkey[];
164 };
165 #endif
166
167 #ifdef GZIO
168 struct kerneldumpgz {
169         struct gzio_stream      *kdgz_stream;
170         uint8_t                 *kdgz_buf;
171         size_t                  kdgz_resid;
172 };
173
174 static struct kerneldumpgz *kerneldumpgz_create(struct dumperinfo *di,
175                     uint8_t compression);
176 static void     kerneldumpgz_destroy(struct dumperinfo *di);
177 static int      kerneldumpgz_write_cb(void *cb, size_t len, off_t off, void *arg);
178
179 static int kerneldump_gzlevel = 6;
180 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
181     &kerneldump_gzlevel, 0,
182     "Kernel crash dump gzip compression level");
183 #endif /* GZIO */
184
185 /*
186  * Variable panicstr contains argument to first call to panic; used as flag
187  * to indicate that the kernel has already called panic.
188  */
189 const char *panicstr;
190
191 int dumping;                            /* system is dumping */
192 int rebooting;                          /* system is rebooting */
193 static struct dumperinfo dumper;        /* our selected dumper */
194
195 /* Context information for dump-debuggers. */
196 static struct pcb dumppcb;              /* Registers. */
197 lwpid_t dumptid;                        /* Thread ID. */
198
199 static struct cdevsw reroot_cdevsw = {
200      .d_version = D_VERSION,
201      .d_name    = "reroot",
202 };
203
204 static void poweroff_wait(void *, int);
205 static void shutdown_halt(void *junk, int howto);
206 static void shutdown_panic(void *junk, int howto);
207 static void shutdown_reset(void *junk, int howto);
208 static int kern_reroot(void);
209
210 /* register various local shutdown events */
211 static void
212 shutdown_conf(void *unused)
213 {
214
215         EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
216             SHUTDOWN_PRI_FIRST);
217         EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
218             SHUTDOWN_PRI_LAST + 100);
219         EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
220             SHUTDOWN_PRI_LAST + 100);
221         EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
222             SHUTDOWN_PRI_LAST + 200);
223 }
224
225 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
226
227 /*
228  * The only reason this exists is to create the /dev/reroot/ directory,
229  * used by reroot code in init(8) as a mountpoint for tmpfs.
230  */
231 static void
232 reroot_conf(void *unused)
233 {
234         int error;
235         struct cdev *cdev;
236
237         error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
238             &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
239         if (error != 0) {
240                 printf("%s: failed to create device node, error %d",
241                     __func__, error);
242         }
243 }
244
245 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
246
247 /*
248  * The system call that results in a reboot.
249  */
250 /* ARGSUSED */
251 int
252 sys_reboot(struct thread *td, struct reboot_args *uap)
253 {
254         int error;
255
256         error = 0;
257 #ifdef MAC
258         error = mac_system_check_reboot(td->td_ucred, uap->opt);
259 #endif
260         if (error == 0)
261                 error = priv_check(td, PRIV_REBOOT);
262         if (error == 0) {
263                 if (uap->opt & RB_REROOT) {
264                         error = kern_reroot();
265                 } else {
266                         mtx_lock(&Giant);
267                         kern_reboot(uap->opt);
268                         mtx_unlock(&Giant);
269                 }
270         }
271         return (error);
272 }
273
274 /*
275  * Called by events that want to shut down.. e.g  <CTL><ALT><DEL> on a PC
276  */
277 void
278 shutdown_nice(int howto)
279 {
280
281         if (initproc != NULL) {
282                 /* Send a signal to init(8) and have it shutdown the world. */
283                 PROC_LOCK(initproc);
284                 if (howto & RB_POWEROFF)
285                         kern_psignal(initproc, SIGUSR2);
286                 else if (howto & RB_HALT)
287                         kern_psignal(initproc, SIGUSR1);
288                 else
289                         kern_psignal(initproc, SIGINT);
290                 PROC_UNLOCK(initproc);
291         } else {
292                 /* No init(8) running, so simply reboot. */
293                 kern_reboot(howto | RB_NOSYNC);
294         }
295 }
296
297 static void
298 print_uptime(void)
299 {
300         int f;
301         struct timespec ts;
302
303         getnanouptime(&ts);
304         printf("Uptime: ");
305         f = 0;
306         if (ts.tv_sec >= 86400) {
307                 printf("%ldd", (long)ts.tv_sec / 86400);
308                 ts.tv_sec %= 86400;
309                 f = 1;
310         }
311         if (f || ts.tv_sec >= 3600) {
312                 printf("%ldh", (long)ts.tv_sec / 3600);
313                 ts.tv_sec %= 3600;
314                 f = 1;
315         }
316         if (f || ts.tv_sec >= 60) {
317                 printf("%ldm", (long)ts.tv_sec / 60);
318                 ts.tv_sec %= 60;
319                 f = 1;
320         }
321         printf("%lds\n", (long)ts.tv_sec);
322 }
323
324 int
325 doadump(boolean_t textdump)
326 {
327         boolean_t coredump;
328         int error;
329
330         error = 0;
331         if (dumping)
332                 return (EBUSY);
333         if (dumper.dumper == NULL)
334                 return (ENXIO);
335
336         savectx(&dumppcb);
337         dumptid = curthread->td_tid;
338         dumping++;
339
340         coredump = TRUE;
341 #ifdef DDB
342         if (textdump && textdump_pending) {
343                 coredump = FALSE;
344                 textdump_dumpsys(&dumper);
345         }
346 #endif
347         if (coredump)
348                 error = dumpsys(&dumper);
349
350         dumping--;
351         return (error);
352 }
353
354 /*
355  * Shutdown the system cleanly to prepare for reboot, halt, or power off.
356  */
357 void
358 kern_reboot(int howto)
359 {
360         static int once = 0;
361
362 #if defined(SMP)
363         /*
364          * Bind us to CPU 0 so that all shutdown code runs there.  Some
365          * systems don't shutdown properly (i.e., ACPI power off) if we
366          * run on another processor.
367          */
368         if (!SCHEDULER_STOPPED()) {
369                 thread_lock(curthread);
370                 sched_bind(curthread, 0);
371                 thread_unlock(curthread);
372                 KASSERT(PCPU_GET(cpuid) == 0, ("boot: not running on cpu 0"));
373         }
374 #endif
375         /* We're in the process of rebooting. */
376         rebooting = 1;
377
378         /* We are out of the debugger now. */
379         kdb_active = 0;
380
381         /*
382          * Do any callouts that should be done BEFORE syncing the filesystems.
383          */
384         EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
385
386         /* 
387          * Now sync filesystems
388          */
389         if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
390                 once = 1;
391                 bufshutdown(show_busybufs);
392         }
393
394         print_uptime();
395
396         cngrab();
397
398         /*
399          * Ok, now do things that assume all filesystem activity has
400          * been completed.
401          */
402         EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
403
404         if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping) 
405                 doadump(TRUE);
406
407         /* Now that we're going to really halt the system... */
408         EVENTHANDLER_INVOKE(shutdown_final, howto);
409
410         for(;;) ;       /* safety against shutdown_reset not working */
411         /* NOTREACHED */
412 }
413
414 /*
415  * The system call that results in changing the rootfs.
416  */
417 static int
418 kern_reroot(void)
419 {
420         struct vnode *oldrootvnode, *vp;
421         struct mount *mp, *devmp;
422         int error;
423
424         if (curproc != initproc)
425                 return (EPERM);
426
427         /*
428          * Mark the filesystem containing currently-running executable
429          * (the temporary copy of init(8)) busy.
430          */
431         vp = curproc->p_textvp;
432         error = vn_lock(vp, LK_SHARED);
433         if (error != 0)
434                 return (error);
435         mp = vp->v_mount;
436         error = vfs_busy(mp, MBF_NOWAIT);
437         if (error != 0) {
438                 vfs_ref(mp);
439                 VOP_UNLOCK(vp, 0);
440                 error = vfs_busy(mp, 0);
441                 vn_lock(vp, LK_SHARED | LK_RETRY);
442                 vfs_rel(mp);
443                 if (error != 0) {
444                         VOP_UNLOCK(vp, 0);
445                         return (ENOENT);
446                 }
447                 if (vp->v_iflag & VI_DOOMED) {
448                         VOP_UNLOCK(vp, 0);
449                         vfs_unbusy(mp);
450                         return (ENOENT);
451                 }
452         }
453         VOP_UNLOCK(vp, 0);
454
455         /*
456          * Remove the filesystem containing currently-running executable
457          * from the mount list, to prevent it from being unmounted
458          * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
459          *
460          * Also preserve /dev - forcibly unmounting it could cause driver
461          * reinitialization.
462          */
463
464         vfs_ref(rootdevmp);
465         devmp = rootdevmp;
466         rootdevmp = NULL;
467
468         mtx_lock(&mountlist_mtx);
469         TAILQ_REMOVE(&mountlist, mp, mnt_list);
470         TAILQ_REMOVE(&mountlist, devmp, mnt_list);
471         mtx_unlock(&mountlist_mtx);
472
473         oldrootvnode = rootvnode;
474
475         /*
476          * Unmount everything except for the two filesystems preserved above.
477          */
478         vfs_unmountall();
479
480         /*
481          * Add /dev back; vfs_mountroot() will move it into its new place.
482          */
483         mtx_lock(&mountlist_mtx);
484         TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
485         mtx_unlock(&mountlist_mtx);
486         rootdevmp = devmp;
487         vfs_rel(rootdevmp);
488
489         /*
490          * Mount the new rootfs.
491          */
492         vfs_mountroot();
493
494         /*
495          * Update all references to the old rootvnode.
496          */
497         mountcheckdirs(oldrootvnode, rootvnode);
498
499         /*
500          * Add the temporary filesystem back and unbusy it.
501          */
502         mtx_lock(&mountlist_mtx);
503         TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
504         mtx_unlock(&mountlist_mtx);
505         vfs_unbusy(mp);
506
507         return (0);
508 }
509
510 /*
511  * If the shutdown was a clean halt, behave accordingly.
512  */
513 static void
514 shutdown_halt(void *junk, int howto)
515 {
516
517         if (howto & RB_HALT) {
518                 printf("\n");
519                 printf("The operating system has halted.\n");
520                 printf("Please press any key to reboot.\n\n");
521                 switch (cngetc()) {
522                 case -1:                /* No console, just die */
523                         cpu_halt();
524                         /* NOTREACHED */
525                 default:
526                         howto &= ~RB_HALT;
527                         break;
528                 }
529         }
530 }
531
532 /*
533  * Check to see if the system paniced, pause and then reboot
534  * according to the specified delay.
535  */
536 static void
537 shutdown_panic(void *junk, int howto)
538 {
539         int loop;
540
541         if (howto & RB_DUMP) {
542                 if (panic_reboot_wait_time != 0) {
543                         if (panic_reboot_wait_time != -1) {
544                                 printf("Automatic reboot in %d seconds - "
545                                        "press a key on the console to abort\n",
546                                         panic_reboot_wait_time);
547                                 for (loop = panic_reboot_wait_time * 10;
548                                      loop > 0; --loop) {
549                                         DELAY(1000 * 100); /* 1/10th second */
550                                         /* Did user type a key? */
551                                         if (cncheckc() != -1)
552                                                 break;
553                                 }
554                                 if (!loop)
555                                         return;
556                         }
557                 } else { /* zero time specified - reboot NOW */
558                         return;
559                 }
560                 printf("--> Press a key on the console to reboot,\n");
561                 printf("--> or switch off the system now.\n");
562                 cngetc();
563         }
564 }
565
566 /*
567  * Everything done, now reset
568  */
569 static void
570 shutdown_reset(void *junk, int howto)
571 {
572
573         printf("Rebooting...\n");
574         DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
575
576         /*
577          * Acquiring smp_ipi_mtx here has a double effect:
578          * - it disables interrupts avoiding CPU0 preemption
579          *   by fast handlers (thus deadlocking  against other CPUs)
580          * - it avoids deadlocks against smp_rendezvous() or, more 
581          *   generally, threads busy-waiting, with this spinlock held,
582          *   and waiting for responses by threads on other CPUs
583          *   (ie. smp_tlb_shootdown()).
584          *
585          * For the !SMP case it just needs to handle the former problem.
586          */
587 #ifdef SMP
588         mtx_lock_spin(&smp_ipi_mtx);
589 #else
590         spinlock_enter();
591 #endif
592
593         /* cpu_boot(howto); */ /* doesn't do anything at the moment */
594         cpu_reset();
595         /* NOTREACHED */ /* assuming reset worked */
596 }
597
598 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
599 static int kassert_warn_only = 0;
600 #ifdef KDB
601 static int kassert_do_kdb = 0;
602 #endif
603 #ifdef KTR
604 static int kassert_do_ktr = 0;
605 #endif
606 static int kassert_do_log = 1;
607 static int kassert_log_pps_limit = 4;
608 static int kassert_log_mute_at = 0;
609 static int kassert_log_panic_at = 0;
610 static int kassert_warnings = 0;
611
612 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
613
614 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
615     &kassert_warn_only, 0,
616     "KASSERT triggers a panic (1) or just a warning (0)");
617
618 #ifdef KDB
619 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
620     &kassert_do_kdb, 0, "KASSERT will enter the debugger");
621 #endif
622
623 #ifdef KTR
624 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
625     &kassert_do_ktr, 0,
626     "KASSERT does a KTR, set this to the KTRMASK you want");
627 #endif
628
629 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
630     &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
631
632 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
633     &kassert_warnings, 0, "number of KASSERTs that have been triggered");
634
635 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
636     &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
637
638 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
639     &kassert_log_pps_limit, 0, "limit number of log messages per second");
640
641 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
642     &kassert_log_mute_at, 0, "max number of KASSERTS to log");
643
644 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
645
646 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
647     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
648     kassert_sysctl_kassert, "I", "set to trigger a test kassert");
649
650 static int
651 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
652 {
653         int error, i;
654
655         error = sysctl_wire_old_buffer(req, sizeof(int));
656         if (error == 0) {
657                 i = 0;
658                 error = sysctl_handle_int(oidp, &i, 0, req);
659         }
660         if (error != 0 || req->newptr == NULL)
661                 return (error);
662         KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
663         return (0);
664 }
665
666 /*
667  * Called by KASSERT, this decides if we will panic
668  * or if we will log via printf and/or ktr.
669  */
670 void
671 kassert_panic(const char *fmt, ...)
672 {
673         static char buf[256];
674         va_list ap;
675
676         va_start(ap, fmt);
677         (void)vsnprintf(buf, sizeof(buf), fmt, ap);
678         va_end(ap);
679
680         /*
681          * panic if we're not just warning, or if we've exceeded
682          * kassert_log_panic_at warnings.
683          */
684         if (!kassert_warn_only ||
685             (kassert_log_panic_at > 0 &&
686              kassert_warnings >= kassert_log_panic_at)) {
687                 va_start(ap, fmt);
688                 vpanic(fmt, ap);
689                 /* NORETURN */
690         }
691 #ifdef KTR
692         if (kassert_do_ktr)
693                 CTR0(ktr_mask, buf);
694 #endif /* KTR */
695         /*
696          * log if we've not yet met the mute limit.
697          */
698         if (kassert_do_log &&
699             (kassert_log_mute_at == 0 ||
700              kassert_warnings < kassert_log_mute_at)) {
701                 static  struct timeval lasterr;
702                 static  int curerr;
703
704                 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
705                         printf("KASSERT failed: %s\n", buf);
706                         kdb_backtrace();
707                 }
708         }
709 #ifdef KDB
710         if (kassert_do_kdb) {
711                 kdb_enter(KDB_WHY_KASSERT, buf);
712         }
713 #endif
714         atomic_add_int(&kassert_warnings, 1);
715 }
716 #endif
717
718 /*
719  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
720  * and then reboots.  If we are called twice, then we avoid trying to sync
721  * the disks as this often leads to recursive panics.
722  */
723 void
724 panic(const char *fmt, ...)
725 {
726         va_list ap;
727
728         va_start(ap, fmt);
729         vpanic(fmt, ap);
730 }
731
732 void
733 vpanic(const char *fmt, va_list ap)
734 {
735 #ifdef SMP
736         cpuset_t other_cpus;
737 #endif
738         struct thread *td = curthread;
739         int bootopt, newpanic;
740         static char buf[256];
741
742         spinlock_enter();
743
744 #ifdef SMP
745         /*
746          * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
747          * concurrently entering panic.  Only the winner will proceed
748          * further.
749          */
750         if (panicstr == NULL && !kdb_active) {
751                 other_cpus = all_cpus;
752                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
753                 stop_cpus_hard(other_cpus);
754         }
755 #endif
756
757         /*
758          * Ensure that the scheduler is stopped while panicking, even if panic
759          * has been entered from kdb.
760          */
761         td->td_stopsched = 1;
762
763         bootopt = RB_AUTOBOOT;
764         newpanic = 0;
765         if (panicstr)
766                 bootopt |= RB_NOSYNC;
767         else {
768                 bootopt |= RB_DUMP;
769                 panicstr = fmt;
770                 newpanic = 1;
771         }
772
773         if (newpanic) {
774                 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
775                 panicstr = buf;
776                 cngrab();
777                 printf("panic: %s\n", buf);
778         } else {
779                 printf("panic: ");
780                 vprintf(fmt, ap);
781                 printf("\n");
782         }
783 #ifdef SMP
784         printf("cpuid = %d\n", PCPU_GET(cpuid));
785 #endif
786         printf("time = %jd\n", (intmax_t )time_second);
787 #ifdef KDB
788         if (newpanic && trace_on_panic)
789                 kdb_backtrace();
790         if (debugger_on_panic)
791                 kdb_enter(KDB_WHY_PANIC, "panic");
792 #endif
793         /*thread_lock(td); */
794         td->td_flags |= TDF_INPANIC;
795         /* thread_unlock(td); */
796         if (!sync_on_panic)
797                 bootopt |= RB_NOSYNC;
798         kern_reboot(bootopt);
799 }
800
801 /*
802  * Support for poweroff delay.
803  *
804  * Please note that setting this delay too short might power off your machine
805  * before the write cache on your hard disk has been flushed, leading to
806  * soft-updates inconsistencies.
807  */
808 #ifndef POWEROFF_DELAY
809 # define POWEROFF_DELAY 5000
810 #endif
811 static int poweroff_delay = POWEROFF_DELAY;
812
813 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
814     &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
815
816 static void
817 poweroff_wait(void *junk, int howto)
818 {
819
820         if (!(howto & RB_POWEROFF) || poweroff_delay <= 0)
821                 return;
822         DELAY(poweroff_delay * 1000);
823 }
824
825 /*
826  * Some system processes (e.g. syncer) need to be stopped at appropriate
827  * points in their main loops prior to a system shutdown, so that they
828  * won't interfere with the shutdown process (e.g. by holding a disk buf
829  * to cause sync to fail).  For each of these system processes, register
830  * shutdown_kproc() as a handler for one of shutdown events.
831  */
832 static int kproc_shutdown_wait = 60;
833 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
834     &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
835
836 void
837 kproc_shutdown(void *arg, int howto)
838 {
839         struct proc *p;
840         int error;
841
842         if (panicstr)
843                 return;
844
845         p = (struct proc *)arg;
846         printf("Waiting (max %d seconds) for system process `%s' to stop... ",
847             kproc_shutdown_wait, p->p_comm);
848         error = kproc_suspend(p, kproc_shutdown_wait * hz);
849
850         if (error == EWOULDBLOCK)
851                 printf("timed out\n");
852         else
853                 printf("done\n");
854 }
855
856 void
857 kthread_shutdown(void *arg, int howto)
858 {
859         struct thread *td;
860         int error;
861
862         if (panicstr)
863                 return;
864
865         td = (struct thread *)arg;
866         printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
867             kproc_shutdown_wait, td->td_name);
868         error = kthread_suspend(td, kproc_shutdown_wait * hz);
869
870         if (error == EWOULDBLOCK)
871                 printf("timed out\n");
872         else
873                 printf("done\n");
874 }
875
876 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
877 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
878     dumpdevname, 0, "Device for kernel dumps");
879
880 static int      _dump_append(struct dumperinfo *di, void *virtual,
881                     vm_offset_t physical, size_t length);
882
883 #ifdef EKCD
884 static struct kerneldumpcrypto *
885 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
886     const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
887 {
888         struct kerneldumpcrypto *kdc;
889         struct kerneldumpkey *kdk;
890         uint32_t dumpkeysize;
891
892         dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
893         kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
894
895         arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
896
897         kdc->kdc_encryption = encryption;
898         switch (kdc->kdc_encryption) {
899         case KERNELDUMP_ENC_AES_256_CBC:
900                 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
901                         goto failed;
902                 break;
903         default:
904                 goto failed;
905         }
906
907         kdc->kdc_dumpkeysize = dumpkeysize;
908         kdk = kdc->kdc_dumpkey;
909         kdk->kdk_encryption = kdc->kdc_encryption;
910         memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
911         kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
912         memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
913
914         return (kdc);
915 failed:
916         explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
917         free(kdc, M_EKCD);
918         return (NULL);
919 }
920
921 static int
922 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
923 {
924         uint8_t hash[SHA256_DIGEST_LENGTH];
925         SHA256_CTX ctx;
926         struct kerneldumpkey *kdk;
927         int error;
928
929         error = 0;
930
931         if (kdc == NULL)
932                 return (0);
933
934         /*
935          * When a user enters ddb it can write a crash dump multiple times.
936          * Each time it should be encrypted using a different IV.
937          */
938         SHA256_Init(&ctx);
939         SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
940         SHA256_Final(hash, &ctx);
941         bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
942
943         switch (kdc->kdc_encryption) {
944         case KERNELDUMP_ENC_AES_256_CBC:
945                 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
946                     kdc->kdc_iv) <= 0) {
947                         error = EINVAL;
948                         goto out;
949                 }
950                 break;
951         default:
952                 error = EINVAL;
953                 goto out;
954         }
955
956         kdk = kdc->kdc_dumpkey;
957         memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
958 out:
959         explicit_bzero(hash, sizeof(hash));
960         return (error);
961 }
962
963 static uint32_t
964 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
965 {
966
967         if (kdc == NULL)
968                 return (0);
969         return (kdc->kdc_dumpkeysize);
970 }
971 #endif /* EKCD */
972
973 #ifdef GZIO
974 static struct kerneldumpgz *
975 kerneldumpgz_create(struct dumperinfo *di, uint8_t compression)
976 {
977         struct kerneldumpgz *kdgz;
978
979         if (compression != KERNELDUMP_COMP_GZIP)
980                 return (NULL);
981         kdgz = malloc(sizeof(*kdgz), M_DUMPER, M_WAITOK | M_ZERO);
982         kdgz->kdgz_stream = gzio_init(kerneldumpgz_write_cb, GZIO_DEFLATE,
983             di->maxiosize, kerneldump_gzlevel, di);
984         if (kdgz->kdgz_stream == NULL) {
985                 free(kdgz, M_DUMPER);
986                 return (NULL);
987         }
988         kdgz->kdgz_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
989         return (kdgz);
990 }
991
992 static void
993 kerneldumpgz_destroy(struct dumperinfo *di)
994 {
995         struct kerneldumpgz *kdgz;
996
997         kdgz = di->kdgz;
998         if (kdgz == NULL)
999                 return;
1000         gzio_fini(kdgz->kdgz_stream);
1001         explicit_bzero(kdgz->kdgz_buf, di->maxiosize);
1002         free(kdgz->kdgz_buf, M_DUMPER);
1003         free(kdgz, M_DUMPER);
1004 }
1005 #endif /* GZIO */
1006
1007 /* Registration of dumpers */
1008 int
1009 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1010     uint8_t compression, uint8_t encryption, const uint8_t *key,
1011     uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1012 {
1013         size_t wantcopy;
1014         int error;
1015
1016         error = priv_check(td, PRIV_SETDUMPER);
1017         if (error != 0)
1018                 return (error);
1019
1020         if (di == NULL) {
1021                 error = 0;
1022                 goto cleanup;
1023         }
1024         if (dumper.dumper != NULL)
1025                 return (EBUSY);
1026         dumper = *di;
1027         dumper.blockbuf = NULL;
1028         dumper.kdc = NULL;
1029         dumper.kdgz = NULL;
1030
1031         if (encryption != KERNELDUMP_ENC_NONE) {
1032 #ifdef EKCD
1033                 dumper.kdc = kerneldumpcrypto_create(di->blocksize, encryption,
1034                     key, encryptedkeysize, encryptedkey);
1035                 if (dumper.kdc == NULL) {
1036                         error = EINVAL;
1037                         goto cleanup;
1038                 }
1039 #else
1040                 error = EOPNOTSUPP;
1041                 goto cleanup;
1042 #endif
1043         }
1044
1045         wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1046         if (wantcopy >= sizeof(dumpdevname)) {
1047                 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1048                     devname, dumpdevname);
1049         }
1050
1051         if (compression != KERNELDUMP_COMP_NONE) {
1052 #ifdef GZIO
1053                 /*
1054                  * We currently can't support simultaneous encryption and
1055                  * compression.
1056                  */
1057                 if (encryption != KERNELDUMP_ENC_NONE) {
1058                         error = EOPNOTSUPP;
1059                         goto cleanup;
1060                 }
1061                 dumper.kdgz = kerneldumpgz_create(&dumper, compression);
1062                 if (dumper.kdgz == NULL) {
1063                         error = EINVAL;
1064                         goto cleanup;
1065                 }
1066 #else
1067                 error = EOPNOTSUPP;
1068                 goto cleanup;
1069 #endif
1070         }
1071
1072         dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1073         return (0);
1074 cleanup:
1075 #ifdef EKCD
1076         if (dumper.kdc != NULL) {
1077                 explicit_bzero(dumper.kdc, sizeof(*dumper.kdc) +
1078                     dumper.kdc->kdc_dumpkeysize);
1079                 free(dumper.kdc, M_EKCD);
1080         }
1081 #endif
1082
1083 #ifdef GZIO
1084         kerneldumpgz_destroy(&dumper);
1085 #endif
1086
1087         if (dumper.blockbuf != NULL) {
1088                 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1089                 free(dumper.blockbuf, M_DUMPER);
1090         }
1091         explicit_bzero(&dumper, sizeof(dumper));
1092         dumpdevname[0] = '\0';
1093         return (error);
1094 }
1095
1096 static int
1097 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1098 {
1099
1100         if (length != 0 && (offset < di->mediaoffset ||
1101             offset - di->mediaoffset + length > di->mediasize)) {
1102                 printf("Attempt to write outside dump device boundaries.\n"
1103             "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1104                     (intmax_t)offset, (intmax_t)di->mediaoffset,
1105                     (uintmax_t)length, (intmax_t)di->mediasize);
1106                 return (ENOSPC);
1107         }
1108         if (length % di->blocksize != 0) {
1109                 printf("Attempt to write partial block of length %ju.\n",
1110                     (uintmax_t)length);
1111                 return (EINVAL);
1112         }
1113         if (offset % di->blocksize != 0) {
1114                 printf("Attempt to write at unaligned offset %jd.\n",
1115                     (intmax_t)offset);
1116                 return (EINVAL);
1117         }
1118
1119         return (0);
1120 }
1121
1122 #ifdef EKCD
1123 static int
1124 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1125 {
1126
1127         switch (kdc->kdc_encryption) {
1128         case KERNELDUMP_ENC_AES_256_CBC:
1129                 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1130                     8 * size, buf) <= 0) {
1131                         return (EIO);
1132                 }
1133                 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1134                     buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1135                         return (EIO);
1136                 }
1137                 break;
1138         default:
1139                 return (EINVAL);
1140         }
1141
1142         return (0);
1143 }
1144
1145 /* Encrypt data and call dumper. */
1146 static int
1147 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1148     vm_offset_t physical, off_t offset, size_t length)
1149 {
1150         static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1151         struct kerneldumpcrypto *kdc;
1152         int error;
1153         size_t nbytes;
1154
1155         kdc = di->kdc;
1156
1157         while (length > 0) {
1158                 nbytes = MIN(length, sizeof(buf));
1159                 bcopy(virtual, buf, nbytes);
1160
1161                 if (dump_encrypt(kdc, buf, nbytes) != 0)
1162                         return (EIO);
1163
1164                 error = dump_write(di, buf, physical, offset, nbytes);
1165                 if (error != 0)
1166                         return (error);
1167
1168                 offset += nbytes;
1169                 virtual = (void *)((uint8_t *)virtual + nbytes);
1170                 length -= nbytes;
1171         }
1172
1173         return (0);
1174 }
1175
1176 static int
1177 dump_write_key(struct dumperinfo *di, off_t offset)
1178 {
1179         struct kerneldumpcrypto *kdc;
1180
1181         kdc = di->kdc;
1182         if (kdc == NULL)
1183                 return (0);
1184         return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1185             kdc->kdc_dumpkeysize));
1186 }
1187 #endif /* EKCD */
1188
1189 #ifdef GZIO
1190 static int
1191 kerneldumpgz_write_cb(void *base, size_t length, off_t offset, void *arg)
1192 {
1193         struct dumperinfo *di;
1194         size_t resid, rlength;
1195         int error;
1196
1197         di = arg;
1198
1199         if (length % di->blocksize != 0) {
1200                 /*
1201                  * This must be the final write after flushing the compression
1202                  * stream. Write as many full blocks as possible and stash the
1203                  * residual data in the dumper's block buffer. It will be
1204                  * padded and written in dump_finish().
1205                  */
1206                 rlength = rounddown(length, di->blocksize);
1207                 if (rlength != 0) {
1208                         error = _dump_append(di, base, 0, rlength);
1209                         if (error != 0)
1210                                 return (error);
1211                 }
1212                 resid = length - rlength;
1213                 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1214                 di->kdgz->kdgz_resid = resid;
1215                 return (EAGAIN);
1216         }
1217         return (_dump_append(di, base, 0, length));
1218 }
1219 #endif /* GZIO */
1220
1221 /*
1222  * Write a kerneldumpheader at the specified offset. The header structure is 512
1223  * bytes in size, but we must pad to the device sector size.
1224  */
1225 static int
1226 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1227     off_t offset)
1228 {
1229         void *buf;
1230         size_t hdrsz;
1231
1232         hdrsz = sizeof(*kdh);
1233         if (hdrsz > di->blocksize)
1234                 return (ENOMEM);
1235
1236         if (hdrsz == di->blocksize)
1237                 buf = kdh;
1238         else {
1239                 buf = di->blockbuf;
1240                 memset(buf, 0, di->blocksize);
1241                 memcpy(buf, kdh, hdrsz);
1242         }
1243
1244         return (dump_write(di, buf, 0, offset, di->blocksize));
1245 }
1246
1247 /*
1248  * Don't touch the first SIZEOF_METADATA bytes on the dump device.  This is to
1249  * protect us from metadata and metadata from us.
1250  */
1251 #define SIZEOF_METADATA         (64 * 1024)
1252
1253 /*
1254  * Do some preliminary setup for a kernel dump: initialize state for encryption,
1255  * if requested, and make sure that we have enough space on the dump device.
1256  *
1257  * We set things up so that the dump ends before the last sector of the dump
1258  * device, at which the trailing header is written.
1259  *
1260  *     +-----------+------+-----+----------------------------+------+
1261  *     |           | lhdr | key |    ... kernel dump ...     | thdr |
1262  *     +-----------+------+-----+----------------------------+------+
1263  *                   1 blk  opt <------- dump extent --------> 1 blk
1264  *
1265  * Dumps written using dump_append() start at the beginning of the extent.
1266  * Uncompressed dumps will use the entire extent, but compressed dumps typically
1267  * will not. The true length of the dump is recorded in the leading and trailing
1268  * headers once the dump has been completed.
1269  */
1270 int
1271 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1272 {
1273         uint64_t dumpextent;
1274         uint32_t keysize;
1275
1276 #ifdef EKCD
1277         int error = kerneldumpcrypto_init(di->kdc);
1278         if (error != 0)
1279                 return (error);
1280         keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1281 #else
1282         keysize = 0;
1283 #endif
1284
1285         dumpextent = dtoh64(kdh->dumpextent);
1286         if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1287             keysize) {
1288 #ifdef GZIO
1289                 if (di->kdgz != NULL) {
1290                         /*
1291                          * We don't yet know how much space the compressed dump
1292                          * will occupy, so try to use the whole swap partition
1293                          * (minus the first 64KB) in the hope that the
1294                          * compressed dump will fit. If that doesn't turn out to
1295                          * be enouch, the bounds checking in dump_write()
1296                          * will catch us and cause the dump to fail.
1297                          */
1298                         dumpextent = di->mediasize - SIZEOF_METADATA -
1299                             2 * di->blocksize - keysize;
1300                         kdh->dumpextent = htod64(dumpextent);
1301                 } else
1302 #endif
1303                         return (E2BIG);
1304         }
1305
1306         /* The offset at which to begin writing the dump. */
1307         di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1308             dumpextent;
1309
1310         return (0);
1311 }
1312
1313 static int
1314 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1315     size_t length)
1316 {
1317         int error;
1318
1319 #ifdef EKCD
1320         if (di->kdc != NULL)
1321                 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1322                     length);
1323         else
1324 #endif
1325                 error = dump_write(di, virtual, physical, di->dumpoff, length);
1326         if (error == 0)
1327                 di->dumpoff += length;
1328         return (error);
1329 }
1330
1331 /*
1332  * Write to the dump device starting at dumpoff. When compression is enabled,
1333  * writes to the device will be performed using a callback that gets invoked
1334  * when the compression stream's output buffer is full.
1335  */
1336 int
1337 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1338     size_t length)
1339 {
1340 #ifdef GZIO
1341         void *buf;
1342
1343         if (di->kdgz != NULL) {
1344                 /* Bounce through a buffer to avoid gzip CRC errors. */
1345                 if (length > di->maxiosize)
1346                         return (EINVAL);
1347                 buf = di->kdgz->kdgz_buf;
1348                 memmove(buf, virtual, length);
1349                 return (gzio_write(di->kdgz->kdgz_stream, buf, length));
1350         }
1351 #endif
1352         return (_dump_append(di, virtual, physical, length));
1353 }
1354
1355 /*
1356  * Write to the dump device at the specified offset.
1357  */
1358 int
1359 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1360     off_t offset, size_t length)
1361 {
1362         int error;
1363
1364         error = dump_check_bounds(di, offset, length);
1365         if (error != 0)
1366                 return (error);
1367         return (di->dumper(di->priv, virtual, physical, offset, length));
1368 }
1369
1370 /*
1371  * Perform kernel dump finalization: flush the compression stream, if necessary,
1372  * write the leading and trailing kernel dump headers now that we know the true
1373  * length of the dump, and optionally write the encryption key following the
1374  * leading header.
1375  */
1376 int
1377 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1378 {
1379         uint64_t extent;
1380         uint32_t keysize;
1381         int error;
1382
1383         extent = dtoh64(kdh->dumpextent);
1384
1385 #ifdef EKCD
1386         keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1387 #else
1388         keysize = 0;
1389 #endif
1390
1391 #ifdef GZIO
1392         if (di->kdgz != NULL) {
1393                 error = gzio_flush(di->kdgz->kdgz_stream);
1394                 if (error == EAGAIN) {
1395                         /* We have residual data in di->blockbuf. */
1396                         error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1397                             di->blocksize);
1398                         di->dumpoff += di->kdgz->kdgz_resid;
1399                         di->kdgz->kdgz_resid = 0;
1400                 }
1401                 if (error != 0)
1402                         return (error);
1403
1404                 /*
1405                  * We now know the size of the compressed dump, so update the
1406                  * header accordingly and recompute parity.
1407                  */
1408                 kdh->dumplength = htod64(di->dumpoff -
1409                     (di->mediaoffset + di->mediasize - di->blocksize - extent));
1410                 kdh->parity = 0;
1411                 kdh->parity = kerneldump_parity(kdh);
1412
1413                 gzio_reset(di->kdgz->kdgz_stream);
1414         }
1415 #endif
1416
1417         /*
1418          * Write kerneldump headers at the beginning and end of the dump extent.
1419          * Write the key after the leading header.
1420          */
1421         error = dump_write_header(di, kdh,
1422             di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1423             keysize);
1424         if (error != 0)
1425                 return (error);
1426
1427 #ifdef EKCD
1428         error = dump_write_key(di,
1429             di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1430         if (error != 0)
1431                 return (error);
1432 #endif
1433
1434         error = dump_write_header(di, kdh,
1435             di->mediaoffset + di->mediasize - di->blocksize);
1436         if (error != 0)
1437                 return (error);
1438
1439         (void)dump_write(di, NULL, 0, 0, 0);
1440         return (0);
1441 }
1442
1443 void
1444 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1445     char *magic, uint32_t archver, uint64_t dumplen)
1446 {
1447         size_t dstsize;
1448
1449         bzero(kdh, sizeof(*kdh));
1450         strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1451         strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1452         kdh->version = htod32(KERNELDUMPVERSION);
1453         kdh->architectureversion = htod32(archver);
1454         kdh->dumplength = htod64(dumplen);
1455         kdh->dumpextent = kdh->dumplength;
1456         kdh->dumptime = htod64(time_second);
1457 #ifdef EKCD
1458         kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdc));
1459 #else
1460         kdh->dumpkeysize = 0;
1461 #endif
1462         kdh->blocksize = htod32(di->blocksize);
1463         strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1464         dstsize = sizeof(kdh->versionstring);
1465         if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1466                 kdh->versionstring[dstsize - 2] = '\n';
1467         if (panicstr != NULL)
1468                 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1469 #ifdef GZIO
1470         if (di->kdgz != NULL)
1471                 kdh->compression = KERNELDUMP_COMP_GZIP;
1472 #endif
1473         kdh->parity = kerneldump_parity(kdh);
1474 }
1475
1476 #ifdef DDB
1477 DB_SHOW_COMMAND(panic, db_show_panic)
1478 {
1479
1480         if (panicstr == NULL)
1481                 db_printf("panicstr not set\n");
1482         else
1483                 db_printf("panic: %s\n", panicstr);
1484 }
1485 #endif