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