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$");
46 #include "opt_panic.h"
47 #include "opt_sched.h"
48 #include "opt_watchdog.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
56 #include <sys/eventhandler.h>
57 #include <sys/filedesc.h>
61 #include <sys/kernel.h>
62 #include <sys/kerneldump.h>
63 #include <sys/kthread.h>
65 #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/vnode.h>
77 #include <sys/watchdog.h>
79 #include <crypto/rijndael/rijndael-api-fst.h>
80 #include <crypto/sha2/sha256.h>
84 #include <machine/cpu.h>
85 #include <machine/dump.h>
86 #include <machine/pcb.h>
87 #include <machine/smp.h>
89 #include <security/mac/mac_framework.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pager.h>
95 #include <vm/swap_pager.h>
97 #include <sys/signalvar.h>
99 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
101 #ifndef PANIC_REBOOT_WAIT_TIME
102 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
104 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
105 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
106 &panic_reboot_wait_time, 0,
107 "Seconds to wait before rebooting after a panic");
110 * Note that stdarg.h and the ANSI style va_start macro is used for both
111 * ANSI and traditional C compilers.
113 #include <machine/stdarg.h>
116 #ifdef KDB_UNATTENDED
117 int debugger_on_panic = 0;
119 int debugger_on_panic = 1;
121 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
122 CTLFLAG_RWTUN | CTLFLAG_SECURE,
123 &debugger_on_panic, 0, "Run debugger on kernel panic");
126 static int trace_on_panic = 1;
128 static int trace_on_panic = 0;
130 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
131 CTLFLAG_RWTUN | CTLFLAG_SECURE,
132 &trace_on_panic, 0, "Print stack trace on kernel panic");
135 static int sync_on_panic = 0;
136 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
137 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
139 static bool poweroff_on_panic = 0;
140 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
141 &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
143 static bool powercycle_on_panic = 0;
144 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
145 &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
147 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
148 "Shutdown environment");
151 static int show_busybufs;
153 static int show_busybufs = 1;
155 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
156 &show_busybufs, 0, "");
158 int suspend_blocked = 0;
159 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
160 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
163 FEATURE(ekcd, "Encrypted kernel crash dumps support");
165 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
167 struct kerneldumpcrypto {
168 uint8_t kdc_encryption;
169 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
171 cipherInstance kdc_ci;
172 uint32_t kdc_dumpkeysize;
173 struct kerneldumpkey kdc_dumpkey[];
178 struct kerneldumpgz {
179 struct gzio_stream *kdgz_stream;
184 static struct kerneldumpgz *kerneldumpgz_create(struct dumperinfo *di,
185 uint8_t compression);
186 static void kerneldumpgz_destroy(struct dumperinfo *di);
187 static int kerneldumpgz_write_cb(void *cb, size_t len, off_t off, void *arg);
189 static int kerneldump_gzlevel = 6;
190 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
191 &kerneldump_gzlevel, 0,
192 "Kernel crash dump gzip compression level");
196 * Variable panicstr contains argument to first call to panic; used as flag
197 * to indicate that the kernel has already called panic.
199 const char *panicstr;
201 int dumping; /* system is dumping */
202 int rebooting; /* system is rebooting */
203 static struct dumperinfo dumper; /* our selected dumper */
205 /* Context information for dump-debuggers. */
206 static struct pcb dumppcb; /* Registers. */
207 lwpid_t dumptid; /* Thread ID. */
209 static struct cdevsw reroot_cdevsw = {
210 .d_version = D_VERSION,
214 static void poweroff_wait(void *, int);
215 static void shutdown_halt(void *junk, int howto);
216 static void shutdown_panic(void *junk, int howto);
217 static void shutdown_reset(void *junk, int howto);
218 static int kern_reroot(void);
220 /* register various local shutdown events */
222 shutdown_conf(void *unused)
225 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
227 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
228 SHUTDOWN_PRI_LAST + 100);
229 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
230 SHUTDOWN_PRI_LAST + 100);
231 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
232 SHUTDOWN_PRI_LAST + 200);
235 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
238 * The only reason this exists is to create the /dev/reroot/ directory,
239 * used by reroot code in init(8) as a mountpoint for tmpfs.
242 reroot_conf(void *unused)
247 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
248 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
250 printf("%s: failed to create device node, error %d",
255 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
258 * The system call that results in a reboot.
262 sys_reboot(struct thread *td, struct reboot_args *uap)
268 error = mac_system_check_reboot(td->td_ucred, uap->opt);
271 error = priv_check(td, PRIV_REBOOT);
273 if (uap->opt & RB_REROOT) {
274 error = kern_reroot();
277 kern_reboot(uap->opt);
285 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
288 shutdown_nice(int howto)
291 if (initproc != NULL) {
292 /* Send a signal to init(8) and have it shutdown the world. */
294 if (howto & RB_POWEROFF)
295 kern_psignal(initproc, SIGUSR2);
296 else if (howto & RB_POWERCYCLE)
297 kern_psignal(initproc, SIGWINCH);
298 else if (howto & RB_HALT)
299 kern_psignal(initproc, SIGUSR1);
301 kern_psignal(initproc, SIGINT);
302 PROC_UNLOCK(initproc);
304 /* No init(8) running, so simply reboot. */
305 kern_reboot(howto | RB_NOSYNC);
318 if (ts.tv_sec >= 86400) {
319 printf("%ldd", (long)ts.tv_sec / 86400);
323 if (f || ts.tv_sec >= 3600) {
324 printf("%ldh", (long)ts.tv_sec / 3600);
328 if (f || ts.tv_sec >= 60) {
329 printf("%ldm", (long)ts.tv_sec / 60);
333 printf("%lds\n", (long)ts.tv_sec);
337 doadump(boolean_t textdump)
345 if (dumper.dumper == NULL)
349 dumptid = curthread->td_tid;
354 if (textdump && textdump_pending) {
356 textdump_dumpsys(&dumper);
360 error = dumpsys(&dumper);
367 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
370 kern_reboot(int howto)
376 * Bind us to the first CPU so that all shutdown code runs there. Some
377 * systems don't shutdown properly (i.e., ACPI power off) if we
378 * run on another processor.
380 if (!SCHEDULER_STOPPED()) {
381 thread_lock(curthread);
382 sched_bind(curthread, CPU_FIRST());
383 thread_unlock(curthread);
384 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
385 ("boot: not running on cpu 0"));
388 /* We're in the process of rebooting. */
391 /* We are out of the debugger now. */
395 * Do any callouts that should be done BEFORE syncing the filesystems.
397 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
400 * Now sync filesystems
402 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
404 bufshutdown(show_busybufs);
412 * Ok, now do things that assume all filesystem activity has
415 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
417 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
420 /* Now that we're going to really halt the system... */
421 EVENTHANDLER_INVOKE(shutdown_final, howto);
423 for(;;) ; /* safety against shutdown_reset not working */
428 * The system call that results in changing the rootfs.
433 struct vnode *oldrootvnode, *vp;
434 struct mount *mp, *devmp;
437 if (curproc != initproc)
441 * Mark the filesystem containing currently-running executable
442 * (the temporary copy of init(8)) busy.
444 vp = curproc->p_textvp;
445 error = vn_lock(vp, LK_SHARED);
449 error = vfs_busy(mp, MBF_NOWAIT);
453 error = vfs_busy(mp, 0);
454 vn_lock(vp, LK_SHARED | LK_RETRY);
460 if (vp->v_iflag & VI_DOOMED) {
469 * Remove the filesystem containing currently-running executable
470 * from the mount list, to prevent it from being unmounted
471 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
473 * Also preserve /dev - forcibly unmounting it could cause driver
481 mtx_lock(&mountlist_mtx);
482 TAILQ_REMOVE(&mountlist, mp, mnt_list);
483 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
484 mtx_unlock(&mountlist_mtx);
486 oldrootvnode = rootvnode;
489 * Unmount everything except for the two filesystems preserved above.
494 * Add /dev back; vfs_mountroot() will move it into its new place.
496 mtx_lock(&mountlist_mtx);
497 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
498 mtx_unlock(&mountlist_mtx);
503 * Mount the new rootfs.
508 * Update all references to the old rootvnode.
510 mountcheckdirs(oldrootvnode, rootvnode);
513 * Add the temporary filesystem back and unbusy it.
515 mtx_lock(&mountlist_mtx);
516 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
517 mtx_unlock(&mountlist_mtx);
524 * If the shutdown was a clean halt, behave accordingly.
527 shutdown_halt(void *junk, int howto)
530 if (howto & RB_HALT) {
532 printf("The operating system has halted.\n");
533 printf("Please press any key to reboot.\n\n");
535 case -1: /* No console, just die */
546 * Check to see if the system paniced, pause and then reboot
547 * according to the specified delay.
550 shutdown_panic(void *junk, int howto)
554 if (howto & RB_DUMP) {
555 if (panic_reboot_wait_time != 0) {
556 if (panic_reboot_wait_time != -1) {
557 printf("Automatic reboot in %d seconds - "
558 "press a key on the console to abort\n",
559 panic_reboot_wait_time);
560 for (loop = panic_reboot_wait_time * 10;
562 DELAY(1000 * 100); /* 1/10th second */
563 /* Did user type a key? */
564 if (cncheckc() != -1)
570 } else { /* zero time specified - reboot NOW */
573 printf("--> Press a key on the console to reboot,\n");
574 printf("--> or switch off the system now.\n");
580 * Everything done, now reset
583 shutdown_reset(void *junk, int howto)
586 printf("Rebooting...\n");
587 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
590 * Acquiring smp_ipi_mtx here has a double effect:
591 * - it disables interrupts avoiding CPU0 preemption
592 * by fast handlers (thus deadlocking against other CPUs)
593 * - it avoids deadlocks against smp_rendezvous() or, more
594 * generally, threads busy-waiting, with this spinlock held,
595 * and waiting for responses by threads on other CPUs
596 * (ie. smp_tlb_shootdown()).
598 * For the !SMP case it just needs to handle the former problem.
601 mtx_lock_spin(&smp_ipi_mtx);
606 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
608 /* NOTREACHED */ /* assuming reset worked */
611 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
612 static int kassert_warn_only = 0;
614 static int kassert_do_kdb = 0;
617 static int kassert_do_ktr = 0;
619 static int kassert_do_log = 1;
620 static int kassert_log_pps_limit = 4;
621 static int kassert_log_mute_at = 0;
622 static int kassert_log_panic_at = 0;
623 static int kassert_warnings = 0;
625 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
627 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
628 &kassert_warn_only, 0,
629 "KASSERT triggers a panic (1) or just a warning (0)");
632 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
633 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
637 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
639 "KASSERT does a KTR, set this to the KTRMASK you want");
642 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
643 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
645 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
646 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
648 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
649 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
651 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
652 &kassert_log_pps_limit, 0, "limit number of log messages per second");
654 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
655 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
657 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
659 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
660 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
661 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
664 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
668 error = sysctl_wire_old_buffer(req, sizeof(int));
671 error = sysctl_handle_int(oidp, &i, 0, req);
673 if (error != 0 || req->newptr == NULL)
675 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
680 * Called by KASSERT, this decides if we will panic
681 * or if we will log via printf and/or ktr.
684 kassert_panic(const char *fmt, ...)
686 static char buf[256];
690 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
694 * panic if we're not just warning, or if we've exceeded
695 * kassert_log_panic_at warnings.
697 if (!kassert_warn_only ||
698 (kassert_log_panic_at > 0 &&
699 kassert_warnings >= kassert_log_panic_at)) {
709 * log if we've not yet met the mute limit.
711 if (kassert_do_log &&
712 (kassert_log_mute_at == 0 ||
713 kassert_warnings < kassert_log_mute_at)) {
714 static struct timeval lasterr;
717 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
718 printf("KASSERT failed: %s\n", buf);
723 if (kassert_do_kdb) {
724 kdb_enter(KDB_WHY_KASSERT, buf);
727 atomic_add_int(&kassert_warnings, 1);
732 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
733 * and then reboots. If we are called twice, then we avoid trying to sync
734 * the disks as this often leads to recursive panics.
737 panic(const char *fmt, ...)
746 vpanic(const char *fmt, va_list ap)
751 struct thread *td = curthread;
752 int bootopt, newpanic;
753 static char buf[256];
759 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
760 * concurrently entering panic. Only the winner will proceed
763 if (panicstr == NULL && !kdb_active) {
764 other_cpus = all_cpus;
765 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
766 stop_cpus_hard(other_cpus);
771 * Ensure that the scheduler is stopped while panicking, even if panic
772 * has been entered from kdb.
774 td->td_stopsched = 1;
776 bootopt = RB_AUTOBOOT;
779 bootopt |= RB_NOSYNC;
787 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
790 printf("panic: %s\n", buf);
797 printf("cpuid = %d\n", PCPU_GET(cpuid));
799 printf("time = %jd\n", (intmax_t )time_second);
801 if (newpanic && trace_on_panic)
803 if (debugger_on_panic)
804 kdb_enter(KDB_WHY_PANIC, "panic");
806 /*thread_lock(td); */
807 td->td_flags |= TDF_INPANIC;
808 /* thread_unlock(td); */
810 bootopt |= RB_NOSYNC;
811 if (poweroff_on_panic)
812 bootopt |= RB_POWEROFF;
813 if (powercycle_on_panic)
814 bootopt |= RB_POWERCYCLE;
815 kern_reboot(bootopt);
819 * Support for poweroff delay.
821 * Please note that setting this delay too short might power off your machine
822 * before the write cache on your hard disk has been flushed, leading to
823 * soft-updates inconsistencies.
825 #ifndef POWEROFF_DELAY
826 # define POWEROFF_DELAY 5000
828 static int poweroff_delay = POWEROFF_DELAY;
830 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
831 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
834 poweroff_wait(void *junk, int howto)
837 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
839 DELAY(poweroff_delay * 1000);
843 * Some system processes (e.g. syncer) need to be stopped at appropriate
844 * points in their main loops prior to a system shutdown, so that they
845 * won't interfere with the shutdown process (e.g. by holding a disk buf
846 * to cause sync to fail). For each of these system processes, register
847 * shutdown_kproc() as a handler for one of shutdown events.
849 static int kproc_shutdown_wait = 60;
850 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
851 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
854 kproc_shutdown(void *arg, int howto)
862 p = (struct proc *)arg;
863 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
864 kproc_shutdown_wait, p->p_comm);
865 error = kproc_suspend(p, kproc_shutdown_wait * hz);
867 if (error == EWOULDBLOCK)
868 printf("timed out\n");
874 kthread_shutdown(void *arg, int howto)
882 td = (struct thread *)arg;
883 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
884 kproc_shutdown_wait, td->td_name);
885 error = kthread_suspend(td, kproc_shutdown_wait * hz);
887 if (error == EWOULDBLOCK)
888 printf("timed out\n");
893 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
894 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
895 dumpdevname, 0, "Device for kernel dumps");
897 static int _dump_append(struct dumperinfo *di, void *virtual,
898 vm_offset_t physical, size_t length);
901 static struct kerneldumpcrypto *
902 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
903 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
905 struct kerneldumpcrypto *kdc;
906 struct kerneldumpkey *kdk;
907 uint32_t dumpkeysize;
909 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
910 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
912 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
914 kdc->kdc_encryption = encryption;
915 switch (kdc->kdc_encryption) {
916 case KERNELDUMP_ENC_AES_256_CBC:
917 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
924 kdc->kdc_dumpkeysize = dumpkeysize;
925 kdk = kdc->kdc_dumpkey;
926 kdk->kdk_encryption = kdc->kdc_encryption;
927 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
928 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
929 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
933 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
939 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
941 uint8_t hash[SHA256_DIGEST_LENGTH];
943 struct kerneldumpkey *kdk;
952 * When a user enters ddb it can write a crash dump multiple times.
953 * Each time it should be encrypted using a different IV.
956 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
957 SHA256_Final(hash, &ctx);
958 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
960 switch (kdc->kdc_encryption) {
961 case KERNELDUMP_ENC_AES_256_CBC:
962 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
973 kdk = kdc->kdc_dumpkey;
974 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
976 explicit_bzero(hash, sizeof(hash));
981 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
986 return (kdc->kdc_dumpkeysize);
991 static struct kerneldumpgz *
992 kerneldumpgz_create(struct dumperinfo *di, uint8_t compression)
994 struct kerneldumpgz *kdgz;
996 if (compression != KERNELDUMP_COMP_GZIP)
998 kdgz = malloc(sizeof(*kdgz), M_DUMPER, M_WAITOK | M_ZERO);
999 kdgz->kdgz_stream = gzio_init(kerneldumpgz_write_cb, GZIO_DEFLATE,
1000 di->maxiosize, kerneldump_gzlevel, di);
1001 if (kdgz->kdgz_stream == NULL) {
1002 free(kdgz, M_DUMPER);
1005 kdgz->kdgz_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1010 kerneldumpgz_destroy(struct dumperinfo *di)
1012 struct kerneldumpgz *kdgz;
1017 gzio_fini(kdgz->kdgz_stream);
1018 explicit_bzero(kdgz->kdgz_buf, di->maxiosize);
1019 free(kdgz->kdgz_buf, M_DUMPER);
1020 free(kdgz, M_DUMPER);
1024 /* Registration of dumpers */
1026 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1027 uint8_t compression, uint8_t encryption, const uint8_t *key,
1028 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1033 error = priv_check(td, PRIV_SETDUMPER);
1041 if (dumper.dumper != NULL)
1044 dumper.blockbuf = NULL;
1048 if (encryption != KERNELDUMP_ENC_NONE) {
1050 dumper.kdc = kerneldumpcrypto_create(di->blocksize, encryption,
1051 key, encryptedkeysize, encryptedkey);
1052 if (dumper.kdc == NULL) {
1062 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1063 if (wantcopy >= sizeof(dumpdevname)) {
1064 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1065 devname, dumpdevname);
1068 if (compression != KERNELDUMP_COMP_NONE) {
1071 * We currently can't support simultaneous encryption and
1074 if (encryption != KERNELDUMP_ENC_NONE) {
1078 dumper.kdgz = kerneldumpgz_create(&dumper, compression);
1079 if (dumper.kdgz == NULL) {
1089 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1093 if (dumper.kdc != NULL) {
1094 explicit_bzero(dumper.kdc, sizeof(*dumper.kdc) +
1095 dumper.kdc->kdc_dumpkeysize);
1096 free(dumper.kdc, M_EKCD);
1101 kerneldumpgz_destroy(&dumper);
1104 if (dumper.blockbuf != NULL) {
1105 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1106 free(dumper.blockbuf, M_DUMPER);
1108 explicit_bzero(&dumper, sizeof(dumper));
1109 dumpdevname[0] = '\0';
1114 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1117 if (length != 0 && (offset < di->mediaoffset ||
1118 offset - di->mediaoffset + length > di->mediasize)) {
1119 printf("Attempt to write outside dump device boundaries.\n"
1120 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1121 (intmax_t)offset, (intmax_t)di->mediaoffset,
1122 (uintmax_t)length, (intmax_t)di->mediasize);
1125 if (length % di->blocksize != 0) {
1126 printf("Attempt to write partial block of length %ju.\n",
1130 if (offset % di->blocksize != 0) {
1131 printf("Attempt to write at unaligned offset %jd.\n",
1141 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1144 switch (kdc->kdc_encryption) {
1145 case KERNELDUMP_ENC_AES_256_CBC:
1146 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1147 8 * size, buf) <= 0) {
1150 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1151 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1162 /* Encrypt data and call dumper. */
1164 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1165 vm_offset_t physical, off_t offset, size_t length)
1167 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1168 struct kerneldumpcrypto *kdc;
1174 while (length > 0) {
1175 nbytes = MIN(length, sizeof(buf));
1176 bcopy(virtual, buf, nbytes);
1178 if (dump_encrypt(kdc, buf, nbytes) != 0)
1181 error = dump_write(di, buf, physical, offset, nbytes);
1186 virtual = (void *)((uint8_t *)virtual + nbytes);
1194 dump_write_key(struct dumperinfo *di, off_t offset)
1196 struct kerneldumpcrypto *kdc;
1201 return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1202 kdc->kdc_dumpkeysize));
1208 kerneldumpgz_write_cb(void *base, size_t length, off_t offset, void *arg)
1210 struct dumperinfo *di;
1211 size_t resid, rlength;
1216 if (length % di->blocksize != 0) {
1218 * This must be the final write after flushing the compression
1219 * stream. Write as many full blocks as possible and stash the
1220 * residual data in the dumper's block buffer. It will be
1221 * padded and written in dump_finish().
1223 rlength = rounddown(length, di->blocksize);
1225 error = _dump_append(di, base, 0, rlength);
1229 resid = length - rlength;
1230 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1231 di->kdgz->kdgz_resid = resid;
1234 return (_dump_append(di, base, 0, length));
1239 * Write a kerneldumpheader at the specified offset. The header structure is 512
1240 * bytes in size, but we must pad to the device sector size.
1243 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1249 hdrsz = sizeof(*kdh);
1250 if (hdrsz > di->blocksize)
1253 if (hdrsz == di->blocksize)
1257 memset(buf, 0, di->blocksize);
1258 memcpy(buf, kdh, hdrsz);
1261 return (dump_write(di, buf, 0, offset, di->blocksize));
1265 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1266 * protect us from metadata and metadata from us.
1268 #define SIZEOF_METADATA (64 * 1024)
1271 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1272 * if requested, and make sure that we have enough space on the dump device.
1274 * We set things up so that the dump ends before the last sector of the dump
1275 * device, at which the trailing header is written.
1277 * +-----------+------+-----+----------------------------+------+
1278 * | | lhdr | key | ... kernel dump ... | thdr |
1279 * +-----------+------+-----+----------------------------+------+
1280 * 1 blk opt <------- dump extent --------> 1 blk
1282 * Dumps written using dump_append() start at the beginning of the extent.
1283 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1284 * will not. The true length of the dump is recorded in the leading and trailing
1285 * headers once the dump has been completed.
1288 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1290 uint64_t dumpextent;
1294 int error = kerneldumpcrypto_init(di->kdc);
1297 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1302 dumpextent = dtoh64(kdh->dumpextent);
1303 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1306 if (di->kdgz != NULL) {
1308 * We don't yet know how much space the compressed dump
1309 * will occupy, so try to use the whole swap partition
1310 * (minus the first 64KB) in the hope that the
1311 * compressed dump will fit. If that doesn't turn out to
1312 * be enouch, the bounds checking in dump_write()
1313 * will catch us and cause the dump to fail.
1315 dumpextent = di->mediasize - SIZEOF_METADATA -
1316 2 * di->blocksize - keysize;
1317 kdh->dumpextent = htod64(dumpextent);
1323 /* The offset at which to begin writing the dump. */
1324 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1331 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1337 if (di->kdc != NULL)
1338 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1342 error = dump_write(di, virtual, physical, di->dumpoff, length);
1344 di->dumpoff += length;
1349 * Write to the dump device starting at dumpoff. When compression is enabled,
1350 * writes to the device will be performed using a callback that gets invoked
1351 * when the compression stream's output buffer is full.
1354 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1360 if (di->kdgz != NULL) {
1361 /* Bounce through a buffer to avoid gzip CRC errors. */
1362 if (length > di->maxiosize)
1364 buf = di->kdgz->kdgz_buf;
1365 memmove(buf, virtual, length);
1366 return (gzio_write(di->kdgz->kdgz_stream, buf, length));
1369 return (_dump_append(di, virtual, physical, length));
1373 * Write to the dump device at the specified offset.
1376 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1377 off_t offset, size_t length)
1381 error = dump_check_bounds(di, offset, length);
1384 return (di->dumper(di->priv, virtual, physical, offset, length));
1388 * Perform kernel dump finalization: flush the compression stream, if necessary,
1389 * write the leading and trailing kernel dump headers now that we know the true
1390 * length of the dump, and optionally write the encryption key following the
1394 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1400 extent = dtoh64(kdh->dumpextent);
1403 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1409 if (di->kdgz != NULL) {
1410 error = gzio_flush(di->kdgz->kdgz_stream);
1411 if (error == EAGAIN) {
1412 /* We have residual data in di->blockbuf. */
1413 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1415 di->dumpoff += di->kdgz->kdgz_resid;
1416 di->kdgz->kdgz_resid = 0;
1422 * We now know the size of the compressed dump, so update the
1423 * header accordingly and recompute parity.
1425 kdh->dumplength = htod64(di->dumpoff -
1426 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1428 kdh->parity = kerneldump_parity(kdh);
1430 gzio_reset(di->kdgz->kdgz_stream);
1435 * Write kerneldump headers at the beginning and end of the dump extent.
1436 * Write the key after the leading header.
1438 error = dump_write_header(di, kdh,
1439 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1445 error = dump_write_key(di,
1446 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1451 error = dump_write_header(di, kdh,
1452 di->mediaoffset + di->mediasize - di->blocksize);
1456 (void)dump_write(di, NULL, 0, 0, 0);
1461 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1462 char *magic, uint32_t archver, uint64_t dumplen)
1466 bzero(kdh, sizeof(*kdh));
1467 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1468 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1469 kdh->version = htod32(KERNELDUMPVERSION);
1470 kdh->architectureversion = htod32(archver);
1471 kdh->dumplength = htod64(dumplen);
1472 kdh->dumpextent = kdh->dumplength;
1473 kdh->dumptime = htod64(time_second);
1475 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdc));
1477 kdh->dumpkeysize = 0;
1479 kdh->blocksize = htod32(di->blocksize);
1480 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1481 dstsize = sizeof(kdh->versionstring);
1482 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1483 kdh->versionstring[dstsize - 2] = '\n';
1484 if (panicstr != NULL)
1485 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1487 if (di->kdgz != NULL)
1488 kdh->compression = KERNELDUMP_COMP_GZIP;
1490 kdh->parity = kerneldump_parity(kdh);
1494 DB_SHOW_COMMAND(panic, db_show_panic)
1497 if (panicstr == NULL)
1498 db_printf("panicstr not set\n");
1500 db_printf("panic: %s\n", panicstr);