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