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