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();
274 kern_reboot(uap->opt);
280 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
283 shutdown_nice(int howto)
286 if (initproc != NULL) {
287 /* Send a signal to init(8) and have it shutdown the world. */
289 if (howto & RB_POWEROFF)
290 kern_psignal(initproc, SIGUSR2);
291 else if (howto & RB_POWERCYCLE)
292 kern_psignal(initproc, SIGWINCH);
293 else if (howto & RB_HALT)
294 kern_psignal(initproc, SIGUSR1);
296 kern_psignal(initproc, SIGINT);
297 PROC_UNLOCK(initproc);
299 /* No init(8) running, so simply reboot. */
300 kern_reboot(howto | RB_NOSYNC);
313 if (ts.tv_sec >= 86400) {
314 printf("%ldd", (long)ts.tv_sec / 86400);
318 if (f || ts.tv_sec >= 3600) {
319 printf("%ldh", (long)ts.tv_sec / 3600);
323 if (f || ts.tv_sec >= 60) {
324 printf("%ldm", (long)ts.tv_sec / 60);
328 printf("%lds\n", (long)ts.tv_sec);
332 doadump(boolean_t textdump)
340 if (dumper.dumper == NULL)
344 dumptid = curthread->td_tid;
349 if (textdump && textdump_pending) {
351 textdump_dumpsys(&dumper);
355 error = dumpsys(&dumper);
362 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
365 kern_reboot(int howto)
371 * Bind us to the first CPU so that all shutdown code runs there. Some
372 * systems don't shutdown properly (i.e., ACPI power off) if we
373 * run on another processor.
375 if (!SCHEDULER_STOPPED()) {
376 thread_lock(curthread);
377 sched_bind(curthread, CPU_FIRST());
378 thread_unlock(curthread);
379 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
380 ("boot: not running on cpu 0"));
383 /* We're in the process of rebooting. */
386 /* We are out of the debugger now. */
390 * Do any callouts that should be done BEFORE syncing the filesystems.
392 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
395 * Now sync filesystems
397 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
399 bufshutdown(show_busybufs);
407 * Ok, now do things that assume all filesystem activity has
410 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
412 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
415 /* Now that we're going to really halt the system... */
416 EVENTHANDLER_INVOKE(shutdown_final, howto);
418 for(;;) ; /* safety against shutdown_reset not working */
423 * The system call that results in changing the rootfs.
428 struct vnode *oldrootvnode, *vp;
429 struct mount *mp, *devmp;
432 if (curproc != initproc)
436 * Mark the filesystem containing currently-running executable
437 * (the temporary copy of init(8)) busy.
439 vp = curproc->p_textvp;
440 error = vn_lock(vp, LK_SHARED);
444 error = vfs_busy(mp, MBF_NOWAIT);
448 error = vfs_busy(mp, 0);
449 vn_lock(vp, LK_SHARED | LK_RETRY);
455 if (vp->v_iflag & VI_DOOMED) {
464 * Remove the filesystem containing currently-running executable
465 * from the mount list, to prevent it from being unmounted
466 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
468 * Also preserve /dev - forcibly unmounting it could cause driver
476 mtx_lock(&mountlist_mtx);
477 TAILQ_REMOVE(&mountlist, mp, mnt_list);
478 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
479 mtx_unlock(&mountlist_mtx);
481 oldrootvnode = rootvnode;
484 * Unmount everything except for the two filesystems preserved above.
489 * Add /dev back; vfs_mountroot() will move it into its new place.
491 mtx_lock(&mountlist_mtx);
492 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
493 mtx_unlock(&mountlist_mtx);
498 * Mount the new rootfs.
503 * Update all references to the old rootvnode.
505 mountcheckdirs(oldrootvnode, rootvnode);
508 * Add the temporary filesystem back and unbusy it.
510 mtx_lock(&mountlist_mtx);
511 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
512 mtx_unlock(&mountlist_mtx);
519 * If the shutdown was a clean halt, behave accordingly.
522 shutdown_halt(void *junk, int howto)
525 if (howto & RB_HALT) {
527 printf("The operating system has halted.\n");
528 printf("Please press any key to reboot.\n\n");
530 case -1: /* No console, just die */
540 * Check to see if the system paniced, pause and then reboot
541 * according to the specified delay.
544 shutdown_panic(void *junk, int howto)
548 if (howto & RB_DUMP) {
549 if (panic_reboot_wait_time != 0) {
550 if (panic_reboot_wait_time != -1) {
551 printf("Automatic reboot in %d seconds - "
552 "press a key on the console to abort\n",
553 panic_reboot_wait_time);
554 for (loop = panic_reboot_wait_time * 10;
556 DELAY(1000 * 100); /* 1/10th second */
557 /* Did user type a key? */
558 if (cncheckc() != -1)
564 } else { /* zero time specified - reboot NOW */
567 printf("--> Press a key on the console to reboot,\n");
568 printf("--> or switch off the system now.\n");
574 * Everything done, now reset
577 shutdown_reset(void *junk, int howto)
580 printf("Rebooting...\n");
581 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
584 * Acquiring smp_ipi_mtx here has a double effect:
585 * - it disables interrupts avoiding CPU0 preemption
586 * by fast handlers (thus deadlocking against other CPUs)
587 * - it avoids deadlocks against smp_rendezvous() or, more
588 * generally, threads busy-waiting, with this spinlock held,
589 * and waiting for responses by threads on other CPUs
590 * (ie. smp_tlb_shootdown()).
592 * For the !SMP case it just needs to handle the former problem.
595 mtx_lock_spin(&smp_ipi_mtx);
600 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
602 /* NOTREACHED */ /* assuming reset worked */
605 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
606 static int kassert_warn_only = 0;
608 static int kassert_do_kdb = 0;
611 static int kassert_do_ktr = 0;
613 static int kassert_do_log = 1;
614 static int kassert_log_pps_limit = 4;
615 static int kassert_log_mute_at = 0;
616 static int kassert_log_panic_at = 0;
617 static int kassert_warnings = 0;
619 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
621 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
622 &kassert_warn_only, 0,
623 "KASSERT triggers a panic (1) or just a warning (0)");
626 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
627 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
631 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
633 "KASSERT does a KTR, set this to the KTRMASK you want");
636 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
637 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
639 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
640 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
642 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
643 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
645 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
646 &kassert_log_pps_limit, 0, "limit number of log messages per second");
648 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
649 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
651 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
653 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
654 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
655 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
658 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
662 error = sysctl_wire_old_buffer(req, sizeof(int));
665 error = sysctl_handle_int(oidp, &i, 0, req);
667 if (error != 0 || req->newptr == NULL)
669 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
674 * Called by KASSERT, this decides if we will panic
675 * or if we will log via printf and/or ktr.
678 kassert_panic(const char *fmt, ...)
680 static char buf[256];
684 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
688 * panic if we're not just warning, or if we've exceeded
689 * kassert_log_panic_at warnings.
691 if (!kassert_warn_only ||
692 (kassert_log_panic_at > 0 &&
693 kassert_warnings >= kassert_log_panic_at)) {
703 * log if we've not yet met the mute limit.
705 if (kassert_do_log &&
706 (kassert_log_mute_at == 0 ||
707 kassert_warnings < kassert_log_mute_at)) {
708 static struct timeval lasterr;
711 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
712 printf("KASSERT failed: %s\n", buf);
717 if (kassert_do_kdb) {
718 kdb_enter(KDB_WHY_KASSERT, buf);
721 atomic_add_int(&kassert_warnings, 1);
726 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
727 * and then reboots. If we are called twice, then we avoid trying to sync
728 * the disks as this often leads to recursive panics.
731 panic(const char *fmt, ...)
740 vpanic(const char *fmt, va_list ap)
745 struct thread *td = curthread;
746 int bootopt, newpanic;
747 static char buf[256];
753 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
754 * concurrently entering panic. Only the winner will proceed
757 if (panicstr == NULL && !kdb_active) {
758 other_cpus = all_cpus;
759 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
760 stop_cpus_hard(other_cpus);
765 * Ensure that the scheduler is stopped while panicking, even if panic
766 * has been entered from kdb.
768 td->td_stopsched = 1;
770 bootopt = RB_AUTOBOOT;
773 bootopt |= RB_NOSYNC;
781 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
784 printf("panic: %s\n", buf);
791 printf("cpuid = %d\n", PCPU_GET(cpuid));
793 printf("time = %jd\n", (intmax_t )time_second);
795 if (newpanic && trace_on_panic)
797 if (debugger_on_panic)
798 kdb_enter(KDB_WHY_PANIC, "panic");
800 /*thread_lock(td); */
801 td->td_flags |= TDF_INPANIC;
802 /* thread_unlock(td); */
804 bootopt |= RB_NOSYNC;
805 if (poweroff_on_panic)
806 bootopt |= RB_POWEROFF;
807 if (powercycle_on_panic)
808 bootopt |= RB_POWERCYCLE;
809 kern_reboot(bootopt);
813 * Support for poweroff delay.
815 * Please note that setting this delay too short might power off your machine
816 * before the write cache on your hard disk has been flushed, leading to
817 * soft-updates inconsistencies.
819 #ifndef POWEROFF_DELAY
820 # define POWEROFF_DELAY 5000
822 static int poweroff_delay = POWEROFF_DELAY;
824 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
825 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
828 poweroff_wait(void *junk, int howto)
831 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
833 DELAY(poweroff_delay * 1000);
837 * Some system processes (e.g. syncer) need to be stopped at appropriate
838 * points in their main loops prior to a system shutdown, so that they
839 * won't interfere with the shutdown process (e.g. by holding a disk buf
840 * to cause sync to fail). For each of these system processes, register
841 * shutdown_kproc() as a handler for one of shutdown events.
843 static int kproc_shutdown_wait = 60;
844 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
845 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
848 kproc_shutdown(void *arg, int howto)
856 p = (struct proc *)arg;
857 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
858 kproc_shutdown_wait, p->p_comm);
859 error = kproc_suspend(p, kproc_shutdown_wait * hz);
861 if (error == EWOULDBLOCK)
862 printf("timed out\n");
868 kthread_shutdown(void *arg, int howto)
876 td = (struct thread *)arg;
877 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
878 kproc_shutdown_wait, td->td_name);
879 error = kthread_suspend(td, kproc_shutdown_wait * hz);
881 if (error == EWOULDBLOCK)
882 printf("timed out\n");
887 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
888 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
889 dumpdevname, 0, "Device for kernel dumps");
891 static int _dump_append(struct dumperinfo *di, void *virtual,
892 vm_offset_t physical, size_t length);
895 static struct kerneldumpcrypto *
896 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
897 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
899 struct kerneldumpcrypto *kdc;
900 struct kerneldumpkey *kdk;
901 uint32_t dumpkeysize;
903 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
904 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
906 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
908 kdc->kdc_encryption = encryption;
909 switch (kdc->kdc_encryption) {
910 case KERNELDUMP_ENC_AES_256_CBC:
911 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
918 kdc->kdc_dumpkeysize = dumpkeysize;
919 kdk = kdc->kdc_dumpkey;
920 kdk->kdk_encryption = kdc->kdc_encryption;
921 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
922 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
923 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
927 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
933 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
935 uint8_t hash[SHA256_DIGEST_LENGTH];
937 struct kerneldumpkey *kdk;
946 * When a user enters ddb it can write a crash dump multiple times.
947 * Each time it should be encrypted using a different IV.
950 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
951 SHA256_Final(hash, &ctx);
952 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
954 switch (kdc->kdc_encryption) {
955 case KERNELDUMP_ENC_AES_256_CBC:
956 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
967 kdk = kdc->kdc_dumpkey;
968 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
970 explicit_bzero(hash, sizeof(hash));
975 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
980 return (kdc->kdc_dumpkeysize);
984 static struct kerneldumpcomp *
985 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
987 struct kerneldumpcomp *kdcomp;
990 switch (compression) {
991 case KERNELDUMP_COMP_GZIP:
992 format = COMPRESS_GZIP;
994 case KERNELDUMP_COMP_ZSTD:
995 format = COMPRESS_ZSTD;
1001 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1002 kdcomp->kdc_format = compression;
1003 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1004 format, di->maxiosize, kerneldump_gzlevel, di);
1005 if (kdcomp->kdc_stream == NULL) {
1006 free(kdcomp, M_DUMPER);
1009 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1014 kerneldumpcomp_destroy(struct dumperinfo *di)
1016 struct kerneldumpcomp *kdcomp;
1018 kdcomp = di->kdcomp;
1021 compressor_fini(kdcomp->kdc_stream);
1022 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1023 free(kdcomp->kdc_buf, M_DUMPER);
1024 free(kdcomp, M_DUMPER);
1027 /* Registration of dumpers */
1029 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1030 uint8_t compression, uint8_t encryption, const uint8_t *key,
1031 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1036 error = priv_check(td, PRIV_SETDUMPER);
1044 if (dumper.dumper != NULL)
1047 dumper.blockbuf = NULL;
1048 dumper.kdcrypto = NULL;
1049 dumper.kdcomp = NULL;
1051 if (encryption != KERNELDUMP_ENC_NONE) {
1053 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1054 encryption, key, encryptedkeysize, encryptedkey);
1055 if (dumper.kdcrypto == NULL) {
1065 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1066 if (wantcopy >= sizeof(dumpdevname)) {
1067 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1068 devname, dumpdevname);
1071 if (compression != KERNELDUMP_COMP_NONE) {
1073 * We currently can't support simultaneous encryption and
1076 if (encryption != KERNELDUMP_ENC_NONE) {
1080 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1081 if (dumper.kdcomp == NULL) {
1087 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1091 if (dumper.kdcrypto != NULL) {
1092 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1093 dumper.kdcrypto->kdc_dumpkeysize);
1094 free(dumper.kdcrypto, M_EKCD);
1098 kerneldumpcomp_destroy(&dumper);
1100 if (dumper.blockbuf != NULL) {
1101 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1102 free(dumper.blockbuf, M_DUMPER);
1104 explicit_bzero(&dumper, sizeof(dumper));
1105 dumpdevname[0] = '\0';
1110 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1113 if (length != 0 && (offset < di->mediaoffset ||
1114 offset - di->mediaoffset + length > di->mediasize)) {
1115 if (di->kdcomp != NULL && offset >= di->mediaoffset) {
1117 "Compressed dump failed to fit in device boundaries.\n");
1121 printf("Attempt to write outside dump device boundaries.\n"
1122 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1123 (intmax_t)offset, (intmax_t)di->mediaoffset,
1124 (uintmax_t)length, (intmax_t)di->mediasize);
1127 if (length % di->blocksize != 0) {
1128 printf("Attempt to write partial block of length %ju.\n",
1132 if (offset % di->blocksize != 0) {
1133 printf("Attempt to write at unaligned offset %jd.\n",
1143 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1146 switch (kdc->kdc_encryption) {
1147 case KERNELDUMP_ENC_AES_256_CBC:
1148 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1149 8 * size, buf) <= 0) {
1152 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1153 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1164 /* Encrypt data and call dumper. */
1166 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1167 vm_offset_t physical, off_t offset, size_t length)
1169 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1170 struct kerneldumpcrypto *kdc;
1176 while (length > 0) {
1177 nbytes = MIN(length, sizeof(buf));
1178 bcopy(virtual, buf, nbytes);
1180 if (dump_encrypt(kdc, buf, nbytes) != 0)
1183 error = dump_write(di, buf, physical, offset, nbytes);
1188 virtual = (void *)((uint8_t *)virtual + nbytes);
1196 dump_write_key(struct dumperinfo *di, off_t offset)
1198 struct kerneldumpcrypto *kdc;
1203 return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1204 kdc->kdc_dumpkeysize));
1209 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1211 struct dumperinfo *di;
1212 size_t resid, rlength;
1217 if (length % di->blocksize != 0) {
1219 * This must be the final write after flushing the compression
1220 * stream. Write as many full blocks as possible and stash the
1221 * residual data in the dumper's block buffer. It will be
1222 * padded and written in dump_finish().
1224 rlength = rounddown(length, di->blocksize);
1226 error = _dump_append(di, base, 0, rlength);
1230 resid = length - rlength;
1231 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1232 di->kdcomp->kdc_resid = resid;
1235 return (_dump_append(di, base, 0, length));
1239 * Write a kerneldumpheader at the specified offset. The header structure is 512
1240 * bytes in size, but we must pad to the device sector size.
1243 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1249 hdrsz = sizeof(*kdh);
1250 if (hdrsz > di->blocksize)
1253 if (hdrsz == di->blocksize)
1257 memset(buf, 0, di->blocksize);
1258 memcpy(buf, kdh, hdrsz);
1261 return (dump_write(di, buf, 0, offset, di->blocksize));
1265 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1266 * protect us from metadata and metadata from us.
1268 #define SIZEOF_METADATA (64 * 1024)
1271 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1272 * if requested, and make sure that we have enough space on the dump device.
1274 * We set things up so that the dump ends before the last sector of the dump
1275 * device, at which the trailing header is written.
1277 * +-----------+------+-----+----------------------------+------+
1278 * | | lhdr | key | ... kernel dump ... | thdr |
1279 * +-----------+------+-----+----------------------------+------+
1280 * 1 blk opt <------- dump extent --------> 1 blk
1282 * Dumps written using dump_append() start at the beginning of the extent.
1283 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1284 * will not. The true length of the dump is recorded in the leading and trailing
1285 * headers once the dump has been completed.
1288 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1290 uint64_t dumpextent;
1294 int error = kerneldumpcrypto_init(di->kdcrypto);
1297 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1302 dumpextent = dtoh64(kdh->dumpextent);
1303 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1305 if (di->kdcomp != 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 enough, 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);
1321 /* The offset at which to begin writing the dump. */
1322 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1329 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1335 if (di->kdcrypto != NULL)
1336 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1340 error = dump_write(di, virtual, physical, di->dumpoff, length);
1342 di->dumpoff += length;
1347 * Write to the dump device starting at dumpoff. When compression is enabled,
1348 * writes to the device will be performed using a callback that gets invoked
1349 * when the compression stream's output buffer is full.
1352 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1357 if (di->kdcomp != NULL) {
1358 /* Bounce through a buffer to avoid CRC errors. */
1359 if (length > di->maxiosize)
1361 buf = di->kdcomp->kdc_buf;
1362 memmove(buf, virtual, length);
1363 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1365 return (_dump_append(di, virtual, physical, length));
1369 * Write to the dump device at the specified offset.
1372 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1373 off_t offset, size_t length)
1377 error = dump_check_bounds(di, offset, length);
1380 return (di->dumper(di->priv, virtual, physical, offset, length));
1384 * Perform kernel dump finalization: flush the compression stream, if necessary,
1385 * write the leading and trailing kernel dump headers now that we know the true
1386 * length of the dump, and optionally write the encryption key following the
1390 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1396 extent = dtoh64(kdh->dumpextent);
1399 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1404 if (di->kdcomp != NULL) {
1405 error = compressor_flush(di->kdcomp->kdc_stream);
1406 if (error == EAGAIN) {
1407 /* We have residual data in di->blockbuf. */
1408 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1410 di->dumpoff += di->kdcomp->kdc_resid;
1411 di->kdcomp->kdc_resid = 0;
1417 * We now know the size of the compressed dump, so update the
1418 * header accordingly and recompute parity.
1420 kdh->dumplength = htod64(di->dumpoff -
1421 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1423 kdh->parity = kerneldump_parity(kdh);
1425 compressor_reset(di->kdcomp->kdc_stream);
1429 * Write kerneldump headers at the beginning and end of the dump extent.
1430 * Write the key after the leading header.
1432 error = dump_write_header(di, kdh,
1433 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1439 error = dump_write_key(di,
1440 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1445 error = dump_write_header(di, kdh,
1446 di->mediaoffset + di->mediasize - di->blocksize);
1450 (void)dump_write(di, NULL, 0, 0, 0);
1455 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1456 char *magic, uint32_t archver, uint64_t dumplen)
1460 bzero(kdh, sizeof(*kdh));
1461 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1462 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1463 kdh->version = htod32(KERNELDUMPVERSION);
1464 kdh->architectureversion = htod32(archver);
1465 kdh->dumplength = htod64(dumplen);
1466 kdh->dumpextent = kdh->dumplength;
1467 kdh->dumptime = htod64(time_second);
1469 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1471 kdh->dumpkeysize = 0;
1473 kdh->blocksize = htod32(di->blocksize);
1474 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1475 dstsize = sizeof(kdh->versionstring);
1476 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1477 kdh->versionstring[dstsize - 2] = '\n';
1478 if (panicstr != NULL)
1479 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1480 if (di->kdcomp != NULL)
1481 kdh->compression = di->kdcomp->kdc_format;
1482 kdh->parity = kerneldump_parity(kdh);
1486 DB_SHOW_COMMAND(panic, db_show_panic)
1489 if (panicstr == NULL)
1490 db_printf("panicstr not set\n");
1492 db_printf("panic: %s\n", panicstr);