]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_shutdown.c
Update to zstd 1.3.2
[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_POWERCYCLE)
287                         kern_psignal(initproc, SIGWINCH);
288                 else if (howto & RB_HALT)
289                         kern_psignal(initproc, SIGUSR1);
290                 else
291                         kern_psignal(initproc, SIGINT);
292                 PROC_UNLOCK(initproc);
293         } else {
294                 /* No init(8) running, so simply reboot. */
295                 kern_reboot(howto | RB_NOSYNC);
296         }
297 }
298
299 static void
300 print_uptime(void)
301 {
302         int f;
303         struct timespec ts;
304
305         getnanouptime(&ts);
306         printf("Uptime: ");
307         f = 0;
308         if (ts.tv_sec >= 86400) {
309                 printf("%ldd", (long)ts.tv_sec / 86400);
310                 ts.tv_sec %= 86400;
311                 f = 1;
312         }
313         if (f || ts.tv_sec >= 3600) {
314                 printf("%ldh", (long)ts.tv_sec / 3600);
315                 ts.tv_sec %= 3600;
316                 f = 1;
317         }
318         if (f || ts.tv_sec >= 60) {
319                 printf("%ldm", (long)ts.tv_sec / 60);
320                 ts.tv_sec %= 60;
321                 f = 1;
322         }
323         printf("%lds\n", (long)ts.tv_sec);
324 }
325
326 int
327 doadump(boolean_t textdump)
328 {
329         boolean_t coredump;
330         int error;
331
332         error = 0;
333         if (dumping)
334                 return (EBUSY);
335         if (dumper.dumper == NULL)
336                 return (ENXIO);
337
338         savectx(&dumppcb);
339         dumptid = curthread->td_tid;
340         dumping++;
341
342         coredump = TRUE;
343 #ifdef DDB
344         if (textdump && textdump_pending) {
345                 coredump = FALSE;
346                 textdump_dumpsys(&dumper);
347         }
348 #endif
349         if (coredump)
350                 error = dumpsys(&dumper);
351
352         dumping--;
353         return (error);
354 }
355
356 /*
357  * Shutdown the system cleanly to prepare for reboot, halt, or power off.
358  */
359 void
360 kern_reboot(int howto)
361 {
362         static int once = 0;
363
364 #if defined(SMP)
365         /*
366          * Bind us to CPU 0 so that all shutdown code runs there.  Some
367          * systems don't shutdown properly (i.e., ACPI power off) if we
368          * run on another processor.
369          */
370         if (!SCHEDULER_STOPPED()) {
371                 thread_lock(curthread);
372                 sched_bind(curthread, 0);
373                 thread_unlock(curthread);
374                 KASSERT(PCPU_GET(cpuid) == 0, ("boot: not running on cpu 0"));
375         }
376 #endif
377         /* We're in the process of rebooting. */
378         rebooting = 1;
379
380         /* We are out of the debugger now. */
381         kdb_active = 0;
382
383         /*
384          * Do any callouts that should be done BEFORE syncing the filesystems.
385          */
386         EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
387
388         /* 
389          * Now sync filesystems
390          */
391         if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
392                 once = 1;
393                 bufshutdown(show_busybufs);
394         }
395
396         print_uptime();
397
398         cngrab();
399
400         /*
401          * Ok, now do things that assume all filesystem activity has
402          * been completed.
403          */
404         EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
405
406         if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping) 
407                 doadump(TRUE);
408
409         /* Now that we're going to really halt the system... */
410         EVENTHANDLER_INVOKE(shutdown_final, howto);
411
412         for(;;) ;       /* safety against shutdown_reset not working */
413         /* NOTREACHED */
414 }
415
416 /*
417  * The system call that results in changing the rootfs.
418  */
419 static int
420 kern_reroot(void)
421 {
422         struct vnode *oldrootvnode, *vp;
423         struct mount *mp, *devmp;
424         int error;
425
426         if (curproc != initproc)
427                 return (EPERM);
428
429         /*
430          * Mark the filesystem containing currently-running executable
431          * (the temporary copy of init(8)) busy.
432          */
433         vp = curproc->p_textvp;
434         error = vn_lock(vp, LK_SHARED);
435         if (error != 0)
436                 return (error);
437         mp = vp->v_mount;
438         error = vfs_busy(mp, MBF_NOWAIT);
439         if (error != 0) {
440                 vfs_ref(mp);
441                 VOP_UNLOCK(vp, 0);
442                 error = vfs_busy(mp, 0);
443                 vn_lock(vp, LK_SHARED | LK_RETRY);
444                 vfs_rel(mp);
445                 if (error != 0) {
446                         VOP_UNLOCK(vp, 0);
447                         return (ENOENT);
448                 }
449                 if (vp->v_iflag & VI_DOOMED) {
450                         VOP_UNLOCK(vp, 0);
451                         vfs_unbusy(mp);
452                         return (ENOENT);
453                 }
454         }
455         VOP_UNLOCK(vp, 0);
456
457         /*
458          * Remove the filesystem containing currently-running executable
459          * from the mount list, to prevent it from being unmounted
460          * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
461          *
462          * Also preserve /dev - forcibly unmounting it could cause driver
463          * reinitialization.
464          */
465
466         vfs_ref(rootdevmp);
467         devmp = rootdevmp;
468         rootdevmp = NULL;
469
470         mtx_lock(&mountlist_mtx);
471         TAILQ_REMOVE(&mountlist, mp, mnt_list);
472         TAILQ_REMOVE(&mountlist, devmp, mnt_list);
473         mtx_unlock(&mountlist_mtx);
474
475         oldrootvnode = rootvnode;
476
477         /*
478          * Unmount everything except for the two filesystems preserved above.
479          */
480         vfs_unmountall();
481
482         /*
483          * Add /dev back; vfs_mountroot() will move it into its new place.
484          */
485         mtx_lock(&mountlist_mtx);
486         TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
487         mtx_unlock(&mountlist_mtx);
488         rootdevmp = devmp;
489         vfs_rel(rootdevmp);
490
491         /*
492          * Mount the new rootfs.
493          */
494         vfs_mountroot();
495
496         /*
497          * Update all references to the old rootvnode.
498          */
499         mountcheckdirs(oldrootvnode, rootvnode);
500
501         /*
502          * Add the temporary filesystem back and unbusy it.
503          */
504         mtx_lock(&mountlist_mtx);
505         TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
506         mtx_unlock(&mountlist_mtx);
507         vfs_unbusy(mp);
508
509         return (0);
510 }
511
512 /*
513  * If the shutdown was a clean halt, behave accordingly.
514  */
515 static void
516 shutdown_halt(void *junk, int howto)
517 {
518
519         if (howto & RB_HALT) {
520                 printf("\n");
521                 printf("The operating system has halted.\n");
522                 printf("Please press any key to reboot.\n\n");
523                 switch (cngetc()) {
524                 case -1:                /* No console, just die */
525                         cpu_halt();
526                         /* NOTREACHED */
527                 default:
528                         howto &= ~RB_HALT;
529                         break;
530                 }
531         }
532 }
533
534 /*
535  * Check to see if the system paniced, pause and then reboot
536  * according to the specified delay.
537  */
538 static void
539 shutdown_panic(void *junk, int howto)
540 {
541         int loop;
542
543         if (howto & RB_DUMP) {
544                 if (panic_reboot_wait_time != 0) {
545                         if (panic_reboot_wait_time != -1) {
546                                 printf("Automatic reboot in %d seconds - "
547                                        "press a key on the console to abort\n",
548                                         panic_reboot_wait_time);
549                                 for (loop = panic_reboot_wait_time * 10;
550                                      loop > 0; --loop) {
551                                         DELAY(1000 * 100); /* 1/10th second */
552                                         /* Did user type a key? */
553                                         if (cncheckc() != -1)
554                                                 break;
555                                 }
556                                 if (!loop)
557                                         return;
558                         }
559                 } else { /* zero time specified - reboot NOW */
560                         return;
561                 }
562                 printf("--> Press a key on the console to reboot,\n");
563                 printf("--> or switch off the system now.\n");
564                 cngetc();
565         }
566 }
567
568 /*
569  * Everything done, now reset
570  */
571 static void
572 shutdown_reset(void *junk, int howto)
573 {
574
575         printf("Rebooting...\n");
576         DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
577
578         /*
579          * Acquiring smp_ipi_mtx here has a double effect:
580          * - it disables interrupts avoiding CPU0 preemption
581          *   by fast handlers (thus deadlocking  against other CPUs)
582          * - it avoids deadlocks against smp_rendezvous() or, more 
583          *   generally, threads busy-waiting, with this spinlock held,
584          *   and waiting for responses by threads on other CPUs
585          *   (ie. smp_tlb_shootdown()).
586          *
587          * For the !SMP case it just needs to handle the former problem.
588          */
589 #ifdef SMP
590         mtx_lock_spin(&smp_ipi_mtx);
591 #else
592         spinlock_enter();
593 #endif
594
595         /* cpu_boot(howto); */ /* doesn't do anything at the moment */
596         cpu_reset();
597         /* NOTREACHED */ /* assuming reset worked */
598 }
599
600 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
601 static int kassert_warn_only = 0;
602 #ifdef KDB
603 static int kassert_do_kdb = 0;
604 #endif
605 #ifdef KTR
606 static int kassert_do_ktr = 0;
607 #endif
608 static int kassert_do_log = 1;
609 static int kassert_log_pps_limit = 4;
610 static int kassert_log_mute_at = 0;
611 static int kassert_log_panic_at = 0;
612 static int kassert_warnings = 0;
613
614 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
615
616 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
617     &kassert_warn_only, 0,
618     "KASSERT triggers a panic (1) or just a warning (0)");
619
620 #ifdef KDB
621 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
622     &kassert_do_kdb, 0, "KASSERT will enter the debugger");
623 #endif
624
625 #ifdef KTR
626 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
627     &kassert_do_ktr, 0,
628     "KASSERT does a KTR, set this to the KTRMASK you want");
629 #endif
630
631 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
632     &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
633
634 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
635     &kassert_warnings, 0, "number of KASSERTs that have been triggered");
636
637 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
638     &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
639
640 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
641     &kassert_log_pps_limit, 0, "limit number of log messages per second");
642
643 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
644     &kassert_log_mute_at, 0, "max number of KASSERTS to log");
645
646 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
647
648 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
649     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
650     kassert_sysctl_kassert, "I", "set to trigger a test kassert");
651
652 static int
653 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
654 {
655         int error, i;
656
657         error = sysctl_wire_old_buffer(req, sizeof(int));
658         if (error == 0) {
659                 i = 0;
660                 error = sysctl_handle_int(oidp, &i, 0, req);
661         }
662         if (error != 0 || req->newptr == NULL)
663                 return (error);
664         KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
665         return (0);
666 }
667
668 /*
669  * Called by KASSERT, this decides if we will panic
670  * or if we will log via printf and/or ktr.
671  */
672 void
673 kassert_panic(const char *fmt, ...)
674 {
675         static char buf[256];
676         va_list ap;
677
678         va_start(ap, fmt);
679         (void)vsnprintf(buf, sizeof(buf), fmt, ap);
680         va_end(ap);
681
682         /*
683          * panic if we're not just warning, or if we've exceeded
684          * kassert_log_panic_at warnings.
685          */
686         if (!kassert_warn_only ||
687             (kassert_log_panic_at > 0 &&
688              kassert_warnings >= kassert_log_panic_at)) {
689                 va_start(ap, fmt);
690                 vpanic(fmt, ap);
691                 /* NORETURN */
692         }
693 #ifdef KTR
694         if (kassert_do_ktr)
695                 CTR0(ktr_mask, buf);
696 #endif /* KTR */
697         /*
698          * log if we've not yet met the mute limit.
699          */
700         if (kassert_do_log &&
701             (kassert_log_mute_at == 0 ||
702              kassert_warnings < kassert_log_mute_at)) {
703                 static  struct timeval lasterr;
704                 static  int curerr;
705
706                 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
707                         printf("KASSERT failed: %s\n", buf);
708                         kdb_backtrace();
709                 }
710         }
711 #ifdef KDB
712         if (kassert_do_kdb) {
713                 kdb_enter(KDB_WHY_KASSERT, buf);
714         }
715 #endif
716         atomic_add_int(&kassert_warnings, 1);
717 }
718 #endif
719
720 /*
721  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
722  * and then reboots.  If we are called twice, then we avoid trying to sync
723  * the disks as this often leads to recursive panics.
724  */
725 void
726 panic(const char *fmt, ...)
727 {
728         va_list ap;
729
730         va_start(ap, fmt);
731         vpanic(fmt, ap);
732 }
733
734 void
735 vpanic(const char *fmt, va_list ap)
736 {
737 #ifdef SMP
738         cpuset_t other_cpus;
739 #endif
740         struct thread *td = curthread;
741         int bootopt, newpanic;
742         static char buf[256];
743
744         spinlock_enter();
745
746 #ifdef SMP
747         /*
748          * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
749          * concurrently entering panic.  Only the winner will proceed
750          * further.
751          */
752         if (panicstr == NULL && !kdb_active) {
753                 other_cpus = all_cpus;
754                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
755                 stop_cpus_hard(other_cpus);
756         }
757 #endif
758
759         /*
760          * Ensure that the scheduler is stopped while panicking, even if panic
761          * has been entered from kdb.
762          */
763         td->td_stopsched = 1;
764
765         bootopt = RB_AUTOBOOT;
766         newpanic = 0;
767         if (panicstr)
768                 bootopt |= RB_NOSYNC;
769         else {
770                 bootopt |= RB_DUMP;
771                 panicstr = fmt;
772                 newpanic = 1;
773         }
774
775         if (newpanic) {
776                 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
777                 panicstr = buf;
778                 cngrab();
779                 printf("panic: %s\n", buf);
780         } else {
781                 printf("panic: ");
782                 vprintf(fmt, ap);
783                 printf("\n");
784         }
785 #ifdef SMP
786         printf("cpuid = %d\n", PCPU_GET(cpuid));
787 #endif
788         printf("time = %jd\n", (intmax_t )time_second);
789 #ifdef KDB
790         if (newpanic && trace_on_panic)
791                 kdb_backtrace();
792         if (debugger_on_panic)
793                 kdb_enter(KDB_WHY_PANIC, "panic");
794 #endif
795         /*thread_lock(td); */
796         td->td_flags |= TDF_INPANIC;
797         /* thread_unlock(td); */
798         if (!sync_on_panic)
799                 bootopt |= RB_NOSYNC;
800         kern_reboot(bootopt);
801 }
802
803 /*
804  * Support for poweroff delay.
805  *
806  * Please note that setting this delay too short might power off your machine
807  * before the write cache on your hard disk has been flushed, leading to
808  * soft-updates inconsistencies.
809  */
810 #ifndef POWEROFF_DELAY
811 # define POWEROFF_DELAY 5000
812 #endif
813 static int poweroff_delay = POWEROFF_DELAY;
814
815 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
816     &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
817
818 static void
819 poweroff_wait(void *junk, int howto)
820 {
821
822         if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
823                 return;
824         DELAY(poweroff_delay * 1000);
825 }
826
827 /*
828  * Some system processes (e.g. syncer) need to be stopped at appropriate
829  * points in their main loops prior to a system shutdown, so that they
830  * won't interfere with the shutdown process (e.g. by holding a disk buf
831  * to cause sync to fail).  For each of these system processes, register
832  * shutdown_kproc() as a handler for one of shutdown events.
833  */
834 static int kproc_shutdown_wait = 60;
835 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
836     &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
837
838 void
839 kproc_shutdown(void *arg, int howto)
840 {
841         struct proc *p;
842         int error;
843
844         if (panicstr)
845                 return;
846
847         p = (struct proc *)arg;
848         printf("Waiting (max %d seconds) for system process `%s' to stop... ",
849             kproc_shutdown_wait, p->p_comm);
850         error = kproc_suspend(p, kproc_shutdown_wait * hz);
851
852         if (error == EWOULDBLOCK)
853                 printf("timed out\n");
854         else
855                 printf("done\n");
856 }
857
858 void
859 kthread_shutdown(void *arg, int howto)
860 {
861         struct thread *td;
862         int error;
863
864         if (panicstr)
865                 return;
866
867         td = (struct thread *)arg;
868         printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
869             kproc_shutdown_wait, td->td_name);
870         error = kthread_suspend(td, kproc_shutdown_wait * hz);
871
872         if (error == EWOULDBLOCK)
873                 printf("timed out\n");
874         else
875                 printf("done\n");
876 }
877
878 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
879 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
880     dumpdevname, 0, "Device for kernel dumps");
881
882 static int      _dump_append(struct dumperinfo *di, void *virtual,
883                     vm_offset_t physical, size_t length);
884
885 #ifdef EKCD
886 static struct kerneldumpcrypto *
887 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
888     const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
889 {
890         struct kerneldumpcrypto *kdc;
891         struct kerneldumpkey *kdk;
892         uint32_t dumpkeysize;
893
894         dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
895         kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
896
897         arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
898
899         kdc->kdc_encryption = encryption;
900         switch (kdc->kdc_encryption) {
901         case KERNELDUMP_ENC_AES_256_CBC:
902                 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
903                         goto failed;
904                 break;
905         default:
906                 goto failed;
907         }
908
909         kdc->kdc_dumpkeysize = dumpkeysize;
910         kdk = kdc->kdc_dumpkey;
911         kdk->kdk_encryption = kdc->kdc_encryption;
912         memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
913         kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
914         memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
915
916         return (kdc);
917 failed:
918         explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
919         free(kdc, M_EKCD);
920         return (NULL);
921 }
922
923 static int
924 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
925 {
926         uint8_t hash[SHA256_DIGEST_LENGTH];
927         SHA256_CTX ctx;
928         struct kerneldumpkey *kdk;
929         int error;
930
931         error = 0;
932
933         if (kdc == NULL)
934                 return (0);
935
936         /*
937          * When a user enters ddb it can write a crash dump multiple times.
938          * Each time it should be encrypted using a different IV.
939          */
940         SHA256_Init(&ctx);
941         SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
942         SHA256_Final(hash, &ctx);
943         bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
944
945         switch (kdc->kdc_encryption) {
946         case KERNELDUMP_ENC_AES_256_CBC:
947                 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
948                     kdc->kdc_iv) <= 0) {
949                         error = EINVAL;
950                         goto out;
951                 }
952                 break;
953         default:
954                 error = EINVAL;
955                 goto out;
956         }
957
958         kdk = kdc->kdc_dumpkey;
959         memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
960 out:
961         explicit_bzero(hash, sizeof(hash));
962         return (error);
963 }
964
965 static uint32_t
966 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
967 {
968
969         if (kdc == NULL)
970                 return (0);
971         return (kdc->kdc_dumpkeysize);
972 }
973 #endif /* EKCD */
974
975 #ifdef GZIO
976 static struct kerneldumpgz *
977 kerneldumpgz_create(struct dumperinfo *di, uint8_t compression)
978 {
979         struct kerneldumpgz *kdgz;
980
981         if (compression != KERNELDUMP_COMP_GZIP)
982                 return (NULL);
983         kdgz = malloc(sizeof(*kdgz), M_DUMPER, M_WAITOK | M_ZERO);
984         kdgz->kdgz_stream = gzio_init(kerneldumpgz_write_cb, GZIO_DEFLATE,
985             di->maxiosize, kerneldump_gzlevel, di);
986         if (kdgz->kdgz_stream == NULL) {
987                 free(kdgz, M_DUMPER);
988                 return (NULL);
989         }
990         kdgz->kdgz_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
991         return (kdgz);
992 }
993
994 static void
995 kerneldumpgz_destroy(struct dumperinfo *di)
996 {
997         struct kerneldumpgz *kdgz;
998
999         kdgz = di->kdgz;
1000         if (kdgz == NULL)
1001                 return;
1002         gzio_fini(kdgz->kdgz_stream);
1003         explicit_bzero(kdgz->kdgz_buf, di->maxiosize);
1004         free(kdgz->kdgz_buf, M_DUMPER);
1005         free(kdgz, M_DUMPER);
1006 }
1007 #endif /* GZIO */
1008
1009 /* Registration of dumpers */
1010 int
1011 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1012     uint8_t compression, uint8_t encryption, const uint8_t *key,
1013     uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1014 {
1015         size_t wantcopy;
1016         int error;
1017
1018         error = priv_check(td, PRIV_SETDUMPER);
1019         if (error != 0)
1020                 return (error);
1021
1022         if (di == NULL) {
1023                 error = 0;
1024                 goto cleanup;
1025         }
1026         if (dumper.dumper != NULL)
1027                 return (EBUSY);
1028         dumper = *di;
1029         dumper.blockbuf = NULL;
1030         dumper.kdc = NULL;
1031         dumper.kdgz = NULL;
1032
1033         if (encryption != KERNELDUMP_ENC_NONE) {
1034 #ifdef EKCD
1035                 dumper.kdc = kerneldumpcrypto_create(di->blocksize, encryption,
1036                     key, encryptedkeysize, encryptedkey);
1037                 if (dumper.kdc == NULL) {
1038                         error = EINVAL;
1039                         goto cleanup;
1040                 }
1041 #else
1042                 error = EOPNOTSUPP;
1043                 goto cleanup;
1044 #endif
1045         }
1046
1047         wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1048         if (wantcopy >= sizeof(dumpdevname)) {
1049                 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1050                     devname, dumpdevname);
1051         }
1052
1053         if (compression != KERNELDUMP_COMP_NONE) {
1054 #ifdef GZIO
1055                 /*
1056                  * We currently can't support simultaneous encryption and
1057                  * compression.
1058                  */
1059                 if (encryption != KERNELDUMP_ENC_NONE) {
1060                         error = EOPNOTSUPP;
1061                         goto cleanup;
1062                 }
1063                 dumper.kdgz = kerneldumpgz_create(&dumper, compression);
1064                 if (dumper.kdgz == NULL) {
1065                         error = EINVAL;
1066                         goto cleanup;
1067                 }
1068 #else
1069                 error = EOPNOTSUPP;
1070                 goto cleanup;
1071 #endif
1072         }
1073
1074         dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1075         return (0);
1076 cleanup:
1077 #ifdef EKCD
1078         if (dumper.kdc != NULL) {
1079                 explicit_bzero(dumper.kdc, sizeof(*dumper.kdc) +
1080                     dumper.kdc->kdc_dumpkeysize);
1081                 free(dumper.kdc, M_EKCD);
1082         }
1083 #endif
1084
1085 #ifdef GZIO
1086         kerneldumpgz_destroy(&dumper);
1087 #endif
1088
1089         if (dumper.blockbuf != NULL) {
1090                 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1091                 free(dumper.blockbuf, M_DUMPER);
1092         }
1093         explicit_bzero(&dumper, sizeof(dumper));
1094         dumpdevname[0] = '\0';
1095         return (error);
1096 }
1097
1098 static int
1099 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1100 {
1101
1102         if (length != 0 && (offset < di->mediaoffset ||
1103             offset - di->mediaoffset + length > di->mediasize)) {
1104                 printf("Attempt to write outside dump device boundaries.\n"
1105             "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1106                     (intmax_t)offset, (intmax_t)di->mediaoffset,
1107                     (uintmax_t)length, (intmax_t)di->mediasize);
1108                 return (ENOSPC);
1109         }
1110         if (length % di->blocksize != 0) {
1111                 printf("Attempt to write partial block of length %ju.\n",
1112                     (uintmax_t)length);
1113                 return (EINVAL);
1114         }
1115         if (offset % di->blocksize != 0) {
1116                 printf("Attempt to write at unaligned offset %jd.\n",
1117                     (intmax_t)offset);
1118                 return (EINVAL);
1119         }
1120
1121         return (0);
1122 }
1123
1124 #ifdef EKCD
1125 static int
1126 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1127 {
1128
1129         switch (kdc->kdc_encryption) {
1130         case KERNELDUMP_ENC_AES_256_CBC:
1131                 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1132                     8 * size, buf) <= 0) {
1133                         return (EIO);
1134                 }
1135                 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1136                     buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1137                         return (EIO);
1138                 }
1139                 break;
1140         default:
1141                 return (EINVAL);
1142         }
1143
1144         return (0);
1145 }
1146
1147 /* Encrypt data and call dumper. */
1148 static int
1149 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1150     vm_offset_t physical, off_t offset, size_t length)
1151 {
1152         static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1153         struct kerneldumpcrypto *kdc;
1154         int error;
1155         size_t nbytes;
1156
1157         kdc = di->kdc;
1158
1159         while (length > 0) {
1160                 nbytes = MIN(length, sizeof(buf));
1161                 bcopy(virtual, buf, nbytes);
1162
1163                 if (dump_encrypt(kdc, buf, nbytes) != 0)
1164                         return (EIO);
1165
1166                 error = dump_write(di, buf, physical, offset, nbytes);
1167                 if (error != 0)
1168                         return (error);
1169
1170                 offset += nbytes;
1171                 virtual = (void *)((uint8_t *)virtual + nbytes);
1172                 length -= nbytes;
1173         }
1174
1175         return (0);
1176 }
1177
1178 static int
1179 dump_write_key(struct dumperinfo *di, off_t offset)
1180 {
1181         struct kerneldumpcrypto *kdc;
1182
1183         kdc = di->kdc;
1184         if (kdc == NULL)
1185                 return (0);
1186         return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1187             kdc->kdc_dumpkeysize));
1188 }
1189 #endif /* EKCD */
1190
1191 #ifdef GZIO
1192 static int
1193 kerneldumpgz_write_cb(void *base, size_t length, off_t offset, void *arg)
1194 {
1195         struct dumperinfo *di;
1196         size_t resid, rlength;
1197         int error;
1198
1199         di = arg;
1200
1201         if (length % di->blocksize != 0) {
1202                 /*
1203                  * This must be the final write after flushing the compression
1204                  * stream. Write as many full blocks as possible and stash the
1205                  * residual data in the dumper's block buffer. It will be
1206                  * padded and written in dump_finish().
1207                  */
1208                 rlength = rounddown(length, di->blocksize);
1209                 if (rlength != 0) {
1210                         error = _dump_append(di, base, 0, rlength);
1211                         if (error != 0)
1212                                 return (error);
1213                 }
1214                 resid = length - rlength;
1215                 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1216                 di->kdgz->kdgz_resid = resid;
1217                 return (EAGAIN);
1218         }
1219         return (_dump_append(di, base, 0, length));
1220 }
1221 #endif /* GZIO */
1222
1223 /*
1224  * Write a kerneldumpheader at the specified offset. The header structure is 512
1225  * bytes in size, but we must pad to the device sector size.
1226  */
1227 static int
1228 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1229     off_t offset)
1230 {
1231         void *buf;
1232         size_t hdrsz;
1233
1234         hdrsz = sizeof(*kdh);
1235         if (hdrsz > di->blocksize)
1236                 return (ENOMEM);
1237
1238         if (hdrsz == di->blocksize)
1239                 buf = kdh;
1240         else {
1241                 buf = di->blockbuf;
1242                 memset(buf, 0, di->blocksize);
1243                 memcpy(buf, kdh, hdrsz);
1244         }
1245
1246         return (dump_write(di, buf, 0, offset, di->blocksize));
1247 }
1248
1249 /*
1250  * Don't touch the first SIZEOF_METADATA bytes on the dump device.  This is to
1251  * protect us from metadata and metadata from us.
1252  */
1253 #define SIZEOF_METADATA         (64 * 1024)
1254
1255 /*
1256  * Do some preliminary setup for a kernel dump: initialize state for encryption,
1257  * if requested, and make sure that we have enough space on the dump device.
1258  *
1259  * We set things up so that the dump ends before the last sector of the dump
1260  * device, at which the trailing header is written.
1261  *
1262  *     +-----------+------+-----+----------------------------+------+
1263  *     |           | lhdr | key |    ... kernel dump ...     | thdr |
1264  *     +-----------+------+-----+----------------------------+------+
1265  *                   1 blk  opt <------- dump extent --------> 1 blk
1266  *
1267  * Dumps written using dump_append() start at the beginning of the extent.
1268  * Uncompressed dumps will use the entire extent, but compressed dumps typically
1269  * will not. The true length of the dump is recorded in the leading and trailing
1270  * headers once the dump has been completed.
1271  */
1272 int
1273 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1274 {
1275         uint64_t dumpextent;
1276         uint32_t keysize;
1277
1278 #ifdef EKCD
1279         int error = kerneldumpcrypto_init(di->kdc);
1280         if (error != 0)
1281                 return (error);
1282         keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1283 #else
1284         keysize = 0;
1285 #endif
1286
1287         dumpextent = dtoh64(kdh->dumpextent);
1288         if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1289             keysize) {
1290 #ifdef GZIO
1291                 if (di->kdgz != NULL) {
1292                         /*
1293                          * We don't yet know how much space the compressed dump
1294                          * will occupy, so try to use the whole swap partition
1295                          * (minus the first 64KB) in the hope that the
1296                          * compressed dump will fit. If that doesn't turn out to
1297                          * be enouch, the bounds checking in dump_write()
1298                          * will catch us and cause the dump to fail.
1299                          */
1300                         dumpextent = di->mediasize - SIZEOF_METADATA -
1301                             2 * di->blocksize - keysize;
1302                         kdh->dumpextent = htod64(dumpextent);
1303                 } else
1304 #endif
1305                         return (E2BIG);
1306         }
1307
1308         /* The offset at which to begin writing the dump. */
1309         di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1310             dumpextent;
1311
1312         return (0);
1313 }
1314
1315 static int
1316 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1317     size_t length)
1318 {
1319         int error;
1320
1321 #ifdef EKCD
1322         if (di->kdc != NULL)
1323                 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1324                     length);
1325         else
1326 #endif
1327                 error = dump_write(di, virtual, physical, di->dumpoff, length);
1328         if (error == 0)
1329                 di->dumpoff += length;
1330         return (error);
1331 }
1332
1333 /*
1334  * Write to the dump device starting at dumpoff. When compression is enabled,
1335  * writes to the device will be performed using a callback that gets invoked
1336  * when the compression stream's output buffer is full.
1337  */
1338 int
1339 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1340     size_t length)
1341 {
1342 #ifdef GZIO
1343         void *buf;
1344
1345         if (di->kdgz != NULL) {
1346                 /* Bounce through a buffer to avoid gzip CRC errors. */
1347                 if (length > di->maxiosize)
1348                         return (EINVAL);
1349                 buf = di->kdgz->kdgz_buf;
1350                 memmove(buf, virtual, length);
1351                 return (gzio_write(di->kdgz->kdgz_stream, buf, length));
1352         }
1353 #endif
1354         return (_dump_append(di, virtual, physical, length));
1355 }
1356
1357 /*
1358  * Write to the dump device at the specified offset.
1359  */
1360 int
1361 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1362     off_t offset, size_t length)
1363 {
1364         int error;
1365
1366         error = dump_check_bounds(di, offset, length);
1367         if (error != 0)
1368                 return (error);
1369         return (di->dumper(di->priv, virtual, physical, offset, length));
1370 }
1371
1372 /*
1373  * Perform kernel dump finalization: flush the compression stream, if necessary,
1374  * write the leading and trailing kernel dump headers now that we know the true
1375  * length of the dump, and optionally write the encryption key following the
1376  * leading header.
1377  */
1378 int
1379 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1380 {
1381         uint64_t extent;
1382         uint32_t keysize;
1383         int error;
1384
1385         extent = dtoh64(kdh->dumpextent);
1386
1387 #ifdef EKCD
1388         keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1389 #else
1390         keysize = 0;
1391 #endif
1392
1393 #ifdef GZIO
1394         if (di->kdgz != NULL) {
1395                 error = gzio_flush(di->kdgz->kdgz_stream);
1396                 if (error == EAGAIN) {
1397                         /* We have residual data in di->blockbuf. */
1398                         error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1399                             di->blocksize);
1400                         di->dumpoff += di->kdgz->kdgz_resid;
1401                         di->kdgz->kdgz_resid = 0;
1402                 }
1403                 if (error != 0)
1404                         return (error);
1405
1406                 /*
1407                  * We now know the size of the compressed dump, so update the
1408                  * header accordingly and recompute parity.
1409                  */
1410                 kdh->dumplength = htod64(di->dumpoff -
1411                     (di->mediaoffset + di->mediasize - di->blocksize - extent));
1412                 kdh->parity = 0;
1413                 kdh->parity = kerneldump_parity(kdh);
1414
1415                 gzio_reset(di->kdgz->kdgz_stream);
1416         }
1417 #endif
1418
1419         /*
1420          * Write kerneldump headers at the beginning and end of the dump extent.
1421          * Write the key after the leading header.
1422          */
1423         error = dump_write_header(di, kdh,
1424             di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1425             keysize);
1426         if (error != 0)
1427                 return (error);
1428
1429 #ifdef EKCD
1430         error = dump_write_key(di,
1431             di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1432         if (error != 0)
1433                 return (error);
1434 #endif
1435
1436         error = dump_write_header(di, kdh,
1437             di->mediaoffset + di->mediasize - di->blocksize);
1438         if (error != 0)
1439                 return (error);
1440
1441         (void)dump_write(di, NULL, 0, 0, 0);
1442         return (0);
1443 }
1444
1445 void
1446 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1447     char *magic, uint32_t archver, uint64_t dumplen)
1448 {
1449         size_t dstsize;
1450
1451         bzero(kdh, sizeof(*kdh));
1452         strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1453         strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1454         kdh->version = htod32(KERNELDUMPVERSION);
1455         kdh->architectureversion = htod32(archver);
1456         kdh->dumplength = htod64(dumplen);
1457         kdh->dumpextent = kdh->dumplength;
1458         kdh->dumptime = htod64(time_second);
1459 #ifdef EKCD
1460         kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdc));
1461 #else
1462         kdh->dumpkeysize = 0;
1463 #endif
1464         kdh->blocksize = htod32(di->blocksize);
1465         strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1466         dstsize = sizeof(kdh->versionstring);
1467         if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1468                 kdh->versionstring[dstsize - 2] = '\n';
1469         if (panicstr != NULL)
1470                 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1471 #ifdef GZIO
1472         if (di->kdgz != NULL)
1473                 kdh->compression = KERNELDUMP_COMP_GZIP;
1474 #endif
1475         kdh->parity = kerneldump_parity(kdh);
1476 }
1477
1478 #ifdef DDB
1479 DB_SHOW_COMMAND(panic, db_show_panic)
1480 {
1481
1482         if (panicstr == NULL)
1483                 db_printf("panicstr not set\n");
1484         else
1485                 db_printf("panic: %s\n", panicstr);
1486 }
1487 #endif