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