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