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