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