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$");
45 #include "opt_panic.h"
46 #include "opt_sched.h"
47 #include "opt_watchdog.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
54 #include <sys/compressor.h>
56 #include <sys/eventhandler.h>
57 #include <sys/filedesc.h>
60 #include <sys/kernel.h>
61 #include <sys/kerneldump.h>
62 #include <sys/kthread.h>
64 #include <sys/malloc.h>
65 #include <sys/mount.h>
68 #include <sys/reboot.h>
69 #include <sys/resourcevar.h>
70 #include <sys/rwlock.h>
71 #include <sys/sched.h>
73 #include <sys/sysctl.h>
74 #include <sys/sysproto.h>
75 #include <sys/vnode.h>
76 #include <sys/watchdog.h>
78 #include <crypto/rijndael/rijndael-api-fst.h>
79 #include <crypto/sha2/sha256.h>
83 #include <machine/cpu.h>
84 #include <machine/dump.h>
85 #include <machine/pcb.h>
86 #include <machine/smp.h>
88 #include <security/mac/mac_framework.h>
91 #include <vm/vm_object.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_pager.h>
94 #include <vm/swap_pager.h>
96 #include <sys/signalvar.h>
98 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
100 #ifndef PANIC_REBOOT_WAIT_TIME
101 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
103 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
104 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
105 &panic_reboot_wait_time, 0,
106 "Seconds to wait before rebooting after a panic");
109 * Note that stdarg.h and the ANSI style va_start macro is used for both
110 * ANSI and traditional C compilers.
112 #include <machine/stdarg.h>
115 #ifdef KDB_UNATTENDED
116 int debugger_on_panic = 0;
118 int debugger_on_panic = 1;
120 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
121 CTLFLAG_RWTUN | CTLFLAG_SECURE,
122 &debugger_on_panic, 0, "Run debugger on kernel panic");
125 static int trace_on_panic = 1;
127 static int trace_on_panic = 0;
129 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
130 CTLFLAG_RWTUN | CTLFLAG_SECURE,
131 &trace_on_panic, 0, "Print stack trace on kernel panic");
134 static int sync_on_panic = 0;
135 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
136 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
138 static bool poweroff_on_panic = 0;
139 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
140 &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
142 static bool powercycle_on_panic = 0;
143 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
144 &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
146 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
147 "Shutdown environment");
150 static int show_busybufs;
152 static int show_busybufs = 1;
154 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
155 &show_busybufs, 0, "");
157 int suspend_blocked = 0;
158 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
159 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
162 FEATURE(ekcd, "Encrypted kernel crash dumps support");
164 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
166 struct kerneldumpcrypto {
167 uint8_t kdc_encryption;
168 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
170 cipherInstance kdc_ci;
171 uint32_t kdc_dumpkeysize;
172 struct kerneldumpkey kdc_dumpkey[];
176 struct kerneldumpcomp {
178 struct compressor *kdc_stream;
183 static struct kerneldumpcomp *kerneldumpcomp_create(struct dumperinfo *di,
184 uint8_t compression);
185 static void kerneldumpcomp_destroy(struct dumperinfo *di);
186 static int kerneldumpcomp_write_cb(void *base, size_t len, off_t off, void *arg);
188 static int kerneldump_gzlevel = 6;
189 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
190 &kerneldump_gzlevel, 0,
191 "Kernel crash dump compression level");
194 * Variable panicstr contains argument to first call to panic; used as flag
195 * to indicate that the kernel has already called panic.
197 const char *panicstr;
199 int dumping; /* system is dumping */
200 int rebooting; /* system is rebooting */
201 static struct dumperinfo dumper; /* our selected dumper */
203 /* Context information for dump-debuggers. */
204 static struct pcb dumppcb; /* Registers. */
205 lwpid_t dumptid; /* Thread ID. */
207 static struct cdevsw reroot_cdevsw = {
208 .d_version = D_VERSION,
212 static void poweroff_wait(void *, int);
213 static void shutdown_halt(void *junk, int howto);
214 static void shutdown_panic(void *junk, int howto);
215 static void shutdown_reset(void *junk, int howto);
216 static int kern_reroot(void);
218 /* register various local shutdown events */
220 shutdown_conf(void *unused)
223 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
225 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
226 SHUTDOWN_PRI_LAST + 100);
227 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
228 SHUTDOWN_PRI_LAST + 100);
229 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
230 SHUTDOWN_PRI_LAST + 200);
233 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
236 * The only reason this exists is to create the /dev/reroot/ directory,
237 * used by reroot code in init(8) as a mountpoint for tmpfs.
240 reroot_conf(void *unused)
245 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
246 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
248 printf("%s: failed to create device node, error %d",
253 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
256 * The system call that results in a reboot.
260 sys_reboot(struct thread *td, struct reboot_args *uap)
266 error = mac_system_check_reboot(td->td_ucred, uap->opt);
269 error = priv_check(td, PRIV_REBOOT);
271 if (uap->opt & RB_REROOT) {
272 error = kern_reroot();
275 kern_reboot(uap->opt);
283 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
286 shutdown_nice(int howto)
289 if (initproc != NULL) {
290 /* Send a signal to init(8) and have it shutdown the world. */
292 if (howto & RB_POWEROFF)
293 kern_psignal(initproc, SIGUSR2);
294 else if (howto & RB_POWERCYCLE)
295 kern_psignal(initproc, SIGWINCH);
296 else if (howto & RB_HALT)
297 kern_psignal(initproc, SIGUSR1);
299 kern_psignal(initproc, SIGINT);
300 PROC_UNLOCK(initproc);
302 /* No init(8) running, so simply reboot. */
303 kern_reboot(howto | RB_NOSYNC);
316 if (ts.tv_sec >= 86400) {
317 printf("%ldd", (long)ts.tv_sec / 86400);
321 if (f || ts.tv_sec >= 3600) {
322 printf("%ldh", (long)ts.tv_sec / 3600);
326 if (f || ts.tv_sec >= 60) {
327 printf("%ldm", (long)ts.tv_sec / 60);
331 printf("%lds\n", (long)ts.tv_sec);
335 doadump(boolean_t textdump)
343 if (dumper.dumper == NULL)
347 dumptid = curthread->td_tid;
352 if (textdump && textdump_pending) {
354 textdump_dumpsys(&dumper);
358 error = dumpsys(&dumper);
365 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
368 kern_reboot(int howto)
374 * Bind us to the first CPU so that all shutdown code runs there. Some
375 * systems don't shutdown properly (i.e., ACPI power off) if we
376 * run on another processor.
378 if (!SCHEDULER_STOPPED()) {
379 thread_lock(curthread);
380 sched_bind(curthread, CPU_FIRST());
381 thread_unlock(curthread);
382 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
383 ("boot: not running on cpu 0"));
386 /* We're in the process of rebooting. */
389 /* We are out of the debugger now. */
393 * Do any callouts that should be done BEFORE syncing the filesystems.
395 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
398 * Now sync filesystems
400 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
402 bufshutdown(show_busybufs);
410 * Ok, now do things that assume all filesystem activity has
413 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
415 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
418 /* Now that we're going to really halt the system... */
419 EVENTHANDLER_INVOKE(shutdown_final, howto);
421 for(;;) ; /* safety against shutdown_reset not working */
426 * The system call that results in changing the rootfs.
431 struct vnode *oldrootvnode, *vp;
432 struct mount *mp, *devmp;
435 if (curproc != initproc)
439 * Mark the filesystem containing currently-running executable
440 * (the temporary copy of init(8)) busy.
442 vp = curproc->p_textvp;
443 error = vn_lock(vp, LK_SHARED);
447 error = vfs_busy(mp, MBF_NOWAIT);
451 error = vfs_busy(mp, 0);
452 vn_lock(vp, LK_SHARED | LK_RETRY);
458 if (vp->v_iflag & VI_DOOMED) {
467 * Remove the filesystem containing currently-running executable
468 * from the mount list, to prevent it from being unmounted
469 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
471 * Also preserve /dev - forcibly unmounting it could cause driver
479 mtx_lock(&mountlist_mtx);
480 TAILQ_REMOVE(&mountlist, mp, mnt_list);
481 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
482 mtx_unlock(&mountlist_mtx);
484 oldrootvnode = rootvnode;
487 * Unmount everything except for the two filesystems preserved above.
492 * Add /dev back; vfs_mountroot() will move it into its new place.
494 mtx_lock(&mountlist_mtx);
495 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
496 mtx_unlock(&mountlist_mtx);
501 * Mount the new rootfs.
506 * Update all references to the old rootvnode.
508 mountcheckdirs(oldrootvnode, rootvnode);
511 * Add the temporary filesystem back and unbusy it.
513 mtx_lock(&mountlist_mtx);
514 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
515 mtx_unlock(&mountlist_mtx);
522 * If the shutdown was a clean halt, behave accordingly.
525 shutdown_halt(void *junk, int howto)
528 if (howto & RB_HALT) {
530 printf("The operating system has halted.\n");
531 printf("Please press any key to reboot.\n\n");
533 case -1: /* No console, just die */
543 * Check to see if the system paniced, pause and then reboot
544 * according to the specified delay.
547 shutdown_panic(void *junk, int howto)
551 if (howto & RB_DUMP) {
552 if (panic_reboot_wait_time != 0) {
553 if (panic_reboot_wait_time != -1) {
554 printf("Automatic reboot in %d seconds - "
555 "press a key on the console to abort\n",
556 panic_reboot_wait_time);
557 for (loop = panic_reboot_wait_time * 10;
559 DELAY(1000 * 100); /* 1/10th second */
560 /* Did user type a key? */
561 if (cncheckc() != -1)
567 } else { /* zero time specified - reboot NOW */
570 printf("--> Press a key on the console to reboot,\n");
571 printf("--> or switch off the system now.\n");
577 * Everything done, now reset
580 shutdown_reset(void *junk, int howto)
583 printf("Rebooting...\n");
584 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
587 * Acquiring smp_ipi_mtx here has a double effect:
588 * - it disables interrupts avoiding CPU0 preemption
589 * by fast handlers (thus deadlocking against other CPUs)
590 * - it avoids deadlocks against smp_rendezvous() or, more
591 * generally, threads busy-waiting, with this spinlock held,
592 * and waiting for responses by threads on other CPUs
593 * (ie. smp_tlb_shootdown()).
595 * For the !SMP case it just needs to handle the former problem.
598 mtx_lock_spin(&smp_ipi_mtx);
603 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
605 /* NOTREACHED */ /* assuming reset worked */
608 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
609 static int kassert_warn_only = 0;
611 static int kassert_do_kdb = 0;
614 static int kassert_do_ktr = 0;
616 static int kassert_do_log = 1;
617 static int kassert_log_pps_limit = 4;
618 static int kassert_log_mute_at = 0;
619 static int kassert_log_panic_at = 0;
620 static int kassert_warnings = 0;
622 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
624 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
625 &kassert_warn_only, 0,
626 "KASSERT triggers a panic (1) or just a warning (0)");
629 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
630 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
634 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
636 "KASSERT does a KTR, set this to the KTRMASK you want");
639 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
640 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
642 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
643 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
645 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
646 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
648 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
649 &kassert_log_pps_limit, 0, "limit number of log messages per second");
651 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
652 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
654 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
656 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
657 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
658 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
661 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
665 error = sysctl_wire_old_buffer(req, sizeof(int));
668 error = sysctl_handle_int(oidp, &i, 0, req);
670 if (error != 0 || req->newptr == NULL)
672 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
677 * Called by KASSERT, this decides if we will panic
678 * or if we will log via printf and/or ktr.
681 kassert_panic(const char *fmt, ...)
683 static char buf[256];
687 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
691 * panic if we're not just warning, or if we've exceeded
692 * kassert_log_panic_at warnings.
694 if (!kassert_warn_only ||
695 (kassert_log_panic_at > 0 &&
696 kassert_warnings >= kassert_log_panic_at)) {
706 * log if we've not yet met the mute limit.
708 if (kassert_do_log &&
709 (kassert_log_mute_at == 0 ||
710 kassert_warnings < kassert_log_mute_at)) {
711 static struct timeval lasterr;
714 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
715 printf("KASSERT failed: %s\n", buf);
720 if (kassert_do_kdb) {
721 kdb_enter(KDB_WHY_KASSERT, buf);
724 atomic_add_int(&kassert_warnings, 1);
729 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
730 * and then reboots. If we are called twice, then we avoid trying to sync
731 * the disks as this often leads to recursive panics.
734 panic(const char *fmt, ...)
743 vpanic(const char *fmt, va_list ap)
748 struct thread *td = curthread;
749 int bootopt, newpanic;
750 static char buf[256];
756 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
757 * concurrently entering panic. Only the winner will proceed
760 if (panicstr == NULL && !kdb_active) {
761 other_cpus = all_cpus;
762 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
763 stop_cpus_hard(other_cpus);
768 * Ensure that the scheduler is stopped while panicking, even if panic
769 * has been entered from kdb.
771 td->td_stopsched = 1;
773 bootopt = RB_AUTOBOOT;
776 bootopt |= RB_NOSYNC;
784 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
787 printf("panic: %s\n", buf);
794 printf("cpuid = %d\n", PCPU_GET(cpuid));
796 printf("time = %jd\n", (intmax_t )time_second);
798 if (newpanic && trace_on_panic)
800 if (debugger_on_panic)
801 kdb_enter(KDB_WHY_PANIC, "panic");
803 /*thread_lock(td); */
804 td->td_flags |= TDF_INPANIC;
805 /* thread_unlock(td); */
807 bootopt |= RB_NOSYNC;
808 if (poweroff_on_panic)
809 bootopt |= RB_POWEROFF;
810 if (powercycle_on_panic)
811 bootopt |= RB_POWERCYCLE;
812 kern_reboot(bootopt);
816 * Support for poweroff delay.
818 * Please note that setting this delay too short might power off your machine
819 * before the write cache on your hard disk has been flushed, leading to
820 * soft-updates inconsistencies.
822 #ifndef POWEROFF_DELAY
823 # define POWEROFF_DELAY 5000
825 static int poweroff_delay = POWEROFF_DELAY;
827 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
828 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
831 poweroff_wait(void *junk, int howto)
834 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
836 DELAY(poweroff_delay * 1000);
840 * Some system processes (e.g. syncer) need to be stopped at appropriate
841 * points in their main loops prior to a system shutdown, so that they
842 * won't interfere with the shutdown process (e.g. by holding a disk buf
843 * to cause sync to fail). For each of these system processes, register
844 * shutdown_kproc() as a handler for one of shutdown events.
846 static int kproc_shutdown_wait = 60;
847 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
848 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
851 kproc_shutdown(void *arg, int howto)
859 p = (struct proc *)arg;
860 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
861 kproc_shutdown_wait, p->p_comm);
862 error = kproc_suspend(p, kproc_shutdown_wait * hz);
864 if (error == EWOULDBLOCK)
865 printf("timed out\n");
871 kthread_shutdown(void *arg, int howto)
879 td = (struct thread *)arg;
880 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
881 kproc_shutdown_wait, td->td_name);
882 error = kthread_suspend(td, kproc_shutdown_wait * hz);
884 if (error == EWOULDBLOCK)
885 printf("timed out\n");
890 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
891 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
892 dumpdevname, 0, "Device for kernel dumps");
894 static int _dump_append(struct dumperinfo *di, void *virtual,
895 vm_offset_t physical, size_t length);
898 static struct kerneldumpcrypto *
899 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
900 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
902 struct kerneldumpcrypto *kdc;
903 struct kerneldumpkey *kdk;
904 uint32_t dumpkeysize;
906 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
907 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
909 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
911 kdc->kdc_encryption = encryption;
912 switch (kdc->kdc_encryption) {
913 case KERNELDUMP_ENC_AES_256_CBC:
914 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
921 kdc->kdc_dumpkeysize = dumpkeysize;
922 kdk = kdc->kdc_dumpkey;
923 kdk->kdk_encryption = kdc->kdc_encryption;
924 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
925 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
926 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
930 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
936 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
938 uint8_t hash[SHA256_DIGEST_LENGTH];
940 struct kerneldumpkey *kdk;
949 * When a user enters ddb it can write a crash dump multiple times.
950 * Each time it should be encrypted using a different IV.
953 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
954 SHA256_Final(hash, &ctx);
955 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
957 switch (kdc->kdc_encryption) {
958 case KERNELDUMP_ENC_AES_256_CBC:
959 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
970 kdk = kdc->kdc_dumpkey;
971 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
973 explicit_bzero(hash, sizeof(hash));
978 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
983 return (kdc->kdc_dumpkeysize);
987 static struct kerneldumpcomp *
988 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
990 struct kerneldumpcomp *kdcomp;
993 switch (compression) {
994 case KERNELDUMP_COMP_GZIP:
995 format = COMPRESS_GZIP;
997 case KERNELDUMP_COMP_ZSTD:
998 format = COMPRESS_ZSTD;
1004 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1005 kdcomp->kdc_format = compression;
1006 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1007 format, di->maxiosize, kerneldump_gzlevel, di);
1008 if (kdcomp->kdc_stream == NULL) {
1009 free(kdcomp, M_DUMPER);
1012 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1017 kerneldumpcomp_destroy(struct dumperinfo *di)
1019 struct kerneldumpcomp *kdcomp;
1021 kdcomp = di->kdcomp;
1024 compressor_fini(kdcomp->kdc_stream);
1025 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1026 free(kdcomp->kdc_buf, M_DUMPER);
1027 free(kdcomp, M_DUMPER);
1030 /* Registration of dumpers */
1032 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1033 uint8_t compression, uint8_t encryption, const uint8_t *key,
1034 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1039 error = priv_check(td, PRIV_SETDUMPER);
1047 if (dumper.dumper != NULL)
1050 dumper.blockbuf = NULL;
1051 dumper.kdcrypto = NULL;
1052 dumper.kdcomp = NULL;
1054 if (encryption != KERNELDUMP_ENC_NONE) {
1056 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1057 encryption, key, encryptedkeysize, encryptedkey);
1058 if (dumper.kdcrypto == NULL) {
1068 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1069 if (wantcopy >= sizeof(dumpdevname)) {
1070 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1071 devname, dumpdevname);
1074 if (compression != KERNELDUMP_COMP_NONE) {
1076 * We currently can't support simultaneous encryption and
1079 if (encryption != KERNELDUMP_ENC_NONE) {
1083 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1084 if (dumper.kdcomp == NULL) {
1090 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1094 if (dumper.kdcrypto != NULL) {
1095 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1096 dumper.kdcrypto->kdc_dumpkeysize);
1097 free(dumper.kdcrypto, M_EKCD);
1101 kerneldumpcomp_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));
1206 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1208 struct dumperinfo *di;
1209 size_t resid, rlength;
1214 if (length % di->blocksize != 0) {
1216 * This must be the final write after flushing the compression
1217 * stream. Write as many full blocks as possible and stash the
1218 * residual data in the dumper's block buffer. It will be
1219 * padded and written in dump_finish().
1221 rlength = rounddown(length, di->blocksize);
1223 error = _dump_append(di, base, 0, rlength);
1227 resid = length - rlength;
1228 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1229 di->kdcomp->kdc_resid = resid;
1232 return (_dump_append(di, base, 0, length));
1236 * Write a kerneldumpheader at the specified offset. The header structure is 512
1237 * bytes in size, but we must pad to the device sector size.
1240 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1246 hdrsz = sizeof(*kdh);
1247 if (hdrsz > di->blocksize)
1250 if (hdrsz == di->blocksize)
1254 memset(buf, 0, di->blocksize);
1255 memcpy(buf, kdh, hdrsz);
1258 return (dump_write(di, buf, 0, offset, di->blocksize));
1262 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1263 * protect us from metadata and metadata from us.
1265 #define SIZEOF_METADATA (64 * 1024)
1268 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1269 * if requested, and make sure that we have enough space on the dump device.
1271 * We set things up so that the dump ends before the last sector of the dump
1272 * device, at which the trailing header is written.
1274 * +-----------+------+-----+----------------------------+------+
1275 * | | lhdr | key | ... kernel dump ... | thdr |
1276 * +-----------+------+-----+----------------------------+------+
1277 * 1 blk opt <------- dump extent --------> 1 blk
1279 * Dumps written using dump_append() start at the beginning of the extent.
1280 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1281 * will not. The true length of the dump is recorded in the leading and trailing
1282 * headers once the dump has been completed.
1285 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1287 uint64_t dumpextent;
1291 int error = kerneldumpcrypto_init(di->kdcrypto);
1294 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1299 dumpextent = dtoh64(kdh->dumpextent);
1300 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1302 if (di->kdcomp != NULL) {
1304 * We don't yet know how much space the compressed dump
1305 * will occupy, so try to use the whole swap partition
1306 * (minus the first 64KB) in the hope that the
1307 * compressed dump will fit. If that doesn't turn out to
1308 * be enough, the bounds checking in dump_write()
1309 * will catch us and cause the dump to fail.
1311 dumpextent = di->mediasize - SIZEOF_METADATA -
1312 2 * di->blocksize - keysize;
1313 kdh->dumpextent = htod64(dumpextent);
1318 /* The offset at which to begin writing the dump. */
1319 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1326 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1332 if (di->kdcrypto != NULL)
1333 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1337 error = dump_write(di, virtual, physical, di->dumpoff, length);
1339 di->dumpoff += length;
1344 * Write to the dump device starting at dumpoff. When compression is enabled,
1345 * writes to the device will be performed using a callback that gets invoked
1346 * when the compression stream's output buffer is full.
1349 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1354 if (di->kdcomp != NULL) {
1355 /* Bounce through a buffer to avoid CRC errors. */
1356 if (length > di->maxiosize)
1358 buf = di->kdcomp->kdc_buf;
1359 memmove(buf, virtual, length);
1360 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1362 return (_dump_append(di, virtual, physical, length));
1366 * Write to the dump device at the specified offset.
1369 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1370 off_t offset, size_t length)
1374 error = dump_check_bounds(di, offset, length);
1377 return (di->dumper(di->priv, virtual, physical, offset, length));
1381 * Perform kernel dump finalization: flush the compression stream, if necessary,
1382 * write the leading and trailing kernel dump headers now that we know the true
1383 * length of the dump, and optionally write the encryption key following the
1387 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1393 extent = dtoh64(kdh->dumpextent);
1396 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1401 if (di->kdcomp != NULL) {
1402 error = compressor_flush(di->kdcomp->kdc_stream);
1403 if (error == EAGAIN) {
1404 /* We have residual data in di->blockbuf. */
1405 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1407 di->dumpoff += di->kdcomp->kdc_resid;
1408 di->kdcomp->kdc_resid = 0;
1414 * We now know the size of the compressed dump, so update the
1415 * header accordingly and recompute parity.
1417 kdh->dumplength = htod64(di->dumpoff -
1418 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1420 kdh->parity = kerneldump_parity(kdh);
1422 compressor_reset(di->kdcomp->kdc_stream);
1426 * Write kerneldump headers at the beginning and end of the dump extent.
1427 * Write the key after the leading header.
1429 error = dump_write_header(di, kdh,
1430 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1436 error = dump_write_key(di,
1437 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1442 error = dump_write_header(di, kdh,
1443 di->mediaoffset + di->mediasize - di->blocksize);
1447 (void)dump_write(di, NULL, 0, 0, 0);
1452 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1453 char *magic, uint32_t archver, uint64_t dumplen)
1457 bzero(kdh, sizeof(*kdh));
1458 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1459 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1460 kdh->version = htod32(KERNELDUMPVERSION);
1461 kdh->architectureversion = htod32(archver);
1462 kdh->dumplength = htod64(dumplen);
1463 kdh->dumpextent = kdh->dumplength;
1464 kdh->dumptime = htod64(time_second);
1466 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1468 kdh->dumpkeysize = 0;
1470 kdh->blocksize = htod32(di->blocksize);
1471 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1472 dstsize = sizeof(kdh->versionstring);
1473 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1474 kdh->versionstring[dstsize - 2] = '\n';
1475 if (panicstr != NULL)
1476 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1477 if (di->kdcomp != NULL)
1478 kdh->compression = di->kdcomp->kdc_format;
1479 kdh->parity = kerneldump_parity(kdh);
1483 DB_SHOW_COMMAND(panic, db_show_panic)
1486 if (panicstr == NULL)
1487 db_printf("panicstr not set\n");
1489 db_printf("panic: %s\n", panicstr);