2 * Copyright (c) 1986, 1988, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_shutdown.c 8.3 (Berkeley) 1/21/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
44 #include "opt_panic.h"
45 #include "opt_sched.h"
46 #include "opt_watchdog.h"
48 #include <sys/param.h>
49 #include <sys/systm.h>
54 #include <sys/eventhandler.h>
55 #include <sys/filedesc.h>
59 #include <sys/kernel.h>
60 #include <sys/kerneldump.h>
61 #include <sys/kthread.h>
63 #include <sys/malloc.h>
64 #include <sys/mount.h>
67 #include <sys/reboot.h>
68 #include <sys/resourcevar.h>
69 #include <sys/rwlock.h>
70 #include <sys/sched.h>
72 #include <sys/sysctl.h>
73 #include <sys/sysproto.h>
74 #include <sys/vnode.h>
75 #include <sys/watchdog.h>
77 #include <crypto/rijndael/rijndael-api-fst.h>
78 #include <crypto/sha2/sha256.h>
82 #include <machine/cpu.h>
83 #include <machine/dump.h>
84 #include <machine/pcb.h>
85 #include <machine/smp.h>
87 #include <security/mac/mac_framework.h>
90 #include <vm/vm_object.h>
91 #include <vm/vm_page.h>
92 #include <vm/vm_pager.h>
93 #include <vm/swap_pager.h>
95 #include <sys/signalvar.h>
97 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
99 #ifndef PANIC_REBOOT_WAIT_TIME
100 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
102 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
103 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
104 &panic_reboot_wait_time, 0,
105 "Seconds to wait before rebooting after a panic");
108 * Note that stdarg.h and the ANSI style va_start macro is used for both
109 * ANSI and traditional C compilers.
111 #include <machine/stdarg.h>
114 #ifdef KDB_UNATTENDED
115 int debugger_on_panic = 0;
117 int debugger_on_panic = 1;
119 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
120 CTLFLAG_RWTUN | CTLFLAG_SECURE,
121 &debugger_on_panic, 0, "Run debugger on kernel panic");
124 static int trace_on_panic = 1;
126 static int trace_on_panic = 0;
128 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
129 CTLFLAG_RWTUN | CTLFLAG_SECURE,
130 &trace_on_panic, 0, "Print stack trace on kernel panic");
133 static int sync_on_panic = 0;
134 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
135 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
137 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
138 "Shutdown environment");
141 static int show_busybufs;
143 static int show_busybufs = 1;
145 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
146 &show_busybufs, 0, "");
148 int suspend_blocked = 0;
149 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
150 &suspend_blocked, 0, "Block suspend due to a pending shutdown");
153 FEATURE(ekcd, "Encrypted kernel crash dumps support");
155 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
157 struct kerneldumpcrypto {
158 uint8_t kdc_encryption;
159 uint8_t kdc_iv[KERNELDUMP_IV_MAX_SIZE];
161 cipherInstance kdc_ci;
162 uint32_t kdc_dumpkeysize;
163 struct kerneldumpkey kdc_dumpkey[];
168 struct kerneldumpgz {
169 struct gzio_stream *kdgz_stream;
174 static struct kerneldumpgz *kerneldumpgz_create(struct dumperinfo *di,
175 uint8_t compression);
176 static void kerneldumpgz_destroy(struct dumperinfo *di);
177 static int kerneldumpgz_write_cb(void *cb, size_t len, off_t off, void *arg);
179 static int kerneldump_gzlevel = 6;
180 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
181 &kerneldump_gzlevel, 0,
182 "Kernel crash dump gzip compression level");
186 * Variable panicstr contains argument to first call to panic; used as flag
187 * to indicate that the kernel has already called panic.
189 const char *panicstr;
191 int dumping; /* system is dumping */
192 int rebooting; /* system is rebooting */
193 static struct dumperinfo dumper; /* our selected dumper */
195 /* Context information for dump-debuggers. */
196 static struct pcb dumppcb; /* Registers. */
197 lwpid_t dumptid; /* Thread ID. */
199 static struct cdevsw reroot_cdevsw = {
200 .d_version = D_VERSION,
204 static void poweroff_wait(void *, int);
205 static void shutdown_halt(void *junk, int howto);
206 static void shutdown_panic(void *junk, int howto);
207 static void shutdown_reset(void *junk, int howto);
208 static int kern_reroot(void);
210 /* register various local shutdown events */
212 shutdown_conf(void *unused)
215 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
217 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
218 SHUTDOWN_PRI_LAST + 100);
219 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
220 SHUTDOWN_PRI_LAST + 100);
221 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
222 SHUTDOWN_PRI_LAST + 200);
225 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
228 * The only reason this exists is to create the /dev/reroot/ directory,
229 * used by reroot code in init(8) as a mountpoint for tmpfs.
232 reroot_conf(void *unused)
237 error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
238 &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
240 printf("%s: failed to create device node, error %d",
245 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
248 * The system call that results in a reboot.
252 sys_reboot(struct thread *td, struct reboot_args *uap)
258 error = mac_system_check_reboot(td->td_ucred, uap->opt);
261 error = priv_check(td, PRIV_REBOOT);
263 if (uap->opt & RB_REROOT) {
264 error = kern_reroot();
267 kern_reboot(uap->opt);
275 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
278 shutdown_nice(int howto)
281 if (initproc != NULL) {
282 /* Send a signal to init(8) and have it shutdown the world. */
284 if (howto & RB_POWEROFF)
285 kern_psignal(initproc, SIGUSR2);
286 else if (howto & RB_HALT)
287 kern_psignal(initproc, SIGUSR1);
289 kern_psignal(initproc, SIGINT);
290 PROC_UNLOCK(initproc);
292 /* No init(8) running, so simply reboot. */
293 kern_reboot(howto | RB_NOSYNC);
306 if (ts.tv_sec >= 86400) {
307 printf("%ldd", (long)ts.tv_sec / 86400);
311 if (f || ts.tv_sec >= 3600) {
312 printf("%ldh", (long)ts.tv_sec / 3600);
316 if (f || ts.tv_sec >= 60) {
317 printf("%ldm", (long)ts.tv_sec / 60);
321 printf("%lds\n", (long)ts.tv_sec);
325 doadump(boolean_t textdump)
333 if (dumper.dumper == NULL)
337 dumptid = curthread->td_tid;
342 if (textdump && textdump_pending) {
344 textdump_dumpsys(&dumper);
348 error = dumpsys(&dumper);
355 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
358 kern_reboot(int howto)
364 * Bind us to CPU 0 so that all shutdown code runs there. Some
365 * systems don't shutdown properly (i.e., ACPI power off) if we
366 * run on another processor.
368 if (!SCHEDULER_STOPPED()) {
369 thread_lock(curthread);
370 sched_bind(curthread, 0);
371 thread_unlock(curthread);
372 KASSERT(PCPU_GET(cpuid) == 0, ("boot: not running on cpu 0"));
375 /* We're in the process of rebooting. */
378 /* We are out of the debugger now. */
382 * Do any callouts that should be done BEFORE syncing the filesystems.
384 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
387 * Now sync filesystems
389 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
391 bufshutdown(show_busybufs);
399 * Ok, now do things that assume all filesystem activity has
402 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
404 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
407 /* Now that we're going to really halt the system... */
408 EVENTHANDLER_INVOKE(shutdown_final, howto);
410 for(;;) ; /* safety against shutdown_reset not working */
415 * The system call that results in changing the rootfs.
420 struct vnode *oldrootvnode, *vp;
421 struct mount *mp, *devmp;
424 if (curproc != initproc)
428 * Mark the filesystem containing currently-running executable
429 * (the temporary copy of init(8)) busy.
431 vp = curproc->p_textvp;
432 error = vn_lock(vp, LK_SHARED);
436 error = vfs_busy(mp, MBF_NOWAIT);
440 error = vfs_busy(mp, 0);
441 vn_lock(vp, LK_SHARED | LK_RETRY);
447 if (vp->v_iflag & VI_DOOMED) {
456 * Remove the filesystem containing currently-running executable
457 * from the mount list, to prevent it from being unmounted
458 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
460 * Also preserve /dev - forcibly unmounting it could cause driver
468 mtx_lock(&mountlist_mtx);
469 TAILQ_REMOVE(&mountlist, mp, mnt_list);
470 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
471 mtx_unlock(&mountlist_mtx);
473 oldrootvnode = rootvnode;
476 * Unmount everything except for the two filesystems preserved above.
481 * Add /dev back; vfs_mountroot() will move it into its new place.
483 mtx_lock(&mountlist_mtx);
484 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
485 mtx_unlock(&mountlist_mtx);
490 * Mount the new rootfs.
495 * Update all references to the old rootvnode.
497 mountcheckdirs(oldrootvnode, rootvnode);
500 * Add the temporary filesystem back and unbusy it.
502 mtx_lock(&mountlist_mtx);
503 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
504 mtx_unlock(&mountlist_mtx);
511 * If the shutdown was a clean halt, behave accordingly.
514 shutdown_halt(void *junk, int howto)
517 if (howto & RB_HALT) {
519 printf("The operating system has halted.\n");
520 printf("Please press any key to reboot.\n\n");
522 case -1: /* No console, just die */
533 * Check to see if the system paniced, pause and then reboot
534 * according to the specified delay.
537 shutdown_panic(void *junk, int howto)
541 if (howto & RB_DUMP) {
542 if (panic_reboot_wait_time != 0) {
543 if (panic_reboot_wait_time != -1) {
544 printf("Automatic reboot in %d seconds - "
545 "press a key on the console to abort\n",
546 panic_reboot_wait_time);
547 for (loop = panic_reboot_wait_time * 10;
549 DELAY(1000 * 100); /* 1/10th second */
550 /* Did user type a key? */
551 if (cncheckc() != -1)
557 } else { /* zero time specified - reboot NOW */
560 printf("--> Press a key on the console to reboot,\n");
561 printf("--> or switch off the system now.\n");
567 * Everything done, now reset
570 shutdown_reset(void *junk, int howto)
573 printf("Rebooting...\n");
574 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
577 * Acquiring smp_ipi_mtx here has a double effect:
578 * - it disables interrupts avoiding CPU0 preemption
579 * by fast handlers (thus deadlocking against other CPUs)
580 * - it avoids deadlocks against smp_rendezvous() or, more
581 * generally, threads busy-waiting, with this spinlock held,
582 * and waiting for responses by threads on other CPUs
583 * (ie. smp_tlb_shootdown()).
585 * For the !SMP case it just needs to handle the former problem.
588 mtx_lock_spin(&smp_ipi_mtx);
593 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
595 /* NOTREACHED */ /* assuming reset worked */
598 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
599 static int kassert_warn_only = 0;
601 static int kassert_do_kdb = 0;
604 static int kassert_do_ktr = 0;
606 static int kassert_do_log = 1;
607 static int kassert_log_pps_limit = 4;
608 static int kassert_log_mute_at = 0;
609 static int kassert_log_panic_at = 0;
610 static int kassert_warnings = 0;
612 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
614 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
615 &kassert_warn_only, 0,
616 "KASSERT triggers a panic (1) or just a warning (0)");
619 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
620 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
624 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
626 "KASSERT does a KTR, set this to the KTRMASK you want");
629 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
630 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
632 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
633 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
635 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
636 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
638 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
639 &kassert_log_pps_limit, 0, "limit number of log messages per second");
641 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
642 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
644 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
646 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
647 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
648 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
651 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
655 error = sysctl_wire_old_buffer(req, sizeof(int));
658 error = sysctl_handle_int(oidp, &i, 0, req);
660 if (error != 0 || req->newptr == NULL)
662 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
667 * Called by KASSERT, this decides if we will panic
668 * or if we will log via printf and/or ktr.
671 kassert_panic(const char *fmt, ...)
673 static char buf[256];
677 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
681 * panic if we're not just warning, or if we've exceeded
682 * kassert_log_panic_at warnings.
684 if (!kassert_warn_only ||
685 (kassert_log_panic_at > 0 &&
686 kassert_warnings >= kassert_log_panic_at)) {
696 * log if we've not yet met the mute limit.
698 if (kassert_do_log &&
699 (kassert_log_mute_at == 0 ||
700 kassert_warnings < kassert_log_mute_at)) {
701 static struct timeval lasterr;
704 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
705 printf("KASSERT failed: %s\n", buf);
710 if (kassert_do_kdb) {
711 kdb_enter(KDB_WHY_KASSERT, buf);
714 atomic_add_int(&kassert_warnings, 1);
719 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
720 * and then reboots. If we are called twice, then we avoid trying to sync
721 * the disks as this often leads to recursive panics.
724 panic(const char *fmt, ...)
733 vpanic(const char *fmt, va_list ap)
738 struct thread *td = curthread;
739 int bootopt, newpanic;
740 static char buf[256];
746 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
747 * concurrently entering panic. Only the winner will proceed
750 if (panicstr == NULL && !kdb_active) {
751 other_cpus = all_cpus;
752 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
753 stop_cpus_hard(other_cpus);
758 * Ensure that the scheduler is stopped while panicking, even if panic
759 * has been entered from kdb.
761 td->td_stopsched = 1;
763 bootopt = RB_AUTOBOOT;
766 bootopt |= RB_NOSYNC;
774 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
777 printf("panic: %s\n", buf);
784 printf("cpuid = %d\n", PCPU_GET(cpuid));
786 printf("time = %jd\n", (intmax_t )time_second);
788 if (newpanic && trace_on_panic)
790 if (debugger_on_panic)
791 kdb_enter(KDB_WHY_PANIC, "panic");
793 /*thread_lock(td); */
794 td->td_flags |= TDF_INPANIC;
795 /* thread_unlock(td); */
797 bootopt |= RB_NOSYNC;
798 kern_reboot(bootopt);
802 * Support for poweroff delay.
804 * Please note that setting this delay too short might power off your machine
805 * before the write cache on your hard disk has been flushed, leading to
806 * soft-updates inconsistencies.
808 #ifndef POWEROFF_DELAY
809 # define POWEROFF_DELAY 5000
811 static int poweroff_delay = POWEROFF_DELAY;
813 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
814 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
817 poweroff_wait(void *junk, int howto)
820 if (!(howto & RB_POWEROFF) || poweroff_delay <= 0)
822 DELAY(poweroff_delay * 1000);
826 * Some system processes (e.g. syncer) need to be stopped at appropriate
827 * points in their main loops prior to a system shutdown, so that they
828 * won't interfere with the shutdown process (e.g. by holding a disk buf
829 * to cause sync to fail). For each of these system processes, register
830 * shutdown_kproc() as a handler for one of shutdown events.
832 static int kproc_shutdown_wait = 60;
833 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
834 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
837 kproc_shutdown(void *arg, int howto)
845 p = (struct proc *)arg;
846 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
847 kproc_shutdown_wait, p->p_comm);
848 error = kproc_suspend(p, kproc_shutdown_wait * hz);
850 if (error == EWOULDBLOCK)
851 printf("timed out\n");
857 kthread_shutdown(void *arg, int howto)
865 td = (struct thread *)arg;
866 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
867 kproc_shutdown_wait, td->td_name);
868 error = kthread_suspend(td, kproc_shutdown_wait * hz);
870 if (error == EWOULDBLOCK)
871 printf("timed out\n");
876 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
877 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
878 dumpdevname, 0, "Device for kernel dumps");
880 static int _dump_append(struct dumperinfo *di, void *virtual,
881 vm_offset_t physical, size_t length);
884 static struct kerneldumpcrypto *
885 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
886 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
888 struct kerneldumpcrypto *kdc;
889 struct kerneldumpkey *kdk;
890 uint32_t dumpkeysize;
892 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
893 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
895 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
897 kdc->kdc_encryption = encryption;
898 switch (kdc->kdc_encryption) {
899 case KERNELDUMP_ENC_AES_256_CBC:
900 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
907 kdc->kdc_dumpkeysize = dumpkeysize;
908 kdk = kdc->kdc_dumpkey;
909 kdk->kdk_encryption = kdc->kdc_encryption;
910 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
911 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
912 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
916 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
922 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
924 uint8_t hash[SHA256_DIGEST_LENGTH];
926 struct kerneldumpkey *kdk;
935 * When a user enters ddb it can write a crash dump multiple times.
936 * Each time it should be encrypted using a different IV.
939 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
940 SHA256_Final(hash, &ctx);
941 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
943 switch (kdc->kdc_encryption) {
944 case KERNELDUMP_ENC_AES_256_CBC:
945 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
956 kdk = kdc->kdc_dumpkey;
957 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
959 explicit_bzero(hash, sizeof(hash));
964 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
969 return (kdc->kdc_dumpkeysize);
974 static struct kerneldumpgz *
975 kerneldumpgz_create(struct dumperinfo *di, uint8_t compression)
977 struct kerneldumpgz *kdgz;
979 if (compression != KERNELDUMP_COMP_GZIP)
981 kdgz = malloc(sizeof(*kdgz), M_DUMPER, M_WAITOK | M_ZERO);
982 kdgz->kdgz_stream = gzio_init(kerneldumpgz_write_cb, GZIO_DEFLATE,
983 di->maxiosize, kerneldump_gzlevel, di);
984 if (kdgz->kdgz_stream == NULL) {
985 free(kdgz, M_DUMPER);
988 kdgz->kdgz_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
993 kerneldumpgz_destroy(struct dumperinfo *di)
995 struct kerneldumpgz *kdgz;
1000 gzio_fini(kdgz->kdgz_stream);
1001 explicit_bzero(kdgz->kdgz_buf, di->maxiosize);
1002 free(kdgz->kdgz_buf, M_DUMPER);
1003 free(kdgz, M_DUMPER);
1007 /* Registration of dumpers */
1009 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1010 uint8_t compression, uint8_t encryption, const uint8_t *key,
1011 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1016 error = priv_check(td, PRIV_SETDUMPER);
1024 if (dumper.dumper != NULL)
1027 dumper.blockbuf = NULL;
1031 if (encryption != KERNELDUMP_ENC_NONE) {
1033 dumper.kdc = kerneldumpcrypto_create(di->blocksize, encryption,
1034 key, encryptedkeysize, encryptedkey);
1035 if (dumper.kdc == NULL) {
1045 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1046 if (wantcopy >= sizeof(dumpdevname)) {
1047 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1048 devname, dumpdevname);
1051 if (compression != KERNELDUMP_COMP_NONE) {
1054 * We currently can't support simultaneous encryption and
1057 if (encryption != KERNELDUMP_ENC_NONE) {
1061 dumper.kdgz = kerneldumpgz_create(&dumper, compression);
1062 if (dumper.kdgz == NULL) {
1072 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1076 if (dumper.kdc != NULL) {
1077 explicit_bzero(dumper.kdc, sizeof(*dumper.kdc) +
1078 dumper.kdc->kdc_dumpkeysize);
1079 free(dumper.kdc, M_EKCD);
1084 kerneldumpgz_destroy(&dumper);
1087 if (dumper.blockbuf != NULL) {
1088 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1089 free(dumper.blockbuf, M_DUMPER);
1091 explicit_bzero(&dumper, sizeof(dumper));
1092 dumpdevname[0] = '\0';
1097 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1100 if (length != 0 && (offset < di->mediaoffset ||
1101 offset - di->mediaoffset + length > di->mediasize)) {
1102 printf("Attempt to write outside dump device boundaries.\n"
1103 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1104 (intmax_t)offset, (intmax_t)di->mediaoffset,
1105 (uintmax_t)length, (intmax_t)di->mediasize);
1108 if (length % di->blocksize != 0) {
1109 printf("Attempt to write partial block of length %ju.\n",
1113 if (offset % di->blocksize != 0) {
1114 printf("Attempt to write at unaligned offset %jd.\n",
1124 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1127 switch (kdc->kdc_encryption) {
1128 case KERNELDUMP_ENC_AES_256_CBC:
1129 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1130 8 * size, buf) <= 0) {
1133 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1134 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1145 /* Encrypt data and call dumper. */
1147 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1148 vm_offset_t physical, off_t offset, size_t length)
1150 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1151 struct kerneldumpcrypto *kdc;
1157 while (length > 0) {
1158 nbytes = MIN(length, sizeof(buf));
1159 bcopy(virtual, buf, nbytes);
1161 if (dump_encrypt(kdc, buf, nbytes) != 0)
1164 error = dump_write(di, buf, physical, offset, nbytes);
1169 virtual = (void *)((uint8_t *)virtual + nbytes);
1177 dump_write_key(struct dumperinfo *di, off_t offset)
1179 struct kerneldumpcrypto *kdc;
1184 return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1185 kdc->kdc_dumpkeysize));
1191 kerneldumpgz_write_cb(void *base, size_t length, off_t offset, void *arg)
1193 struct dumperinfo *di;
1194 size_t resid, rlength;
1199 if (length % di->blocksize != 0) {
1201 * This must be the final write after flushing the compression
1202 * stream. Write as many full blocks as possible and stash the
1203 * residual data in the dumper's block buffer. It will be
1204 * padded and written in dump_finish().
1206 rlength = rounddown(length, di->blocksize);
1208 error = _dump_append(di, base, 0, rlength);
1212 resid = length - rlength;
1213 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1214 di->kdgz->kdgz_resid = resid;
1217 return (_dump_append(di, base, 0, length));
1222 * Write a kerneldumpheader at the specified offset. The header structure is 512
1223 * bytes in size, but we must pad to the device sector size.
1226 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1232 hdrsz = sizeof(*kdh);
1233 if (hdrsz > di->blocksize)
1236 if (hdrsz == di->blocksize)
1240 memset(buf, 0, di->blocksize);
1241 memcpy(buf, kdh, hdrsz);
1244 return (dump_write(di, buf, 0, offset, di->blocksize));
1248 * Don't touch the first SIZEOF_METADATA bytes on the dump device. This is to
1249 * protect us from metadata and metadata from us.
1251 #define SIZEOF_METADATA (64 * 1024)
1254 * Do some preliminary setup for a kernel dump: initialize state for encryption,
1255 * if requested, and make sure that we have enough space on the dump device.
1257 * We set things up so that the dump ends before the last sector of the dump
1258 * device, at which the trailing header is written.
1260 * +-----------+------+-----+----------------------------+------+
1261 * | | lhdr | key | ... kernel dump ... | thdr |
1262 * +-----------+------+-----+----------------------------+------+
1263 * 1 blk opt <------- dump extent --------> 1 blk
1265 * Dumps written using dump_append() start at the beginning of the extent.
1266 * Uncompressed dumps will use the entire extent, but compressed dumps typically
1267 * will not. The true length of the dump is recorded in the leading and trailing
1268 * headers once the dump has been completed.
1271 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1273 uint64_t dumpextent;
1277 int error = kerneldumpcrypto_init(di->kdc);
1280 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1285 dumpextent = dtoh64(kdh->dumpextent);
1286 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1289 if (di->kdgz != NULL) {
1291 * We don't yet know how much space the compressed dump
1292 * will occupy, so try to use the whole swap partition
1293 * (minus the first 64KB) in the hope that the
1294 * compressed dump will fit. If that doesn't turn out to
1295 * be enouch, the bounds checking in dump_write()
1296 * will catch us and cause the dump to fail.
1298 dumpextent = di->mediasize - SIZEOF_METADATA -
1299 2 * di->blocksize - keysize;
1300 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->kdc != 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,
1343 if (di->kdgz != NULL) {
1344 /* Bounce through a buffer to avoid gzip CRC errors. */
1345 if (length > di->maxiosize)
1347 buf = di->kdgz->kdgz_buf;
1348 memmove(buf, virtual, length);
1349 return (gzio_write(di->kdgz->kdgz_stream, buf, length));
1352 return (_dump_append(di, virtual, physical, length));
1356 * Write to the dump device at the specified offset.
1359 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1360 off_t offset, size_t length)
1364 error = dump_check_bounds(di, offset, length);
1367 return (di->dumper(di->priv, virtual, physical, offset, length));
1371 * Perform kernel dump finalization: flush the compression stream, if necessary,
1372 * write the leading and trailing kernel dump headers now that we know the true
1373 * length of the dump, and optionally write the encryption key following the
1377 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1383 extent = dtoh64(kdh->dumpextent);
1386 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1392 if (di->kdgz != NULL) {
1393 error = gzio_flush(di->kdgz->kdgz_stream);
1394 if (error == EAGAIN) {
1395 /* We have residual data in di->blockbuf. */
1396 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1398 di->dumpoff += di->kdgz->kdgz_resid;
1399 di->kdgz->kdgz_resid = 0;
1405 * We now know the size of the compressed dump, so update the
1406 * header accordingly and recompute parity.
1408 kdh->dumplength = htod64(di->dumpoff -
1409 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1411 kdh->parity = kerneldump_parity(kdh);
1413 gzio_reset(di->kdgz->kdgz_stream);
1418 * Write kerneldump headers at the beginning and end of the dump extent.
1419 * Write the key after the leading header.
1421 error = dump_write_header(di, kdh,
1422 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1428 error = dump_write_key(di,
1429 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1434 error = dump_write_header(di, kdh,
1435 di->mediaoffset + di->mediasize - di->blocksize);
1439 (void)dump_write(di, NULL, 0, 0, 0);
1444 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1445 char *magic, uint32_t archver, uint64_t dumplen)
1449 bzero(kdh, sizeof(*kdh));
1450 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1451 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1452 kdh->version = htod32(KERNELDUMPVERSION);
1453 kdh->architectureversion = htod32(archver);
1454 kdh->dumplength = htod64(dumplen);
1455 kdh->dumpextent = kdh->dumplength;
1456 kdh->dumptime = htod64(time_second);
1458 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdc));
1460 kdh->dumpkeysize = 0;
1462 kdh->blocksize = htod32(di->blocksize);
1463 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1464 dstsize = sizeof(kdh->versionstring);
1465 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1466 kdh->versionstring[dstsize - 2] = '\n';
1467 if (panicstr != NULL)
1468 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1470 if (di->kdgz != NULL)
1471 kdh->compression = KERNELDUMP_COMP_GZIP;
1473 kdh->parity = kerneldump_parity(kdh);
1477 DB_SHOW_COMMAND(panic, db_show_panic)
1480 if (panicstr == NULL)
1481 db_printf("panicstr not set\n");
1483 db_printf("panic: %s\n", panicstr);