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 static int debugger_on_panic = 0;
120 static 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");
126 int debugger_on_trap = 0;
127 SYSCTL_INT(_debug, OID_AUTO, debugger_on_trap,
128 CTLFLAG_RWTUN | CTLFLAG_SECURE,
129 &debugger_on_trap, 0, "Run debugger on kernel trap before panic");
132 static int trace_on_panic = 1;
133 static bool trace_all_panics = true;
135 static int trace_on_panic = 0;
136 static bool trace_all_panics = false;
138 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
139 CTLFLAG_RWTUN | CTLFLAG_SECURE,
140 &trace_on_panic, 0, "Print stack trace on kernel panic");
141 SYSCTL_BOOL(_debug, OID_AUTO, trace_all_panics, CTLFLAG_RWTUN,
142 &trace_all_panics, 0, "Print stack traces on secondary kernel panics");
145 static int sync_on_panic = 0;
146 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
147 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
149 static bool poweroff_on_panic = 0;
150 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
151 &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
153 static bool powercycle_on_panic = 0;
154 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
155 &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
157 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
158 "Shutdown environment");
161 static int show_busybufs;
163 static int show_busybufs = 1;
165 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
166 &show_busybufs, 0, "");
168 int suspend_blocked = 0;
169 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
170 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
173 FEATURE(ekcd, "Encrypted kernel crash dumps support");
175 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
177 struct kerneldumpcrypto {
178 uint8_t kdc_encryption;
179 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
181 cipherInstance kdc_ci;
182 uint32_t kdc_dumpkeysize;
183 struct kerneldumpkey kdc_dumpkey[];
187 struct kerneldumpcomp {
189 struct compressor *kdc_stream;
194 static struct kerneldumpcomp *kerneldumpcomp_create(struct dumperinfo *di,
195 uint8_t compression);
196 static void kerneldumpcomp_destroy(struct dumperinfo *di);
197 static int kerneldumpcomp_write_cb(void *base, size_t len, off_t off, void *arg);
199 static int kerneldump_gzlevel = 6;
200 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
201 &kerneldump_gzlevel, 0,
202 "Kernel crash dump compression level");
205 * Variable panicstr contains argument to first call to panic; used as flag
206 * to indicate that the kernel has already called panic.
208 const char *panicstr;
210 int dumping; /* system is dumping */
211 int rebooting; /* system is rebooting */
212 static struct dumperinfo dumper; /* our selected dumper */
214 /* Context information for dump-debuggers. */
215 static struct pcb dumppcb; /* Registers. */
216 lwpid_t dumptid; /* Thread ID. */
218 static struct cdevsw reroot_cdevsw = {
219 .d_version = D_VERSION,
223 static void poweroff_wait(void *, int);
224 static void shutdown_halt(void *junk, int howto);
225 static void shutdown_panic(void *junk, int howto);
226 static void shutdown_reset(void *junk, int howto);
227 static int kern_reroot(void);
229 /* register various local shutdown events */
231 shutdown_conf(void *unused)
234 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
236 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
237 SHUTDOWN_PRI_LAST + 100);
238 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
239 SHUTDOWN_PRI_LAST + 100);
240 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
241 SHUTDOWN_PRI_LAST + 200);
244 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
247 * The only reason this exists is to create the /dev/reroot/ directory,
248 * used by reroot code in init(8) as a mountpoint for tmpfs.
251 reroot_conf(void *unused)
256 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
257 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
259 printf("%s: failed to create device node, error %d",
264 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
267 * The system call that results in a reboot.
271 sys_reboot(struct thread *td, struct reboot_args *uap)
277 error = mac_system_check_reboot(td->td_ucred, uap->opt);
280 error = priv_check(td, PRIV_REBOOT);
282 if (uap->opt & RB_REROOT)
283 error = kern_reroot();
285 kern_reboot(uap->opt);
291 shutdown_nice_task_fn(void *arg, int pending __unused)
295 howto = (uintptr_t)arg;
296 /* Send a signal to init(8) and have it shutdown the world. */
298 if (howto & RB_POWEROFF)
299 kern_psignal(initproc, SIGUSR2);
300 else if (howto & RB_POWERCYCLE)
301 kern_psignal(initproc, SIGWINCH);
302 else if (howto & RB_HALT)
303 kern_psignal(initproc, SIGUSR1);
305 kern_psignal(initproc, SIGINT);
306 PROC_UNLOCK(initproc);
309 static struct task shutdown_nice_task = TASK_INITIALIZER(0,
310 &shutdown_nice_task_fn, NULL);
313 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
316 shutdown_nice(int howto)
319 if (initproc != NULL && !SCHEDULER_STOPPED()) {
320 shutdown_nice_task.ta_context = (void *)(uintptr_t)howto;
321 taskqueue_enqueue(taskqueue_fast, &shutdown_nice_task);
324 * No init(8) running, or scheduler would not allow it
325 * to run, so simply reboot.
327 kern_reboot(howto | RB_NOSYNC);
340 if (ts.tv_sec >= 86400) {
341 printf("%ldd", (long)ts.tv_sec / 86400);
345 if (f || ts.tv_sec >= 3600) {
346 printf("%ldh", (long)ts.tv_sec / 3600);
350 if (f || ts.tv_sec >= 60) {
351 printf("%ldm", (long)ts.tv_sec / 60);
355 printf("%lds\n", (long)ts.tv_sec);
359 doadump(boolean_t textdump)
367 if (dumper.dumper == NULL)
371 dumptid = curthread->td_tid;
376 if (textdump && textdump_pending) {
378 textdump_dumpsys(&dumper);
382 error = dumpsys(&dumper);
389 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
392 kern_reboot(int howto)
397 * Normal paths here don't hold Giant, but we can wind up here
398 * unexpectedly with it held. Drop it now so we don't have to
399 * drop and pick it up elsewhere. The paths it is locking will
400 * never be returned to, and it is preferable to preclude
401 * deadlock than to lock against code that won't ever
404 while (mtx_owned(&Giant))
409 * Bind us to the first CPU so that all shutdown code runs there. Some
410 * systems don't shutdown properly (i.e., ACPI power off) if we
411 * run on another processor.
413 if (!SCHEDULER_STOPPED()) {
414 thread_lock(curthread);
415 sched_bind(curthread, CPU_FIRST());
416 thread_unlock(curthread);
417 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
418 ("boot: not running on cpu 0"));
421 /* We're in the process of rebooting. */
424 /* We are out of the debugger now. */
428 * Do any callouts that should be done BEFORE syncing the filesystems.
430 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
433 * Now sync filesystems
435 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
437 bufshutdown(show_busybufs);
445 * Ok, now do things that assume all filesystem activity has
448 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
450 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
453 /* Now that we're going to really halt the system... */
454 EVENTHANDLER_INVOKE(shutdown_final, howto);
456 for(;;) ; /* safety against shutdown_reset not working */
461 * The system call that results in changing the rootfs.
466 struct vnode *oldrootvnode, *vp;
467 struct mount *mp, *devmp;
470 if (curproc != initproc)
474 * Mark the filesystem containing currently-running executable
475 * (the temporary copy of init(8)) busy.
477 vp = curproc->p_textvp;
478 error = vn_lock(vp, LK_SHARED);
482 error = vfs_busy(mp, MBF_NOWAIT);
486 error = vfs_busy(mp, 0);
487 vn_lock(vp, LK_SHARED | LK_RETRY);
493 if (vp->v_iflag & VI_DOOMED) {
502 * Remove the filesystem containing currently-running executable
503 * from the mount list, to prevent it from being unmounted
504 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
506 * Also preserve /dev - forcibly unmounting it could cause driver
514 mtx_lock(&mountlist_mtx);
515 TAILQ_REMOVE(&mountlist, mp, mnt_list);
516 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
517 mtx_unlock(&mountlist_mtx);
519 oldrootvnode = rootvnode;
522 * Unmount everything except for the two filesystems preserved above.
527 * Add /dev back; vfs_mountroot() will move it into its new place.
529 mtx_lock(&mountlist_mtx);
530 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
531 mtx_unlock(&mountlist_mtx);
536 * Mount the new rootfs.
541 * Update all references to the old rootvnode.
543 mountcheckdirs(oldrootvnode, rootvnode);
546 * Add the temporary filesystem back and unbusy it.
548 mtx_lock(&mountlist_mtx);
549 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
550 mtx_unlock(&mountlist_mtx);
557 * If the shutdown was a clean halt, behave accordingly.
560 shutdown_halt(void *junk, int howto)
563 if (howto & RB_HALT) {
565 printf("The operating system has halted.\n");
566 printf("Please press any key to reboot.\n\n");
568 case -1: /* No console, just die */
578 * Check to see if the system paniced, pause and then reboot
579 * according to the specified delay.
582 shutdown_panic(void *junk, int howto)
586 if (howto & RB_DUMP) {
587 if (panic_reboot_wait_time != 0) {
588 if (panic_reboot_wait_time != -1) {
589 printf("Automatic reboot in %d seconds - "
590 "press a key on the console to abort\n",
591 panic_reboot_wait_time);
592 for (loop = panic_reboot_wait_time * 10;
594 DELAY(1000 * 100); /* 1/10th second */
595 /* Did user type a key? */
596 if (cncheckc() != -1)
602 } else { /* zero time specified - reboot NOW */
605 printf("--> Press a key on the console to reboot,\n");
606 printf("--> or switch off the system now.\n");
612 * Everything done, now reset
615 shutdown_reset(void *junk, int howto)
618 printf("Rebooting...\n");
619 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
622 * Acquiring smp_ipi_mtx here has a double effect:
623 * - it disables interrupts avoiding CPU0 preemption
624 * by fast handlers (thus deadlocking against other CPUs)
625 * - it avoids deadlocks against smp_rendezvous() or, more
626 * generally, threads busy-waiting, with this spinlock held,
627 * and waiting for responses by threads on other CPUs
628 * (ie. smp_tlb_shootdown()).
630 * For the !SMP case it just needs to handle the former problem.
633 mtx_lock_spin(&smp_ipi_mtx);
638 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
640 /* NOTREACHED */ /* assuming reset worked */
643 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
644 static int kassert_warn_only = 0;
646 static int kassert_do_kdb = 0;
649 static int kassert_do_ktr = 0;
651 static int kassert_do_log = 1;
652 static int kassert_log_pps_limit = 4;
653 static int kassert_log_mute_at = 0;
654 static int kassert_log_panic_at = 0;
655 static int kassert_suppress_in_panic = 0;
656 static int kassert_warnings = 0;
658 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
660 #ifdef KASSERT_PANIC_OPTIONAL
661 #define KASSERT_RWTUN CTLFLAG_RWTUN
663 #define KASSERT_RWTUN CTLFLAG_RDTUN
666 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, KASSERT_RWTUN,
667 &kassert_warn_only, 0,
668 "KASSERT triggers a panic (0) or just a warning (1)");
671 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, KASSERT_RWTUN,
672 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
676 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, KASSERT_RWTUN,
678 "KASSERT does a KTR, set this to the KTRMASK you want");
681 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, KASSERT_RWTUN,
683 "If warn_only is enabled, log (1) or do not log (0) assertion violations");
685 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, KASSERT_RWTUN,
686 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
688 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, KASSERT_RWTUN,
689 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
691 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, KASSERT_RWTUN,
692 &kassert_log_pps_limit, 0, "limit number of log messages per second");
694 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, KASSERT_RWTUN,
695 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
697 SYSCTL_INT(_debug_kassert, OID_AUTO, suppress_in_panic, KASSERT_RWTUN,
698 &kassert_suppress_in_panic, 0,
699 "KASSERTs will be suppressed while handling a panic");
702 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
704 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
705 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
706 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
709 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
713 error = sysctl_wire_old_buffer(req, sizeof(int));
716 error = sysctl_handle_int(oidp, &i, 0, req);
718 if (error != 0 || req->newptr == NULL)
720 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
724 #ifdef KASSERT_PANIC_OPTIONAL
726 * Called by KASSERT, this decides if we will panic
727 * or if we will log via printf and/or ktr.
730 kassert_panic(const char *fmt, ...)
732 static char buf[256];
736 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
740 * If we are suppressing secondary panics, log the warning but do not
741 * re-enter panic/kdb.
743 if (panicstr != NULL && kassert_suppress_in_panic) {
744 if (kassert_do_log) {
745 printf("KASSERT failed: %s\n", buf);
747 if (trace_all_panics && trace_on_panic)
755 * panic if we're not just warning, or if we've exceeded
756 * kassert_log_panic_at warnings.
758 if (!kassert_warn_only ||
759 (kassert_log_panic_at > 0 &&
760 kassert_warnings >= kassert_log_panic_at)) {
770 * log if we've not yet met the mute limit.
772 if (kassert_do_log &&
773 (kassert_log_mute_at == 0 ||
774 kassert_warnings < kassert_log_mute_at)) {
775 static struct timeval lasterr;
778 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
779 printf("KASSERT failed: %s\n", buf);
784 if (kassert_do_kdb) {
785 kdb_enter(KDB_WHY_KASSERT, buf);
788 atomic_add_int(&kassert_warnings, 1);
790 #endif /* KASSERT_PANIC_OPTIONAL */
794 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
795 * and then reboots. If we are called twice, then we avoid trying to sync
796 * the disks as this often leads to recursive panics.
799 panic(const char *fmt, ...)
808 vpanic(const char *fmt, va_list ap)
813 struct thread *td = curthread;
814 int bootopt, newpanic;
815 static char buf[256];
821 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
822 * concurrently entering panic. Only the winner will proceed
825 if (panicstr == NULL && !kdb_active) {
826 other_cpus = all_cpus;
827 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
828 stop_cpus_hard(other_cpus);
833 * Ensure that the scheduler is stopped while panicking, even if panic
834 * has been entered from kdb.
836 td->td_stopsched = 1;
838 bootopt = RB_AUTOBOOT;
841 bootopt |= RB_NOSYNC;
849 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
852 printf("panic: %s\n", buf);
859 printf("cpuid = %d\n", PCPU_GET(cpuid));
861 printf("time = %jd\n", (intmax_t )time_second);
863 if ((newpanic || trace_all_panics) && trace_on_panic)
865 if (debugger_on_panic)
866 kdb_enter(KDB_WHY_PANIC, "panic");
868 /*thread_lock(td); */
869 td->td_flags |= TDF_INPANIC;
870 /* thread_unlock(td); */
872 bootopt |= RB_NOSYNC;
873 if (poweroff_on_panic)
874 bootopt |= RB_POWEROFF;
875 if (powercycle_on_panic)
876 bootopt |= RB_POWERCYCLE;
877 kern_reboot(bootopt);
881 * Support for poweroff delay.
883 * Please note that setting this delay too short might power off your machine
884 * before the write cache on your hard disk has been flushed, leading to
885 * soft-updates inconsistencies.
887 #ifndef POWEROFF_DELAY
888 # define POWEROFF_DELAY 5000
890 static int poweroff_delay = POWEROFF_DELAY;
892 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
893 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
896 poweroff_wait(void *junk, int howto)
899 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
901 DELAY(poweroff_delay * 1000);
905 * Some system processes (e.g. syncer) need to be stopped at appropriate
906 * points in their main loops prior to a system shutdown, so that they
907 * won't interfere with the shutdown process (e.g. by holding a disk buf
908 * to cause sync to fail). For each of these system processes, register
909 * shutdown_kproc() as a handler for one of shutdown events.
911 static int kproc_shutdown_wait = 60;
912 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
913 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
916 kproc_shutdown(void *arg, int howto)
924 p = (struct proc *)arg;
925 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
926 kproc_shutdown_wait, p->p_comm);
927 error = kproc_suspend(p, kproc_shutdown_wait * hz);
929 if (error == EWOULDBLOCK)
930 printf("timed out\n");
936 kthread_shutdown(void *arg, int howto)
944 td = (struct thread *)arg;
945 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
946 kproc_shutdown_wait, td->td_name);
947 error = kthread_suspend(td, kproc_shutdown_wait * hz);
949 if (error == EWOULDBLOCK)
950 printf("timed out\n");
955 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
956 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
957 dumpdevname, 0, "Device for kernel dumps");
959 static int _dump_append(struct dumperinfo *di, void *virtual,
960 vm_offset_t physical, size_t length);
963 static struct kerneldumpcrypto *
964 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
965 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
967 struct kerneldumpcrypto *kdc;
968 struct kerneldumpkey *kdk;
969 uint32_t dumpkeysize;
971 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
972 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
974 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
976 kdc->kdc_encryption = encryption;
977 switch (kdc->kdc_encryption) {
978 case KERNELDUMP_ENC_AES_256_CBC:
979 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
986 kdc->kdc_dumpkeysize = dumpkeysize;
987 kdk = kdc->kdc_dumpkey;
988 kdk->kdk_encryption = kdc->kdc_encryption;
989 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
990 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
991 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
995 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
1001 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
1003 uint8_t hash[SHA256_DIGEST_LENGTH];
1005 struct kerneldumpkey *kdk;
1014 * When a user enters ddb it can write a crash dump multiple times.
1015 * Each time it should be encrypted using a different IV.
1018 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1019 SHA256_Final(hash, &ctx);
1020 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
1022 switch (kdc->kdc_encryption) {
1023 case KERNELDUMP_ENC_AES_256_CBC:
1024 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1025 kdc->kdc_iv) <= 0) {
1035 kdk = kdc->kdc_dumpkey;
1036 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
1038 explicit_bzero(hash, sizeof(hash));
1043 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
1048 return (kdc->kdc_dumpkeysize);
1052 static struct kerneldumpcomp *
1053 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
1055 struct kerneldumpcomp *kdcomp;
1058 switch (compression) {
1059 case KERNELDUMP_COMP_GZIP:
1060 format = COMPRESS_GZIP;
1062 case KERNELDUMP_COMP_ZSTD:
1063 format = COMPRESS_ZSTD;
1069 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1070 kdcomp->kdc_format = compression;
1071 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1072 format, di->maxiosize, kerneldump_gzlevel, di);
1073 if (kdcomp->kdc_stream == NULL) {
1074 free(kdcomp, M_DUMPER);
1077 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1082 kerneldumpcomp_destroy(struct dumperinfo *di)
1084 struct kerneldumpcomp *kdcomp;
1086 kdcomp = di->kdcomp;
1089 compressor_fini(kdcomp->kdc_stream);
1090 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1091 free(kdcomp->kdc_buf, M_DUMPER);
1092 free(kdcomp, M_DUMPER);
1095 /* Registration of dumpers */
1097 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1098 uint8_t compression, uint8_t encryption, const uint8_t *key,
1099 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1104 error = priv_check(td, PRIV_SETDUMPER);
1108 if (dumper.dumper != NULL)
1111 dumper.blockbuf = NULL;
1112 dumper.kdcrypto = NULL;
1113 dumper.kdcomp = NULL;
1115 if (encryption != KERNELDUMP_ENC_NONE) {
1117 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1118 encryption, key, encryptedkeysize, encryptedkey);
1119 if (dumper.kdcrypto == NULL) {
1129 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1130 if (wantcopy >= sizeof(dumpdevname)) {
1131 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1132 devname, dumpdevname);
1135 if (compression != KERNELDUMP_COMP_NONE) {
1137 * We currently can't support simultaneous encryption and
1140 if (encryption != KERNELDUMP_ENC_NONE) {
1144 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1145 if (dumper.kdcomp == NULL) {
1151 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1155 (void)clear_dumper(td);
1160 clear_dumper(struct thread *td)
1164 error = priv_check(td, PRIV_SETDUMPER);
1169 netdump_mbuf_drain();
1173 if (dumper.kdcrypto != NULL) {
1174 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1175 dumper.kdcrypto->kdc_dumpkeysize);
1176 free(dumper.kdcrypto, M_EKCD);
1180 kerneldumpcomp_destroy(&dumper);
1182 if (dumper.blockbuf != NULL) {
1183 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1184 free(dumper.blockbuf, M_DUMPER);
1186 explicit_bzero(&dumper, sizeof(dumper));
1187 dumpdevname[0] = '\0';
1192 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1195 if (di->mediasize > 0 && length != 0 && (offset < di->mediaoffset ||
1196 offset - di->mediaoffset + length > di->mediasize)) {
1197 if (di->kdcomp != NULL && offset >= di->mediaoffset) {
1199 "Compressed dump failed to fit in device boundaries.\n");
1203 printf("Attempt to write outside dump device boundaries.\n"
1204 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1205 (intmax_t)offset, (intmax_t)di->mediaoffset,
1206 (uintmax_t)length, (intmax_t)di->mediasize);
1209 if (length % di->blocksize != 0) {
1210 printf("Attempt to write partial block of length %ju.\n",
1214 if (offset % di->blocksize != 0) {
1215 printf("Attempt to write at unaligned offset %jd.\n",
1225 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1228 switch (kdc->kdc_encryption) {
1229 case KERNELDUMP_ENC_AES_256_CBC:
1230 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1231 8 * size, buf) <= 0) {
1234 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1235 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1246 /* Encrypt data and call dumper. */
1248 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1249 vm_offset_t physical, off_t offset, size_t length)
1251 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1252 struct kerneldumpcrypto *kdc;
1258 while (length > 0) {
1259 nbytes = MIN(length, sizeof(buf));
1260 bcopy(virtual, buf, nbytes);
1262 if (dump_encrypt(kdc, buf, nbytes) != 0)
1265 error = dump_write(di, buf, physical, offset, nbytes);
1270 virtual = (void *)((uint8_t *)virtual + nbytes);
1279 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1281 struct dumperinfo *di;
1282 size_t resid, rlength;
1287 if (length % di->blocksize != 0) {
1289 * This must be the final write after flushing the compression
1290 * stream. Write as many full blocks as possible and stash the
1291 * residual data in the dumper's block buffer. It will be
1292 * padded and written in dump_finish().
1294 rlength = rounddown(length, di->blocksize);
1296 error = _dump_append(di, base, 0, rlength);
1300 resid = length - rlength;
1301 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1302 di->kdcomp->kdc_resid = resid;
1305 return (_dump_append(di, base, 0, length));
1309 * Write kernel dump headers at the beginning and end of the dump extent.
1310 * Write the kernel dump encryption key after the leading header if we were
1311 * configured to do so.
1314 dump_write_headers(struct dumperinfo *di, struct kerneldumpheader *kdh)
1317 struct kerneldumpcrypto *kdc;
1325 hdrsz = sizeof(*kdh);
1326 if (hdrsz > di->blocksize)
1331 key = kdc->kdc_dumpkey;
1332 keysize = kerneldumpcrypto_dumpkeysize(kdc);
1339 * If the dump device has special handling for headers, let it take care
1340 * of writing them out.
1342 if (di->dumper_hdr != NULL)
1343 return (di->dumper_hdr(di, kdh, key, keysize));
1345 if (hdrsz == di->blocksize)
1349 memset(buf, 0, di->blocksize);
1350 memcpy(buf, kdh, hdrsz);
1353 extent = dtoh64(kdh->dumpextent);
1356 error = dump_write(di, kdc->kdc_dumpkey, 0,
1357 di->mediaoffset + di->mediasize - di->blocksize - extent -
1364 error = dump_write(di, buf, 0,
1365 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1366 keysize, di->blocksize);
1368 error = dump_write(di, buf, 0, di->mediaoffset + di->mediasize -
1369 di->blocksize, di->blocksize);
1374 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1375 * protect us from metadata and metadata from us.
1377 #define SIZEOF_METADATA (64 * 1024)
1380 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1381 * if requested, and make sure that we have enough space on the dump device.
1383 * We set things up so that the dump ends before the last sector of the dump
1384 * device, at which the trailing header is written.
1386 * +-----------+------+-----+----------------------------+------+
1387 * | | lhdr | key | ... kernel dump ... | thdr |
1388 * +-----------+------+-----+----------------------------+------+
1389 * 1 blk opt <------- dump extent --------> 1 blk
1391 * Dumps written using dump_append() start at the beginning of the extent.
1392 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1393 * will not. The true length of the dump is recorded in the leading and trailing
1394 * headers once the dump has been completed.
1396 * The dump device may provide a callback, in which case it will initialize
1397 * dumpoff and take care of laying out the headers.
1400 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1402 uint64_t dumpextent, span;
1407 error = kerneldumpcrypto_init(di->kdcrypto);
1410 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1416 if (di->dumper_start != NULL) {
1417 error = di->dumper_start(di);
1419 dumpextent = dtoh64(kdh->dumpextent);
1420 span = SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1422 if (di->mediasize < span) {
1423 if (di->kdcomp == NULL)
1427 * We don't yet know how much space the compressed dump
1428 * will occupy, so try to use the whole swap partition
1429 * (minus the first 64KB) in the hope that the
1430 * compressed dump will fit. If that doesn't turn out to
1431 * be enough, the bounds checking in dump_write()
1432 * will catch us and cause the dump to fail.
1434 dumpextent = di->mediasize - span + dumpextent;
1435 kdh->dumpextent = htod64(dumpextent);
1439 * The offset at which to begin writing the dump.
1441 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1444 di->origdumpoff = di->dumpoff;
1449 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1455 if (di->kdcrypto != NULL)
1456 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1460 error = dump_write(di, virtual, physical, di->dumpoff, length);
1462 di->dumpoff += length;
1467 * Write to the dump device starting at dumpoff. When compression is enabled,
1468 * writes to the device will be performed using a callback that gets invoked
1469 * when the compression stream's output buffer is full.
1472 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1477 if (di->kdcomp != NULL) {
1478 /* Bounce through a buffer to avoid CRC errors. */
1479 if (length > di->maxiosize)
1481 buf = di->kdcomp->kdc_buf;
1482 memmove(buf, virtual, length);
1483 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1485 return (_dump_append(di, virtual, physical, length));
1489 * Write to the dump device at the specified offset.
1492 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1493 off_t offset, size_t length)
1497 error = dump_check_bounds(di, offset, length);
1500 return (di->dumper(di->priv, virtual, physical, offset, length));
1504 * Perform kernel dump finalization: flush the compression stream, if necessary,
1505 * write the leading and trailing kernel dump headers now that we know the true
1506 * length of the dump, and optionally write the encryption key following the
1510 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1514 if (di->kdcomp != NULL) {
1515 error = compressor_flush(di->kdcomp->kdc_stream);
1516 if (error == EAGAIN) {
1517 /* We have residual data in di->blockbuf. */
1518 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1520 di->dumpoff += di->kdcomp->kdc_resid;
1521 di->kdcomp->kdc_resid = 0;
1527 * We now know the size of the compressed dump, so update the
1528 * header accordingly and recompute parity.
1530 kdh->dumplength = htod64(di->dumpoff - di->origdumpoff);
1532 kdh->parity = kerneldump_parity(kdh);
1534 compressor_reset(di->kdcomp->kdc_stream);
1537 error = dump_write_headers(di, kdh);
1541 (void)dump_write(di, NULL, 0, 0, 0);
1546 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1547 char *magic, uint32_t archver, uint64_t dumplen)
1551 bzero(kdh, sizeof(*kdh));
1552 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1553 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1554 kdh->version = htod32(KERNELDUMPVERSION);
1555 kdh->architectureversion = htod32(archver);
1556 kdh->dumplength = htod64(dumplen);
1557 kdh->dumpextent = kdh->dumplength;
1558 kdh->dumptime = htod64(time_second);
1560 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1562 kdh->dumpkeysize = 0;
1564 kdh->blocksize = htod32(di->blocksize);
1565 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1566 dstsize = sizeof(kdh->versionstring);
1567 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1568 kdh->versionstring[dstsize - 2] = '\n';
1569 if (panicstr != NULL)
1570 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1571 if (di->kdcomp != NULL)
1572 kdh->compression = di->kdcomp->kdc_format;
1573 kdh->parity = kerneldump_parity(kdh);
1577 DB_SHOW_COMMAND(panic, db_show_panic)
1580 if (panicstr == NULL)
1581 db_printf("panicstr not set\n");
1583 db_printf("panic: %s\n", panicstr);