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>
66 #include <sys/mount.h>
69 #include <sys/reboot.h>
70 #include <sys/resourcevar.h>
71 #include <sys/rwlock.h>
72 #include <sys/sched.h>
74 #include <sys/sysctl.h>
75 #include <sys/sysproto.h>
76 #include <sys/taskqueue.h>
77 #include <sys/vnode.h>
78 #include <sys/watchdog.h>
80 #include <crypto/rijndael/rijndael-api-fst.h>
81 #include <crypto/sha2/sha256.h>
85 #include <machine/cpu.h>
86 #include <machine/dump.h>
87 #include <machine/pcb.h>
88 #include <machine/smp.h>
90 #include <security/mac/mac_framework.h>
93 #include <vm/vm_object.h>
94 #include <vm/vm_page.h>
95 #include <vm/vm_pager.h>
96 #include <vm/swap_pager.h>
98 #include <sys/signalvar.h>
100 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
102 #ifndef PANIC_REBOOT_WAIT_TIME
103 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
105 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
106 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
107 &panic_reboot_wait_time, 0,
108 "Seconds to wait before rebooting after a panic");
111 * Note that stdarg.h and the ANSI style va_start macro is used for both
112 * ANSI and traditional C compilers.
114 #include <machine/stdarg.h>
117 #ifdef KDB_UNATTENDED
118 int debugger_on_panic = 0;
120 int debugger_on_panic = 1;
122 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
123 CTLFLAG_RWTUN | CTLFLAG_SECURE,
124 &debugger_on_panic, 0, "Run debugger on kernel panic");
127 static int trace_on_panic = 1;
128 static bool trace_all_panics = true;
130 static int trace_on_panic = 0;
131 static bool trace_all_panics = false;
133 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
134 CTLFLAG_RWTUN | CTLFLAG_SECURE,
135 &trace_on_panic, 0, "Print stack trace on kernel panic");
136 SYSCTL_BOOL(_debug, OID_AUTO, trace_all_panics, CTLFLAG_RWTUN,
137 &trace_all_panics, 0, "Print stack traces on secondary kernel panics");
140 static int sync_on_panic = 0;
141 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
142 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
144 static bool poweroff_on_panic = 0;
145 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
146 &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
148 static bool powercycle_on_panic = 0;
149 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
150 &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
152 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
153 "Shutdown environment");
156 static int show_busybufs;
158 static int show_busybufs = 1;
160 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
161 &show_busybufs, 0, "");
163 int suspend_blocked = 0;
164 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
165 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
168 FEATURE(ekcd, "Encrypted kernel crash dumps support");
170 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
172 struct kerneldumpcrypto {
173 uint8_t kdc_encryption;
174 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
176 cipherInstance kdc_ci;
177 uint32_t kdc_dumpkeysize;
178 struct kerneldumpkey kdc_dumpkey[];
182 struct kerneldumpcomp {
184 struct compressor *kdc_stream;
189 static struct kerneldumpcomp *kerneldumpcomp_create(struct dumperinfo *di,
190 uint8_t compression);
191 static void kerneldumpcomp_destroy(struct dumperinfo *di);
192 static int kerneldumpcomp_write_cb(void *base, size_t len, off_t off, void *arg);
194 static int kerneldump_gzlevel = 6;
195 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
196 &kerneldump_gzlevel, 0,
197 "Kernel crash dump compression level");
200 * Variable panicstr contains argument to first call to panic; used as flag
201 * to indicate that the kernel has already called panic.
203 const char *panicstr;
205 int dumping; /* system is dumping */
206 int rebooting; /* system is rebooting */
207 static struct dumperinfo dumper; /* our selected dumper */
209 /* Context information for dump-debuggers. */
210 static struct pcb dumppcb; /* Registers. */
211 lwpid_t dumptid; /* Thread ID. */
213 static struct cdevsw reroot_cdevsw = {
214 .d_version = D_VERSION,
218 static void poweroff_wait(void *, int);
219 static void shutdown_halt(void *junk, int howto);
220 static void shutdown_panic(void *junk, int howto);
221 static void shutdown_reset(void *junk, int howto);
222 static int kern_reroot(void);
224 /* register various local shutdown events */
226 shutdown_conf(void *unused)
229 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
231 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
232 SHUTDOWN_PRI_LAST + 100);
233 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
234 SHUTDOWN_PRI_LAST + 100);
235 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
236 SHUTDOWN_PRI_LAST + 200);
239 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
242 * The only reason this exists is to create the /dev/reroot/ directory,
243 * used by reroot code in init(8) as a mountpoint for tmpfs.
246 reroot_conf(void *unused)
251 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
252 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
254 printf("%s: failed to create device node, error %d",
259 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
262 * The system call that results in a reboot.
266 sys_reboot(struct thread *td, struct reboot_args *uap)
272 error = mac_system_check_reboot(td->td_ucred, uap->opt);
275 error = priv_check(td, PRIV_REBOOT);
277 if (uap->opt & RB_REROOT)
278 error = kern_reroot();
280 kern_reboot(uap->opt);
286 shutdown_nice_task_fn(void *arg, int pending __unused)
290 howto = (uintptr_t)arg;
291 /* Send a signal to init(8) and have it shutdown the world. */
293 if (howto & RB_POWEROFF)
294 kern_psignal(initproc, SIGUSR2);
295 else if (howto & RB_POWERCYCLE)
296 kern_psignal(initproc, SIGWINCH);
297 else if (howto & RB_HALT)
298 kern_psignal(initproc, SIGUSR1);
300 kern_psignal(initproc, SIGINT);
301 PROC_UNLOCK(initproc);
304 static struct task shutdown_nice_task = TASK_INITIALIZER(0,
305 &shutdown_nice_task_fn, NULL);
308 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
311 shutdown_nice(int howto)
314 if (initproc != NULL && !SCHEDULER_STOPPED()) {
315 shutdown_nice_task.ta_context = (void *)(uintptr_t)howto;
316 taskqueue_enqueue(taskqueue_fast, &shutdown_nice_task);
319 * No init(8) running, or scheduler would not allow it
320 * to run, so simply reboot.
322 kern_reboot(howto | RB_NOSYNC);
335 if (ts.tv_sec >= 86400) {
336 printf("%ldd", (long)ts.tv_sec / 86400);
340 if (f || ts.tv_sec >= 3600) {
341 printf("%ldh", (long)ts.tv_sec / 3600);
345 if (f || ts.tv_sec >= 60) {
346 printf("%ldm", (long)ts.tv_sec / 60);
350 printf("%lds\n", (long)ts.tv_sec);
354 doadump(boolean_t textdump)
362 if (dumper.dumper == NULL)
366 dumptid = curthread->td_tid;
371 if (textdump && textdump_pending) {
373 textdump_dumpsys(&dumper);
377 error = dumpsys(&dumper);
384 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
387 kern_reboot(int howto)
392 * Normal paths here don't hold Giant, but we can wind up here
393 * unexpectedly with it held. Drop it now so we don't have to
394 * drop and pick it up elsewhere. The paths it is locking will
395 * never be returned to, and it is preferable to preclude
396 * deadlock than to lock against code that won't ever
399 while (mtx_owned(&Giant))
404 * Bind us to the first CPU so that all shutdown code runs there. Some
405 * systems don't shutdown properly (i.e., ACPI power off) if we
406 * run on another processor.
408 if (!SCHEDULER_STOPPED()) {
409 thread_lock(curthread);
410 sched_bind(curthread, CPU_FIRST());
411 thread_unlock(curthread);
412 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
413 ("boot: not running on cpu 0"));
416 /* We're in the process of rebooting. */
419 /* We are out of the debugger now. */
423 * Do any callouts that should be done BEFORE syncing the filesystems.
425 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
428 * Now sync filesystems
430 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
432 bufshutdown(show_busybufs);
440 * Ok, now do things that assume all filesystem activity has
443 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
445 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
448 /* Now that we're going to really halt the system... */
449 EVENTHANDLER_INVOKE(shutdown_final, howto);
451 for(;;) ; /* safety against shutdown_reset not working */
456 * The system call that results in changing the rootfs.
461 struct vnode *oldrootvnode, *vp;
462 struct mount *mp, *devmp;
465 if (curproc != initproc)
469 * Mark the filesystem containing currently-running executable
470 * (the temporary copy of init(8)) busy.
472 vp = curproc->p_textvp;
473 error = vn_lock(vp, LK_SHARED);
477 error = vfs_busy(mp, MBF_NOWAIT);
481 error = vfs_busy(mp, 0);
482 vn_lock(vp, LK_SHARED | LK_RETRY);
488 if (vp->v_iflag & VI_DOOMED) {
497 * Remove the filesystem containing currently-running executable
498 * from the mount list, to prevent it from being unmounted
499 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
501 * Also preserve /dev - forcibly unmounting it could cause driver
509 mtx_lock(&mountlist_mtx);
510 TAILQ_REMOVE(&mountlist, mp, mnt_list);
511 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
512 mtx_unlock(&mountlist_mtx);
514 oldrootvnode = rootvnode;
517 * Unmount everything except for the two filesystems preserved above.
522 * Add /dev back; vfs_mountroot() will move it into its new place.
524 mtx_lock(&mountlist_mtx);
525 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
526 mtx_unlock(&mountlist_mtx);
531 * Mount the new rootfs.
536 * Update all references to the old rootvnode.
538 mountcheckdirs(oldrootvnode, rootvnode);
541 * Add the temporary filesystem back and unbusy it.
543 mtx_lock(&mountlist_mtx);
544 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
545 mtx_unlock(&mountlist_mtx);
552 * If the shutdown was a clean halt, behave accordingly.
555 shutdown_halt(void *junk, int howto)
558 if (howto & RB_HALT) {
560 printf("The operating system has halted.\n");
561 printf("Please press any key to reboot.\n\n");
563 case -1: /* No console, just die */
573 * Check to see if the system paniced, pause and then reboot
574 * according to the specified delay.
577 shutdown_panic(void *junk, int howto)
581 if (howto & RB_DUMP) {
582 if (panic_reboot_wait_time != 0) {
583 if (panic_reboot_wait_time != -1) {
584 printf("Automatic reboot in %d seconds - "
585 "press a key on the console to abort\n",
586 panic_reboot_wait_time);
587 for (loop = panic_reboot_wait_time * 10;
589 DELAY(1000 * 100); /* 1/10th second */
590 /* Did user type a key? */
591 if (cncheckc() != -1)
597 } else { /* zero time specified - reboot NOW */
600 printf("--> Press a key on the console to reboot,\n");
601 printf("--> or switch off the system now.\n");
607 * Everything done, now reset
610 shutdown_reset(void *junk, int howto)
613 printf("Rebooting...\n");
614 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
617 * Acquiring smp_ipi_mtx here has a double effect:
618 * - it disables interrupts avoiding CPU0 preemption
619 * by fast handlers (thus deadlocking against other CPUs)
620 * - it avoids deadlocks against smp_rendezvous() or, more
621 * generally, threads busy-waiting, with this spinlock held,
622 * and waiting for responses by threads on other CPUs
623 * (ie. smp_tlb_shootdown()).
625 * For the !SMP case it just needs to handle the former problem.
628 mtx_lock_spin(&smp_ipi_mtx);
633 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
635 /* NOTREACHED */ /* assuming reset worked */
638 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
639 static int kassert_warn_only = 0;
641 static int kassert_do_kdb = 0;
644 static int kassert_do_ktr = 0;
646 static int kassert_do_log = 1;
647 static int kassert_log_pps_limit = 4;
648 static int kassert_log_mute_at = 0;
649 static int kassert_log_panic_at = 0;
650 static int kassert_suppress_in_panic = 0;
651 static int kassert_warnings = 0;
653 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
655 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
656 &kassert_warn_only, 0,
657 "KASSERT triggers a panic (1) or just a warning (0)");
660 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
661 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
665 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
667 "KASSERT does a KTR, set this to the KTRMASK you want");
670 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
672 "If warn_only is enabled, log (1) or do not log (0) assertion violations");
674 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
675 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
677 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
678 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
680 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
681 &kassert_log_pps_limit, 0, "limit number of log messages per second");
683 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
684 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
686 SYSCTL_INT(_debug_kassert, OID_AUTO, suppress_in_panic, CTLFLAG_RWTUN,
687 &kassert_suppress_in_panic, 0,
688 "KASSERTs will be suppressed while handling a panic");
690 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
692 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
693 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
694 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
697 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
701 error = sysctl_wire_old_buffer(req, sizeof(int));
704 error = sysctl_handle_int(oidp, &i, 0, req);
706 if (error != 0 || req->newptr == NULL)
708 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
713 * Called by KASSERT, this decides if we will panic
714 * or if we will log via printf and/or ktr.
717 kassert_panic(const char *fmt, ...)
719 static char buf[256];
723 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
727 * If we are suppressing secondary panics, log the warning but do not
728 * re-enter panic/kdb.
730 if (panicstr != NULL && kassert_suppress_in_panic) {
731 if (kassert_do_log) {
732 printf("KASSERT failed: %s\n", buf);
734 if (trace_all_panics && trace_on_panic)
742 * panic if we're not just warning, or if we've exceeded
743 * kassert_log_panic_at warnings.
745 if (!kassert_warn_only ||
746 (kassert_log_panic_at > 0 &&
747 kassert_warnings >= kassert_log_panic_at)) {
757 * log if we've not yet met the mute limit.
759 if (kassert_do_log &&
760 (kassert_log_mute_at == 0 ||
761 kassert_warnings < kassert_log_mute_at)) {
762 static struct timeval lasterr;
765 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
766 printf("KASSERT failed: %s\n", buf);
771 if (kassert_do_kdb) {
772 kdb_enter(KDB_WHY_KASSERT, buf);
775 atomic_add_int(&kassert_warnings, 1);
780 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
781 * and then reboots. If we are called twice, then we avoid trying to sync
782 * the disks as this often leads to recursive panics.
785 panic(const char *fmt, ...)
794 vpanic(const char *fmt, va_list ap)
799 struct thread *td = curthread;
800 int bootopt, newpanic;
801 static char buf[256];
807 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
808 * concurrently entering panic. Only the winner will proceed
811 if (panicstr == NULL && !kdb_active) {
812 other_cpus = all_cpus;
813 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
814 stop_cpus_hard(other_cpus);
819 * Ensure that the scheduler is stopped while panicking, even if panic
820 * has been entered from kdb.
822 td->td_stopsched = 1;
824 bootopt = RB_AUTOBOOT;
827 bootopt |= RB_NOSYNC;
835 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
838 printf("panic: %s\n", buf);
845 printf("cpuid = %d\n", PCPU_GET(cpuid));
847 printf("time = %jd\n", (intmax_t )time_second);
849 if ((newpanic || trace_all_panics) && trace_on_panic)
851 if (debugger_on_panic)
852 kdb_enter(KDB_WHY_PANIC, "panic");
854 /*thread_lock(td); */
855 td->td_flags |= TDF_INPANIC;
856 /* thread_unlock(td); */
858 bootopt |= RB_NOSYNC;
859 if (poweroff_on_panic)
860 bootopt |= RB_POWEROFF;
861 if (powercycle_on_panic)
862 bootopt |= RB_POWERCYCLE;
863 kern_reboot(bootopt);
867 * Support for poweroff delay.
869 * Please note that setting this delay too short might power off your machine
870 * before the write cache on your hard disk has been flushed, leading to
871 * soft-updates inconsistencies.
873 #ifndef POWEROFF_DELAY
874 # define POWEROFF_DELAY 5000
876 static int poweroff_delay = POWEROFF_DELAY;
878 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
879 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
882 poweroff_wait(void *junk, int howto)
885 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
887 DELAY(poweroff_delay * 1000);
891 * Some system processes (e.g. syncer) need to be stopped at appropriate
892 * points in their main loops prior to a system shutdown, so that they
893 * won't interfere with the shutdown process (e.g. by holding a disk buf
894 * to cause sync to fail). For each of these system processes, register
895 * shutdown_kproc() as a handler for one of shutdown events.
897 static int kproc_shutdown_wait = 60;
898 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
899 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
902 kproc_shutdown(void *arg, int howto)
910 p = (struct proc *)arg;
911 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
912 kproc_shutdown_wait, p->p_comm);
913 error = kproc_suspend(p, kproc_shutdown_wait * hz);
915 if (error == EWOULDBLOCK)
916 printf("timed out\n");
922 kthread_shutdown(void *arg, int howto)
930 td = (struct thread *)arg;
931 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
932 kproc_shutdown_wait, td->td_name);
933 error = kthread_suspend(td, kproc_shutdown_wait * hz);
935 if (error == EWOULDBLOCK)
936 printf("timed out\n");
941 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
942 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
943 dumpdevname, 0, "Device for kernel dumps");
945 static int _dump_append(struct dumperinfo *di, void *virtual,
946 vm_offset_t physical, size_t length);
949 static struct kerneldumpcrypto *
950 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
951 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
953 struct kerneldumpcrypto *kdc;
954 struct kerneldumpkey *kdk;
955 uint32_t dumpkeysize;
957 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
958 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
960 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
962 kdc->kdc_encryption = encryption;
963 switch (kdc->kdc_encryption) {
964 case KERNELDUMP_ENC_AES_256_CBC:
965 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
972 kdc->kdc_dumpkeysize = dumpkeysize;
973 kdk = kdc->kdc_dumpkey;
974 kdk->kdk_encryption = kdc->kdc_encryption;
975 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
976 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
977 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
981 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
987 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
989 uint8_t hash[SHA256_DIGEST_LENGTH];
991 struct kerneldumpkey *kdk;
1000 * When a user enters ddb it can write a crash dump multiple times.
1001 * Each time it should be encrypted using a different IV.
1004 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1005 SHA256_Final(hash, &ctx);
1006 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1008 switch (kdc->kdc_encryption) {
1009 case KERNELDUMP_ENC_AES_256_CBC:
1010 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1011 kdc->kdc_iv) <= 0) {
1021 kdk = kdc->kdc_dumpkey;
1022 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
1024 explicit_bzero(hash, sizeof(hash));
1029 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
1034 return (kdc->kdc_dumpkeysize);
1038 static struct kerneldumpcomp *
1039 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
1041 struct kerneldumpcomp *kdcomp;
1044 switch (compression) {
1045 case KERNELDUMP_COMP_GZIP:
1046 format = COMPRESS_GZIP;
1048 case KERNELDUMP_COMP_ZSTD:
1049 format = COMPRESS_ZSTD;
1055 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1056 kdcomp->kdc_format = compression;
1057 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1058 format, di->maxiosize, kerneldump_gzlevel, di);
1059 if (kdcomp->kdc_stream == NULL) {
1060 free(kdcomp, M_DUMPER);
1063 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1068 kerneldumpcomp_destroy(struct dumperinfo *di)
1070 struct kerneldumpcomp *kdcomp;
1072 kdcomp = di->kdcomp;
1075 compressor_fini(kdcomp->kdc_stream);
1076 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1077 free(kdcomp->kdc_buf, M_DUMPER);
1078 free(kdcomp, M_DUMPER);
1081 /* Registration of dumpers */
1083 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1084 uint8_t compression, uint8_t encryption, const uint8_t *key,
1085 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1090 error = priv_check(td, PRIV_SETDUMPER);
1094 if (dumper.dumper != NULL)
1097 dumper.blockbuf = NULL;
1098 dumper.kdcrypto = NULL;
1099 dumper.kdcomp = NULL;
1101 if (encryption != KERNELDUMP_ENC_NONE) {
1103 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1104 encryption, key, encryptedkeysize, encryptedkey);
1105 if (dumper.kdcrypto == NULL) {
1115 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1116 if (wantcopy >= sizeof(dumpdevname)) {
1117 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1118 devname, dumpdevname);
1121 if (compression != KERNELDUMP_COMP_NONE) {
1123 * We currently can't support simultaneous encryption and
1126 if (encryption != KERNELDUMP_ENC_NONE) {
1130 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1131 if (dumper.kdcomp == NULL) {
1137 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1141 (void)clear_dumper(td);
1146 clear_dumper(struct thread *td)
1150 error = priv_check(td, PRIV_SETDUMPER);
1155 netdump_mbuf_drain();
1159 if (dumper.kdcrypto != NULL) {
1160 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1161 dumper.kdcrypto->kdc_dumpkeysize);
1162 free(dumper.kdcrypto, M_EKCD);
1166 kerneldumpcomp_destroy(&dumper);
1168 if (dumper.blockbuf != NULL) {
1169 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1170 free(dumper.blockbuf, M_DUMPER);
1172 explicit_bzero(&dumper, sizeof(dumper));
1173 dumpdevname[0] = '\0';
1178 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1181 if (di->mediasize > 0 && length != 0 && (offset < di->mediaoffset ||
1182 offset - di->mediaoffset + length > di->mediasize)) {
1183 if (di->kdcomp != NULL && offset >= di->mediaoffset) {
1185 "Compressed dump failed to fit in device boundaries.\n");
1189 printf("Attempt to write outside dump device boundaries.\n"
1190 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1191 (intmax_t)offset, (intmax_t)di->mediaoffset,
1192 (uintmax_t)length, (intmax_t)di->mediasize);
1195 if (length % di->blocksize != 0) {
1196 printf("Attempt to write partial block of length %ju.\n",
1200 if (offset % di->blocksize != 0) {
1201 printf("Attempt to write at unaligned offset %jd.\n",
1211 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1214 switch (kdc->kdc_encryption) {
1215 case KERNELDUMP_ENC_AES_256_CBC:
1216 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1217 8 * size, buf) <= 0) {
1220 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1221 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1232 /* Encrypt data and call dumper. */
1234 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1235 vm_offset_t physical, off_t offset, size_t length)
1237 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1238 struct kerneldumpcrypto *kdc;
1244 while (length > 0) {
1245 nbytes = MIN(length, sizeof(buf));
1246 bcopy(virtual, buf, nbytes);
1248 if (dump_encrypt(kdc, buf, nbytes) != 0)
1251 error = dump_write(di, buf, physical, offset, nbytes);
1256 virtual = (void *)((uint8_t *)virtual + nbytes);
1265 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1267 struct dumperinfo *di;
1268 size_t resid, rlength;
1273 if (length % di->blocksize != 0) {
1275 * This must be the final write after flushing the compression
1276 * stream. Write as many full blocks as possible and stash the
1277 * residual data in the dumper's block buffer. It will be
1278 * padded and written in dump_finish().
1280 rlength = rounddown(length, di->blocksize);
1282 error = _dump_append(di, base, 0, rlength);
1286 resid = length - rlength;
1287 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1288 di->kdcomp->kdc_resid = resid;
1291 return (_dump_append(di, base, 0, length));
1295 * Write kernel dump headers at the beginning and end of the dump extent.
1296 * Write the kernel dump encryption key after the leading header if we were
1297 * configured to do so.
1300 dump_write_headers(struct dumperinfo *di, struct kerneldumpheader *kdh)
1303 struct kerneldumpcrypto *kdc;
1311 hdrsz = sizeof(*kdh);
1312 if (hdrsz > di->blocksize)
1317 key = kdc->kdc_dumpkey;
1318 keysize = kerneldumpcrypto_dumpkeysize(kdc);
1325 * If the dump device has special handling for headers, let it take care
1326 * of writing them out.
1328 if (di->dumper_hdr != NULL)
1329 return (di->dumper_hdr(di, kdh, key, keysize));
1331 if (hdrsz == di->blocksize)
1335 memset(buf, 0, di->blocksize);
1336 memcpy(buf, kdh, hdrsz);
1339 extent = dtoh64(kdh->dumpextent);
1342 error = dump_write(di, kdc->kdc_dumpkey, 0,
1343 di->mediaoffset + di->mediasize - di->blocksize - extent -
1350 error = dump_write(di, buf, 0,
1351 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1352 keysize, di->blocksize);
1354 error = dump_write(di, buf, 0, di->mediaoffset + di->mediasize -
1355 di->blocksize, di->blocksize);
1360 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1361 * protect us from metadata and metadata from us.
1363 #define SIZEOF_METADATA (64 * 1024)
1366 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1367 * if requested, and make sure that we have enough space on the dump device.
1369 * We set things up so that the dump ends before the last sector of the dump
1370 * device, at which the trailing header is written.
1372 * +-----------+------+-----+----------------------------+------+
1373 * | | lhdr | key | ... kernel dump ... | thdr |
1374 * +-----------+------+-----+----------------------------+------+
1375 * 1 blk opt <------- dump extent --------> 1 blk
1377 * Dumps written using dump_append() start at the beginning of the extent.
1378 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1379 * will not. The true length of the dump is recorded in the leading and trailing
1380 * headers once the dump has been completed.
1382 * The dump device may provide a callback, in which case it will initialize
1383 * dumpoff and take care of laying out the headers.
1386 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1388 uint64_t dumpextent, span;
1393 error = kerneldumpcrypto_init(di->kdcrypto);
1396 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1402 if (di->dumper_start != NULL) {
1403 error = di->dumper_start(di);
1405 dumpextent = dtoh64(kdh->dumpextent);
1406 span = SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1408 if (di->mediasize < span) {
1409 if (di->kdcomp == NULL)
1413 * We don't yet know how much space the compressed dump
1414 * will occupy, so try to use the whole swap partition
1415 * (minus the first 64KB) in the hope that the
1416 * compressed dump will fit. If that doesn't turn out to
1417 * be enough, the bounds checking in dump_write()
1418 * will catch us and cause the dump to fail.
1420 dumpextent = di->mediasize - span + dumpextent;
1421 kdh->dumpextent = htod64(dumpextent);
1425 * The offset at which to begin writing the dump.
1427 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1430 di->origdumpoff = di->dumpoff;
1435 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1441 if (di->kdcrypto != NULL)
1442 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1446 error = dump_write(di, virtual, physical, di->dumpoff, length);
1448 di->dumpoff += length;
1453 * Write to the dump device starting at dumpoff. When compression is enabled,
1454 * writes to the device will be performed using a callback that gets invoked
1455 * when the compression stream's output buffer is full.
1458 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1463 if (di->kdcomp != NULL) {
1464 /* Bounce through a buffer to avoid CRC errors. */
1465 if (length > di->maxiosize)
1467 buf = di->kdcomp->kdc_buf;
1468 memmove(buf, virtual, length);
1469 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1471 return (_dump_append(di, virtual, physical, length));
1475 * Write to the dump device at the specified offset.
1478 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1479 off_t offset, size_t length)
1483 error = dump_check_bounds(di, offset, length);
1486 return (di->dumper(di->priv, virtual, physical, offset, length));
1490 * Perform kernel dump finalization: flush the compression stream, if necessary,
1491 * write the leading and trailing kernel dump headers now that we know the true
1492 * length of the dump, and optionally write the encryption key following the
1496 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1500 if (di->kdcomp != NULL) {
1501 error = compressor_flush(di->kdcomp->kdc_stream);
1502 if (error == EAGAIN) {
1503 /* We have residual data in di->blockbuf. */
1504 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1506 di->dumpoff += di->kdcomp->kdc_resid;
1507 di->kdcomp->kdc_resid = 0;
1513 * We now know the size of the compressed dump, so update the
1514 * header accordingly and recompute parity.
1516 kdh->dumplength = htod64(di->dumpoff - di->origdumpoff);
1518 kdh->parity = kerneldump_parity(kdh);
1520 compressor_reset(di->kdcomp->kdc_stream);
1523 error = dump_write_headers(di, kdh);
1527 (void)dump_write(di, NULL, 0, 0, 0);
1532 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1533 char *magic, uint32_t archver, uint64_t dumplen)
1537 bzero(kdh, sizeof(*kdh));
1538 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1539 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1540 kdh->version = htod32(KERNELDUMPVERSION);
1541 kdh->architectureversion = htod32(archver);
1542 kdh->dumplength = htod64(dumplen);
1543 kdh->dumpextent = kdh->dumplength;
1544 kdh->dumptime = htod64(time_second);
1546 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1548 kdh->dumpkeysize = 0;
1550 kdh->blocksize = htod32(di->blocksize);
1551 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1552 dstsize = sizeof(kdh->versionstring);
1553 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1554 kdh->versionstring[dstsize - 2] = '\n';
1555 if (panicstr != NULL)
1556 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1557 if (di->kdcomp != NULL)
1558 kdh->compression = di->kdcomp->kdc_format;
1559 kdh->parity = kerneldump_parity(kdh);
1563 DB_SHOW_COMMAND(panic, db_show_panic)
1566 if (panicstr == NULL)
1567 db_printf("panicstr not set\n");
1569 db_printf("panic: %s\n", panicstr);