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 #ifdef KASSERT_PANIC_OPTIONAL
656 #define KASSERT_RWTUN CTLFLAG_RWTUN
658 #define KASSERT_RWTUN CTLFLAG_RDTUN
661 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, KASSERT_RWTUN,
662 &kassert_warn_only, 0,
663 "KASSERT triggers a panic (0) or just a warning (1)");
666 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, KASSERT_RWTUN,
667 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
671 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, KASSERT_RWTUN,
673 "KASSERT does a KTR, set this to the KTRMASK you want");
676 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, KASSERT_RWTUN,
678 "If warn_only is enabled, log (1) or do not log (0) assertion violations");
680 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, KASSERT_RWTUN,
681 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
683 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, KASSERT_RWTUN,
684 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
686 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, KASSERT_RWTUN,
687 &kassert_log_pps_limit, 0, "limit number of log messages per second");
689 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, KASSERT_RWTUN,
690 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
692 SYSCTL_INT(_debug_kassert, OID_AUTO, suppress_in_panic, KASSERT_RWTUN,
693 &kassert_suppress_in_panic, 0,
694 "KASSERTs will be suppressed while handling a panic");
697 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
699 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
700 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
701 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
704 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
708 error = sysctl_wire_old_buffer(req, sizeof(int));
711 error = sysctl_handle_int(oidp, &i, 0, req);
713 if (error != 0 || req->newptr == NULL)
715 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
719 #ifdef KASSERT_PANIC_OPTIONAL
721 * Called by KASSERT, this decides if we will panic
722 * or if we will log via printf and/or ktr.
725 kassert_panic(const char *fmt, ...)
727 static char buf[256];
731 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
735 * If we are suppressing secondary panics, log the warning but do not
736 * re-enter panic/kdb.
738 if (panicstr != NULL && kassert_suppress_in_panic) {
739 if (kassert_do_log) {
740 printf("KASSERT failed: %s\n", buf);
742 if (trace_all_panics && trace_on_panic)
750 * panic if we're not just warning, or if we've exceeded
751 * kassert_log_panic_at warnings.
753 if (!kassert_warn_only ||
754 (kassert_log_panic_at > 0 &&
755 kassert_warnings >= kassert_log_panic_at)) {
765 * log if we've not yet met the mute limit.
767 if (kassert_do_log &&
768 (kassert_log_mute_at == 0 ||
769 kassert_warnings < kassert_log_mute_at)) {
770 static struct timeval lasterr;
773 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
774 printf("KASSERT failed: %s\n", buf);
779 if (kassert_do_kdb) {
780 kdb_enter(KDB_WHY_KASSERT, buf);
783 atomic_add_int(&kassert_warnings, 1);
785 #endif /* KASSERT_PANIC_OPTIONAL */
789 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
790 * and then reboots. If we are called twice, then we avoid trying to sync
791 * the disks as this often leads to recursive panics.
794 panic(const char *fmt, ...)
803 vpanic(const char *fmt, va_list ap)
808 struct thread *td = curthread;
809 int bootopt, newpanic;
810 static char buf[256];
816 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
817 * concurrently entering panic. Only the winner will proceed
820 if (panicstr == NULL && !kdb_active) {
821 other_cpus = all_cpus;
822 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
823 stop_cpus_hard(other_cpus);
828 * Ensure that the scheduler is stopped while panicking, even if panic
829 * has been entered from kdb.
831 td->td_stopsched = 1;
833 bootopt = RB_AUTOBOOT;
836 bootopt |= RB_NOSYNC;
844 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
847 printf("panic: %s\n", buf);
854 printf("cpuid = %d\n", PCPU_GET(cpuid));
856 printf("time = %jd\n", (intmax_t )time_second);
858 if ((newpanic || trace_all_panics) && trace_on_panic)
860 if (debugger_on_panic)
861 kdb_enter(KDB_WHY_PANIC, "panic");
863 /*thread_lock(td); */
864 td->td_flags |= TDF_INPANIC;
865 /* thread_unlock(td); */
867 bootopt |= RB_NOSYNC;
868 if (poweroff_on_panic)
869 bootopt |= RB_POWEROFF;
870 if (powercycle_on_panic)
871 bootopt |= RB_POWERCYCLE;
872 kern_reboot(bootopt);
876 * Support for poweroff delay.
878 * Please note that setting this delay too short might power off your machine
879 * before the write cache on your hard disk has been flushed, leading to
880 * soft-updates inconsistencies.
882 #ifndef POWEROFF_DELAY
883 # define POWEROFF_DELAY 5000
885 static int poweroff_delay = POWEROFF_DELAY;
887 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
888 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
891 poweroff_wait(void *junk, int howto)
894 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
896 DELAY(poweroff_delay * 1000);
900 * Some system processes (e.g. syncer) need to be stopped at appropriate
901 * points in their main loops prior to a system shutdown, so that they
902 * won't interfere with the shutdown process (e.g. by holding a disk buf
903 * to cause sync to fail). For each of these system processes, register
904 * shutdown_kproc() as a handler for one of shutdown events.
906 static int kproc_shutdown_wait = 60;
907 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
908 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
911 kproc_shutdown(void *arg, int howto)
919 p = (struct proc *)arg;
920 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
921 kproc_shutdown_wait, p->p_comm);
922 error = kproc_suspend(p, kproc_shutdown_wait * hz);
924 if (error == EWOULDBLOCK)
925 printf("timed out\n");
931 kthread_shutdown(void *arg, int howto)
939 td = (struct thread *)arg;
940 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
941 kproc_shutdown_wait, td->td_name);
942 error = kthread_suspend(td, kproc_shutdown_wait * hz);
944 if (error == EWOULDBLOCK)
945 printf("timed out\n");
950 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
951 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
952 dumpdevname, 0, "Device for kernel dumps");
954 static int _dump_append(struct dumperinfo *di, void *virtual,
955 vm_offset_t physical, size_t length);
958 static struct kerneldumpcrypto *
959 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
960 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
962 struct kerneldumpcrypto *kdc;
963 struct kerneldumpkey *kdk;
964 uint32_t dumpkeysize;
966 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
967 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
969 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
971 kdc->kdc_encryption = encryption;
972 switch (kdc->kdc_encryption) {
973 case KERNELDUMP_ENC_AES_256_CBC:
974 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
981 kdc->kdc_dumpkeysize = dumpkeysize;
982 kdk = kdc->kdc_dumpkey;
983 kdk->kdk_encryption = kdc->kdc_encryption;
984 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
985 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
986 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
990 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
996 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
998 uint8_t hash[SHA256_DIGEST_LENGTH];
1000 struct kerneldumpkey *kdk;
1009 * When a user enters ddb it can write a crash dump multiple times.
1010 * Each time it should be encrypted using a different IV.
1013 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1014 SHA256_Final(hash, &ctx);
1015 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1017 switch (kdc->kdc_encryption) {
1018 case KERNELDUMP_ENC_AES_256_CBC:
1019 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1020 kdc->kdc_iv) <= 0) {
1030 kdk = kdc->kdc_dumpkey;
1031 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
1033 explicit_bzero(hash, sizeof(hash));
1038 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
1043 return (kdc->kdc_dumpkeysize);
1047 static struct kerneldumpcomp *
1048 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
1050 struct kerneldumpcomp *kdcomp;
1053 switch (compression) {
1054 case KERNELDUMP_COMP_GZIP:
1055 format = COMPRESS_GZIP;
1057 case KERNELDUMP_COMP_ZSTD:
1058 format = COMPRESS_ZSTD;
1064 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1065 kdcomp->kdc_format = compression;
1066 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1067 format, di->maxiosize, kerneldump_gzlevel, di);
1068 if (kdcomp->kdc_stream == NULL) {
1069 free(kdcomp, M_DUMPER);
1072 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1077 kerneldumpcomp_destroy(struct dumperinfo *di)
1079 struct kerneldumpcomp *kdcomp;
1081 kdcomp = di->kdcomp;
1084 compressor_fini(kdcomp->kdc_stream);
1085 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1086 free(kdcomp->kdc_buf, M_DUMPER);
1087 free(kdcomp, M_DUMPER);
1090 /* Registration of dumpers */
1092 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1093 uint8_t compression, uint8_t encryption, const uint8_t *key,
1094 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1099 error = priv_check(td, PRIV_SETDUMPER);
1103 if (dumper.dumper != NULL)
1106 dumper.blockbuf = NULL;
1107 dumper.kdcrypto = NULL;
1108 dumper.kdcomp = NULL;
1110 if (encryption != KERNELDUMP_ENC_NONE) {
1112 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1113 encryption, key, encryptedkeysize, encryptedkey);
1114 if (dumper.kdcrypto == NULL) {
1124 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1125 if (wantcopy >= sizeof(dumpdevname)) {
1126 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1127 devname, dumpdevname);
1130 if (compression != KERNELDUMP_COMP_NONE) {
1132 * We currently can't support simultaneous encryption and
1135 if (encryption != KERNELDUMP_ENC_NONE) {
1139 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1140 if (dumper.kdcomp == NULL) {
1146 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1150 (void)clear_dumper(td);
1155 clear_dumper(struct thread *td)
1159 error = priv_check(td, PRIV_SETDUMPER);
1164 netdump_mbuf_drain();
1168 if (dumper.kdcrypto != NULL) {
1169 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1170 dumper.kdcrypto->kdc_dumpkeysize);
1171 free(dumper.kdcrypto, M_EKCD);
1175 kerneldumpcomp_destroy(&dumper);
1177 if (dumper.blockbuf != NULL) {
1178 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1179 free(dumper.blockbuf, M_DUMPER);
1181 explicit_bzero(&dumper, sizeof(dumper));
1182 dumpdevname[0] = '\0';
1187 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1190 if (di->mediasize > 0 && length != 0 && (offset < di->mediaoffset ||
1191 offset - di->mediaoffset + length > di->mediasize)) {
1192 if (di->kdcomp != NULL && offset >= di->mediaoffset) {
1194 "Compressed dump failed to fit in device boundaries.\n");
1198 printf("Attempt to write outside dump device boundaries.\n"
1199 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1200 (intmax_t)offset, (intmax_t)di->mediaoffset,
1201 (uintmax_t)length, (intmax_t)di->mediasize);
1204 if (length % di->blocksize != 0) {
1205 printf("Attempt to write partial block of length %ju.\n",
1209 if (offset % di->blocksize != 0) {
1210 printf("Attempt to write at unaligned offset %jd.\n",
1220 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1223 switch (kdc->kdc_encryption) {
1224 case KERNELDUMP_ENC_AES_256_CBC:
1225 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1226 8 * size, buf) <= 0) {
1229 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1230 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1241 /* Encrypt data and call dumper. */
1243 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1244 vm_offset_t physical, off_t offset, size_t length)
1246 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1247 struct kerneldumpcrypto *kdc;
1253 while (length > 0) {
1254 nbytes = MIN(length, sizeof(buf));
1255 bcopy(virtual, buf, nbytes);
1257 if (dump_encrypt(kdc, buf, nbytes) != 0)
1260 error = dump_write(di, buf, physical, offset, nbytes);
1265 virtual = (void *)((uint8_t *)virtual + nbytes);
1274 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1276 struct dumperinfo *di;
1277 size_t resid, rlength;
1282 if (length % di->blocksize != 0) {
1284 * This must be the final write after flushing the compression
1285 * stream. Write as many full blocks as possible and stash the
1286 * residual data in the dumper's block buffer. It will be
1287 * padded and written in dump_finish().
1289 rlength = rounddown(length, di->blocksize);
1291 error = _dump_append(di, base, 0, rlength);
1295 resid = length - rlength;
1296 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1297 di->kdcomp->kdc_resid = resid;
1300 return (_dump_append(di, base, 0, length));
1304 * Write kernel dump headers at the beginning and end of the dump extent.
1305 * Write the kernel dump encryption key after the leading header if we were
1306 * configured to do so.
1309 dump_write_headers(struct dumperinfo *di, struct kerneldumpheader *kdh)
1312 struct kerneldumpcrypto *kdc;
1320 hdrsz = sizeof(*kdh);
1321 if (hdrsz > di->blocksize)
1326 key = kdc->kdc_dumpkey;
1327 keysize = kerneldumpcrypto_dumpkeysize(kdc);
1334 * If the dump device has special handling for headers, let it take care
1335 * of writing them out.
1337 if (di->dumper_hdr != NULL)
1338 return (di->dumper_hdr(di, kdh, key, keysize));
1340 if (hdrsz == di->blocksize)
1344 memset(buf, 0, di->blocksize);
1345 memcpy(buf, kdh, hdrsz);
1348 extent = dtoh64(kdh->dumpextent);
1351 error = dump_write(di, kdc->kdc_dumpkey, 0,
1352 di->mediaoffset + di->mediasize - di->blocksize - extent -
1359 error = dump_write(di, buf, 0,
1360 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1361 keysize, di->blocksize);
1363 error = dump_write(di, buf, 0, di->mediaoffset + di->mediasize -
1364 di->blocksize, di->blocksize);
1369 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1370 * protect us from metadata and metadata from us.
1372 #define SIZEOF_METADATA (64 * 1024)
1375 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1376 * if requested, and make sure that we have enough space on the dump device.
1378 * We set things up so that the dump ends before the last sector of the dump
1379 * device, at which the trailing header is written.
1381 * +-----------+------+-----+----------------------------+------+
1382 * | | lhdr | key | ... kernel dump ... | thdr |
1383 * +-----------+------+-----+----------------------------+------+
1384 * 1 blk opt <------- dump extent --------> 1 blk
1386 * Dumps written using dump_append() start at the beginning of the extent.
1387 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1388 * will not. The true length of the dump is recorded in the leading and trailing
1389 * headers once the dump has been completed.
1391 * The dump device may provide a callback, in which case it will initialize
1392 * dumpoff and take care of laying out the headers.
1395 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1397 uint64_t dumpextent, span;
1402 error = kerneldumpcrypto_init(di->kdcrypto);
1405 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1411 if (di->dumper_start != NULL) {
1412 error = di->dumper_start(di);
1414 dumpextent = dtoh64(kdh->dumpextent);
1415 span = SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1417 if (di->mediasize < span) {
1418 if (di->kdcomp == NULL)
1422 * We don't yet know how much space the compressed dump
1423 * will occupy, so try to use the whole swap partition
1424 * (minus the first 64KB) in the hope that the
1425 * compressed dump will fit. If that doesn't turn out to
1426 * be enough, the bounds checking in dump_write()
1427 * will catch us and cause the dump to fail.
1429 dumpextent = di->mediasize - span + dumpextent;
1430 kdh->dumpextent = htod64(dumpextent);
1434 * The offset at which to begin writing the dump.
1436 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1439 di->origdumpoff = di->dumpoff;
1444 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1450 if (di->kdcrypto != NULL)
1451 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1455 error = dump_write(di, virtual, physical, di->dumpoff, length);
1457 di->dumpoff += length;
1462 * Write to the dump device starting at dumpoff. When compression is enabled,
1463 * writes to the device will be performed using a callback that gets invoked
1464 * when the compression stream's output buffer is full.
1467 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1472 if (di->kdcomp != NULL) {
1473 /* Bounce through a buffer to avoid CRC errors. */
1474 if (length > di->maxiosize)
1476 buf = di->kdcomp->kdc_buf;
1477 memmove(buf, virtual, length);
1478 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1480 return (_dump_append(di, virtual, physical, length));
1484 * Write to the dump device at the specified offset.
1487 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1488 off_t offset, size_t length)
1492 error = dump_check_bounds(di, offset, length);
1495 return (di->dumper(di->priv, virtual, physical, offset, length));
1499 * Perform kernel dump finalization: flush the compression stream, if necessary,
1500 * write the leading and trailing kernel dump headers now that we know the true
1501 * length of the dump, and optionally write the encryption key following the
1505 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1509 if (di->kdcomp != NULL) {
1510 error = compressor_flush(di->kdcomp->kdc_stream);
1511 if (error == EAGAIN) {
1512 /* We have residual data in di->blockbuf. */
1513 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1515 di->dumpoff += di->kdcomp->kdc_resid;
1516 di->kdcomp->kdc_resid = 0;
1522 * We now know the size of the compressed dump, so update the
1523 * header accordingly and recompute parity.
1525 kdh->dumplength = htod64(di->dumpoff - di->origdumpoff);
1527 kdh->parity = kerneldump_parity(kdh);
1529 compressor_reset(di->kdcomp->kdc_stream);
1532 error = dump_write_headers(di, kdh);
1536 (void)dump_write(di, NULL, 0, 0, 0);
1541 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1542 char *magic, uint32_t archver, uint64_t dumplen)
1546 bzero(kdh, sizeof(*kdh));
1547 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1548 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1549 kdh->version = htod32(KERNELDUMPVERSION);
1550 kdh->architectureversion = htod32(archver);
1551 kdh->dumplength = htod64(dumplen);
1552 kdh->dumpextent = kdh->dumplength;
1553 kdh->dumptime = htod64(time_second);
1555 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1557 kdh->dumpkeysize = 0;
1559 kdh->blocksize = htod32(di->blocksize);
1560 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1561 dstsize = sizeof(kdh->versionstring);
1562 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1563 kdh->versionstring[dstsize - 2] = '\n';
1564 if (panicstr != NULL)
1565 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1566 if (di->kdcomp != NULL)
1567 kdh->compression = di->kdcomp->kdc_format;
1568 kdh->parity = kerneldump_parity(kdh);
1572 DB_SHOW_COMMAND(panic, db_show_panic)
1575 if (panicstr == NULL)
1576 db_printf("panicstr not set\n");
1578 db_printf("panic: %s\n", panicstr);