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_printf.h"
47 #include "opt_sched.h"
48 #include "opt_watchdog.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
55 #include <sys/compressor.h>
58 #include <sys/eventhandler.h>
59 #include <sys/filedesc.h>
62 #include <sys/kernel.h>
63 #include <sys/kerneldump.h>
64 #include <sys/kthread.h>
66 #include <sys/malloc.h>
68 #include <sys/mount.h>
71 #include <sys/reboot.h>
72 #include <sys/resourcevar.h>
73 #include <sys/rwlock.h>
75 #include <sys/sched.h>
77 #include <sys/sysctl.h>
78 #include <sys/sysproto.h>
79 #include <sys/taskqueue.h>
80 #include <sys/vnode.h>
81 #include <sys/watchdog.h>
83 #include <crypto/chacha20/chacha.h>
84 #include <crypto/rijndael/rijndael-api-fst.h>
85 #include <crypto/sha2/sha256.h>
89 #include <machine/cpu.h>
90 #include <machine/dump.h>
91 #include <machine/pcb.h>
92 #include <machine/smp.h>
94 #include <security/mac/mac_framework.h>
97 #include <vm/vm_object.h>
98 #include <vm/vm_page.h>
99 #include <vm/vm_pager.h>
100 #include <vm/swap_pager.h>
102 #include <sys/signalvar.h>
104 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
106 #ifndef PANIC_REBOOT_WAIT_TIME
107 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
109 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
110 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
111 &panic_reboot_wait_time, 0,
112 "Seconds to wait before rebooting after a panic");
115 * Note that stdarg.h and the ANSI style va_start macro is used for both
116 * ANSI and traditional C compilers.
118 #include <machine/stdarg.h>
121 #ifdef KDB_UNATTENDED
122 static int debugger_on_panic = 0;
124 static int debugger_on_panic = 1;
126 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
127 CTLFLAG_RWTUN | CTLFLAG_SECURE,
128 &debugger_on_panic, 0, "Run debugger on kernel panic");
130 int debugger_on_trap = 0;
131 SYSCTL_INT(_debug, OID_AUTO, debugger_on_trap,
132 CTLFLAG_RWTUN | CTLFLAG_SECURE,
133 &debugger_on_trap, 0, "Run debugger on kernel trap before panic");
136 static int trace_on_panic = 1;
137 static bool trace_all_panics = true;
139 static int trace_on_panic = 0;
140 static bool trace_all_panics = false;
142 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
143 CTLFLAG_RWTUN | CTLFLAG_SECURE,
144 &trace_on_panic, 0, "Print stack trace on kernel panic");
145 SYSCTL_BOOL(_debug, OID_AUTO, trace_all_panics, CTLFLAG_RWTUN,
146 &trace_all_panics, 0, "Print stack traces on secondary kernel panics");
149 static int sync_on_panic = 0;
150 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
151 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
153 static bool poweroff_on_panic = 0;
154 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
155 &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
157 static bool powercycle_on_panic = 0;
158 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
159 &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
161 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
162 "Shutdown environment");
165 static int show_busybufs;
167 static int show_busybufs = 1;
169 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
170 &show_busybufs, 0, "");
172 int suspend_blocked = 0;
173 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
174 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
177 FEATURE(ekcd, "Encrypted kernel crash dumps support");
179 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
181 struct kerneldumpcrypto {
182 uint8_t kdc_encryption;
183 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
187 cipherInstance aes_ci;
189 struct chacha_ctx u_chacha;
191 #define kdc_ki u.u_aes.aes_ki
192 #define kdc_ci u.u_aes.aes_ci
193 #define kdc_chacha u.u_chacha
194 uint32_t kdc_dumpkeysize;
195 struct kerneldumpkey kdc_dumpkey[];
199 struct kerneldumpcomp {
201 struct compressor *kdc_stream;
206 static struct kerneldumpcomp *kerneldumpcomp_create(struct dumperinfo *di,
207 uint8_t compression);
208 static void kerneldumpcomp_destroy(struct dumperinfo *di);
209 static int kerneldumpcomp_write_cb(void *base, size_t len, off_t off, void *arg);
211 static int kerneldump_gzlevel = 6;
212 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
213 &kerneldump_gzlevel, 0,
214 "Kernel crash dump compression level");
217 * Variable panicstr contains argument to first call to panic; used as flag
218 * to indicate that the kernel has already called panic.
220 const char *panicstr;
221 bool __read_frequently panicked;
223 int __read_mostly dumping; /* system is dumping */
224 int rebooting; /* system is rebooting */
226 * Used to serialize between sysctl kern.shutdown.dumpdevname and list
227 * modifications via ioctl.
229 static struct mtx dumpconf_list_lk;
230 MTX_SYSINIT(dumper_configs, &dumpconf_list_lk, "dumper config list", MTX_DEF);
232 /* Our selected dumper(s). */
233 static TAILQ_HEAD(dumpconflist, dumperinfo) dumper_configs =
234 TAILQ_HEAD_INITIALIZER(dumper_configs);
236 /* Context information for dump-debuggers. */
237 static struct pcb dumppcb; /* Registers. */
238 lwpid_t dumptid; /* Thread ID. */
240 static struct cdevsw reroot_cdevsw = {
241 .d_version = D_VERSION,
245 static void poweroff_wait(void *, int);
246 static void shutdown_halt(void *junk, int howto);
247 static void shutdown_panic(void *junk, int howto);
248 static void shutdown_reset(void *junk, int howto);
249 static int kern_reroot(void);
251 /* register various local shutdown events */
253 shutdown_conf(void *unused)
256 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
258 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
259 SHUTDOWN_PRI_LAST + 100);
260 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
261 SHUTDOWN_PRI_LAST + 100);
262 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
263 SHUTDOWN_PRI_LAST + 200);
266 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
269 * The only reason this exists is to create the /dev/reroot/ directory,
270 * used by reroot code in init(8) as a mountpoint for tmpfs.
273 reroot_conf(void *unused)
278 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
279 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
281 printf("%s: failed to create device node, error %d",
286 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
289 * The system call that results in a reboot.
293 sys_reboot(struct thread *td, struct reboot_args *uap)
299 error = mac_system_check_reboot(td->td_ucred, uap->opt);
302 error = priv_check(td, PRIV_REBOOT);
304 if (uap->opt & RB_REROOT)
305 error = kern_reroot();
307 kern_reboot(uap->opt);
313 shutdown_nice_task_fn(void *arg, int pending __unused)
317 howto = (uintptr_t)arg;
318 /* Send a signal to init(8) and have it shutdown the world. */
320 if (howto & RB_POWEROFF)
321 kern_psignal(initproc, SIGUSR2);
322 else if (howto & RB_POWERCYCLE)
323 kern_psignal(initproc, SIGWINCH);
324 else if (howto & RB_HALT)
325 kern_psignal(initproc, SIGUSR1);
327 kern_psignal(initproc, SIGINT);
328 PROC_UNLOCK(initproc);
331 static struct task shutdown_nice_task = TASK_INITIALIZER(0,
332 &shutdown_nice_task_fn, NULL);
335 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
338 shutdown_nice(int howto)
341 if (initproc != NULL && !SCHEDULER_STOPPED()) {
342 shutdown_nice_task.ta_context = (void *)(uintptr_t)howto;
343 taskqueue_enqueue(taskqueue_fast, &shutdown_nice_task);
346 * No init(8) running, or scheduler would not allow it
347 * to run, so simply reboot.
349 kern_reboot(howto | RB_NOSYNC);
362 if (ts.tv_sec >= 86400) {
363 printf("%ldd", (long)ts.tv_sec / 86400);
367 if (f || ts.tv_sec >= 3600) {
368 printf("%ldh", (long)ts.tv_sec / 3600);
372 if (f || ts.tv_sec >= 60) {
373 printf("%ldm", (long)ts.tv_sec / 60);
377 printf("%lds\n", (long)ts.tv_sec);
381 doadump(boolean_t textdump)
389 if (TAILQ_EMPTY(&dumper_configs))
393 dumptid = curthread->td_tid;
398 if (textdump && textdump_pending) {
400 textdump_dumpsys(TAILQ_FIRST(&dumper_configs));
404 struct dumperinfo *di;
406 TAILQ_FOREACH(di, &dumper_configs, di_next) {
418 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
421 kern_reboot(int howto)
426 * Normal paths here don't hold Giant, but we can wind up here
427 * unexpectedly with it held. Drop it now so we don't have to
428 * drop and pick it up elsewhere. The paths it is locking will
429 * never be returned to, and it is preferable to preclude
430 * deadlock than to lock against code that won't ever
433 while (mtx_owned(&Giant))
438 * Bind us to the first CPU so that all shutdown code runs there. Some
439 * systems don't shutdown properly (i.e., ACPI power off) if we
440 * run on another processor.
442 if (!SCHEDULER_STOPPED()) {
443 thread_lock(curthread);
444 sched_bind(curthread, CPU_FIRST());
445 thread_unlock(curthread);
446 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
447 ("boot: not running on cpu 0"));
450 /* We're in the process of rebooting. */
453 /* We are out of the debugger now. */
457 * Do any callouts that should be done BEFORE syncing the filesystems.
459 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
462 * Now sync filesystems
464 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
466 bufshutdown(show_busybufs);
474 * Ok, now do things that assume all filesystem activity has
477 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
479 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
482 /* Now that we're going to really halt the system... */
483 EVENTHANDLER_INVOKE(shutdown_final, howto);
485 for(;;) ; /* safety against shutdown_reset not working */
490 * The system call that results in changing the rootfs.
495 struct vnode *oldrootvnode, *vp;
496 struct mount *mp, *devmp;
499 if (curproc != initproc)
503 * Mark the filesystem containing currently-running executable
504 * (the temporary copy of init(8)) busy.
506 vp = curproc->p_textvp;
507 error = vn_lock(vp, LK_SHARED);
511 error = vfs_busy(mp, MBF_NOWAIT);
515 error = vfs_busy(mp, 0);
516 vn_lock(vp, LK_SHARED | LK_RETRY);
522 if (VN_IS_DOOMED(vp)) {
531 * Remove the filesystem containing currently-running executable
532 * from the mount list, to prevent it from being unmounted
533 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
535 * Also preserve /dev - forcibly unmounting it could cause driver
543 mtx_lock(&mountlist_mtx);
544 TAILQ_REMOVE(&mountlist, mp, mnt_list);
545 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
546 mtx_unlock(&mountlist_mtx);
548 oldrootvnode = rootvnode;
551 * Unmount everything except for the two filesystems preserved above.
556 * Add /dev back; vfs_mountroot() will move it into its new place.
558 mtx_lock(&mountlist_mtx);
559 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
560 mtx_unlock(&mountlist_mtx);
565 * Mount the new rootfs.
570 * Update all references to the old rootvnode.
572 mountcheckdirs(oldrootvnode, rootvnode);
575 * Add the temporary filesystem back and unbusy it.
577 mtx_lock(&mountlist_mtx);
578 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
579 mtx_unlock(&mountlist_mtx);
586 * If the shutdown was a clean halt, behave accordingly.
589 shutdown_halt(void *junk, int howto)
592 if (howto & RB_HALT) {
594 printf("The operating system has halted.\n");
595 printf("Please press any key to reboot.\n\n");
597 wdog_kern_pat(WD_TO_NEVER);
600 case -1: /* No console, just die */
610 * Check to see if the system paniced, pause and then reboot
611 * according to the specified delay.
614 shutdown_panic(void *junk, int howto)
618 if (howto & RB_DUMP) {
619 if (panic_reboot_wait_time != 0) {
620 if (panic_reboot_wait_time != -1) {
621 printf("Automatic reboot in %d seconds - "
622 "press a key on the console to abort\n",
623 panic_reboot_wait_time);
624 for (loop = panic_reboot_wait_time * 10;
626 DELAY(1000 * 100); /* 1/10th second */
627 /* Did user type a key? */
628 if (cncheckc() != -1)
634 } else { /* zero time specified - reboot NOW */
637 printf("--> Press a key on the console to reboot,\n");
638 printf("--> or switch off the system now.\n");
644 * Everything done, now reset
647 shutdown_reset(void *junk, int howto)
650 printf("Rebooting...\n");
651 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
654 * Acquiring smp_ipi_mtx here has a double effect:
655 * - it disables interrupts avoiding CPU0 preemption
656 * by fast handlers (thus deadlocking against other CPUs)
657 * - it avoids deadlocks against smp_rendezvous() or, more
658 * generally, threads busy-waiting, with this spinlock held,
659 * and waiting for responses by threads on other CPUs
660 * (ie. smp_tlb_shootdown()).
662 * For the !SMP case it just needs to handle the former problem.
665 mtx_lock_spin(&smp_ipi_mtx);
670 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
672 /* NOTREACHED */ /* assuming reset worked */
675 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
676 static int kassert_warn_only = 0;
678 static int kassert_do_kdb = 0;
681 static int kassert_do_ktr = 0;
683 static int kassert_do_log = 1;
684 static int kassert_log_pps_limit = 4;
685 static int kassert_log_mute_at = 0;
686 static int kassert_log_panic_at = 0;
687 static int kassert_suppress_in_panic = 0;
688 static int kassert_warnings = 0;
690 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
693 #ifdef KASSERT_PANIC_OPTIONAL
694 #define KASSERT_RWTUN CTLFLAG_RWTUN
696 #define KASSERT_RWTUN CTLFLAG_RDTUN
699 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, KASSERT_RWTUN,
700 &kassert_warn_only, 0,
701 "KASSERT triggers a panic (0) or just a warning (1)");
704 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, KASSERT_RWTUN,
705 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
709 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, KASSERT_RWTUN,
711 "KASSERT does a KTR, set this to the KTRMASK you want");
714 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, KASSERT_RWTUN,
716 "If warn_only is enabled, log (1) or do not log (0) assertion violations");
718 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RD | CTLFLAG_STATS,
719 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
721 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, KASSERT_RWTUN,
722 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
724 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, KASSERT_RWTUN,
725 &kassert_log_pps_limit, 0, "limit number of log messages per second");
727 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, KASSERT_RWTUN,
728 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
730 SYSCTL_INT(_debug_kassert, OID_AUTO, suppress_in_panic, KASSERT_RWTUN,
731 &kassert_suppress_in_panic, 0,
732 "KASSERTs will be suppressed while handling a panic");
735 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
737 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
738 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_NEEDGIANT, NULL, 0,
739 kassert_sysctl_kassert, "I",
740 "set to trigger a test kassert");
743 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
747 error = sysctl_wire_old_buffer(req, sizeof(int));
750 error = sysctl_handle_int(oidp, &i, 0, req);
752 if (error != 0 || req->newptr == NULL)
754 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
758 #ifdef KASSERT_PANIC_OPTIONAL
760 * Called by KASSERT, this decides if we will panic
761 * or if we will log via printf and/or ktr.
764 kassert_panic(const char *fmt, ...)
766 static char buf[256];
770 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
774 * If we are suppressing secondary panics, log the warning but do not
775 * re-enter panic/kdb.
777 if (panicstr != NULL && kassert_suppress_in_panic) {
778 if (kassert_do_log) {
779 printf("KASSERT failed: %s\n", buf);
781 if (trace_all_panics && trace_on_panic)
789 * panic if we're not just warning, or if we've exceeded
790 * kassert_log_panic_at warnings.
792 if (!kassert_warn_only ||
793 (kassert_log_panic_at > 0 &&
794 kassert_warnings >= kassert_log_panic_at)) {
804 * log if we've not yet met the mute limit.
806 if (kassert_do_log &&
807 (kassert_log_mute_at == 0 ||
808 kassert_warnings < kassert_log_mute_at)) {
809 static struct timeval lasterr;
812 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
813 printf("KASSERT failed: %s\n", buf);
818 if (kassert_do_kdb) {
819 kdb_enter(KDB_WHY_KASSERT, buf);
822 atomic_add_int(&kassert_warnings, 1);
824 #endif /* KASSERT_PANIC_OPTIONAL */
828 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
829 * and then reboots. If we are called twice, then we avoid trying to sync
830 * the disks as this often leads to recursive panics.
833 panic(const char *fmt, ...)
842 vpanic(const char *fmt, va_list ap)
847 struct thread *td = curthread;
848 int bootopt, newpanic;
849 static char buf[256];
855 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
856 * concurrently entering panic. Only the winner will proceed
859 if (panicstr == NULL && !kdb_active) {
860 other_cpus = all_cpus;
861 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
862 stop_cpus_hard(other_cpus);
867 * Ensure that the scheduler is stopped while panicking, even if panic
868 * has been entered from kdb.
870 td->td_stopsched = 1;
872 bootopt = RB_AUTOBOOT;
875 bootopt |= RB_NOSYNC;
884 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
887 printf("panic: %s\n", buf);
894 printf("cpuid = %d\n", PCPU_GET(cpuid));
896 printf("time = %jd\n", (intmax_t )time_second);
898 if ((newpanic || trace_all_panics) && trace_on_panic)
900 if (debugger_on_panic)
901 kdb_enter(KDB_WHY_PANIC, "panic");
903 /*thread_lock(td); */
904 td->td_flags |= TDF_INPANIC;
905 /* thread_unlock(td); */
907 bootopt |= RB_NOSYNC;
908 if (poweroff_on_panic)
909 bootopt |= RB_POWEROFF;
910 if (powercycle_on_panic)
911 bootopt |= RB_POWERCYCLE;
912 kern_reboot(bootopt);
916 * Support for poweroff delay.
918 * Please note that setting this delay too short might power off your machine
919 * before the write cache on your hard disk has been flushed, leading to
920 * soft-updates inconsistencies.
922 #ifndef POWEROFF_DELAY
923 # define POWEROFF_DELAY 5000
925 static int poweroff_delay = POWEROFF_DELAY;
927 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
928 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
931 poweroff_wait(void *junk, int howto)
934 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
936 DELAY(poweroff_delay * 1000);
940 * Some system processes (e.g. syncer) need to be stopped at appropriate
941 * points in their main loops prior to a system shutdown, so that they
942 * won't interfere with the shutdown process (e.g. by holding a disk buf
943 * to cause sync to fail). For each of these system processes, register
944 * shutdown_kproc() as a handler for one of shutdown events.
946 static int kproc_shutdown_wait = 60;
947 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
948 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
951 kproc_shutdown(void *arg, int howto)
959 p = (struct proc *)arg;
960 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
961 kproc_shutdown_wait, p->p_comm);
962 error = kproc_suspend(p, kproc_shutdown_wait * hz);
964 if (error == EWOULDBLOCK)
965 printf("timed out\n");
971 kthread_shutdown(void *arg, int howto)
979 td = (struct thread *)arg;
980 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
981 kproc_shutdown_wait, td->td_name);
982 error = kthread_suspend(td, kproc_shutdown_wait * hz);
984 if (error == EWOULDBLOCK)
985 printf("timed out\n");
991 dumpdevname_sysctl_handler(SYSCTL_HANDLER_ARGS)
994 struct dumperinfo *di;
998 error = sysctl_wire_old_buffer(req, 0);
1002 sbuf_new_for_sysctl(&sb, buf, sizeof(buf), req);
1004 mtx_lock(&dumpconf_list_lk);
1005 TAILQ_FOREACH(di, &dumper_configs, di_next) {
1006 if (di != TAILQ_FIRST(&dumper_configs))
1007 sbuf_putc(&sb, ',');
1008 sbuf_cat(&sb, di->di_devname);
1010 mtx_unlock(&dumpconf_list_lk);
1012 error = sbuf_finish(&sb);
1016 SYSCTL_PROC(_kern_shutdown, OID_AUTO, dumpdevname,
1017 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, &dumper_configs, 0,
1018 dumpdevname_sysctl_handler, "A",
1019 "Device(s) for kernel dumps");
1021 static int _dump_append(struct dumperinfo *di, void *virtual,
1022 vm_offset_t physical, size_t length);
1025 static struct kerneldumpcrypto *
1026 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
1027 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1029 struct kerneldumpcrypto *kdc;
1030 struct kerneldumpkey *kdk;
1031 uint32_t dumpkeysize;
1033 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
1034 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
1036 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
1038 kdc->kdc_encryption = encryption;
1039 switch (kdc->kdc_encryption) {
1040 case KERNELDUMP_ENC_AES_256_CBC:
1041 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
1044 case KERNELDUMP_ENC_CHACHA20:
1045 chacha_keysetup(&kdc->kdc_chacha, key, 256);
1051 kdc->kdc_dumpkeysize = dumpkeysize;
1052 kdk = kdc->kdc_dumpkey;
1053 kdk->kdk_encryption = kdc->kdc_encryption;
1054 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
1055 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
1056 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
1060 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
1066 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
1068 uint8_t hash[SHA256_DIGEST_LENGTH];
1070 struct kerneldumpkey *kdk;
1079 * When a user enters ddb it can write a crash dump multiple times.
1080 * Each time it should be encrypted using a different IV.
1083 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1084 SHA256_Final(hash, &ctx);
1085 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1087 switch (kdc->kdc_encryption) {
1088 case KERNELDUMP_ENC_AES_256_CBC:
1089 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1090 kdc->kdc_iv) <= 0) {
1095 case KERNELDUMP_ENC_CHACHA20:
1096 chacha_ivsetup(&kdc->kdc_chacha, kdc->kdc_iv, NULL);
1103 kdk = kdc->kdc_dumpkey;
1104 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
1106 explicit_bzero(hash, sizeof(hash));
1111 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
1116 return (kdc->kdc_dumpkeysize);
1120 static struct kerneldumpcomp *
1121 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
1123 struct kerneldumpcomp *kdcomp;
1126 switch (compression) {
1127 case KERNELDUMP_COMP_GZIP:
1128 format = COMPRESS_GZIP;
1130 case KERNELDUMP_COMP_ZSTD:
1131 format = COMPRESS_ZSTD;
1137 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1138 kdcomp->kdc_format = compression;
1139 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1140 format, di->maxiosize, kerneldump_gzlevel, di);
1141 if (kdcomp->kdc_stream == NULL) {
1142 free(kdcomp, M_DUMPER);
1145 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1150 kerneldumpcomp_destroy(struct dumperinfo *di)
1152 struct kerneldumpcomp *kdcomp;
1154 kdcomp = di->kdcomp;
1157 compressor_fini(kdcomp->kdc_stream);
1158 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1159 free(kdcomp->kdc_buf, M_DUMPER);
1160 free(kdcomp, M_DUMPER);
1164 * Must not be present on global list.
1167 free_single_dumper(struct dumperinfo *di)
1173 if (di->blockbuf != NULL) {
1174 explicit_bzero(di->blockbuf, di->blocksize);
1175 free(di->blockbuf, M_DUMPER);
1178 kerneldumpcomp_destroy(di);
1181 if (di->kdcrypto != NULL) {
1182 explicit_bzero(di->kdcrypto, sizeof(*di->kdcrypto) +
1183 di->kdcrypto->kdc_dumpkeysize);
1184 free(di->kdcrypto, M_EKCD);
1188 explicit_bzero(di, sizeof(*di));
1192 /* Registration of dumpers */
1194 dumper_insert(const struct dumperinfo *di_template, const char *devname,
1195 const struct diocskerneldump_arg *kda)
1197 struct dumperinfo *newdi, *listdi;
1202 index = kda->kda_index;
1203 MPASS(index != KDA_REMOVE && index != KDA_REMOVE_DEV &&
1204 index != KDA_REMOVE_ALL);
1206 error = priv_check(curthread, PRIV_SETDUMPER);
1210 newdi = malloc(sizeof(*newdi) + strlen(devname) + 1, M_DUMPER, M_WAITOK
1212 memcpy(newdi, di_template, sizeof(*newdi));
1213 newdi->blockbuf = NULL;
1214 newdi->kdcrypto = NULL;
1215 newdi->kdcomp = NULL;
1216 strcpy(newdi->di_devname, devname);
1218 if (kda->kda_encryption != KERNELDUMP_ENC_NONE) {
1220 newdi->kdcrypto = kerneldumpcrypto_create(di_template->blocksize,
1221 kda->kda_encryption, kda->kda_key,
1222 kda->kda_encryptedkeysize, kda->kda_encryptedkey);
1223 if (newdi->kdcrypto == NULL) {
1232 if (kda->kda_compression != KERNELDUMP_COMP_NONE) {
1234 * We can't support simultaneous unpadded block cipher
1235 * encryption and compression because there is no guarantee the
1236 * length of the compressed result is exactly a multiple of the
1237 * cipher block size.
1239 if (kda->kda_encryption == KERNELDUMP_ENC_AES_256_CBC) {
1243 newdi->kdcomp = kerneldumpcomp_create(newdi,
1244 kda->kda_compression);
1245 if (newdi->kdcomp == NULL) {
1251 newdi->blockbuf = malloc(newdi->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1253 /* Add the new configuration to the queue */
1254 mtx_lock(&dumpconf_list_lk);
1256 TAILQ_FOREACH(listdi, &dumper_configs, di_next) {
1258 TAILQ_INSERT_BEFORE(listdi, newdi, di_next);
1265 TAILQ_INSERT_TAIL(&dumper_configs, newdi, di_next);
1266 mtx_unlock(&dumpconf_list_lk);
1271 free_single_dumper(newdi);
1277 dumper_ddb_insert(struct dumperinfo *newdi)
1279 TAILQ_INSERT_HEAD(&dumper_configs, newdi, di_next);
1283 dumper_ddb_remove(struct dumperinfo *di)
1285 TAILQ_REMOVE(&dumper_configs, di, di_next);
1290 dumper_config_match(const struct dumperinfo *di, const char *devname,
1291 const struct diocskerneldump_arg *kda)
1293 if (kda->kda_index == KDA_REMOVE_ALL)
1296 if (strcmp(di->di_devname, devname) != 0)
1300 * Allow wildcard removal of configs matching a device on g_dev_orphan.
1302 if (kda->kda_index == KDA_REMOVE_DEV)
1305 if (di->kdcomp != NULL) {
1306 if (di->kdcomp->kdc_format != kda->kda_compression)
1308 } else if (kda->kda_compression != KERNELDUMP_COMP_NONE)
1311 if (di->kdcrypto != NULL) {
1312 if (di->kdcrypto->kdc_encryption != kda->kda_encryption)
1315 * Do we care to verify keys match to delete? It seems weird
1316 * to expect multiple fallback dump configurations on the same
1317 * device that only differ in crypto key.
1321 if (kda->kda_encryption != KERNELDUMP_ENC_NONE)
1328 dumper_remove(const char *devname, const struct diocskerneldump_arg *kda)
1330 struct dumperinfo *di, *sdi;
1334 error = priv_check(curthread, PRIV_SETDUMPER);
1339 * Try to find a matching configuration, and kill it.
1341 * NULL 'kda' indicates remove any configuration matching 'devname',
1342 * which may remove multiple configurations in atypical configurations.
1345 mtx_lock(&dumpconf_list_lk);
1346 TAILQ_FOREACH_SAFE(di, &dumper_configs, di_next, sdi) {
1347 if (dumper_config_match(di, devname, kda)) {
1349 TAILQ_REMOVE(&dumper_configs, di, di_next);
1350 free_single_dumper(di);
1353 mtx_unlock(&dumpconf_list_lk);
1355 /* Only produce ENOENT if a more targeted match didn't match. */
1356 if (!found && kda->kda_index == KDA_REMOVE)
1362 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1365 if (di->mediasize > 0 && length != 0 && (offset < di->mediaoffset ||
1366 offset - di->mediaoffset + length > di->mediasize)) {
1367 if (di->kdcomp != NULL && offset >= di->mediaoffset) {
1369 "Compressed dump failed to fit in device boundaries.\n");
1373 printf("Attempt to write outside dump device boundaries.\n"
1374 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1375 (intmax_t)offset, (intmax_t)di->mediaoffset,
1376 (uintmax_t)length, (intmax_t)di->mediasize);
1379 if (length % di->blocksize != 0) {
1380 printf("Attempt to write partial block of length %ju.\n",
1384 if (offset % di->blocksize != 0) {
1385 printf("Attempt to write at unaligned offset %jd.\n",
1395 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1398 switch (kdc->kdc_encryption) {
1399 case KERNELDUMP_ENC_AES_256_CBC:
1400 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1401 8 * size, buf) <= 0) {
1404 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1405 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1409 case KERNELDUMP_ENC_CHACHA20:
1410 chacha_encrypt_bytes(&kdc->kdc_chacha, buf, buf, size);
1419 /* Encrypt data and call dumper. */
1421 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1422 vm_offset_t physical, off_t offset, size_t length)
1424 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1425 struct kerneldumpcrypto *kdc;
1431 while (length > 0) {
1432 nbytes = MIN(length, sizeof(buf));
1433 bcopy(virtual, buf, nbytes);
1435 if (dump_encrypt(kdc, buf, nbytes) != 0)
1438 error = dump_write(di, buf, physical, offset, nbytes);
1443 virtual = (void *)((uint8_t *)virtual + nbytes);
1452 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1454 struct dumperinfo *di;
1455 size_t resid, rlength;
1460 if (length % di->blocksize != 0) {
1462 * This must be the final write after flushing the compression
1463 * stream. Write as many full blocks as possible and stash the
1464 * residual data in the dumper's block buffer. It will be
1465 * padded and written in dump_finish().
1467 rlength = rounddown(length, di->blocksize);
1469 error = _dump_append(di, base, 0, rlength);
1473 resid = length - rlength;
1474 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1475 di->kdcomp->kdc_resid = resid;
1478 return (_dump_append(di, base, 0, length));
1482 * Write kernel dump headers at the beginning and end of the dump extent.
1483 * Write the kernel dump encryption key after the leading header if we were
1484 * configured to do so.
1487 dump_write_headers(struct dumperinfo *di, struct kerneldumpheader *kdh)
1490 struct kerneldumpcrypto *kdc;
1498 hdrsz = sizeof(*kdh);
1499 if (hdrsz > di->blocksize)
1504 key = kdc->kdc_dumpkey;
1505 keysize = kerneldumpcrypto_dumpkeysize(kdc);
1512 * If the dump device has special handling for headers, let it take care
1513 * of writing them out.
1515 if (di->dumper_hdr != NULL)
1516 return (di->dumper_hdr(di, kdh, key, keysize));
1518 if (hdrsz == di->blocksize)
1522 memset(buf, 0, di->blocksize);
1523 memcpy(buf, kdh, hdrsz);
1526 extent = dtoh64(kdh->dumpextent);
1529 error = dump_write(di, kdc->kdc_dumpkey, 0,
1530 di->mediaoffset + di->mediasize - di->blocksize - extent -
1537 error = dump_write(di, buf, 0,
1538 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1539 keysize, di->blocksize);
1541 error = dump_write(di, buf, 0, di->mediaoffset + di->mediasize -
1542 di->blocksize, di->blocksize);
1547 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1548 * protect us from metadata and metadata from us.
1550 #define SIZEOF_METADATA (64 * 1024)
1553 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1554 * if requested, and make sure that we have enough space on the dump device.
1556 * We set things up so that the dump ends before the last sector of the dump
1557 * device, at which the trailing header is written.
1559 * +-----------+------+-----+----------------------------+------+
1560 * | | lhdr | key | ... kernel dump ... | thdr |
1561 * +-----------+------+-----+----------------------------+------+
1562 * 1 blk opt <------- dump extent --------> 1 blk
1564 * Dumps written using dump_append() start at the beginning of the extent.
1565 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1566 * will not. The true length of the dump is recorded in the leading and trailing
1567 * headers once the dump has been completed.
1569 * The dump device may provide a callback, in which case it will initialize
1570 * dumpoff and take care of laying out the headers.
1573 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1575 uint64_t dumpextent, span;
1580 error = kerneldumpcrypto_init(di->kdcrypto);
1583 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1589 if (di->dumper_start != NULL) {
1590 error = di->dumper_start(di);
1592 dumpextent = dtoh64(kdh->dumpextent);
1593 span = SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1595 if (di->mediasize < span) {
1596 if (di->kdcomp == NULL)
1600 * We don't yet know how much space the compressed dump
1601 * will occupy, so try to use the whole swap partition
1602 * (minus the first 64KB) in the hope that the
1603 * compressed dump will fit. If that doesn't turn out to
1604 * be enough, the bounds checking in dump_write()
1605 * will catch us and cause the dump to fail.
1607 dumpextent = di->mediasize - span + dumpextent;
1608 kdh->dumpextent = htod64(dumpextent);
1612 * The offset at which to begin writing the dump.
1614 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1617 di->origdumpoff = di->dumpoff;
1622 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1628 if (di->kdcrypto != NULL)
1629 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1633 error = dump_write(di, virtual, physical, di->dumpoff, length);
1635 di->dumpoff += length;
1640 * Write to the dump device starting at dumpoff. When compression is enabled,
1641 * writes to the device will be performed using a callback that gets invoked
1642 * when the compression stream's output buffer is full.
1645 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1650 if (di->kdcomp != NULL) {
1651 /* Bounce through a buffer to avoid CRC errors. */
1652 if (length > di->maxiosize)
1654 buf = di->kdcomp->kdc_buf;
1655 memmove(buf, virtual, length);
1656 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1658 return (_dump_append(di, virtual, physical, length));
1662 * Write to the dump device at the specified offset.
1665 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1666 off_t offset, size_t length)
1670 error = dump_check_bounds(di, offset, length);
1673 return (di->dumper(di->priv, virtual, physical, offset, length));
1677 * Perform kernel dump finalization: flush the compression stream, if necessary,
1678 * write the leading and trailing kernel dump headers now that we know the true
1679 * length of the dump, and optionally write the encryption key following the
1683 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1687 if (di->kdcomp != NULL) {
1688 error = compressor_flush(di->kdcomp->kdc_stream);
1689 if (error == EAGAIN) {
1690 /* We have residual data in di->blockbuf. */
1691 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1693 di->dumpoff += di->kdcomp->kdc_resid;
1694 di->kdcomp->kdc_resid = 0;
1700 * We now know the size of the compressed dump, so update the
1701 * header accordingly and recompute parity.
1703 kdh->dumplength = htod64(di->dumpoff - di->origdumpoff);
1705 kdh->parity = kerneldump_parity(kdh);
1707 compressor_reset(di->kdcomp->kdc_stream);
1710 error = dump_write_headers(di, kdh);
1714 (void)dump_write(di, NULL, 0, 0, 0);
1719 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1720 const char *magic, uint32_t archver, uint64_t dumplen)
1724 bzero(kdh, sizeof(*kdh));
1725 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1726 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1727 kdh->version = htod32(KERNELDUMPVERSION);
1728 kdh->architectureversion = htod32(archver);
1729 kdh->dumplength = htod64(dumplen);
1730 kdh->dumpextent = kdh->dumplength;
1731 kdh->dumptime = htod64(time_second);
1733 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1735 kdh->dumpkeysize = 0;
1737 kdh->blocksize = htod32(di->blocksize);
1738 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1739 dstsize = sizeof(kdh->versionstring);
1740 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1741 kdh->versionstring[dstsize - 2] = '\n';
1742 if (panicstr != NULL)
1743 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1744 if (di->kdcomp != NULL)
1745 kdh->compression = di->kdcomp->kdc_format;
1746 kdh->parity = kerneldump_parity(kdh);
1750 DB_SHOW_COMMAND(panic, db_show_panic)
1753 if (panicstr == NULL)
1754 db_printf("panicstr not set\n");
1756 db_printf("panic: %s\n", panicstr);