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/taskqueue.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[];
177 struct kerneldumpcomp {
179 struct compressor *kdc_stream;
184 static struct kerneldumpcomp *kerneldumpcomp_create(struct dumperinfo *di,
185 uint8_t compression);
186 static void kerneldumpcomp_destroy(struct dumperinfo *di);
187 static int kerneldumpcomp_write_cb(void *base, 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 compression level");
195 * Variable panicstr contains argument to first call to panic; used as flag
196 * to indicate that the kernel has already called panic.
198 const char *panicstr;
200 int dumping; /* system is dumping */
201 int rebooting; /* system is rebooting */
202 static struct dumperinfo dumper; /* our selected dumper */
204 /* Context information for dump-debuggers. */
205 static struct pcb dumppcb; /* Registers. */
206 lwpid_t dumptid; /* Thread ID. */
208 static struct cdevsw reroot_cdevsw = {
209 .d_version = D_VERSION,
213 static void poweroff_wait(void *, int);
214 static void shutdown_halt(void *junk, int howto);
215 static void shutdown_panic(void *junk, int howto);
216 static void shutdown_reset(void *junk, int howto);
217 static int kern_reroot(void);
219 /* register various local shutdown events */
221 shutdown_conf(void *unused)
224 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
226 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
227 SHUTDOWN_PRI_LAST + 100);
228 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
229 SHUTDOWN_PRI_LAST + 100);
230 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
231 SHUTDOWN_PRI_LAST + 200);
234 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
237 * The only reason this exists is to create the /dev/reroot/ directory,
238 * used by reroot code in init(8) as a mountpoint for tmpfs.
241 reroot_conf(void *unused)
246 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
247 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
249 printf("%s: failed to create device node, error %d",
254 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
257 * The system call that results in a reboot.
261 sys_reboot(struct thread *td, struct reboot_args *uap)
267 error = mac_system_check_reboot(td->td_ucred, uap->opt);
270 error = priv_check(td, PRIV_REBOOT);
272 if (uap->opt & RB_REROOT)
273 error = kern_reroot();
275 kern_reboot(uap->opt);
281 shutdown_nice_task_fn(void *arg, int pending __unused)
285 howto = (uintptr_t)arg;
286 /* Send a signal to init(8) and have it shutdown the world. */
288 if (howto & RB_POWEROFF)
289 kern_psignal(initproc, SIGUSR2);
290 else if (howto & RB_POWERCYCLE)
291 kern_psignal(initproc, SIGWINCH);
292 else if (howto & RB_HALT)
293 kern_psignal(initproc, SIGUSR1);
295 kern_psignal(initproc, SIGINT);
296 PROC_UNLOCK(initproc);
299 static struct task shutdown_nice_task = TASK_INITIALIZER(0,
300 &shutdown_nice_task_fn, NULL);
303 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
306 shutdown_nice(int howto)
309 if (initproc != NULL && !SCHEDULER_STOPPED()) {
310 shutdown_nice_task.ta_context = (void *)(uintptr_t)howto;
311 taskqueue_enqueue(taskqueue_fast, &shutdown_nice_task);
314 * No init(8) running, or scheduler would not allow it
315 * to run, so simply reboot.
317 kern_reboot(howto | RB_NOSYNC);
330 if (ts.tv_sec >= 86400) {
331 printf("%ldd", (long)ts.tv_sec / 86400);
335 if (f || ts.tv_sec >= 3600) {
336 printf("%ldh", (long)ts.tv_sec / 3600);
340 if (f || ts.tv_sec >= 60) {
341 printf("%ldm", (long)ts.tv_sec / 60);
345 printf("%lds\n", (long)ts.tv_sec);
349 doadump(boolean_t textdump)
357 if (dumper.dumper == NULL)
361 dumptid = curthread->td_tid;
366 if (textdump && textdump_pending) {
368 textdump_dumpsys(&dumper);
372 error = dumpsys(&dumper);
379 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
382 kern_reboot(int howto)
387 * Normal paths here don't hold Giant, but we can wind up here
388 * unexpectedly with it held. Drop it now so we don't have to
389 * drop and pick it up elsewhere. The paths it is locking will
390 * never be returned to, and it is preferable to preclude
391 * deadlock than to lock against code that won't ever
394 while (mtx_owned(&Giant))
399 * Bind us to the first CPU so that all shutdown code runs there. Some
400 * systems don't shutdown properly (i.e., ACPI power off) if we
401 * run on another processor.
403 if (!SCHEDULER_STOPPED()) {
404 thread_lock(curthread);
405 sched_bind(curthread, CPU_FIRST());
406 thread_unlock(curthread);
407 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
408 ("boot: not running on cpu 0"));
411 /* We're in the process of rebooting. */
414 /* We are out of the debugger now. */
418 * Do any callouts that should be done BEFORE syncing the filesystems.
420 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
423 * Now sync filesystems
425 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
427 bufshutdown(show_busybufs);
435 * Ok, now do things that assume all filesystem activity has
438 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
440 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
443 /* Now that we're going to really halt the system... */
444 EVENTHANDLER_INVOKE(shutdown_final, howto);
446 for(;;) ; /* safety against shutdown_reset not working */
451 * The system call that results in changing the rootfs.
456 struct vnode *oldrootvnode, *vp;
457 struct mount *mp, *devmp;
460 if (curproc != initproc)
464 * Mark the filesystem containing currently-running executable
465 * (the temporary copy of init(8)) busy.
467 vp = curproc->p_textvp;
468 error = vn_lock(vp, LK_SHARED);
472 error = vfs_busy(mp, MBF_NOWAIT);
476 error = vfs_busy(mp, 0);
477 vn_lock(vp, LK_SHARED | LK_RETRY);
483 if (vp->v_iflag & VI_DOOMED) {
492 * Remove the filesystem containing currently-running executable
493 * from the mount list, to prevent it from being unmounted
494 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
496 * Also preserve /dev - forcibly unmounting it could cause driver
504 mtx_lock(&mountlist_mtx);
505 TAILQ_REMOVE(&mountlist, mp, mnt_list);
506 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
507 mtx_unlock(&mountlist_mtx);
509 oldrootvnode = rootvnode;
512 * Unmount everything except for the two filesystems preserved above.
517 * Add /dev back; vfs_mountroot() will move it into its new place.
519 mtx_lock(&mountlist_mtx);
520 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
521 mtx_unlock(&mountlist_mtx);
526 * Mount the new rootfs.
531 * Update all references to the old rootvnode.
533 mountcheckdirs(oldrootvnode, rootvnode);
536 * Add the temporary filesystem back and unbusy it.
538 mtx_lock(&mountlist_mtx);
539 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
540 mtx_unlock(&mountlist_mtx);
547 * If the shutdown was a clean halt, behave accordingly.
550 shutdown_halt(void *junk, int howto)
553 if (howto & RB_HALT) {
555 printf("The operating system has halted.\n");
556 printf("Please press any key to reboot.\n\n");
558 case -1: /* No console, just die */
568 * Check to see if the system paniced, pause and then reboot
569 * according to the specified delay.
572 shutdown_panic(void *junk, int howto)
576 if (howto & RB_DUMP) {
577 if (panic_reboot_wait_time != 0) {
578 if (panic_reboot_wait_time != -1) {
579 printf("Automatic reboot in %d seconds - "
580 "press a key on the console to abort\n",
581 panic_reboot_wait_time);
582 for (loop = panic_reboot_wait_time * 10;
584 DELAY(1000 * 100); /* 1/10th second */
585 /* Did user type a key? */
586 if (cncheckc() != -1)
592 } else { /* zero time specified - reboot NOW */
595 printf("--> Press a key on the console to reboot,\n");
596 printf("--> or switch off the system now.\n");
602 * Everything done, now reset
605 shutdown_reset(void *junk, int howto)
608 printf("Rebooting...\n");
609 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
612 * Acquiring smp_ipi_mtx here has a double effect:
613 * - it disables interrupts avoiding CPU0 preemption
614 * by fast handlers (thus deadlocking against other CPUs)
615 * - it avoids deadlocks against smp_rendezvous() or, more
616 * generally, threads busy-waiting, with this spinlock held,
617 * and waiting for responses by threads on other CPUs
618 * (ie. smp_tlb_shootdown()).
620 * For the !SMP case it just needs to handle the former problem.
623 mtx_lock_spin(&smp_ipi_mtx);
628 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
630 /* NOTREACHED */ /* assuming reset worked */
633 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
634 static int kassert_warn_only = 0;
636 static int kassert_do_kdb = 0;
639 static int kassert_do_ktr = 0;
641 static int kassert_do_log = 1;
642 static int kassert_log_pps_limit = 4;
643 static int kassert_log_mute_at = 0;
644 static int kassert_log_panic_at = 0;
645 static int kassert_warnings = 0;
647 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
649 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
650 &kassert_warn_only, 0,
651 "KASSERT triggers a panic (1) or just a warning (0)");
654 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
655 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
659 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
661 "KASSERT does a KTR, set this to the KTRMASK you want");
664 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
665 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
667 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
668 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
670 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
671 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
673 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
674 &kassert_log_pps_limit, 0, "limit number of log messages per second");
676 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
677 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
679 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
681 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
682 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
683 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
686 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
690 error = sysctl_wire_old_buffer(req, sizeof(int));
693 error = sysctl_handle_int(oidp, &i, 0, req);
695 if (error != 0 || req->newptr == NULL)
697 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
702 * Called by KASSERT, this decides if we will panic
703 * or if we will log via printf and/or ktr.
706 kassert_panic(const char *fmt, ...)
708 static char buf[256];
712 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
716 * panic if we're not just warning, or if we've exceeded
717 * kassert_log_panic_at warnings.
719 if (!kassert_warn_only ||
720 (kassert_log_panic_at > 0 &&
721 kassert_warnings >= kassert_log_panic_at)) {
731 * log if we've not yet met the mute limit.
733 if (kassert_do_log &&
734 (kassert_log_mute_at == 0 ||
735 kassert_warnings < kassert_log_mute_at)) {
736 static struct timeval lasterr;
739 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
740 printf("KASSERT failed: %s\n", buf);
745 if (kassert_do_kdb) {
746 kdb_enter(KDB_WHY_KASSERT, buf);
749 atomic_add_int(&kassert_warnings, 1);
754 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
755 * and then reboots. If we are called twice, then we avoid trying to sync
756 * the disks as this often leads to recursive panics.
759 panic(const char *fmt, ...)
768 vpanic(const char *fmt, va_list ap)
773 struct thread *td = curthread;
774 int bootopt, newpanic;
775 static char buf[256];
781 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
782 * concurrently entering panic. Only the winner will proceed
785 if (panicstr == NULL && !kdb_active) {
786 other_cpus = all_cpus;
787 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
788 stop_cpus_hard(other_cpus);
793 * Ensure that the scheduler is stopped while panicking, even if panic
794 * has been entered from kdb.
796 td->td_stopsched = 1;
798 bootopt = RB_AUTOBOOT;
801 bootopt |= RB_NOSYNC;
809 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
812 printf("panic: %s\n", buf);
819 printf("cpuid = %d\n", PCPU_GET(cpuid));
821 printf("time = %jd\n", (intmax_t )time_second);
823 if (newpanic && trace_on_panic)
825 if (debugger_on_panic)
826 kdb_enter(KDB_WHY_PANIC, "panic");
828 /*thread_lock(td); */
829 td->td_flags |= TDF_INPANIC;
830 /* thread_unlock(td); */
832 bootopt |= RB_NOSYNC;
833 if (poweroff_on_panic)
834 bootopt |= RB_POWEROFF;
835 if (powercycle_on_panic)
836 bootopt |= RB_POWERCYCLE;
837 kern_reboot(bootopt);
841 * Support for poweroff delay.
843 * Please note that setting this delay too short might power off your machine
844 * before the write cache on your hard disk has been flushed, leading to
845 * soft-updates inconsistencies.
847 #ifndef POWEROFF_DELAY
848 # define POWEROFF_DELAY 5000
850 static int poweroff_delay = POWEROFF_DELAY;
852 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
853 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
856 poweroff_wait(void *junk, int howto)
859 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
861 DELAY(poweroff_delay * 1000);
865 * Some system processes (e.g. syncer) need to be stopped at appropriate
866 * points in their main loops prior to a system shutdown, so that they
867 * won't interfere with the shutdown process (e.g. by holding a disk buf
868 * to cause sync to fail). For each of these system processes, register
869 * shutdown_kproc() as a handler for one of shutdown events.
871 static int kproc_shutdown_wait = 60;
872 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
873 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
876 kproc_shutdown(void *arg, int howto)
884 p = (struct proc *)arg;
885 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
886 kproc_shutdown_wait, p->p_comm);
887 error = kproc_suspend(p, kproc_shutdown_wait * hz);
889 if (error == EWOULDBLOCK)
890 printf("timed out\n");
896 kthread_shutdown(void *arg, int howto)
904 td = (struct thread *)arg;
905 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
906 kproc_shutdown_wait, td->td_name);
907 error = kthread_suspend(td, kproc_shutdown_wait * hz);
909 if (error == EWOULDBLOCK)
910 printf("timed out\n");
915 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
916 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
917 dumpdevname, 0, "Device for kernel dumps");
919 static int _dump_append(struct dumperinfo *di, void *virtual,
920 vm_offset_t physical, size_t length);
923 static struct kerneldumpcrypto *
924 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
925 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
927 struct kerneldumpcrypto *kdc;
928 struct kerneldumpkey *kdk;
929 uint32_t dumpkeysize;
931 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
932 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
934 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
936 kdc->kdc_encryption = encryption;
937 switch (kdc->kdc_encryption) {
938 case KERNELDUMP_ENC_AES_256_CBC:
939 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
946 kdc->kdc_dumpkeysize = dumpkeysize;
947 kdk = kdc->kdc_dumpkey;
948 kdk->kdk_encryption = kdc->kdc_encryption;
949 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
950 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
951 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
955 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
961 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
963 uint8_t hash[SHA256_DIGEST_LENGTH];
965 struct kerneldumpkey *kdk;
974 * When a user enters ddb it can write a crash dump multiple times.
975 * Each time it should be encrypted using a different IV.
978 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
979 SHA256_Final(hash, &ctx);
980 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
982 switch (kdc->kdc_encryption) {
983 case KERNELDUMP_ENC_AES_256_CBC:
984 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
995 kdk = kdc->kdc_dumpkey;
996 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
998 explicit_bzero(hash, sizeof(hash));
1003 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
1008 return (kdc->kdc_dumpkeysize);
1012 static struct kerneldumpcomp *
1013 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
1015 struct kerneldumpcomp *kdcomp;
1018 switch (compression) {
1019 case KERNELDUMP_COMP_GZIP:
1020 format = COMPRESS_GZIP;
1022 case KERNELDUMP_COMP_ZSTD:
1023 format = COMPRESS_ZSTD;
1029 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1030 kdcomp->kdc_format = compression;
1031 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1032 format, di->maxiosize, kerneldump_gzlevel, di);
1033 if (kdcomp->kdc_stream == NULL) {
1034 free(kdcomp, M_DUMPER);
1037 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1042 kerneldumpcomp_destroy(struct dumperinfo *di)
1044 struct kerneldumpcomp *kdcomp;
1046 kdcomp = di->kdcomp;
1049 compressor_fini(kdcomp->kdc_stream);
1050 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1051 free(kdcomp->kdc_buf, M_DUMPER);
1052 free(kdcomp, M_DUMPER);
1055 /* Registration of dumpers */
1057 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1058 uint8_t compression, uint8_t encryption, const uint8_t *key,
1059 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1064 error = priv_check(td, PRIV_SETDUMPER);
1072 if (dumper.dumper != NULL)
1075 dumper.blockbuf = NULL;
1076 dumper.kdcrypto = NULL;
1077 dumper.kdcomp = NULL;
1079 if (encryption != KERNELDUMP_ENC_NONE) {
1081 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1082 encryption, key, encryptedkeysize, encryptedkey);
1083 if (dumper.kdcrypto == NULL) {
1093 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1094 if (wantcopy >= sizeof(dumpdevname)) {
1095 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1096 devname, dumpdevname);
1099 if (compression != KERNELDUMP_COMP_NONE) {
1101 * We currently can't support simultaneous encryption and
1104 if (encryption != KERNELDUMP_ENC_NONE) {
1108 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1109 if (dumper.kdcomp == NULL) {
1115 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1119 if (dumper.kdcrypto != NULL) {
1120 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1121 dumper.kdcrypto->kdc_dumpkeysize);
1122 free(dumper.kdcrypto, M_EKCD);
1126 kerneldumpcomp_destroy(&dumper);
1128 if (dumper.blockbuf != NULL) {
1129 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1130 free(dumper.blockbuf, M_DUMPER);
1132 explicit_bzero(&dumper, sizeof(dumper));
1133 dumpdevname[0] = '\0';
1138 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1141 if (length != 0 && (offset < di->mediaoffset ||
1142 offset - di->mediaoffset + length > di->mediasize)) {
1143 if (di->kdcomp != NULL && offset >= di->mediaoffset) {
1145 "Compressed dump failed to fit in device boundaries.\n");
1149 printf("Attempt to write outside dump device boundaries.\n"
1150 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1151 (intmax_t)offset, (intmax_t)di->mediaoffset,
1152 (uintmax_t)length, (intmax_t)di->mediasize);
1155 if (length % di->blocksize != 0) {
1156 printf("Attempt to write partial block of length %ju.\n",
1160 if (offset % di->blocksize != 0) {
1161 printf("Attempt to write at unaligned offset %jd.\n",
1171 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1174 switch (kdc->kdc_encryption) {
1175 case KERNELDUMP_ENC_AES_256_CBC:
1176 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1177 8 * size, buf) <= 0) {
1180 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1181 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1192 /* Encrypt data and call dumper. */
1194 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1195 vm_offset_t physical, off_t offset, size_t length)
1197 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1198 struct kerneldumpcrypto *kdc;
1204 while (length > 0) {
1205 nbytes = MIN(length, sizeof(buf));
1206 bcopy(virtual, buf, nbytes);
1208 if (dump_encrypt(kdc, buf, nbytes) != 0)
1211 error = dump_write(di, buf, physical, offset, nbytes);
1216 virtual = (void *)((uint8_t *)virtual + nbytes);
1224 dump_write_key(struct dumperinfo *di, off_t offset)
1226 struct kerneldumpcrypto *kdc;
1231 return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1232 kdc->kdc_dumpkeysize));
1237 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1239 struct dumperinfo *di;
1240 size_t resid, rlength;
1245 if (length % di->blocksize != 0) {
1247 * This must be the final write after flushing the compression
1248 * stream. Write as many full blocks as possible and stash the
1249 * residual data in the dumper's block buffer. It will be
1250 * padded and written in dump_finish().
1252 rlength = rounddown(length, di->blocksize);
1254 error = _dump_append(di, base, 0, rlength);
1258 resid = length - rlength;
1259 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1260 di->kdcomp->kdc_resid = resid;
1263 return (_dump_append(di, base, 0, length));
1267 * Write a kerneldumpheader at the specified offset. The header structure is 512
1268 * bytes in size, but we must pad to the device sector size.
1271 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1277 hdrsz = sizeof(*kdh);
1278 if (hdrsz > di->blocksize)
1281 if (hdrsz == di->blocksize)
1285 memset(buf, 0, di->blocksize);
1286 memcpy(buf, kdh, hdrsz);
1289 return (dump_write(di, buf, 0, offset, di->blocksize));
1293 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1294 * protect us from metadata and metadata from us.
1296 #define SIZEOF_METADATA (64 * 1024)
1299 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1300 * if requested, and make sure that we have enough space on the dump device.
1302 * We set things up so that the dump ends before the last sector of the dump
1303 * device, at which the trailing header is written.
1305 * +-----------+------+-----+----------------------------+------+
1306 * | | lhdr | key | ... kernel dump ... | thdr |
1307 * +-----------+------+-----+----------------------------+------+
1308 * 1 blk opt <------- dump extent --------> 1 blk
1310 * Dumps written using dump_append() start at the beginning of the extent.
1311 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1312 * will not. The true length of the dump is recorded in the leading and trailing
1313 * headers once the dump has been completed.
1316 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1318 uint64_t dumpextent;
1322 int error = kerneldumpcrypto_init(di->kdcrypto);
1325 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1330 dumpextent = dtoh64(kdh->dumpextent);
1331 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1333 if (di->kdcomp != NULL) {
1335 * We don't yet know how much space the compressed dump
1336 * will occupy, so try to use the whole swap partition
1337 * (minus the first 64KB) in the hope that the
1338 * compressed dump will fit. If that doesn't turn out to
1339 * be enough, the bounds checking in dump_write()
1340 * will catch us and cause the dump to fail.
1342 dumpextent = di->mediasize - SIZEOF_METADATA -
1343 2 * di->blocksize - keysize;
1344 kdh->dumpextent = htod64(dumpextent);
1349 /* The offset at which to begin writing the dump. */
1350 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1357 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1363 if (di->kdcrypto != NULL)
1364 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1368 error = dump_write(di, virtual, physical, di->dumpoff, length);
1370 di->dumpoff += length;
1375 * Write to the dump device starting at dumpoff. When compression is enabled,
1376 * writes to the device will be performed using a callback that gets invoked
1377 * when the compression stream's output buffer is full.
1380 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1385 if (di->kdcomp != NULL) {
1386 /* Bounce through a buffer to avoid CRC errors. */
1387 if (length > di->maxiosize)
1389 buf = di->kdcomp->kdc_buf;
1390 memmove(buf, virtual, length);
1391 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1393 return (_dump_append(di, virtual, physical, length));
1397 * Write to the dump device at the specified offset.
1400 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1401 off_t offset, size_t length)
1405 error = dump_check_bounds(di, offset, length);
1408 return (di->dumper(di->priv, virtual, physical, offset, length));
1412 * Perform kernel dump finalization: flush the compression stream, if necessary,
1413 * write the leading and trailing kernel dump headers now that we know the true
1414 * length of the dump, and optionally write the encryption key following the
1418 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1424 extent = dtoh64(kdh->dumpextent);
1427 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1432 if (di->kdcomp != NULL) {
1433 error = compressor_flush(di->kdcomp->kdc_stream);
1434 if (error == EAGAIN) {
1435 /* We have residual data in di->blockbuf. */
1436 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1438 di->dumpoff += di->kdcomp->kdc_resid;
1439 di->kdcomp->kdc_resid = 0;
1445 * We now know the size of the compressed dump, so update the
1446 * header accordingly and recompute parity.
1448 kdh->dumplength = htod64(di->dumpoff -
1449 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1451 kdh->parity = kerneldump_parity(kdh);
1453 compressor_reset(di->kdcomp->kdc_stream);
1457 * Write kerneldump headers at the beginning and end of the dump extent.
1458 * Write the key after the leading header.
1460 error = dump_write_header(di, kdh,
1461 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1467 error = dump_write_key(di,
1468 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1473 error = dump_write_header(di, kdh,
1474 di->mediaoffset + di->mediasize - di->blocksize);
1478 (void)dump_write(di, NULL, 0, 0, 0);
1483 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1484 char *magic, uint32_t archver, uint64_t dumplen)
1488 bzero(kdh, sizeof(*kdh));
1489 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1490 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1491 kdh->version = htod32(KERNELDUMPVERSION);
1492 kdh->architectureversion = htod32(archver);
1493 kdh->dumplength = htod64(dumplen);
1494 kdh->dumpextent = kdh->dumplength;
1495 kdh->dumptime = htod64(time_second);
1497 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1499 kdh->dumpkeysize = 0;
1501 kdh->blocksize = htod32(di->blocksize);
1502 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1503 dstsize = sizeof(kdh->versionstring);
1504 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1505 kdh->versionstring[dstsize - 2] = '\n';
1506 if (panicstr != NULL)
1507 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1508 if (di->kdcomp != NULL)
1509 kdh->compression = di->kdcomp->kdc_format;
1510 kdh->parity = kerneldump_parity(kdh);
1514 DB_SHOW_COMMAND(panic, db_show_panic)
1517 if (panicstr == NULL)
1518 db_printf("panicstr not set\n");
1520 db_printf("panic: %s\n", panicstr);