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