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>
65 #include <sys/mount.h>
68 #include <sys/reboot.h>
69 #include <sys/resourcevar.h>
70 #include <sys/rwlock.h>
71 #include <sys/sched.h>
73 #include <sys/sysctl.h>
74 #include <sys/sysproto.h>
75 #include <sys/vnode.h>
76 #include <sys/watchdog.h>
78 #include <crypto/rijndael/rijndael-api-fst.h>
79 #include <crypto/sha2/sha256.h>
83 #include <machine/cpu.h>
84 #include <machine/dump.h>
85 #include <machine/pcb.h>
86 #include <machine/smp.h>
88 #include <security/mac/mac_framework.h>
91 #include <vm/vm_object.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_pager.h>
94 #include <vm/swap_pager.h>
96 #include <sys/signalvar.h>
98 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
100 #ifndef PANIC_REBOOT_WAIT_TIME
101 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
103 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
104 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
105 &panic_reboot_wait_time, 0,
106 "Seconds to wait before rebooting after a panic");
109 * Note that stdarg.h and the ANSI style va_start macro is used for both
110 * ANSI and traditional C compilers.
112 #include <machine/stdarg.h>
115 #ifdef KDB_UNATTENDED
116 int debugger_on_panic = 0;
118 int debugger_on_panic = 1;
120 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
121 CTLFLAG_RWTUN | CTLFLAG_SECURE,
122 &debugger_on_panic, 0, "Run debugger on kernel panic");
125 static int trace_on_panic = 1;
127 static int trace_on_panic = 0;
129 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
130 CTLFLAG_RWTUN | CTLFLAG_SECURE,
131 &trace_on_panic, 0, "Print stack trace on kernel panic");
134 static int sync_on_panic = 0;
135 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
136 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
138 static bool poweroff_on_panic = 0;
139 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
140 &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
142 static bool powercycle_on_panic = 0;
143 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
144 &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
146 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
147 "Shutdown environment");
150 static int show_busybufs;
152 static int show_busybufs = 1;
154 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
155 &show_busybufs, 0, "");
157 int suspend_blocked = 0;
158 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
159 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
162 FEATURE(ekcd, "Encrypted kernel crash dumps support");
164 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
166 struct kerneldumpcrypto {
167 uint8_t kdc_encryption;
168 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
170 cipherInstance kdc_ci;
171 uint32_t kdc_dumpkeysize;
172 struct kerneldumpkey kdc_dumpkey[];
176 struct kerneldumpcomp {
177 struct compressor *kdc_stream;
182 static struct kerneldumpcomp *kerneldumpcomp_create(struct dumperinfo *di,
183 uint8_t compression);
184 static void kerneldumpcomp_destroy(struct dumperinfo *di);
185 static int kerneldumpcomp_write_cb(void *base, size_t len, off_t off, void *arg);
187 static int kerneldump_gzlevel = 6;
188 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
189 &kerneldump_gzlevel, 0,
190 "Kernel crash dump compression level");
193 * Variable panicstr contains argument to first call to panic; used as flag
194 * to indicate that the kernel has already called panic.
196 const char *panicstr;
198 int dumping; /* system is dumping */
199 int rebooting; /* system is rebooting */
200 static struct dumperinfo dumper; /* our selected dumper */
202 /* Context information for dump-debuggers. */
203 static struct pcb dumppcb; /* Registers. */
204 lwpid_t dumptid; /* Thread ID. */
206 static struct cdevsw reroot_cdevsw = {
207 .d_version = D_VERSION,
211 static void poweroff_wait(void *, int);
212 static void shutdown_halt(void *junk, int howto);
213 static void shutdown_panic(void *junk, int howto);
214 static void shutdown_reset(void *junk, int howto);
215 static int kern_reroot(void);
217 /* register various local shutdown events */
219 shutdown_conf(void *unused)
222 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
224 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
225 SHUTDOWN_PRI_LAST + 100);
226 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
227 SHUTDOWN_PRI_LAST + 100);
228 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
229 SHUTDOWN_PRI_LAST + 200);
232 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
235 * The only reason this exists is to create the /dev/reroot/ directory,
236 * used by reroot code in init(8) as a mountpoint for tmpfs.
239 reroot_conf(void *unused)
244 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
245 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
247 printf("%s: failed to create device node, error %d",
252 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
255 * The system call that results in a reboot.
259 sys_reboot(struct thread *td, struct reboot_args *uap)
265 error = mac_system_check_reboot(td->td_ucred, uap->opt);
268 error = priv_check(td, PRIV_REBOOT);
270 if (uap->opt & RB_REROOT) {
271 error = kern_reroot();
274 kern_reboot(uap->opt);
282 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
285 shutdown_nice(int howto)
288 if (initproc != NULL) {
289 /* Send a signal to init(8) and have it shutdown the world. */
291 if (howto & RB_POWEROFF)
292 kern_psignal(initproc, SIGUSR2);
293 else if (howto & RB_POWERCYCLE)
294 kern_psignal(initproc, SIGWINCH);
295 else if (howto & RB_HALT)
296 kern_psignal(initproc, SIGUSR1);
298 kern_psignal(initproc, SIGINT);
299 PROC_UNLOCK(initproc);
301 /* No init(8) running, so simply reboot. */
302 kern_reboot(howto | RB_NOSYNC);
315 if (ts.tv_sec >= 86400) {
316 printf("%ldd", (long)ts.tv_sec / 86400);
320 if (f || ts.tv_sec >= 3600) {
321 printf("%ldh", (long)ts.tv_sec / 3600);
325 if (f || ts.tv_sec >= 60) {
326 printf("%ldm", (long)ts.tv_sec / 60);
330 printf("%lds\n", (long)ts.tv_sec);
334 doadump(boolean_t textdump)
342 if (dumper.dumper == NULL)
346 dumptid = curthread->td_tid;
351 if (textdump && textdump_pending) {
353 textdump_dumpsys(&dumper);
357 error = dumpsys(&dumper);
364 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
367 kern_reboot(int howto)
373 * Bind us to the first CPU so that all shutdown code runs there. Some
374 * systems don't shutdown properly (i.e., ACPI power off) if we
375 * run on another processor.
377 if (!SCHEDULER_STOPPED()) {
378 thread_lock(curthread);
379 sched_bind(curthread, CPU_FIRST());
380 thread_unlock(curthread);
381 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
382 ("boot: not running on cpu 0"));
385 /* We're in the process of rebooting. */
388 /* We are out of the debugger now. */
392 * Do any callouts that should be done BEFORE syncing the filesystems.
394 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
397 * Now sync filesystems
399 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
401 bufshutdown(show_busybufs);
409 * Ok, now do things that assume all filesystem activity has
412 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
414 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
417 /* Now that we're going to really halt the system... */
418 EVENTHANDLER_INVOKE(shutdown_final, howto);
420 for(;;) ; /* safety against shutdown_reset not working */
425 * The system call that results in changing the rootfs.
430 struct vnode *oldrootvnode, *vp;
431 struct mount *mp, *devmp;
434 if (curproc != initproc)
438 * Mark the filesystem containing currently-running executable
439 * (the temporary copy of init(8)) busy.
441 vp = curproc->p_textvp;
442 error = vn_lock(vp, LK_SHARED);
446 error = vfs_busy(mp, MBF_NOWAIT);
450 error = vfs_busy(mp, 0);
451 vn_lock(vp, LK_SHARED | LK_RETRY);
457 if (vp->v_iflag & VI_DOOMED) {
466 * Remove the filesystem containing currently-running executable
467 * from the mount list, to prevent it from being unmounted
468 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
470 * Also preserve /dev - forcibly unmounting it could cause driver
478 mtx_lock(&mountlist_mtx);
479 TAILQ_REMOVE(&mountlist, mp, mnt_list);
480 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
481 mtx_unlock(&mountlist_mtx);
483 oldrootvnode = rootvnode;
486 * Unmount everything except for the two filesystems preserved above.
491 * Add /dev back; vfs_mountroot() will move it into its new place.
493 mtx_lock(&mountlist_mtx);
494 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
495 mtx_unlock(&mountlist_mtx);
500 * Mount the new rootfs.
505 * Update all references to the old rootvnode.
507 mountcheckdirs(oldrootvnode, rootvnode);
510 * Add the temporary filesystem back and unbusy it.
512 mtx_lock(&mountlist_mtx);
513 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
514 mtx_unlock(&mountlist_mtx);
521 * If the shutdown was a clean halt, behave accordingly.
524 shutdown_halt(void *junk, int howto)
527 if (howto & RB_HALT) {
529 printf("The operating system has halted.\n");
530 printf("Please press any key to reboot.\n\n");
532 case -1: /* No console, just die */
542 * Check to see if the system paniced, pause and then reboot
543 * according to the specified delay.
546 shutdown_panic(void *junk, int howto)
550 if (howto & RB_DUMP) {
551 if (panic_reboot_wait_time != 0) {
552 if (panic_reboot_wait_time != -1) {
553 printf("Automatic reboot in %d seconds - "
554 "press a key on the console to abort\n",
555 panic_reboot_wait_time);
556 for (loop = panic_reboot_wait_time * 10;
558 DELAY(1000 * 100); /* 1/10th second */
559 /* Did user type a key? */
560 if (cncheckc() != -1)
566 } else { /* zero time specified - reboot NOW */
569 printf("--> Press a key on the console to reboot,\n");
570 printf("--> or switch off the system now.\n");
576 * Everything done, now reset
579 shutdown_reset(void *junk, int howto)
582 printf("Rebooting...\n");
583 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
586 * Acquiring smp_ipi_mtx here has a double effect:
587 * - it disables interrupts avoiding CPU0 preemption
588 * by fast handlers (thus deadlocking against other CPUs)
589 * - it avoids deadlocks against smp_rendezvous() or, more
590 * generally, threads busy-waiting, with this spinlock held,
591 * and waiting for responses by threads on other CPUs
592 * (ie. smp_tlb_shootdown()).
594 * For the !SMP case it just needs to handle the former problem.
597 mtx_lock_spin(&smp_ipi_mtx);
602 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
604 /* NOTREACHED */ /* assuming reset worked */
607 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
608 static int kassert_warn_only = 0;
610 static int kassert_do_kdb = 0;
613 static int kassert_do_ktr = 0;
615 static int kassert_do_log = 1;
616 static int kassert_log_pps_limit = 4;
617 static int kassert_log_mute_at = 0;
618 static int kassert_log_panic_at = 0;
619 static int kassert_warnings = 0;
621 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
623 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
624 &kassert_warn_only, 0,
625 "KASSERT triggers a panic (1) or just a warning (0)");
628 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
629 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
633 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
635 "KASSERT does a KTR, set this to the KTRMASK you want");
638 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
639 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
641 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
642 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
644 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
645 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
647 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
648 &kassert_log_pps_limit, 0, "limit number of log messages per second");
650 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
651 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
653 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
655 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
656 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
657 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
660 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
664 error = sysctl_wire_old_buffer(req, sizeof(int));
667 error = sysctl_handle_int(oidp, &i, 0, req);
669 if (error != 0 || req->newptr == NULL)
671 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
676 * Called by KASSERT, this decides if we will panic
677 * or if we will log via printf and/or ktr.
680 kassert_panic(const char *fmt, ...)
682 static char buf[256];
686 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
690 * panic if we're not just warning, or if we've exceeded
691 * kassert_log_panic_at warnings.
693 if (!kassert_warn_only ||
694 (kassert_log_panic_at > 0 &&
695 kassert_warnings >= kassert_log_panic_at)) {
705 * log if we've not yet met the mute limit.
707 if (kassert_do_log &&
708 (kassert_log_mute_at == 0 ||
709 kassert_warnings < kassert_log_mute_at)) {
710 static struct timeval lasterr;
713 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
714 printf("KASSERT failed: %s\n", buf);
719 if (kassert_do_kdb) {
720 kdb_enter(KDB_WHY_KASSERT, buf);
723 atomic_add_int(&kassert_warnings, 1);
728 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
729 * and then reboots. If we are called twice, then we avoid trying to sync
730 * the disks as this often leads to recursive panics.
733 panic(const char *fmt, ...)
742 vpanic(const char *fmt, va_list ap)
747 struct thread *td = curthread;
748 int bootopt, newpanic;
749 static char buf[256];
755 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
756 * concurrently entering panic. Only the winner will proceed
759 if (panicstr == NULL && !kdb_active) {
760 other_cpus = all_cpus;
761 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
762 stop_cpus_hard(other_cpus);
767 * Ensure that the scheduler is stopped while panicking, even if panic
768 * has been entered from kdb.
770 td->td_stopsched = 1;
772 bootopt = RB_AUTOBOOT;
775 bootopt |= RB_NOSYNC;
783 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
786 printf("panic: %s\n", buf);
793 printf("cpuid = %d\n", PCPU_GET(cpuid));
795 printf("time = %jd\n", (intmax_t )time_second);
797 if (newpanic && trace_on_panic)
799 if (debugger_on_panic)
800 kdb_enter(KDB_WHY_PANIC, "panic");
802 /*thread_lock(td); */
803 td->td_flags |= TDF_INPANIC;
804 /* thread_unlock(td); */
806 bootopt |= RB_NOSYNC;
807 if (poweroff_on_panic)
808 bootopt |= RB_POWEROFF;
809 if (powercycle_on_panic)
810 bootopt |= RB_POWERCYCLE;
811 kern_reboot(bootopt);
815 * Support for poweroff delay.
817 * Please note that setting this delay too short might power off your machine
818 * before the write cache on your hard disk has been flushed, leading to
819 * soft-updates inconsistencies.
821 #ifndef POWEROFF_DELAY
822 # define POWEROFF_DELAY 5000
824 static int poweroff_delay = POWEROFF_DELAY;
826 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
827 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
830 poweroff_wait(void *junk, int howto)
833 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
835 DELAY(poweroff_delay * 1000);
839 * Some system processes (e.g. syncer) need to be stopped at appropriate
840 * points in their main loops prior to a system shutdown, so that they
841 * won't interfere with the shutdown process (e.g. by holding a disk buf
842 * to cause sync to fail). For each of these system processes, register
843 * shutdown_kproc() as a handler for one of shutdown events.
845 static int kproc_shutdown_wait = 60;
846 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
847 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
850 kproc_shutdown(void *arg, int howto)
858 p = (struct proc *)arg;
859 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
860 kproc_shutdown_wait, p->p_comm);
861 error = kproc_suspend(p, kproc_shutdown_wait * hz);
863 if (error == EWOULDBLOCK)
864 printf("timed out\n");
870 kthread_shutdown(void *arg, int howto)
878 td = (struct thread *)arg;
879 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
880 kproc_shutdown_wait, td->td_name);
881 error = kthread_suspend(td, kproc_shutdown_wait * hz);
883 if (error == EWOULDBLOCK)
884 printf("timed out\n");
889 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
890 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
891 dumpdevname, 0, "Device for kernel dumps");
893 static int _dump_append(struct dumperinfo *di, void *virtual,
894 vm_offset_t physical, size_t length);
897 static struct kerneldumpcrypto *
898 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
899 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
901 struct kerneldumpcrypto *kdc;
902 struct kerneldumpkey *kdk;
903 uint32_t dumpkeysize;
905 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
906 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
908 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
910 kdc->kdc_encryption = encryption;
911 switch (kdc->kdc_encryption) {
912 case KERNELDUMP_ENC_AES_256_CBC:
913 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
920 kdc->kdc_dumpkeysize = dumpkeysize;
921 kdk = kdc->kdc_dumpkey;
922 kdk->kdk_encryption = kdc->kdc_encryption;
923 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
924 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
925 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
929 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
935 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
937 uint8_t hash[SHA256_DIGEST_LENGTH];
939 struct kerneldumpkey *kdk;
948 * When a user enters ddb it can write a crash dump multiple times.
949 * Each time it should be encrypted using a different IV.
952 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
953 SHA256_Final(hash, &ctx);
954 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
956 switch (kdc->kdc_encryption) {
957 case KERNELDUMP_ENC_AES_256_CBC:
958 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
969 kdk = kdc->kdc_dumpkey;
970 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
972 explicit_bzero(hash, sizeof(hash));
977 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
982 return (kdc->kdc_dumpkeysize);
986 static struct kerneldumpcomp *
987 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
989 struct kerneldumpcomp *kdcomp;
991 if (compression != KERNELDUMP_COMP_GZIP)
993 kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
994 kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
995 COMPRESS_GZIP, di->maxiosize, kerneldump_gzlevel, di);
996 if (kdcomp->kdc_stream == NULL) {
997 free(kdcomp, M_DUMPER);
1000 kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1005 kerneldumpcomp_destroy(struct dumperinfo *di)
1007 struct kerneldumpcomp *kdcomp;
1009 kdcomp = di->kdcomp;
1012 compressor_fini(kdcomp->kdc_stream);
1013 explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1014 free(kdcomp->kdc_buf, M_DUMPER);
1015 free(kdcomp, M_DUMPER);
1018 /* Registration of dumpers */
1020 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1021 uint8_t compression, uint8_t encryption, const uint8_t *key,
1022 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1027 error = priv_check(td, PRIV_SETDUMPER);
1035 if (dumper.dumper != NULL)
1038 dumper.blockbuf = NULL;
1039 dumper.kdcrypto = NULL;
1040 dumper.kdcomp = NULL;
1042 if (encryption != KERNELDUMP_ENC_NONE) {
1044 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1045 encryption, key, encryptedkeysize, encryptedkey);
1046 if (dumper.kdcrypto == NULL) {
1056 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1057 if (wantcopy >= sizeof(dumpdevname)) {
1058 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1059 devname, dumpdevname);
1062 if (compression != KERNELDUMP_COMP_NONE) {
1064 * We currently can't support simultaneous encryption and
1067 if (encryption != KERNELDUMP_ENC_NONE) {
1071 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1072 if (dumper.kdcomp == NULL) {
1078 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1082 if (dumper.kdcrypto != NULL) {
1083 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1084 dumper.kdcrypto->kdc_dumpkeysize);
1085 free(dumper.kdcrypto, M_EKCD);
1089 kerneldumpcomp_destroy(&dumper);
1091 if (dumper.blockbuf != NULL) {
1092 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1093 free(dumper.blockbuf, M_DUMPER);
1095 explicit_bzero(&dumper, sizeof(dumper));
1096 dumpdevname[0] = '\0';
1101 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1104 if (length != 0 && (offset < di->mediaoffset ||
1105 offset - di->mediaoffset + length > di->mediasize)) {
1106 printf("Attempt to write outside dump device boundaries.\n"
1107 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1108 (intmax_t)offset, (intmax_t)di->mediaoffset,
1109 (uintmax_t)length, (intmax_t)di->mediasize);
1112 if (length % di->blocksize != 0) {
1113 printf("Attempt to write partial block of length %ju.\n",
1117 if (offset % di->blocksize != 0) {
1118 printf("Attempt to write at unaligned offset %jd.\n",
1128 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1131 switch (kdc->kdc_encryption) {
1132 case KERNELDUMP_ENC_AES_256_CBC:
1133 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1134 8 * size, buf) <= 0) {
1137 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1138 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1149 /* Encrypt data and call dumper. */
1151 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1152 vm_offset_t physical, off_t offset, size_t length)
1154 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1155 struct kerneldumpcrypto *kdc;
1161 while (length > 0) {
1162 nbytes = MIN(length, sizeof(buf));
1163 bcopy(virtual, buf, nbytes);
1165 if (dump_encrypt(kdc, buf, nbytes) != 0)
1168 error = dump_write(di, buf, physical, offset, nbytes);
1173 virtual = (void *)((uint8_t *)virtual + nbytes);
1181 dump_write_key(struct dumperinfo *di, off_t offset)
1183 struct kerneldumpcrypto *kdc;
1188 return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1189 kdc->kdc_dumpkeysize));
1194 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1196 struct dumperinfo *di;
1197 size_t resid, rlength;
1202 if (length % di->blocksize != 0) {
1204 * This must be the final write after flushing the compression
1205 * stream. Write as many full blocks as possible and stash the
1206 * residual data in the dumper's block buffer. It will be
1207 * padded and written in dump_finish().
1209 rlength = rounddown(length, di->blocksize);
1211 error = _dump_append(di, base, 0, rlength);
1215 resid = length - rlength;
1216 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1217 di->kdcomp->kdc_resid = resid;
1220 return (_dump_append(di, base, 0, length));
1224 * Write a kerneldumpheader at the specified offset. The header structure is 512
1225 * bytes in size, but we must pad to the device sector size.
1228 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1234 hdrsz = sizeof(*kdh);
1235 if (hdrsz > di->blocksize)
1238 if (hdrsz == di->blocksize)
1242 memset(buf, 0, di->blocksize);
1243 memcpy(buf, kdh, hdrsz);
1246 return (dump_write(di, buf, 0, offset, di->blocksize));
1250 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1251 * protect us from metadata and metadata from us.
1253 #define SIZEOF_METADATA (64 * 1024)
1256 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1257 * if requested, and make sure that we have enough space on the dump device.
1259 * We set things up so that the dump ends before the last sector of the dump
1260 * device, at which the trailing header is written.
1262 * +-----------+------+-----+----------------------------+------+
1263 * | | lhdr | key | ... kernel dump ... | thdr |
1264 * +-----------+------+-----+----------------------------+------+
1265 * 1 blk opt <------- dump extent --------> 1 blk
1267 * Dumps written using dump_append() start at the beginning of the extent.
1268 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1269 * will not. The true length of the dump is recorded in the leading and trailing
1270 * headers once the dump has been completed.
1273 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1275 uint64_t dumpextent;
1279 int error = kerneldumpcrypto_init(di->kdcrypto);
1282 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1287 dumpextent = dtoh64(kdh->dumpextent);
1288 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1290 if (di->kdcomp != NULL) {
1292 * We don't yet know how much space the compressed dump
1293 * will occupy, so try to use the whole swap partition
1294 * (minus the first 64KB) in the hope that the
1295 * compressed dump will fit. If that doesn't turn out to
1296 * be enouch, the bounds checking in dump_write()
1297 * will catch us and cause the dump to fail.
1299 dumpextent = di->mediasize - SIZEOF_METADATA -
1300 2 * di->blocksize - keysize;
1301 kdh->dumpextent = htod64(dumpextent);
1306 /* The offset at which to begin writing the dump. */
1307 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1314 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1320 if (di->kdcrypto != NULL)
1321 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1325 error = dump_write(di, virtual, physical, di->dumpoff, length);
1327 di->dumpoff += length;
1332 * Write to the dump device starting at dumpoff. When compression is enabled,
1333 * writes to the device will be performed using a callback that gets invoked
1334 * when the compression stream's output buffer is full.
1337 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1342 if (di->kdcomp != NULL) {
1343 /* Bounce through a buffer to avoid CRC errors. */
1344 if (length > di->maxiosize)
1346 buf = di->kdcomp->kdc_buf;
1347 memmove(buf, virtual, length);
1348 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1350 return (_dump_append(di, virtual, physical, length));
1354 * Write to the dump device at the specified offset.
1357 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1358 off_t offset, size_t length)
1362 error = dump_check_bounds(di, offset, length);
1365 return (di->dumper(di->priv, virtual, physical, offset, length));
1369 * Perform kernel dump finalization: flush the compression stream, if necessary,
1370 * write the leading and trailing kernel dump headers now that we know the true
1371 * length of the dump, and optionally write the encryption key following the
1375 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1381 extent = dtoh64(kdh->dumpextent);
1384 keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1389 if (di->kdcomp != NULL) {
1390 error = compressor_flush(di->kdcomp->kdc_stream);
1391 if (error == EAGAIN) {
1392 /* We have residual data in di->blockbuf. */
1393 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1395 di->dumpoff += di->kdcomp->kdc_resid;
1396 di->kdcomp->kdc_resid = 0;
1402 * We now know the size of the compressed dump, so update the
1403 * header accordingly and recompute parity.
1405 kdh->dumplength = htod64(di->dumpoff -
1406 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1408 kdh->parity = kerneldump_parity(kdh);
1410 compressor_reset(di->kdcomp->kdc_stream);
1414 * Write kerneldump headers at the beginning and end of the dump extent.
1415 * Write the key after the leading header.
1417 error = dump_write_header(di, kdh,
1418 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1424 error = dump_write_key(di,
1425 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1430 error = dump_write_header(di, kdh,
1431 di->mediaoffset + di->mediasize - di->blocksize);
1435 (void)dump_write(di, NULL, 0, 0, 0);
1440 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1441 char *magic, uint32_t archver, uint64_t dumplen)
1445 bzero(kdh, sizeof(*kdh));
1446 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1447 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1448 kdh->version = htod32(KERNELDUMPVERSION);
1449 kdh->architectureversion = htod32(archver);
1450 kdh->dumplength = htod64(dumplen);
1451 kdh->dumpextent = kdh->dumplength;
1452 kdh->dumptime = htod64(time_second);
1454 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1456 kdh->dumpkeysize = 0;
1458 kdh->blocksize = htod32(di->blocksize);
1459 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1460 dstsize = sizeof(kdh->versionstring);
1461 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1462 kdh->versionstring[dstsize - 2] = '\n';
1463 if (panicstr != NULL)
1464 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1465 if (di->kdcomp != NULL)
1466 kdh->compression = KERNELDUMP_COMP_GZIP;
1467 kdh->parity = kerneldump_parity(kdh);
1471 DB_SHOW_COMMAND(panic, db_show_panic)
1474 if (panicstr == NULL)
1475 db_printf("panicstr not set\n");
1477 db_printf("panic: %s\n", panicstr);