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