]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_shutdown.c
Import OpenCSD -- an ARM CoreSight(tm) Trace Decode Library.
[FreeBSD/FreeBSD.git] / sys / kern / kern_shutdown.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
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.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
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.
23  *
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
34  * SUCH DAMAGE.
35  *
36  *      @(#)kern_shutdown.c     8.3 (Berkeley) 1/21/94
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 #include "opt_ddb.h"
43 #include "opt_ekcd.h"
44 #include "opt_kdb.h"
45 #include "opt_panic.h"
46 #include "opt_sched.h"
47 #include "opt_watchdog.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/bio.h>
52 #include <sys/buf.h>
53 #include <sys/conf.h>
54 #include <sys/compressor.h>
55 #include <sys/cons.h>
56 #include <sys/eventhandler.h>
57 #include <sys/filedesc.h>
58 #include <sys/jail.h>
59 #include <sys/kdb.h>
60 #include <sys/kernel.h>
61 #include <sys/kerneldump.h>
62 #include <sys/kthread.h>
63 #include <sys/ktr.h>
64 #include <sys/malloc.h>
65 #include <sys/mount.h>
66 #include <sys/priv.h>
67 #include <sys/proc.h>
68 #include <sys/reboot.h>
69 #include <sys/resourcevar.h>
70 #include <sys/rwlock.h>
71 #include <sys/sched.h>
72 #include <sys/smp.h>
73 #include <sys/sysctl.h>
74 #include <sys/sysproto.h>
75 #include <sys/taskqueue.h>
76 #include <sys/vnode.h>
77 #include <sys/watchdog.h>
78
79 #include <crypto/rijndael/rijndael-api-fst.h>
80 #include <crypto/sha2/sha256.h>
81
82 #include <ddb/ddb.h>
83
84 #include <machine/cpu.h>
85 #include <machine/dump.h>
86 #include <machine/pcb.h>
87 #include <machine/smp.h>
88
89 #include <security/mac/mac_framework.h>
90
91 #include <vm/vm.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pager.h>
95 #include <vm/swap_pager.h>
96
97 #include <sys/signalvar.h>
98
99 static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer");
100
101 #ifndef PANIC_REBOOT_WAIT_TIME
102 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
103 #endif
104 static int panic_reboot_wait_time = PANIC_REBOOT_WAIT_TIME;
105 SYSCTL_INT(_kern, OID_AUTO, panic_reboot_wait_time, CTLFLAG_RWTUN,
106     &panic_reboot_wait_time, 0,
107     "Seconds to wait before rebooting after a panic");
108
109 /*
110  * Note that stdarg.h and the ANSI style va_start macro is used for both
111  * ANSI and traditional C compilers.
112  */
113 #include <machine/stdarg.h>
114
115 #ifdef KDB
116 #ifdef KDB_UNATTENDED
117 int debugger_on_panic = 0;
118 #else
119 int debugger_on_panic = 1;
120 #endif
121 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic,
122     CTLFLAG_RWTUN | CTLFLAG_SECURE,
123     &debugger_on_panic, 0, "Run debugger on kernel panic");
124
125 #ifdef KDB_TRACE
126 static int trace_on_panic = 1;
127 #else
128 static int trace_on_panic = 0;
129 #endif
130 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic,
131     CTLFLAG_RWTUN | CTLFLAG_SECURE,
132     &trace_on_panic, 0, "Print stack trace on kernel panic");
133 #endif /* KDB */
134
135 static int sync_on_panic = 0;
136 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RWTUN,
137         &sync_on_panic, 0, "Do a sync before rebooting from a panic");
138
139 static bool poweroff_on_panic = 0;
140 SYSCTL_BOOL(_kern, OID_AUTO, poweroff_on_panic, CTLFLAG_RWTUN,
141         &poweroff_on_panic, 0, "Do a power off instead of a reboot on a panic");
142
143 static bool powercycle_on_panic = 0;
144 SYSCTL_BOOL(_kern, OID_AUTO, powercycle_on_panic, CTLFLAG_RWTUN,
145         &powercycle_on_panic, 0, "Do a power cycle instead of a reboot on a panic");
146
147 static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
148     "Shutdown environment");
149
150 #ifndef DIAGNOSTIC
151 static int show_busybufs;
152 #else
153 static int show_busybufs = 1;
154 #endif
155 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
156         &show_busybufs, 0, "");
157
158 int suspend_blocked = 0;
159 SYSCTL_INT(_kern, OID_AUTO, suspend_blocked, CTLFLAG_RW,
160         &suspend_blocked, 0, "Block suspend due to a pending shutdown");
161
162 #ifdef EKCD
163 FEATURE(ekcd, "Encrypted kernel crash dumps support");
164
165 MALLOC_DEFINE(M_EKCD, "ekcd", "Encrypted kernel crash dumps data");
166
167 struct kerneldumpcrypto {
168         uint8_t                 kdc_encryption;
169         uint8_t                 kdc_iv[KERNELDUMP_IV_MAX_SIZE];
170         keyInstance             kdc_ki;
171         cipherInstance          kdc_ci;
172         uint32_t                kdc_dumpkeysize;
173         struct kerneldumpkey    kdc_dumpkey[];
174 };
175 #endif
176
177 struct kerneldumpcomp {
178         uint8_t                 kdc_format;
179         struct compressor       *kdc_stream;
180         uint8_t                 *kdc_buf;
181         size_t                  kdc_resid;
182 };
183
184 static struct kerneldumpcomp *kerneldumpcomp_create(struct dumperinfo *di,
185                     uint8_t compression);
186 static void     kerneldumpcomp_destroy(struct dumperinfo *di);
187 static int      kerneldumpcomp_write_cb(void *base, size_t len, off_t off, void *arg);
188
189 static int kerneldump_gzlevel = 6;
190 SYSCTL_INT(_kern, OID_AUTO, kerneldump_gzlevel, CTLFLAG_RWTUN,
191     &kerneldump_gzlevel, 0,
192     "Kernel crash dump compression level");
193
194 /*
195  * Variable panicstr contains argument to first call to panic; used as flag
196  * to indicate that the kernel has already called panic.
197  */
198 const char *panicstr;
199
200 int dumping;                            /* system is dumping */
201 int rebooting;                          /* system is rebooting */
202 static struct dumperinfo dumper;        /* our selected dumper */
203
204 /* Context information for dump-debuggers. */
205 static struct pcb dumppcb;              /* Registers. */
206 lwpid_t dumptid;                        /* Thread ID. */
207
208 static struct cdevsw reroot_cdevsw = {
209      .d_version = D_VERSION,
210      .d_name    = "reroot",
211 };
212
213 static void poweroff_wait(void *, int);
214 static void shutdown_halt(void *junk, int howto);
215 static void shutdown_panic(void *junk, int howto);
216 static void shutdown_reset(void *junk, int howto);
217 static int kern_reroot(void);
218
219 /* register various local shutdown events */
220 static void
221 shutdown_conf(void *unused)
222 {
223
224         EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
225             SHUTDOWN_PRI_FIRST);
226         EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
227             SHUTDOWN_PRI_LAST + 100);
228         EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
229             SHUTDOWN_PRI_LAST + 100);
230         EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
231             SHUTDOWN_PRI_LAST + 200);
232 }
233
234 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
235
236 /*
237  * The only reason this exists is to create the /dev/reroot/ directory,
238  * used by reroot code in init(8) as a mountpoint for tmpfs.
239  */
240 static void
241 reroot_conf(void *unused)
242 {
243         int error;
244         struct cdev *cdev;
245
246         error = make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &cdev,
247             &reroot_cdevsw, NULL, UID_ROOT, GID_WHEEL, 0600, "reroot/reroot");
248         if (error != 0) {
249                 printf("%s: failed to create device node, error %d",
250                     __func__, error);
251         }
252 }
253
254 SYSINIT(reroot_conf, SI_SUB_DEVFS, SI_ORDER_ANY, reroot_conf, NULL);
255
256 /*
257  * The system call that results in a reboot.
258  */
259 /* ARGSUSED */
260 int
261 sys_reboot(struct thread *td, struct reboot_args *uap)
262 {
263         int error;
264
265         error = 0;
266 #ifdef MAC
267         error = mac_system_check_reboot(td->td_ucred, uap->opt);
268 #endif
269         if (error == 0)
270                 error = priv_check(td, PRIV_REBOOT);
271         if (error == 0) {
272                 if (uap->opt & RB_REROOT)
273                         error = kern_reroot();
274                 else
275                         kern_reboot(uap->opt);
276         }
277         return (error);
278 }
279
280 static void
281 shutdown_nice_task_fn(void *arg, int pending __unused)
282 {
283         int howto;
284
285         howto = (uintptr_t)arg;
286         /* Send a signal to init(8) and have it shutdown the world. */
287         PROC_LOCK(initproc);
288         if (howto & RB_POWEROFF)
289                 kern_psignal(initproc, SIGUSR2);
290         else if (howto & RB_POWERCYCLE)
291                 kern_psignal(initproc, SIGWINCH);
292         else if (howto & RB_HALT)
293                 kern_psignal(initproc, SIGUSR1);
294         else
295                 kern_psignal(initproc, SIGINT);
296         PROC_UNLOCK(initproc);
297 }
298
299 static struct task shutdown_nice_task = TASK_INITIALIZER(0,
300     &shutdown_nice_task_fn, NULL);
301
302 /*
303  * Called by events that want to shut down.. e.g  <CTL><ALT><DEL> on a PC
304  */
305 void
306 shutdown_nice(int howto)
307 {
308
309         if (initproc != NULL && !SCHEDULER_STOPPED()) {
310                 shutdown_nice_task.ta_context = (void *)(uintptr_t)howto;
311                 taskqueue_enqueue(taskqueue_fast, &shutdown_nice_task);
312         } else {
313                 /*
314                  * No init(8) running, or scheduler would not allow it
315                  * to run, so simply reboot.
316                  */
317                 kern_reboot(howto | RB_NOSYNC);
318         }
319 }
320
321 static void
322 print_uptime(void)
323 {
324         int f;
325         struct timespec ts;
326
327         getnanouptime(&ts);
328         printf("Uptime: ");
329         f = 0;
330         if (ts.tv_sec >= 86400) {
331                 printf("%ldd", (long)ts.tv_sec / 86400);
332                 ts.tv_sec %= 86400;
333                 f = 1;
334         }
335         if (f || ts.tv_sec >= 3600) {
336                 printf("%ldh", (long)ts.tv_sec / 3600);
337                 ts.tv_sec %= 3600;
338                 f = 1;
339         }
340         if (f || ts.tv_sec >= 60) {
341                 printf("%ldm", (long)ts.tv_sec / 60);
342                 ts.tv_sec %= 60;
343                 f = 1;
344         }
345         printf("%lds\n", (long)ts.tv_sec);
346 }
347
348 int
349 doadump(boolean_t textdump)
350 {
351         boolean_t coredump;
352         int error;
353
354         error = 0;
355         if (dumping)
356                 return (EBUSY);
357         if (dumper.dumper == NULL)
358                 return (ENXIO);
359
360         savectx(&dumppcb);
361         dumptid = curthread->td_tid;
362         dumping++;
363
364         coredump = TRUE;
365 #ifdef DDB
366         if (textdump && textdump_pending) {
367                 coredump = FALSE;
368                 textdump_dumpsys(&dumper);
369         }
370 #endif
371         if (coredump)
372                 error = dumpsys(&dumper);
373
374         dumping--;
375         return (error);
376 }
377
378 /*
379  * Shutdown the system cleanly to prepare for reboot, halt, or power off.
380  */
381 void
382 kern_reboot(int howto)
383 {
384         static int once = 0;
385
386         /*
387          * Normal paths here don't hold Giant, but we can wind up here
388          * unexpectedly with it held.  Drop it now so we don't have to
389          * drop and pick it up elsewhere. The paths it is locking will
390          * never be returned to, and it is preferable to preclude
391          * deadlock than to lock against code that won't ever
392          * continue.
393          */
394         while (mtx_owned(&Giant))
395                 mtx_unlock(&Giant);
396
397 #if defined(SMP)
398         /*
399          * Bind us to the first CPU so that all shutdown code runs there.  Some
400          * systems don't shutdown properly (i.e., ACPI power off) if we
401          * run on another processor.
402          */
403         if (!SCHEDULER_STOPPED()) {
404                 thread_lock(curthread);
405                 sched_bind(curthread, CPU_FIRST());
406                 thread_unlock(curthread);
407                 KASSERT(PCPU_GET(cpuid) == CPU_FIRST(),
408                     ("boot: not running on cpu 0"));
409         }
410 #endif
411         /* We're in the process of rebooting. */
412         rebooting = 1;
413
414         /* We are out of the debugger now. */
415         kdb_active = 0;
416
417         /*
418          * Do any callouts that should be done BEFORE syncing the filesystems.
419          */
420         EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
421
422         /* 
423          * Now sync filesystems
424          */
425         if (!cold && (howto & RB_NOSYNC) == 0 && once == 0) {
426                 once = 1;
427                 bufshutdown(show_busybufs);
428         }
429
430         print_uptime();
431
432         cngrab();
433
434         /*
435          * Ok, now do things that assume all filesystem activity has
436          * been completed.
437          */
438         EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
439
440         if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping) 
441                 doadump(TRUE);
442
443         /* Now that we're going to really halt the system... */
444         EVENTHANDLER_INVOKE(shutdown_final, howto);
445
446         for(;;) ;       /* safety against shutdown_reset not working */
447         /* NOTREACHED */
448 }
449
450 /*
451  * The system call that results in changing the rootfs.
452  */
453 static int
454 kern_reroot(void)
455 {
456         struct vnode *oldrootvnode, *vp;
457         struct mount *mp, *devmp;
458         int error;
459
460         if (curproc != initproc)
461                 return (EPERM);
462
463         /*
464          * Mark the filesystem containing currently-running executable
465          * (the temporary copy of init(8)) busy.
466          */
467         vp = curproc->p_textvp;
468         error = vn_lock(vp, LK_SHARED);
469         if (error != 0)
470                 return (error);
471         mp = vp->v_mount;
472         error = vfs_busy(mp, MBF_NOWAIT);
473         if (error != 0) {
474                 vfs_ref(mp);
475                 VOP_UNLOCK(vp, 0);
476                 error = vfs_busy(mp, 0);
477                 vn_lock(vp, LK_SHARED | LK_RETRY);
478                 vfs_rel(mp);
479                 if (error != 0) {
480                         VOP_UNLOCK(vp, 0);
481                         return (ENOENT);
482                 }
483                 if (vp->v_iflag & VI_DOOMED) {
484                         VOP_UNLOCK(vp, 0);
485                         vfs_unbusy(mp);
486                         return (ENOENT);
487                 }
488         }
489         VOP_UNLOCK(vp, 0);
490
491         /*
492          * Remove the filesystem containing currently-running executable
493          * from the mount list, to prevent it from being unmounted
494          * by vfs_unmountall(), and to avoid confusing vfs_mountroot().
495          *
496          * Also preserve /dev - forcibly unmounting it could cause driver
497          * reinitialization.
498          */
499
500         vfs_ref(rootdevmp);
501         devmp = rootdevmp;
502         rootdevmp = NULL;
503
504         mtx_lock(&mountlist_mtx);
505         TAILQ_REMOVE(&mountlist, mp, mnt_list);
506         TAILQ_REMOVE(&mountlist, devmp, mnt_list);
507         mtx_unlock(&mountlist_mtx);
508
509         oldrootvnode = rootvnode;
510
511         /*
512          * Unmount everything except for the two filesystems preserved above.
513          */
514         vfs_unmountall();
515
516         /*
517          * Add /dev back; vfs_mountroot() will move it into its new place.
518          */
519         mtx_lock(&mountlist_mtx);
520         TAILQ_INSERT_HEAD(&mountlist, devmp, mnt_list);
521         mtx_unlock(&mountlist_mtx);
522         rootdevmp = devmp;
523         vfs_rel(rootdevmp);
524
525         /*
526          * Mount the new rootfs.
527          */
528         vfs_mountroot();
529
530         /*
531          * Update all references to the old rootvnode.
532          */
533         mountcheckdirs(oldrootvnode, rootvnode);
534
535         /*
536          * Add the temporary filesystem back and unbusy it.
537          */
538         mtx_lock(&mountlist_mtx);
539         TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
540         mtx_unlock(&mountlist_mtx);
541         vfs_unbusy(mp);
542
543         return (0);
544 }
545
546 /*
547  * If the shutdown was a clean halt, behave accordingly.
548  */
549 static void
550 shutdown_halt(void *junk, int howto)
551 {
552
553         if (howto & RB_HALT) {
554                 printf("\n");
555                 printf("The operating system has halted.\n");
556                 printf("Please press any key to reboot.\n\n");
557                 switch (cngetc()) {
558                 case -1:                /* No console, just die */
559                         cpu_halt();
560                         /* NOTREACHED */
561                 default:
562                         break;
563                 }
564         }
565 }
566
567 /*
568  * Check to see if the system paniced, pause and then reboot
569  * according to the specified delay.
570  */
571 static void
572 shutdown_panic(void *junk, int howto)
573 {
574         int loop;
575
576         if (howto & RB_DUMP) {
577                 if (panic_reboot_wait_time != 0) {
578                         if (panic_reboot_wait_time != -1) {
579                                 printf("Automatic reboot in %d seconds - "
580                                        "press a key on the console to abort\n",
581                                         panic_reboot_wait_time);
582                                 for (loop = panic_reboot_wait_time * 10;
583                                      loop > 0; --loop) {
584                                         DELAY(1000 * 100); /* 1/10th second */
585                                         /* Did user type a key? */
586                                         if (cncheckc() != -1)
587                                                 break;
588                                 }
589                                 if (!loop)
590                                         return;
591                         }
592                 } else { /* zero time specified - reboot NOW */
593                         return;
594                 }
595                 printf("--> Press a key on the console to reboot,\n");
596                 printf("--> or switch off the system now.\n");
597                 cngetc();
598         }
599 }
600
601 /*
602  * Everything done, now reset
603  */
604 static void
605 shutdown_reset(void *junk, int howto)
606 {
607
608         printf("Rebooting...\n");
609         DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
610
611         /*
612          * Acquiring smp_ipi_mtx here has a double effect:
613          * - it disables interrupts avoiding CPU0 preemption
614          *   by fast handlers (thus deadlocking  against other CPUs)
615          * - it avoids deadlocks against smp_rendezvous() or, more 
616          *   generally, threads busy-waiting, with this spinlock held,
617          *   and waiting for responses by threads on other CPUs
618          *   (ie. smp_tlb_shootdown()).
619          *
620          * For the !SMP case it just needs to handle the former problem.
621          */
622 #ifdef SMP
623         mtx_lock_spin(&smp_ipi_mtx);
624 #else
625         spinlock_enter();
626 #endif
627
628         /* cpu_boot(howto); */ /* doesn't do anything at the moment */
629         cpu_reset();
630         /* NOTREACHED */ /* assuming reset worked */
631 }
632
633 #if defined(WITNESS) || defined(INVARIANT_SUPPORT)
634 static int kassert_warn_only = 0;
635 #ifdef KDB
636 static int kassert_do_kdb = 0;
637 #endif
638 #ifdef KTR
639 static int kassert_do_ktr = 0;
640 #endif
641 static int kassert_do_log = 1;
642 static int kassert_log_pps_limit = 4;
643 static int kassert_log_mute_at = 0;
644 static int kassert_log_panic_at = 0;
645 static int kassert_warnings = 0;
646
647 SYSCTL_NODE(_debug, OID_AUTO, kassert, CTLFLAG_RW, NULL, "kassert options");
648
649 SYSCTL_INT(_debug_kassert, OID_AUTO, warn_only, CTLFLAG_RWTUN,
650     &kassert_warn_only, 0,
651     "KASSERT triggers a panic (1) or just a warning (0)");
652
653 #ifdef KDB
654 SYSCTL_INT(_debug_kassert, OID_AUTO, do_kdb, CTLFLAG_RWTUN,
655     &kassert_do_kdb, 0, "KASSERT will enter the debugger");
656 #endif
657
658 #ifdef KTR
659 SYSCTL_UINT(_debug_kassert, OID_AUTO, do_ktr, CTLFLAG_RWTUN,
660     &kassert_do_ktr, 0,
661     "KASSERT does a KTR, set this to the KTRMASK you want");
662 #endif
663
664 SYSCTL_INT(_debug_kassert, OID_AUTO, do_log, CTLFLAG_RWTUN,
665     &kassert_do_log, 0, "KASSERT triggers a panic (1) or just a warning (0)");
666
667 SYSCTL_INT(_debug_kassert, OID_AUTO, warnings, CTLFLAG_RWTUN,
668     &kassert_warnings, 0, "number of KASSERTs that have been triggered");
669
670 SYSCTL_INT(_debug_kassert, OID_AUTO, log_panic_at, CTLFLAG_RWTUN,
671     &kassert_log_panic_at, 0, "max number of KASSERTS before we will panic");
672
673 SYSCTL_INT(_debug_kassert, OID_AUTO, log_pps_limit, CTLFLAG_RWTUN,
674     &kassert_log_pps_limit, 0, "limit number of log messages per second");
675
676 SYSCTL_INT(_debug_kassert, OID_AUTO, log_mute_at, CTLFLAG_RWTUN,
677     &kassert_log_mute_at, 0, "max number of KASSERTS to log");
678
679 static int kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS);
680
681 SYSCTL_PROC(_debug_kassert, OID_AUTO, kassert,
682     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, NULL, 0,
683     kassert_sysctl_kassert, "I", "set to trigger a test kassert");
684
685 static int
686 kassert_sysctl_kassert(SYSCTL_HANDLER_ARGS)
687 {
688         int error, i;
689
690         error = sysctl_wire_old_buffer(req, sizeof(int));
691         if (error == 0) {
692                 i = 0;
693                 error = sysctl_handle_int(oidp, &i, 0, req);
694         }
695         if (error != 0 || req->newptr == NULL)
696                 return (error);
697         KASSERT(0, ("kassert_sysctl_kassert triggered kassert %d", i));
698         return (0);
699 }
700
701 /*
702  * Called by KASSERT, this decides if we will panic
703  * or if we will log via printf and/or ktr.
704  */
705 void
706 kassert_panic(const char *fmt, ...)
707 {
708         static char buf[256];
709         va_list ap;
710
711         va_start(ap, fmt);
712         (void)vsnprintf(buf, sizeof(buf), fmt, ap);
713         va_end(ap);
714
715         /*
716          * panic if we're not just warning, or if we've exceeded
717          * kassert_log_panic_at warnings.
718          */
719         if (!kassert_warn_only ||
720             (kassert_log_panic_at > 0 &&
721              kassert_warnings >= kassert_log_panic_at)) {
722                 va_start(ap, fmt);
723                 vpanic(fmt, ap);
724                 /* NORETURN */
725         }
726 #ifdef KTR
727         if (kassert_do_ktr)
728                 CTR0(ktr_mask, buf);
729 #endif /* KTR */
730         /*
731          * log if we've not yet met the mute limit.
732          */
733         if (kassert_do_log &&
734             (kassert_log_mute_at == 0 ||
735              kassert_warnings < kassert_log_mute_at)) {
736                 static  struct timeval lasterr;
737                 static  int curerr;
738
739                 if (ppsratecheck(&lasterr, &curerr, kassert_log_pps_limit)) {
740                         printf("KASSERT failed: %s\n", buf);
741                         kdb_backtrace();
742                 }
743         }
744 #ifdef KDB
745         if (kassert_do_kdb) {
746                 kdb_enter(KDB_WHY_KASSERT, buf);
747         }
748 #endif
749         atomic_add_int(&kassert_warnings, 1);
750 }
751 #endif
752
753 /*
754  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
755  * and then reboots.  If we are called twice, then we avoid trying to sync
756  * the disks as this often leads to recursive panics.
757  */
758 void
759 panic(const char *fmt, ...)
760 {
761         va_list ap;
762
763         va_start(ap, fmt);
764         vpanic(fmt, ap);
765 }
766
767 void
768 vpanic(const char *fmt, va_list ap)
769 {
770 #ifdef SMP
771         cpuset_t other_cpus;
772 #endif
773         struct thread *td = curthread;
774         int bootopt, newpanic;
775         static char buf[256];
776
777         spinlock_enter();
778
779 #ifdef SMP
780         /*
781          * stop_cpus_hard(other_cpus) should prevent multiple CPUs from
782          * concurrently entering panic.  Only the winner will proceed
783          * further.
784          */
785         if (panicstr == NULL && !kdb_active) {
786                 other_cpus = all_cpus;
787                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
788                 stop_cpus_hard(other_cpus);
789         }
790 #endif
791
792         /*
793          * Ensure that the scheduler is stopped while panicking, even if panic
794          * has been entered from kdb.
795          */
796         td->td_stopsched = 1;
797
798         bootopt = RB_AUTOBOOT;
799         newpanic = 0;
800         if (panicstr)
801                 bootopt |= RB_NOSYNC;
802         else {
803                 bootopt |= RB_DUMP;
804                 panicstr = fmt;
805                 newpanic = 1;
806         }
807
808         if (newpanic) {
809                 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
810                 panicstr = buf;
811                 cngrab();
812                 printf("panic: %s\n", buf);
813         } else {
814                 printf("panic: ");
815                 vprintf(fmt, ap);
816                 printf("\n");
817         }
818 #ifdef SMP
819         printf("cpuid = %d\n", PCPU_GET(cpuid));
820 #endif
821         printf("time = %jd\n", (intmax_t )time_second);
822 #ifdef KDB
823         if (newpanic && trace_on_panic)
824                 kdb_backtrace();
825         if (debugger_on_panic)
826                 kdb_enter(KDB_WHY_PANIC, "panic");
827 #endif
828         /*thread_lock(td); */
829         td->td_flags |= TDF_INPANIC;
830         /* thread_unlock(td); */
831         if (!sync_on_panic)
832                 bootopt |= RB_NOSYNC;
833         if (poweroff_on_panic)
834                 bootopt |= RB_POWEROFF;
835         if (powercycle_on_panic)
836                 bootopt |= RB_POWERCYCLE;
837         kern_reboot(bootopt);
838 }
839
840 /*
841  * Support for poweroff delay.
842  *
843  * Please note that setting this delay too short might power off your machine
844  * before the write cache on your hard disk has been flushed, leading to
845  * soft-updates inconsistencies.
846  */
847 #ifndef POWEROFF_DELAY
848 # define POWEROFF_DELAY 5000
849 #endif
850 static int poweroff_delay = POWEROFF_DELAY;
851
852 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
853     &poweroff_delay, 0, "Delay before poweroff to write disk caches (msec)");
854
855 static void
856 poweroff_wait(void *junk, int howto)
857 {
858
859         if ((howto & (RB_POWEROFF | RB_POWERCYCLE)) == 0 || poweroff_delay <= 0)
860                 return;
861         DELAY(poweroff_delay * 1000);
862 }
863
864 /*
865  * Some system processes (e.g. syncer) need to be stopped at appropriate
866  * points in their main loops prior to a system shutdown, so that they
867  * won't interfere with the shutdown process (e.g. by holding a disk buf
868  * to cause sync to fail).  For each of these system processes, register
869  * shutdown_kproc() as a handler for one of shutdown events.
870  */
871 static int kproc_shutdown_wait = 60;
872 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
873     &kproc_shutdown_wait, 0, "Max wait time (sec) to stop for each process");
874
875 void
876 kproc_shutdown(void *arg, int howto)
877 {
878         struct proc *p;
879         int error;
880
881         if (panicstr)
882                 return;
883
884         p = (struct proc *)arg;
885         printf("Waiting (max %d seconds) for system process `%s' to stop... ",
886             kproc_shutdown_wait, p->p_comm);
887         error = kproc_suspend(p, kproc_shutdown_wait * hz);
888
889         if (error == EWOULDBLOCK)
890                 printf("timed out\n");
891         else
892                 printf("done\n");
893 }
894
895 void
896 kthread_shutdown(void *arg, int howto)
897 {
898         struct thread *td;
899         int error;
900
901         if (panicstr)
902                 return;
903
904         td = (struct thread *)arg;
905         printf("Waiting (max %d seconds) for system thread `%s' to stop... ",
906             kproc_shutdown_wait, td->td_name);
907         error = kthread_suspend(td, kproc_shutdown_wait * hz);
908
909         if (error == EWOULDBLOCK)
910                 printf("timed out\n");
911         else
912                 printf("done\n");
913 }
914
915 static char dumpdevname[sizeof(((struct cdev*)NULL)->si_name)];
916 SYSCTL_STRING(_kern_shutdown, OID_AUTO, dumpdevname, CTLFLAG_RD,
917     dumpdevname, 0, "Device for kernel dumps");
918
919 static int      _dump_append(struct dumperinfo *di, void *virtual,
920                     vm_offset_t physical, size_t length);
921
922 #ifdef EKCD
923 static struct kerneldumpcrypto *
924 kerneldumpcrypto_create(size_t blocksize, uint8_t encryption,
925     const uint8_t *key, uint32_t encryptedkeysize, const uint8_t *encryptedkey)
926 {
927         struct kerneldumpcrypto *kdc;
928         struct kerneldumpkey *kdk;
929         uint32_t dumpkeysize;
930
931         dumpkeysize = roundup2(sizeof(*kdk) + encryptedkeysize, blocksize);
932         kdc = malloc(sizeof(*kdc) + dumpkeysize, M_EKCD, M_WAITOK | M_ZERO);
933
934         arc4rand(kdc->kdc_iv, sizeof(kdc->kdc_iv), 0);
935
936         kdc->kdc_encryption = encryption;
937         switch (kdc->kdc_encryption) {
938         case KERNELDUMP_ENC_AES_256_CBC:
939                 if (rijndael_makeKey(&kdc->kdc_ki, DIR_ENCRYPT, 256, key) <= 0)
940                         goto failed;
941                 break;
942         default:
943                 goto failed;
944         }
945
946         kdc->kdc_dumpkeysize = dumpkeysize;
947         kdk = kdc->kdc_dumpkey;
948         kdk->kdk_encryption = kdc->kdc_encryption;
949         memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
950         kdk->kdk_encryptedkeysize = htod32(encryptedkeysize);
951         memcpy(kdk->kdk_encryptedkey, encryptedkey, encryptedkeysize);
952
953         return (kdc);
954 failed:
955         explicit_bzero(kdc, sizeof(*kdc) + dumpkeysize);
956         free(kdc, M_EKCD);
957         return (NULL);
958 }
959
960 static int
961 kerneldumpcrypto_init(struct kerneldumpcrypto *kdc)
962 {
963         uint8_t hash[SHA256_DIGEST_LENGTH];
964         SHA256_CTX ctx;
965         struct kerneldumpkey *kdk;
966         int error;
967
968         error = 0;
969
970         if (kdc == NULL)
971                 return (0);
972
973         /*
974          * When a user enters ddb it can write a crash dump multiple times.
975          * Each time it should be encrypted using a different IV.
976          */
977         SHA256_Init(&ctx);
978         SHA256_Update(&ctx, kdc->kdc_iv, sizeof(kdc->kdc_iv));
979         SHA256_Final(hash, &ctx);
980         bcopy(hash, kdc->kdc_iv, sizeof(kdc->kdc_iv));
981
982         switch (kdc->kdc_encryption) {
983         case KERNELDUMP_ENC_AES_256_CBC:
984                 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
985                     kdc->kdc_iv) <= 0) {
986                         error = EINVAL;
987                         goto out;
988                 }
989                 break;
990         default:
991                 error = EINVAL;
992                 goto out;
993         }
994
995         kdk = kdc->kdc_dumpkey;
996         memcpy(kdk->kdk_iv, kdc->kdc_iv, sizeof(kdk->kdk_iv));
997 out:
998         explicit_bzero(hash, sizeof(hash));
999         return (error);
1000 }
1001
1002 static uint32_t
1003 kerneldumpcrypto_dumpkeysize(const struct kerneldumpcrypto *kdc)
1004 {
1005
1006         if (kdc == NULL)
1007                 return (0);
1008         return (kdc->kdc_dumpkeysize);
1009 }
1010 #endif /* EKCD */
1011
1012 static struct kerneldumpcomp *
1013 kerneldumpcomp_create(struct dumperinfo *di, uint8_t compression)
1014 {
1015         struct kerneldumpcomp *kdcomp;
1016         int format;
1017
1018         switch (compression) {
1019         case KERNELDUMP_COMP_GZIP:
1020                 format = COMPRESS_GZIP;
1021                 break;
1022         case KERNELDUMP_COMP_ZSTD:
1023                 format = COMPRESS_ZSTD;
1024                 break;
1025         default:
1026                 return (NULL);
1027         }
1028
1029         kdcomp = malloc(sizeof(*kdcomp), M_DUMPER, M_WAITOK | M_ZERO);
1030         kdcomp->kdc_format = compression;
1031         kdcomp->kdc_stream = compressor_init(kerneldumpcomp_write_cb,
1032             format, di->maxiosize, kerneldump_gzlevel, di);
1033         if (kdcomp->kdc_stream == NULL) {
1034                 free(kdcomp, M_DUMPER);
1035                 return (NULL);
1036         }
1037         kdcomp->kdc_buf = malloc(di->maxiosize, M_DUMPER, M_WAITOK | M_NODUMP);
1038         return (kdcomp);
1039 }
1040
1041 static void
1042 kerneldumpcomp_destroy(struct dumperinfo *di)
1043 {
1044         struct kerneldumpcomp *kdcomp;
1045
1046         kdcomp = di->kdcomp;
1047         if (kdcomp == NULL)
1048                 return;
1049         compressor_fini(kdcomp->kdc_stream);
1050         explicit_bzero(kdcomp->kdc_buf, di->maxiosize);
1051         free(kdcomp->kdc_buf, M_DUMPER);
1052         free(kdcomp, M_DUMPER);
1053 }
1054
1055 /* Registration of dumpers */
1056 int
1057 set_dumper(struct dumperinfo *di, const char *devname, struct thread *td,
1058     uint8_t compression, uint8_t encryption, const uint8_t *key,
1059     uint32_t encryptedkeysize, const uint8_t *encryptedkey)
1060 {
1061         size_t wantcopy;
1062         int error;
1063
1064         error = priv_check(td, PRIV_SETDUMPER);
1065         if (error != 0)
1066                 return (error);
1067
1068         if (di == NULL) {
1069                 error = 0;
1070                 goto cleanup;
1071         }
1072         if (dumper.dumper != NULL)
1073                 return (EBUSY);
1074         dumper = *di;
1075         dumper.blockbuf = NULL;
1076         dumper.kdcrypto = NULL;
1077         dumper.kdcomp = NULL;
1078
1079         if (encryption != KERNELDUMP_ENC_NONE) {
1080 #ifdef EKCD
1081                 dumper.kdcrypto = kerneldumpcrypto_create(di->blocksize,
1082                     encryption, key, encryptedkeysize, encryptedkey);
1083                 if (dumper.kdcrypto == NULL) {
1084                         error = EINVAL;
1085                         goto cleanup;
1086                 }
1087 #else
1088                 error = EOPNOTSUPP;
1089                 goto cleanup;
1090 #endif
1091         }
1092
1093         wantcopy = strlcpy(dumpdevname, devname, sizeof(dumpdevname));
1094         if (wantcopy >= sizeof(dumpdevname)) {
1095                 printf("set_dumper: device name truncated from '%s' -> '%s'\n",
1096                     devname, dumpdevname);
1097         }
1098
1099         if (compression != KERNELDUMP_COMP_NONE) {
1100                 /*
1101                  * We currently can't support simultaneous encryption and
1102                  * compression.
1103                  */
1104                 if (encryption != KERNELDUMP_ENC_NONE) {
1105                         error = EOPNOTSUPP;
1106                         goto cleanup;
1107                 }
1108                 dumper.kdcomp = kerneldumpcomp_create(&dumper, compression);
1109                 if (dumper.kdcomp == NULL) {
1110                         error = EINVAL;
1111                         goto cleanup;
1112                 }
1113         }
1114
1115         dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO);
1116         return (0);
1117 cleanup:
1118 #ifdef EKCD
1119         if (dumper.kdcrypto != NULL) {
1120                 explicit_bzero(dumper.kdcrypto, sizeof(*dumper.kdcrypto) +
1121                     dumper.kdcrypto->kdc_dumpkeysize);
1122                 free(dumper.kdcrypto, M_EKCD);
1123         }
1124 #endif
1125
1126         kerneldumpcomp_destroy(&dumper);
1127
1128         if (dumper.blockbuf != NULL) {
1129                 explicit_bzero(dumper.blockbuf, dumper.blocksize);
1130                 free(dumper.blockbuf, M_DUMPER);
1131         }
1132         explicit_bzero(&dumper, sizeof(dumper));
1133         dumpdevname[0] = '\0';
1134         return (error);
1135 }
1136
1137 static int
1138 dump_check_bounds(struct dumperinfo *di, off_t offset, size_t length)
1139 {
1140
1141         if (length != 0 && (offset < di->mediaoffset ||
1142             offset - di->mediaoffset + length > di->mediasize)) {
1143                 if (di->kdcomp != NULL && offset >= di->mediaoffset) {
1144                         printf(
1145                     "Compressed dump failed to fit in device boundaries.\n");
1146                         return (E2BIG);
1147                 }
1148
1149                 printf("Attempt to write outside dump device boundaries.\n"
1150             "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
1151                     (intmax_t)offset, (intmax_t)di->mediaoffset,
1152                     (uintmax_t)length, (intmax_t)di->mediasize);
1153                 return (ENOSPC);
1154         }
1155         if (length % di->blocksize != 0) {
1156                 printf("Attempt to write partial block of length %ju.\n",
1157                     (uintmax_t)length);
1158                 return (EINVAL);
1159         }
1160         if (offset % di->blocksize != 0) {
1161                 printf("Attempt to write at unaligned offset %jd.\n",
1162                     (intmax_t)offset);
1163                 return (EINVAL);
1164         }
1165
1166         return (0);
1167 }
1168
1169 #ifdef EKCD
1170 static int
1171 dump_encrypt(struct kerneldumpcrypto *kdc, uint8_t *buf, size_t size)
1172 {
1173
1174         switch (kdc->kdc_encryption) {
1175         case KERNELDUMP_ENC_AES_256_CBC:
1176                 if (rijndael_blockEncrypt(&kdc->kdc_ci, &kdc->kdc_ki, buf,
1177                     8 * size, buf) <= 0) {
1178                         return (EIO);
1179                 }
1180                 if (rijndael_cipherInit(&kdc->kdc_ci, MODE_CBC,
1181                     buf + size - 16 /* IV size for AES-256-CBC */) <= 0) {
1182                         return (EIO);
1183                 }
1184                 break;
1185         default:
1186                 return (EINVAL);
1187         }
1188
1189         return (0);
1190 }
1191
1192 /* Encrypt data and call dumper. */
1193 static int
1194 dump_encrypted_write(struct dumperinfo *di, void *virtual,
1195     vm_offset_t physical, off_t offset, size_t length)
1196 {
1197         static uint8_t buf[KERNELDUMP_BUFFER_SIZE];
1198         struct kerneldumpcrypto *kdc;
1199         int error;
1200         size_t nbytes;
1201
1202         kdc = di->kdcrypto;
1203
1204         while (length > 0) {
1205                 nbytes = MIN(length, sizeof(buf));
1206                 bcopy(virtual, buf, nbytes);
1207
1208                 if (dump_encrypt(kdc, buf, nbytes) != 0)
1209                         return (EIO);
1210
1211                 error = dump_write(di, buf, physical, offset, nbytes);
1212                 if (error != 0)
1213                         return (error);
1214
1215                 offset += nbytes;
1216                 virtual = (void *)((uint8_t *)virtual + nbytes);
1217                 length -= nbytes;
1218         }
1219
1220         return (0);
1221 }
1222
1223 static int
1224 dump_write_key(struct dumperinfo *di, off_t offset)
1225 {
1226         struct kerneldumpcrypto *kdc;
1227
1228         kdc = di->kdcrypto;
1229         if (kdc == NULL)
1230                 return (0);
1231         return (dump_write(di, kdc->kdc_dumpkey, 0, offset,
1232             kdc->kdc_dumpkeysize));
1233 }
1234 #endif /* EKCD */
1235
1236 static int
1237 kerneldumpcomp_write_cb(void *base, size_t length, off_t offset, void *arg)
1238 {
1239         struct dumperinfo *di;
1240         size_t resid, rlength;
1241         int error;
1242
1243         di = arg;
1244
1245         if (length % di->blocksize != 0) {
1246                 /*
1247                  * This must be the final write after flushing the compression
1248                  * stream. Write as many full blocks as possible and stash the
1249                  * residual data in the dumper's block buffer. It will be
1250                  * padded and written in dump_finish().
1251                  */
1252                 rlength = rounddown(length, di->blocksize);
1253                 if (rlength != 0) {
1254                         error = _dump_append(di, base, 0, rlength);
1255                         if (error != 0)
1256                                 return (error);
1257                 }
1258                 resid = length - rlength;
1259                 memmove(di->blockbuf, (uint8_t *)base + rlength, resid);
1260                 di->kdcomp->kdc_resid = resid;
1261                 return (EAGAIN);
1262         }
1263         return (_dump_append(di, base, 0, length));
1264 }
1265
1266 /*
1267  * Write a kerneldumpheader at the specified offset. The header structure is 512
1268  * bytes in size, but we must pad to the device sector size.
1269  */
1270 static int
1271 dump_write_header(struct dumperinfo *di, struct kerneldumpheader *kdh,
1272     off_t offset)
1273 {
1274         void *buf;
1275         size_t hdrsz;
1276
1277         hdrsz = sizeof(*kdh);
1278         if (hdrsz > di->blocksize)
1279                 return (ENOMEM);
1280
1281         if (hdrsz == di->blocksize)
1282                 buf = kdh;
1283         else {
1284                 buf = di->blockbuf;
1285                 memset(buf, 0, di->blocksize);
1286                 memcpy(buf, kdh, hdrsz);
1287         }
1288
1289         return (dump_write(di, buf, 0, offset, di->blocksize));
1290 }
1291
1292 /*
1293  * Don't touch the first SIZEOF_METADATA bytes on the dump device.  This is to
1294  * protect us from metadata and metadata from us.
1295  */
1296 #define SIZEOF_METADATA         (64 * 1024)
1297
1298 /*
1299  * Do some preliminary setup for a kernel dump: initialize state for encryption,
1300  * if requested, and make sure that we have enough space on the dump device.
1301  *
1302  * We set things up so that the dump ends before the last sector of the dump
1303  * device, at which the trailing header is written.
1304  *
1305  *     +-----------+------+-----+----------------------------+------+
1306  *     |           | lhdr | key |    ... kernel dump ...     | thdr |
1307  *     +-----------+------+-----+----------------------------+------+
1308  *                   1 blk  opt <------- dump extent --------> 1 blk
1309  *
1310  * Dumps written using dump_append() start at the beginning of the extent.
1311  * Uncompressed dumps will use the entire extent, but compressed dumps typically
1312  * will not. The true length of the dump is recorded in the leading and trailing
1313  * headers once the dump has been completed.
1314  */
1315 int
1316 dump_start(struct dumperinfo *di, struct kerneldumpheader *kdh)
1317 {
1318         uint64_t dumpextent;
1319         uint32_t keysize;
1320
1321 #ifdef EKCD
1322         int error = kerneldumpcrypto_init(di->kdcrypto);
1323         if (error != 0)
1324                 return (error);
1325         keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1326 #else
1327         keysize = 0;
1328 #endif
1329
1330         dumpextent = dtoh64(kdh->dumpextent);
1331         if (di->mediasize < SIZEOF_METADATA + dumpextent + 2 * di->blocksize +
1332             keysize) {
1333                 if (di->kdcomp != NULL) {
1334                         /*
1335                          * We don't yet know how much space the compressed dump
1336                          * will occupy, so try to use the whole swap partition
1337                          * (minus the first 64KB) in the hope that the
1338                          * compressed dump will fit. If that doesn't turn out to
1339                          * be enough, the bounds checking in dump_write()
1340                          * will catch us and cause the dump to fail.
1341                          */
1342                         dumpextent = di->mediasize - SIZEOF_METADATA -
1343                             2 * di->blocksize - keysize;
1344                         kdh->dumpextent = htod64(dumpextent);
1345                 } else
1346                         return (E2BIG);
1347         }
1348
1349         /* The offset at which to begin writing the dump. */
1350         di->dumpoff = di->mediaoffset + di->mediasize - di->blocksize -
1351             dumpextent;
1352
1353         return (0);
1354 }
1355
1356 static int
1357 _dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1358     size_t length)
1359 {
1360         int error;
1361
1362 #ifdef EKCD
1363         if (di->kdcrypto != NULL)
1364                 error = dump_encrypted_write(di, virtual, physical, di->dumpoff,
1365                     length);
1366         else
1367 #endif
1368                 error = dump_write(di, virtual, physical, di->dumpoff, length);
1369         if (error == 0)
1370                 di->dumpoff += length;
1371         return (error);
1372 }
1373
1374 /*
1375  * Write to the dump device starting at dumpoff. When compression is enabled,
1376  * writes to the device will be performed using a callback that gets invoked
1377  * when the compression stream's output buffer is full.
1378  */
1379 int
1380 dump_append(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1381     size_t length)
1382 {
1383         void *buf;
1384
1385         if (di->kdcomp != NULL) {
1386                 /* Bounce through a buffer to avoid CRC errors. */
1387                 if (length > di->maxiosize)
1388                         return (EINVAL);
1389                 buf = di->kdcomp->kdc_buf;
1390                 memmove(buf, virtual, length);
1391                 return (compressor_write(di->kdcomp->kdc_stream, buf, length));
1392         }
1393         return (_dump_append(di, virtual, physical, length));
1394 }
1395
1396 /*
1397  * Write to the dump device at the specified offset.
1398  */
1399 int
1400 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
1401     off_t offset, size_t length)
1402 {
1403         int error;
1404
1405         error = dump_check_bounds(di, offset, length);
1406         if (error != 0)
1407                 return (error);
1408         return (di->dumper(di->priv, virtual, physical, offset, length));
1409 }
1410
1411 /*
1412  * Perform kernel dump finalization: flush the compression stream, if necessary,
1413  * write the leading and trailing kernel dump headers now that we know the true
1414  * length of the dump, and optionally write the encryption key following the
1415  * leading header.
1416  */
1417 int
1418 dump_finish(struct dumperinfo *di, struct kerneldumpheader *kdh)
1419 {
1420         uint64_t extent;
1421         uint32_t keysize;
1422         int error;
1423
1424         extent = dtoh64(kdh->dumpextent);
1425
1426 #ifdef EKCD
1427         keysize = kerneldumpcrypto_dumpkeysize(di->kdcrypto);
1428 #else
1429         keysize = 0;
1430 #endif
1431
1432         if (di->kdcomp != NULL) {
1433                 error = compressor_flush(di->kdcomp->kdc_stream);
1434                 if (error == EAGAIN) {
1435                         /* We have residual data in di->blockbuf. */
1436                         error = dump_write(di, di->blockbuf, 0, di->dumpoff,
1437                             di->blocksize);
1438                         di->dumpoff += di->kdcomp->kdc_resid;
1439                         di->kdcomp->kdc_resid = 0;
1440                 }
1441                 if (error != 0)
1442                         return (error);
1443
1444                 /*
1445                  * We now know the size of the compressed dump, so update the
1446                  * header accordingly and recompute parity.
1447                  */
1448                 kdh->dumplength = htod64(di->dumpoff -
1449                     (di->mediaoffset + di->mediasize - di->blocksize - extent));
1450                 kdh->parity = 0;
1451                 kdh->parity = kerneldump_parity(kdh);
1452
1453                 compressor_reset(di->kdcomp->kdc_stream);
1454         }
1455
1456         /*
1457          * Write kerneldump headers at the beginning and end of the dump extent.
1458          * Write the key after the leading header.
1459          */
1460         error = dump_write_header(di, kdh,
1461             di->mediaoffset + di->mediasize - 2 * di->blocksize - extent -
1462             keysize);
1463         if (error != 0)
1464                 return (error);
1465
1466 #ifdef EKCD
1467         error = dump_write_key(di,
1468             di->mediaoffset + di->mediasize - di->blocksize - extent - keysize);
1469         if (error != 0)
1470                 return (error);
1471 #endif
1472
1473         error = dump_write_header(di, kdh,
1474             di->mediaoffset + di->mediasize - di->blocksize);
1475         if (error != 0)
1476                 return (error);
1477
1478         (void)dump_write(di, NULL, 0, 0, 0);
1479         return (0);
1480 }
1481
1482 void
1483 dump_init_header(const struct dumperinfo *di, struct kerneldumpheader *kdh,
1484     char *magic, uint32_t archver, uint64_t dumplen)
1485 {
1486         size_t dstsize;
1487
1488         bzero(kdh, sizeof(*kdh));
1489         strlcpy(kdh->magic, magic, sizeof(kdh->magic));
1490         strlcpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
1491         kdh->version = htod32(KERNELDUMPVERSION);
1492         kdh->architectureversion = htod32(archver);
1493         kdh->dumplength = htod64(dumplen);
1494         kdh->dumpextent = kdh->dumplength;
1495         kdh->dumptime = htod64(time_second);
1496 #ifdef EKCD
1497         kdh->dumpkeysize = htod32(kerneldumpcrypto_dumpkeysize(di->kdcrypto));
1498 #else
1499         kdh->dumpkeysize = 0;
1500 #endif
1501         kdh->blocksize = htod32(di->blocksize);
1502         strlcpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
1503         dstsize = sizeof(kdh->versionstring);
1504         if (strlcpy(kdh->versionstring, version, dstsize) >= dstsize)
1505                 kdh->versionstring[dstsize - 2] = '\n';
1506         if (panicstr != NULL)
1507                 strlcpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
1508         if (di->kdcomp != NULL)
1509                 kdh->compression = di->kdcomp->kdc_format;
1510         kdh->parity = kerneldump_parity(kdh);
1511 }
1512
1513 #ifdef DDB
1514 DB_SHOW_COMMAND(panic, db_show_panic)
1515 {
1516
1517         if (panicstr == NULL)
1518                 db_printf("panicstr not set\n");
1519         else
1520                 db_printf("panic: %s\n", panicstr);
1521 }
1522 #endif