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_POWERCYCLE)
287 kern_psignal(initproc, SIGWINCH);
288 else if (howto & RB_HALT)
289 kern_psignal(initproc, SIGUSR1);
291 kern_psignal(initproc, SIGINT);
292 PROC_UNLOCK(initproc);
294 /* No init(8) running, so simply reboot. */
295 kern_reboot(howto | RB_NOSYNC);
308 if (ts.tv_sec >= 86400) {
309 printf("%ldd", (long)ts.tv_sec / 86400);
313 if (f || ts.tv_sec >= 3600) {
314 printf("%ldh", (long)ts.tv_sec / 3600);
318 if (f || ts.tv_sec >= 60) {
319 printf("%ldm", (long)ts.tv_sec / 60);
323 printf("%lds\n", (long)ts.tv_sec);
327 doadump(boolean_t textdump)
335 if (dumper.dumper == NULL)
339 dumptid = curthread->td_tid;
344 if (textdump && textdump_pending) {
346 textdump_dumpsys(&dumper);
350 error = dumpsys(&dumper);
357 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
360 kern_reboot(int howto)
366 * Bind us to CPU 0 so that all shutdown code runs there. Some
367 * systems don't shutdown properly (i.e., ACPI power off) if we
368 * run on another processor.
370 if (!SCHEDULER_STOPPED()) {
371 thread_lock(curthread);
372 sched_bind(curthread, 0);
373 thread_unlock(curthread);
374 KASSERT(PCPU_GET(cpuid) == 0, ("boot: not running on cpu 0"));
377 /* We're in the process of rebooting. */
380 /* We are out of the debugger now. */
384 * Do any callouts that should be done BEFORE syncing the filesystems.
386 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
389 * Now sync filesystems
391 if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
393 bufshutdown(show_busybufs);
401 * Ok, now do things that assume all filesystem activity has
404 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
406 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
409 /* Now that we're going to really halt the system... */
410 EVENTHANDLER_INVOKE(shutdown_final, howto);
412 for(;;) ; /* safety against shutdown_reset not working */
417 * The system call that results in changing the rootfs.
422 struct vnode *oldrootvnode, *vp;
423 struct mount *mp, *devmp;
426 if (curproc != initproc)
430 * Mark the filesystem containing currently-running executable
431 * (the temporary copy of init(8)) busy.
433 vp = curproc->p_textvp;
434 error = vn_lock(vp, LK_SHARED);
438 error = vfs_busy(mp, MBF_NOWAIT);
442 error = vfs_busy(mp, 0);
443 vn_lock(vp, LK_SHARED | LK_RETRY);
449 if (vp->v_iflag & VI_DOOMED) {
458 * Remove the filesystem containing currently-running executable
459 * from the mount list, to prevent it from being unmounted
460 * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
462 * Also preserve /dev - forcibly unmounting it could cause driver
470 mtx_lock(&mountlist_mtx);
471 TAILQ_REMOVE(&mountlist, mp, mnt_list);
472 TAILQ_REMOVE(&mountlist, devmp, mnt_list);
473 mtx_unlock(&mountlist_mtx);
475 oldrootvnode = rootvnode;
478 * Unmount everything except for the two filesystems preserved above.
483 * Add /dev back; vfs_mountroot() will move it into its new place.
485 mtx_lock(&mountlist_mtx);
486 TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
487 mtx_unlock(&mountlist_mtx);
492 * Mount the new rootfs.
497 * Update all references to the old rootvnode.
499 mountcheckdirs(oldrootvnode, rootvnode);
502 * Add the temporary filesystem back and unbusy it.
504 mtx_lock(&mountlist_mtx);
505 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
506 mtx_unlock(&mountlist_mtx);
513 * If the shutdown was a clean halt, behave accordingly.
516 shutdown_halt(void *junk, int howto)
519 if (howto & RB_HALT) {
521 printf("The operating system has halted.\n");
522 printf("Please press any key to reboot.\n\n");
524 case -1: /* No console, just die */
535 * Check to see if the system paniced, pause and then reboot
536 * according to the specified delay.
539 shutdown_panic(void *junk, int howto)
543 if (howto & RB_DUMP) {
544 if (panic_reboot_wait_time != 0) {
545 if (panic_reboot_wait_time != -1) {
546 printf("Automatic reboot in %d seconds - "
547 "press a key on the console to abort\n",
548 panic_reboot_wait_time);
549 for (loop = panic_reboot_wait_time * 10;
551 DELAY(1000 * 100); /* 1/10th second */
552 /* Did user type a key? */
553 if (cncheckc() != -1)
559 } else { /* zero time specified - reboot NOW */
562 printf("--> Press a key on the console to reboot,\n");
563 printf("--> or switch off the system now.\n");
569 * Everything done, now reset
572 shutdown_reset(void *junk, int howto)
575 printf("Rebooting...\n");
576 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
579 * Acquiring smp_ipi_mtx here has a double effect:
580 * - it disables interrupts avoiding CPU0 preemption
581 * by fast handlers (thus deadlocking against other CPUs)
582 * - it avoids deadlocks against smp_rendezvous() or, more
583 * generally, threads busy-waiting, with this spinlock held,
584 * and waiting for responses by threads on other CPUs
585 * (ie. smp_tlb_shootdown()).
587 * For the !SMP case it just needs to handle the former problem.
590 mtx_lock_spin(&smp_ipi_mtx);
595 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
597 /* NOTREACHED */ /* assuming reset worked */
600 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
601 static int kassert_warn_only = 0;
603 static int kassert_do_kdb = 0;
606 static int kassert_do_ktr = 0;
608 static int kassert_do_log = 1;
609 static int kassert_log_pps_limit = 4;
610 static int kassert_log_mute_at = 0;
611 static int kassert_log_panic_at = 0;
612 static int kassert_warnings = 0;
614 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
616 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
617 &kassert_warn_only, 0,
618 "KASSERT triggers a panic (1) or just a warning (0)");
621 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
622 &kassert_do_kdb, 0, "KASSERT will enter the debugger");
626 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
628 "KASSERT does a KTR, set this to the KTRMASK you want");
631 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
632 &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
634 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
635 &kassert_warnings, 0, "number of KASSERTs that have been triggered");
637 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
638 &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
640 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
641 &kassert_log_pps_limit, 0, "limit number of log messages per second");
643 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
644 &kassert_log_mute_at, 0, "max number of KASSERTS to log");
646 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
648 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
649 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
650 kassert_sysctl_kassert, "I", "set to trigger a test kassert");
653 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
657 error = sysctl_wire_old_buffer(req, sizeof(int));
660 error = sysctl_handle_int(oidp, &i, 0, req);
662 if (error != 0 || req->newptr == NULL)
664 KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
669 * Called by KASSERT, this decides if we will panic
670 * or if we will log via printf and/or ktr.
673 kassert_panic(const char *fmt, ...)
675 static char buf[256];
679 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
683 * panic if we're not just warning, or if we've exceeded
684 * kassert_log_panic_at warnings.
686 if (!kassert_warn_only ||
687 (kassert_log_panic_at > 0 &&
688 kassert_warnings >= kassert_log_panic_at)) {
698 * log if we've not yet met the mute limit.
700 if (kassert_do_log &&
701 (kassert_log_mute_at == 0 ||
702 kassert_warnings < kassert_log_mute_at)) {
703 static struct timeval lasterr;
706 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
707 printf("KASSERT failed: %s\n", buf);
712 if (kassert_do_kdb) {
713 kdb_enter(KDB_WHY_KASSERT, buf);
716 atomic_add_int(&kassert_warnings, 1);
721 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
722 * and then reboots. If we are called twice, then we avoid trying to sync
723 * the disks as this often leads to recursive panics.
726 panic(const char *fmt, ...)
735 vpanic(const char *fmt, va_list ap)
740 struct thread *td = curthread;
741 int bootopt, newpanic;
742 static char buf[256];
748 * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
749 * concurrently entering panic. Only the winner will proceed
752 if (panicstr == NULL && !kdb_active) {
753 other_cpus = all_cpus;
754 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
755 stop_cpus_hard(other_cpus);
760 * Ensure that the scheduler is stopped while panicking, even if panic
761 * has been entered from kdb.
763 td->td_stopsched = 1;
765 bootopt = RB_AUTOBOOT;
768 bootopt |= RB_NOSYNC;
776 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
779 printf("panic: %s\n", buf);
786 printf("cpuid = %d\n", PCPU_GET(cpuid));
788 printf("time = %jd\n", (intmax_t )time_second);
790 if (newpanic && trace_on_panic)
792 if (debugger_on_panic)
793 kdb_enter(KDB_WHY_PANIC, "panic");
795 /*thread_lock(td); */
796 td->td_flags |= TDF_INPANIC;
797 /* thread_unlock(td); */
799 bootopt |= RB_NOSYNC;
800 kern_reboot(bootopt);
804 * Support for poweroff delay.
806 * Please note that setting this delay too short might power off your machine
807 * before the write cache on your hard disk has been flushed, leading to
808 * soft-updates inconsistencies.
810 #ifndef POWEROFF_DELAY
811 # define POWEROFF_DELAY 5000
813 static int poweroff_delay = POWEROFF_DELAY;
815 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
816 &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
819 poweroff_wait(void *junk, int howto)
822 if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
824 DELAY(poweroff_delay * 1000);
828 * Some system processes (e.g. syncer) need to be stopped at appropriate
829 * points in their main loops prior to a system shutdown, so that they
830 * won't interfere with the shutdown process (e.g. by holding a disk buf
831 * to cause sync to fail). For each of these system processes, register
832 * shutdown_kproc() as a handler for one of shutdown events.
834 static int kproc_shutdown_wait = 60;
835 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
836 &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
839 kproc_shutdown(void *arg, int howto)
847 p = (struct proc *)arg;
848 printf("Waiting (max %d seconds) for system process `%s' to stop... ",
849 kproc_shutdown_wait, p->p_comm);
850 error = kproc_suspend(p, kproc_shutdown_wait * hz);
852 if (error == EWOULDBLOCK)
853 printf("timed out\n");
859 kthread_shutdown(void *arg, int howto)
867 td = (struct thread *)arg;
868 printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
869 kproc_shutdown_wait, td->td_name);
870 error = kthread_suspend(td, kproc_shutdown_wait * hz);
872 if (error == EWOULDBLOCK)
873 printf("timed out\n");
878 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
879 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
880 dumpdevname, 0, "Device for kernel dumps");
882 static int _dump_append(struct dumperinfo *di, void *virtual,
883 vm_offset_t physical, size_t length);
886 static struct kerneldumpcrypto *
887 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
888 const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
890 struct kerneldumpcrypto *kdc;
891 struct kerneldumpkey *kdk;
892 uint32_t dumpkeysize;
894 dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
895 kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
897 arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
899 kdc->kdc_encryption = encryption;
900 switch (kdc->kdc_encryption) {
901 case KERNELDUMP_ENC_AES_256_CBC:
902 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
909 kdc->kdc_dumpkeysize = dumpkeysize;
910 kdk = kdc->kdc_dumpkey;
911 kdk->kdk_encryption = kdc->kdc_encryption;
912 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
913 kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
914 memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
918 explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
924 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
926 uint8_t hash[SHA256_DIGEST_LENGTH];
928 struct kerneldumpkey *kdk;
937 * When a user enters ddb it can write a crash dump multiple times.
938 * Each time it should be encrypted using a different IV.
941 SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
942 SHA256_Final(hash, &ctx);
943 bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
945 switch (kdc->kdc_encryption) {
946 case KERNELDUMP_ENC_AES_256_CBC:
947 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
958 kdk = kdc->kdc_dumpkey;
959 memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
961 explicit_bzero(hash, sizeof(hash));
966 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
971 return (kdc->kdc_dumpkeysize);
976 static struct kerneldumpgz *
977 kerneldumpgz_create(struct dumperinfo *di, uint8_t compression)
979 struct kerneldumpgz *kdgz;
981 if (compression != KERNELDUMP_COMP_GZIP)
983 kdgz = malloc(sizeof(*kdgz), M_DUMPER, M_WAITOK | M_ZERO);
984 kdgz->kdgz_stream = gzio_init(kerneldumpgz_write_cb, GZIO_DEFLATE,
985 di->maxiosize, kerneldump_gzlevel, di);
986 if (kdgz->kdgz_stream == NULL) {
987 free(kdgz, M_DUMPER);
990 kdgz->kdgz_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
995 kerneldumpgz_destroy(struct dumperinfo *di)
997 struct kerneldumpgz *kdgz;
1002 gzio_fini(kdgz->kdgz_stream);
1003 explicit_bzero(kdgz->kdgz_buf, di->maxiosize);
1004 free(kdgz->kdgz_buf, M_DUMPER);
1005 free(kdgz, M_DUMPER);
1009 /* Registration of dumpers */
1011 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1012 uint8_t compression, uint8_t encryption, const uint8_t *key,
1013 uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1018 error = priv_check(td, PRIV_SETDUMPER);
1026 if (dumper.dumper != NULL)
1029 dumper.blockbuf = NULL;
1033 if (encryption != KERNELDUMP_ENC_NONE) {
1035 dumper.kdc = kerneldumpcrypto_create(di->blocksize, encryption,
1036 key, encryptedkeysize, encryptedkey);
1037 if (dumper.kdc == NULL) {
1047 wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1048 if (wantcopy >= sizeof(dumpdevname)) {
1049 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1050 devname, dumpdevname);
1053 if (compression != KERNELDUMP_COMP_NONE) {
1056 * We currently can't support simultaneous encryption and
1059 if (encryption != KERNELDUMP_ENC_NONE) {
1063 dumper.kdgz = kerneldumpgz_create(&dumper, compression);
1064 if (dumper.kdgz == NULL) {
1074 dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1078 if (dumper.kdc != NULL) {
1079 explicit_bzero(dumper.kdc, sizeof(*dumper.kdc) +
1080 dumper.kdc->kdc_dumpkeysize);
1081 free(dumper.kdc, M_EKCD);
1086 kerneldumpgz_destroy(&dumper);
1089 if (dumper.blockbuf != NULL) {
1090 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1091 free(dumper.blockbuf, M_DUMPER);
1093 explicit_bzero(&dumper, sizeof(dumper));
1094 dumpdevname[0] = '\0';
1099 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1102 if (length != 0 && (offset < di->mediaoffset ||
1103 offset - di->mediaoffset + length > di->mediasize)) {
1104 printf("Attempt to write outside dump device boundaries.\n"
1105 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1106 (intmax_t)offset, (intmax_t)di->mediaoffset,
1107 (uintmax_t)length, (intmax_t)di->mediasize);
1110 if (length % di->blocksize != 0) {
1111 printf("Attempt to write partial block of length %ju.\n",
1115 if (offset % di->blocksize != 0) {
1116 printf("Attempt to write at unaligned offset %jd.\n",
1126 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1129 switch (kdc->kdc_encryption) {
1130 case KERNELDUMP_ENC_AES_256_CBC:
1131 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1132 8 * size, buf) <= 0) {
1135 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1136 buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1147 /* Encrypt data and call dumper. */
1149 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1150 vm_offset_t physical, off_t offset, size_t length)
1152 static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1153 struct kerneldumpcrypto *kdc;
1159 while (length > 0) {
1160 nbytes = MIN(length, sizeof(buf));
1161 bcopy(virtual, buf, nbytes);
1163 if (dump_encrypt(kdc, buf, nbytes) != 0)
1166 error = dump_write(di, buf, physical, offset, nbytes);
1171 virtual = (void *)((uint8_t *)virtual + nbytes);
1179 dump_write_key(struct dumperinfo *di, off_t offset)
1181 struct kerneldumpcrypto *kdc;
1186 return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1187 kdc->kdc_dumpkeysize));
1193 kerneldumpgz_write_cb(void *base, size_t length, off_t offset, void *arg)
1195 struct dumperinfo *di;
1196 size_t resid, rlength;
1201 if (length % di->blocksize != 0) {
1203 * This must be the final write after flushing the compression
1204 * stream. Write as many full blocks as possible and stash the
1205 * residual data in the dumper's block buffer. It will be
1206 * padded and written in dump_finish().
1208 rlength = rounddown(length, di->blocksize);
1210 error = _dump_append(di, base, 0, rlength);
1214 resid = length - rlength;
1215 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1216 di->kdgz->kdgz_resid = resid;
1219 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->kdc);
1282 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1287 dumpextent = dtoh64(kdh->dumpextent);
1288 if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1291 if (di->kdgz != NULL) {
1293 * We don't yet know how much space the compressed dump
1294 * will occupy, so try to use the whole swap partition
1295 * (minus the first 64KB) in the hope that the
1296 * compressed dump will fit. If that doesn't turn out to
1297 * be enouch, the bounds checking in dump_write()
1298 * will catch us and cause the dump to fail.
1300 dumpextent = di->mediasize - SIZEOF_METADATA -
1301 2 * di->blocksize - keysize;
1302 kdh->dumpextent = htod64(dumpextent);
1308 /* The offset at which to begin writing the dump. */
1309 di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1316 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1322 if (di->kdc != NULL)
1323 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1327 error = dump_write(di, virtual, physical, di->dumpoff, length);
1329 di->dumpoff += length;
1334 * Write to the dump device starting at dumpoff. When compression is enabled,
1335 * writes to the device will be performed using a callback that gets invoked
1336 * when the compression stream's output buffer is full.
1339 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1345 if (di->kdgz != NULL) {
1346 /* Bounce through a buffer to avoid gzip CRC errors. */
1347 if (length > di->maxiosize)
1349 buf = di->kdgz->kdgz_buf;
1350 memmove(buf, virtual, length);
1351 return (gzio_write(di->kdgz->kdgz_stream, buf, length));
1354 return (_dump_append(di, virtual, physical, length));
1358 * Write to the dump device at the specified offset.
1361 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1362 off_t offset, size_t length)
1366 error = dump_check_bounds(di, offset, length);
1369 return (di->dumper(di->priv, virtual, physical, offset, length));
1373 * Perform kernel dump finalization: flush the compression stream, if necessary,
1374 * write the leading and trailing kernel dump headers now that we know the true
1375 * length of the dump, and optionally write the encryption key following the
1379 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1385 extent = dtoh64(kdh->dumpextent);
1388 keysize = kerneldumpcrypto_dumpkeysize(di->kdc);
1394 if (di->kdgz != NULL) {
1395 error = gzio_flush(di->kdgz->kdgz_stream);
1396 if (error == EAGAIN) {
1397 /* We have residual data in di->blockbuf. */
1398 error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1400 di->dumpoff += di->kdgz->kdgz_resid;
1401 di->kdgz->kdgz_resid = 0;
1407 * We now know the size of the compressed dump, so update the
1408 * header accordingly and recompute parity.
1410 kdh->dumplength = htod64(di->dumpoff -
1411 (di->mediaoffset + di->mediasize - di->blocksize - extent));
1413 kdh->parity = kerneldump_parity(kdh);
1415 gzio_reset(di->kdgz->kdgz_stream);
1420 * Write kerneldump headers at the beginning and end of the dump extent.
1421 * Write the key after the leading header.
1423 error = dump_write_header(di, kdh,
1424 di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1430 error = dump_write_key(di,
1431 di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1436 error = dump_write_header(di, kdh,
1437 di->mediaoffset + di->mediasize - di->blocksize);
1441 (void)dump_write(di, NULL, 0, 0, 0);
1446 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1447 char *magic, uint32_t archver, uint64_t dumplen)
1451 bzero(kdh, sizeof(*kdh));
1452 strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1453 strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1454 kdh->version = htod32(KERNELDUMPVERSION);
1455 kdh->architectureversion = htod32(archver);
1456 kdh->dumplength = htod64(dumplen);
1457 kdh->dumpextent = kdh->dumplength;
1458 kdh->dumptime = htod64(time_second);
1460 kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdc));
1462 kdh->dumpkeysize = 0;
1464 kdh->blocksize = htod32(di->blocksize);
1465 strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1466 dstsize = sizeof(kdh->versionstring);
1467 if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1468 kdh->versionstring[dstsize - 2] = '\n';
1469 if (panicstr != NULL)
1470 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1472 if (di->kdgz != NULL)
1473 kdh->compression = KERNELDUMP_COMP_GZIP;
1475 kdh->parity = kerneldump_parity(kdh);
1479 DB_SHOW_COMMAND(panic, db_show_panic)
1482 if (panicstr == NULL)
1483 db_printf("panicstr not set\n");
1485 db_printf("panic: %s\n", panicstr);