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