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