2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1986, 1988, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_shutdown.c 8.3 (Berkeley) 1/21/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
46 #include "opt_panic.h"
47 #include "opt_sched.h"
48 #include "opt_watchdog.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
56 #include <sys/eventhandler.h>
57 #include <sys/filedesc.h>
61 #include <sys/kernel.h>
62 #include <sys/kerneldump.h>
63 #include <sys/kthread.h>
65 #include <sys/malloc.h>
66 #include <sys/mount.h>
69 #include <sys/reboot.h>
70 #include <sys/resourcevar.h>
71 #include <sys/rwlock.h>
72 #include <sys/sched.h>
74 #include <sys/sysctl.h>
75 #include <sys/sysproto.h>
76 #include <sys/vnode.h>
77 #include <sys/watchdog.h>
79 #include <crypto/rijndael/rijndael-api-fst.h>
80 #include <crypto/sha2/sha256.h>
84 #include <machine/cpu.h>
85 #include <machine/dump.h>
86 #include <machine/pcb.h>
87 #include <machine/smp.h>
89 #include <security/mac/mac_framework.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pager.h>
95 #include <vm/swap_pager.h>
97 #include <sys/signalvar.h>
99 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
101 #ifndef PANIC_REBOOT_WAIT_TIME
102 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
104 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
105 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
106 &panic_reboot_wait_time, 0,
107 "Seconds to wait before rebooting after a panic");
110 * Note that stdarg.h and the ANSI style va_start macro is used for both
111 * ANSI and traditional C compilers.
113 #include <machine/stdarg.h>
116 #ifdef KDB_UNATTENDED
117 int debugger_on_panic = 0;
119 int debugger_on_panic = 1;
121 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
122 CTLFLAG_RWTUN | CTLFLAG_SECURE,
123 &debugger_on_panic, 0, "Run debugger on kernel panic");
126 static int trace_on_panic = 1;
128 static int trace_on_panic = 0;
130 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
131 CTLFLAG_RWTUN | CTLFLAG_SECURE,
132 &trace_on_panic, 0, "Print stack trace on kernel panic");
135 static int sync_on_panic = 0;
136 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
137 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
139 static bool poweroff_on_panic = 0;
140 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
141 &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
143 static bool powercycle_on_panic = 0;
144 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
145 &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
147 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
148 "Shutdown environment");
151 static int show_busybufs;
153 static int show_busybufs = 1;
155 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
156 &show_busybufs, 0, "");
158 int suspend_blocked = 0;
159 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
160 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
163 FEATURE(ekcd, "Encrypted kernel crash dumps support");
165 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
167 struct kerneldumpcrypto {
168 uint8_t kdc_encryption;
169 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
171 cipherInstance kdc_ci;
172 uint32_t kdc_dumpkeysize;
173 struct kerneldumpkey kdc_dumpkey[];
178 struct kerneldumpgz {
179 struct gzio_stream *kdgz_stream;
184 static struct kerneldumpgz *kerneldumpgz_create(struct dumperinfo *di,
185 uint8_t compression);
186 static void kerneldumpgz_destroy(struct dumperinfo *di);
187 static int kerneldumpgz_write_cb(void *cb, size_t len, off_t off, void *arg);
189 static int kerneldump_gzlevel = 6;
190 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
191 &kerneldump_gzlevel, 0,
192 "Kernel crash dump gzip compression level");
196 * Variable panicstr contains argument to first call to panic; used as flag
197 * to indicate that the kernel has already called panic.
199 const char *panicstr;
201 int dumping; /* system is dumping */
202 int rebooting; /* system is rebooting */
203 static struct dumperinfo dumper; /* our selected dumper */
205 /* Context information for dump-debuggers. */
206 static struct pcb dumppcb; /* Registers. */
207 lwpid_t dumptid; /* Thread ID. */
209 static struct cdevsw reroot_cdevsw = {
210 .d_version = D_VERSION,
214 static void poweroff_wait(void *, int);
215 static void shutdown_halt(void *junk, int howto);
216 static void shutdown_panic(void *junk, int howto);
217 static void shutdown_reset(void *junk, int howto);
218 static int kern_reroot(void);
220 /* register various local shutdown events */
222 shutdown_conf(void *unused)
225 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
227 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
228 SHUTDOWN_PRI_LAST + 100);
229 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
230 SHUTDOWN_PRI_LAST + 100);
231 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
232 SHUTDOWN_PRI_LAST + 200);
235 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
238 * The only reason this exists is to create the /dev/reroot/ directory,
239 * used by reroot code in init(8) as a mountpoint for tmpfs.
242 reroot_conf(void *unused)
247 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
248 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
250 printf("%s: failed to create device node, error %d",
255 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
258 * The system call that results in a reboot.
262 sys_reboot(struct thread *td, struct reboot_args *uap)
268 error = mac_system_check_reboot(td->td_ucred, uap->opt);
271 error = priv_check(td, PRIV_REBOOT);
273 if (uap->opt & RB_REROOT) {
274 error = kern_reroot();
277 kern_reboot(uap->opt);
285 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
288 shutdown_nice(int howto)
291 if (initproc != NULL) {
292 /* Send a signal to init(8) and have it shutdown the world. */
294 if (howto & RB_POWEROFF)
295 kern_psignal(initproc, SIGUSR2);
296 else if (howto & RB_POWERCYCLE)
297 kern_psignal(initproc, SIGWINCH);
298 else if (howto & RB_HALT)
299 kern_psignal(initproc, SIGUSR1);
301 kern_psignal(initproc, SIGINT);
302 PROC_UNLOCK(initproc);
304 /* No init(8) running, so simply reboot. */
305 kern_reboot(howto | RB_NOSYNC);
318 if (ts.tv_sec >= 86400) {
319 printf("%ldd", (long)ts.tv_sec / 86400);
323 if (f || ts.tv_sec >= 3600) {
324 printf("%ldh", (long)ts.tv_sec / 3600);
328 if (f || ts.tv_sec >= 60) {
329 printf("%ldm", (long)ts.tv_sec / 60);
333 printf("%lds\n", (long)ts.tv_sec);
337 doadump(boolean_t textdump)
345 if (dumper.dumper == NULL)
349 dumptid = curthread->td_tid;
354 if (textdump && textdump_pending) {
356 textdump_dumpsys(&dumper);
360 error = dumpsys(&dumper);
367 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
370 kern_reboot(int howto)
376 * Bind us to the first CPU so that all shutdown code runs there. Some
377 * systems don't shutdown properly (i.e., ACPI power off) if we
378 * run on another processor.
380 if (!SCHEDULER_STOPPED()) {
381 thread_lock(curthread);
382 sched_bind(curthread, CPU_FIRST());
383 thread_unlock(curthread);
384 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
385 ("boot: not running on cpu 0"));
388 /* We're in the process of rebooting. */
391 /* We are out of the debugger now. */
395 * Do any callouts that should be done BEFORE syncing the filesystems.
397 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
400 * Now sync filesystems
402 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
404 bufshutdown(show_busybufs);
412 * Ok, now do things that assume all filesystem activity has
415 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
417 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
420 /* Now that we're going to really halt the system... */
421 EVENTHANDLER_INVOKE(shutdown_final, howto);
423 for(;;) ; /* safety against shutdown_reset not working */
428 * The system call that results in changing the rootfs.
433 struct vnode *oldrootvnode, *vp;
434 struct mount *mp, *devmp;
437 if (curproc != initproc)
441 * Mark the filesystem containing currently-running executable
442 * (the temporary copy of init(8)) busy.
444 vp = curproc->p_textvp;
445 error = vn_lock(vp, LK_SHARED);
449 error = vfs_busy(mp, MBF_NOWAIT);
453 error = vfs_busy(mp, 0);
454 vn_lock(vp, LK_SHARED | LK_RETRY);
460 if (vp->v_iflag & VI_DOOMED) {
469 * Remove the filesystem containing currently-running executable
470 * from the mount list, to prevent it from being unmounted
471 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
473 * Also preserve /dev - forcibly unmounting it could cause driver
481 mtx_lock(&mountlist_mtx);
482 TAILQ_REMOVE(&mountlist, mp, mnt_list);
483 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
484 mtx_unlock(&mountlist_mtx);
486 oldrootvnode = rootvnode;
489 * Unmount everything except for the two filesystems preserved above.
494 * Add /dev back; vfs_mountroot() will move it into its new place.
496 mtx_lock(&mountlist_mtx);
497 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
498 mtx_unlock(&mountlist_mtx);
503 * Mount the new rootfs.
508 * Update all references to the old rootvnode.
510 mountcheckdirs(oldrootvnode, rootvnode);
513 * Add the temporary filesystem back and unbusy it.
515 mtx_lock(&mountlist_mtx);
516 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
517 mtx_unlock(&mountlist_mtx);
524 * If the shutdown was a clean halt, behave accordingly.
527 shutdown_halt(void *junk, int howto)
530 if (howto & RB_HALT) {
532 printf("The operating system has halted.\n");
533 printf("Please press any key to reboot.\n\n");
535 case -1: /* No console, just die */
545 * Check to see if the system paniced, pause and then reboot
546 * according to the specified delay.
549 shutdown_panic(void *junk, int howto)
553 if (howto & RB_DUMP) {
554 if (panic_reboot_wait_time != 0) {
555 if (panic_reboot_wait_time != -1) {
556 printf("Automatic reboot in %d seconds - "
557 "press a key on the console to abort\n",
558 panic_reboot_wait_time);
559 for (loop = panic_reboot_wait_time * 10;
561 DELAY(1000 * 100); /* 1/10th second */
562 /* Did user type a key? */
563 if (cncheckc() != -1)
569 } else { /* zero time specified - reboot NOW */
572 printf("--> Press a key on the console to reboot,\n");
573 printf("--> or switch off the system now.\n");
579 * Everything done, now reset
582 shutdown_reset(void *junk, int howto)
585 printf("Rebooting...\n");
586 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
589 * Acquiring smp_ipi_mtx here has a double effect:
590 * - it disables interrupts avoiding CPU0 preemption
591 * by fast handlers (thus deadlocking against other CPUs)
592 * - it avoids deadlocks against smp_rendezvous() or, more
593 * generally, threads busy-waiting, with this spinlock held,
594 * and waiting for responses by threads on other CPUs
595 * (ie. smp_tlb_shootdown()).
597 * For the !SMP case it just needs to handle the former problem.
600 mtx_lock_spin(&smp_ipi_mtx);
605 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
607 /* NOTREACHED */ /* assuming reset worked */
610 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
611 static int kassert_warn_only = 0;
613 static int kassert_do_kdb = 0;
616 static int kassert_do_ktr = 0;
618 static int kassert_do_log = 1;
619 static int kassert_log_pps_limit = 4;
620 static int kassert_log_mute_at = 0;
621 static int kassert_log_panic_at = 0;
622 static int kassert_warnings = 0;
624 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
626 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
627 &kassert_warn_only, 0,
628 "KASSERT triggers a panic (1) or just a warning (0)");
631 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
632 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
636 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
638 "KASSERT does a KTR, set this to the KTRMASK you want");
641 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
642 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
644 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
645 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
647 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
648 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
650 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
651 &kassert_log_pps_limit, 0, "limit number of log messages per second");
653 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
654 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
656 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
658 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
659 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
660 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
663 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
667 error = sysctl_wire_old_buffer(req, sizeof(int));
670 error = sysctl_handle_int(oidp, &i, 0, req);
672 if (error != 0 || req->newptr == NULL)
674 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
679 * Called by KASSERT, this decides if we will panic
680 * or if we will log via printf and/or ktr.
683 kassert_panic(const char *fmt, ...)
685 static char buf[256];
689 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
693 * panic if we're not just warning, or if we've exceeded
694 * kassert_log_panic_at warnings.
696 if (!kassert_warn_only ||
697 (kassert_log_panic_at > 0 &&
698 kassert_warnings >= kassert_log_panic_at)) {
708 * log if we've not yet met the mute limit.
710 if (kassert_do_log &&
711 (kassert_log_mute_at == 0 ||
712 kassert_warnings < kassert_log_mute_at)) {
713 static struct timeval lasterr;
716 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
717 printf("KASSERT failed: %s\n", buf);
722 if (kassert_do_kdb) {
723 kdb_enter(KDB_WHY_KASSERT, buf);
726 atomic_add_int(&kassert_warnings, 1);
731 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
732 * and then reboots. If we are called twice, then we avoid trying to sync
733 * the disks as this often leads to recursive panics.
736 panic(const char *fmt, ...)
745 vpanic(const char *fmt, va_list ap)
750 struct thread *td = curthread;
751 int bootopt, newpanic;
752 static char buf[256];
758 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
759 * concurrently entering panic. Only the winner will proceed
762 if (panicstr == NULL && !kdb_active) {
763 other_cpus = all_cpus;
764 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
765 stop_cpus_hard(other_cpus);
770 * Ensure that the scheduler is stopped while panicking, even if panic
771 * has been entered from kdb.
773 td->td_stopsched = 1;
775 bootopt = RB_AUTOBOOT;
778 bootopt |= RB_NOSYNC;
786 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
789 printf("panic: %s\n", buf);
796 printf("cpuid = %d\n", PCPU_GET(cpuid));
798 printf("time = %jd\n", (intmax_t )time_second);
800 if (newpanic && trace_on_panic)
802 if (debugger_on_panic)
803 kdb_enter(KDB_WHY_PANIC, "panic");
805 /*thread_lock(td); */
806 td->td_flags |= TDF_INPANIC;
807 /* thread_unlock(td); */
809 bootopt |= RB_NOSYNC;
810 if (poweroff_on_panic)
811 bootopt |= RB_POWEROFF;
812 if (powercycle_on_panic)
813 bootopt |= RB_POWERCYCLE;
814 kern_reboot(bootopt);
818 * Support for poweroff delay.
820 * Please note that setting this delay too short might power off your machine
821 * before the write cache on your hard disk has been flushed, leading to
822 * soft-updates inconsistencies.
824 #ifndef POWEROFF_DELAY
825 # define POWEROFF_DELAY 5000
827 static int poweroff_delay = POWEROFF_DELAY;
829 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
830 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
833 poweroff_wait(void *junk, int howto)
836 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
838 DELAY(poweroff_delay * 1000);
842 * Some system processes (e.g. syncer) need to be stopped at appropriate
843 * points in their main loops prior to a system shutdown, so that they
844 * won't interfere with the shutdown process (e.g. by holding a disk buf
845 * to cause sync to fail). For each of these system processes, register
846 * shutdown_kproc() as a handler for one of shutdown events.
848 static int kproc_shutdown_wait = 60;
849 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
850 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
853 kproc_shutdown(void *arg, int howto)
861 p = (struct proc *)arg;
862 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
863 kproc_shutdown_wait, p->p_comm);
864 error = kproc_suspend(p, kproc_shutdown_wait * hz);
866 if (error == EWOULDBLOCK)
867 printf("timed out\n");
873 kthread_shutdown(void *arg, int howto)
881 td = (struct thread *)arg;
882 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
883 kproc_shutdown_wait, td->td_name);
884 error = kthread_suspend(td, kproc_shutdown_wait * hz);
886 if (error == EWOULDBLOCK)
887 printf("timed out\n");
892 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
893 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
894 dumpdevname, 0, "Device for kernel dumps");
896 static int _dump_append(struct dumperinfo *di, void *virtual,
897 vm_offset_t physical, size_t length);
900 static struct kerneldumpcrypto *
901 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
902 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
904 struct kerneldumpcrypto *kdc;
905 struct kerneldumpkey *kdk;
906 uint32_t dumpkeysize;
908 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
909 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
911 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
913 kdc->kdc_encryption = encryption;
914 switch (kdc->kdc_encryption) {
915 case KERNELDUMP_ENC_AES_256_CBC:
916 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
923 kdc->kdc_dumpkeysize = dumpkeysize;
924 kdk = kdc->kdc_dumpkey;
925 kdk->kdk_encryption = kdc->kdc_encryption;
926 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
927 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
928 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
932 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
938 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
940 uint8_t hash[SHA256_DIGEST_LENGTH];
942 struct kerneldumpkey *kdk;
951 * When a user enters ddb it can write a crash dump multiple times.
952 * Each time it should be encrypted using a different IV.
955 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
956 SHA256_Final(hash, &ctx);
957 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
959 switch (kdc->kdc_encryption) {
960 case KERNELDUMP_ENC_AES_256_CBC:
961 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
972 kdk = kdc->kdc_dumpkey;
973 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
975 explicit_bzero(hash, sizeof(hash));
980 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
985 return (kdc->kdc_dumpkeysize);
990 static struct kerneldumpgz *
991 kerneldumpgz_create(struct dumperinfo *di, uint8_t compression)
993 struct kerneldumpgz *kdgz;
995 if (compression != KERNELDUMP_COMP_GZIP)
997 kdgz = malloc(sizeof(*kdgz), M_DUMPER, M_WAITOK | M_ZERO);
998 kdgz->kdgz_stream = gzio_init(kerneldumpgz_write_cb, GZIO_DEFLATE,
999 di->maxiosize, kerneldump_gzlevel, di);
1000 if (kdgz->kdgz_stream == NULL) {
1001 free(kdgz, M_DUMPER);
1004 kdgz->kdgz_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1009 kerneldumpgz_destroy(struct dumperinfo *di)
1011 struct kerneldumpgz *kdgz;
1016 gzio_fini(kdgz->kdgz_stream);
1017 explicit_bzero(kdgz->kdgz_buf, di->maxiosize);
1018 free(kdgz->kdgz_buf, M_DUMPER);
1019 free(kdgz, M_DUMPER);
1023 /* Registration of dumpers */
1025 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1026 uint8_t compression, uint8_t encryption, const uint8_t *key,
1027 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1032 error = priv_check(td, PRIV_SETDUMPER);
1040 if (dumper.dumper != NULL)
1043 dumper.blockbuf = NULL;
1047 if (encryption != KERNELDUMP_ENC_NONE) {
1049 dumper.kdc = kerneldumpcrypto_create(di->blocksize, encryption,
1050 key, encryptedkeysize, encryptedkey);
1051 if (dumper.kdc == NULL) {
1061 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1062 if (wantcopy >= sizeof(dumpdevname)) {
1063 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1064 devname, dumpdevname);
1067 if (compression != KERNELDUMP_COMP_NONE) {
1070 * We currently can't support simultaneous encryption and
1073 if (encryption != KERNELDUMP_ENC_NONE) {
1077 dumper.kdgz = kerneldumpgz_create(&dumper, compression);
1078 if (dumper.kdgz == NULL) {
1088 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1092 if (dumper.kdc != NULL) {
1093 explicit_bzero(dumper.kdc, sizeof(*dumper.kdc) +
1094 dumper.kdc->kdc_dumpkeysize);
1095 free(dumper.kdc, M_EKCD);
1100 kerneldumpgz_destroy(&dumper);
1103 if (dumper.blockbuf != NULL) {
1104 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1105 free(dumper.blockbuf, M_DUMPER);
1107 explicit_bzero(&dumper, sizeof(dumper));
1108 dumpdevname[0] = '\0';
1113 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1116 if (length != 0 && (offset < di->mediaoffset ||
1117 offset - di->mediaoffset + length > di->mediasize)) {
1118 printf("Attempt to write outside dump device boundaries.\n"
1119 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1120 (intmax_t)offset, (intmax_t)di->mediaoffset,
1121 (uintmax_t)length, (intmax_t)di->mediasize);
1124 if (length % di->blocksize != 0) {
1125 printf("Attempt to write partial block of length %ju.\n",
1129 if (offset % di->blocksize != 0) {
1130 printf("Attempt to write at unaligned offset %jd.\n",
1140 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1143 switch (kdc->kdc_encryption) {
1144 case KERNELDUMP_ENC_AES_256_CBC:
1145 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1146 8 * size, buf) <= 0) {
1149 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1150 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1161 /* Encrypt data and call dumper. */
1163 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1164 vm_offset_t physical, off_t offset, size_t length)
1166 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1167 struct kerneldumpcrypto *kdc;
1173 while (length > 0) {
1174 nbytes = MIN(length, sizeof(buf));
1175 bcopy(virtual, buf, nbytes);
1177 if (dump_encrypt(kdc, buf, nbytes) != 0)
1180 error = dump_write(di, buf, physical, offset, nbytes);
1185 virtual = (void *)((uint8_t *)virtual + nbytes);
1193 dump_write_key(struct dumperinfo *di, off_t offset)
1195 struct kerneldumpcrypto *kdc;
1200 return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1201 kdc->kdc_dumpkeysize));
1207 kerneldumpgz_write_cb(void *base, size_t length, off_t offset, void *arg)
1209 struct dumperinfo *di;
1210 size_t resid, rlength;
1215 if (length % di->blocksize != 0) {
1217 * This must be the final write after flushing the compression
1218 * stream. Write as many full blocks as possible and stash the
1219 * residual data in the dumper's block buffer. It will be
1220 * padded and written in dump_finish().
1222 rlength = rounddown(length, di->blocksize);
1224 error = _dump_append(di, base, 0, rlength);
1228 resid = length - rlength;
1229 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1230 di->kdgz->kdgz_resid = resid;
1233 return (_dump_append(di, base, 0, length));
1238 * Write a kerneldumpheader at the specified offset. The header structure is 512
1239 * bytes in size, but we must pad to the device sector size.
1242 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1248 hdrsz = sizeof(*kdh);
1249 if (hdrsz > di->blocksize)
1252 if (hdrsz == di->blocksize)
1256 memset(buf, 0, di->blocksize);
1257 memcpy(buf, kdh, hdrsz);
1260 return (dump_write(di, buf, 0, offset, di->blocksize));
1264 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1265 * protect us from metadata and metadata from us.
1267 #define SIZEOF_METADATA (64 * 1024)
1270 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1271 * if requested, and make sure that we have enough space on the dump device.
1273 * We set things up so that the dump ends before the last sector of the dump
1274 * device, at which the trailing header is written.
1276 * +-----------+------+-----+----------------------------+------+
1277 * | | lhdr | key | ... kernel dump ... | thdr |
1278 * +-----------+------+-----+----------------------------+------+
1279 * 1 blk opt <------- dump extent --------> 1 blk
1281 * Dumps written using dump_append() start at the beginning of the extent.
1282 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1283 * will not. The true length of the dump is recorded in the leading and trailing
1284 * headers once the dump has been completed.
1287 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1289 uint64_t dumpextent;
1293 int error = kerneldumpcrypto_init(di->kdc);
1296 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1301 dumpextent = dtoh64(kdh->dumpextent);
1302 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1305 if (di->kdgz != NULL) {
1307 * We don't yet know how much space the compressed dump
1308 * will occupy, so try to use the whole swap partition
1309 * (minus the first 64KB) in the hope that the
1310 * compressed dump will fit. If that doesn't turn out to
1311 * be enouch, the bounds checking in dump_write()
1312 * will catch us and cause the dump to fail.
1314 dumpextent = di->mediasize - SIZEOF_METADATA -
1315 2 * di->blocksize - keysize;
1316 kdh->dumpextent = htod64(dumpextent);
1322 /* The offset at which to begin writing the dump. */
1323 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1330 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1336 if (di->kdc != NULL)
1337 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1341 error = dump_write(di, virtual, physical, di->dumpoff, length);
1343 di->dumpoff += length;
1348 * Write to the dump device starting at dumpoff. When compression is enabled,
1349 * writes to the device will be performed using a callback that gets invoked
1350 * when the compression stream's output buffer is full.
1353 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1359 if (di->kdgz != NULL) {
1360 /* Bounce through a buffer to avoid gzip CRC errors. */
1361 if (length > di->maxiosize)
1363 buf = di->kdgz->kdgz_buf;
1364 memmove(buf, virtual, length);
1365 return (gzio_write(di->kdgz->kdgz_stream, buf, length));
1368 return (_dump_append(di, virtual, physical, length));
1372 * Write to the dump device at the specified offset.
1375 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1376 off_t offset, size_t length)
1380 error = dump_check_bounds(di, offset, length);
1383 return (di->dumper(di->priv, virtual, physical, offset, length));
1387 * Perform kernel dump finalization: flush the compression stream, if necessary,
1388 * write the leading and trailing kernel dump headers now that we know the true
1389 * length of the dump, and optionally write the encryption key following the
1393 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1399 extent = dtoh64(kdh->dumpextent);
1402 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1408 if (di->kdgz != NULL) {
1409 error = gzio_flush(di->kdgz->kdgz_stream);
1410 if (error == EAGAIN) {
1411 /* We have residual data in di->blockbuf. */
1412 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1414 di->dumpoff += di->kdgz->kdgz_resid;
1415 di->kdgz->kdgz_resid = 0;
1421 * We now know the size of the compressed dump, so update the
1422 * header accordingly and recompute parity.
1424 kdh->dumplength = htod64(di->dumpoff -
1425 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1427 kdh->parity = kerneldump_parity(kdh);
1429 gzio_reset(di->kdgz->kdgz_stream);
1434 * Write kerneldump headers at the beginning and end of the dump extent.
1435 * Write the key after the leading header.
1437 error = dump_write_header(di, kdh,
1438 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1444 error = dump_write_key(di,
1445 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1450 error = dump_write_header(di, kdh,
1451 di->mediaoffset + di->mediasize - di->blocksize);
1455 (void)dump_write(di, NULL, 0, 0, 0);
1460 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1461 char *magic, uint32_t archver, uint64_t dumplen)
1465 bzero(kdh, sizeof(*kdh));
1466 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1467 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1468 kdh->version = htod32(KERNELDUMPVERSION);
1469 kdh->architectureversion = htod32(archver);
1470 kdh->dumplength = htod64(dumplen);
1471 kdh->dumpextent = kdh->dumplength;
1472 kdh->dumptime = htod64(time_second);
1474 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdc));
1476 kdh->dumpkeysize = 0;
1478 kdh->blocksize = htod32(di->blocksize);
1479 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1480 dstsize = sizeof(kdh->versionstring);
1481 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1482 kdh->versionstring[dstsize - 2] = '\n';
1483 if (panicstr != NULL)
1484 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1486 if (di->kdgz != NULL)
1487 kdh->compression = KERNELDUMP_COMP_GZIP;
1489 kdh->parity = kerneldump_parity(kdh);
1493 DB_SHOW_COMMAND(panic, db_show_panic)
1496 if (panicstr == NULL)
1497 db_printf("panicstr not set\n");
1499 db_printf("panic: %s\n", panicstr);