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