]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/trap.c
Merge r357339 from the clang1000-import branch:
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / trap.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (C) 1994, David Greenman
5  * Copyright (c) 1990, 1993
6  *      The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * the University of Utah, and William Jolitz.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  *      from: @(#)trap.c        7.4 (Berkeley) 5/13/91
40  */
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 /*
46  * AMD64 Trap and System call handling
47  */
48
49 #include "opt_clock.h"
50 #include "opt_compat.h"
51 #include "opt_cpu.h"
52 #include "opt_hwpmc_hooks.h"
53 #include "opt_isa.h"
54 #include "opt_kdb.h"
55
56 #include <sys/param.h>
57 #include <sys/bus.h>
58 #include <sys/systm.h>
59 #include <sys/proc.h>
60 #include <sys/pioctl.h>
61 #include <sys/ptrace.h>
62 #include <sys/kdb.h>
63 #include <sys/kernel.h>
64 #include <sys/ktr.h>
65 #include <sys/lock.h>
66 #include <sys/mutex.h>
67 #include <sys/resourcevar.h>
68 #include <sys/signalvar.h>
69 #include <sys/syscall.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysent.h>
72 #include <sys/uio.h>
73 #include <sys/vmmeter.h>
74 #ifdef HWPMC_HOOKS
75 #include <sys/pmckern.h>
76 PMC_SOFT_DEFINE( , , page_fault, all);
77 PMC_SOFT_DEFINE( , , page_fault, read);
78 PMC_SOFT_DEFINE( , , page_fault, write);
79 #endif
80
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_kern.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_page.h>
87 #include <vm/vm_extern.h>
88
89 #include <machine/cpu.h>
90 #include <machine/intr_machdep.h>
91 #include <x86/mca.h>
92 #include <machine/md_var.h>
93 #include <machine/pcb.h>
94 #ifdef SMP
95 #include <machine/smp.h>
96 #endif
97 #include <machine/stack.h>
98 #include <machine/trap.h>
99 #include <machine/tss.h>
100
101 #ifdef KDTRACE_HOOKS
102 #include <sys/dtrace_bsd.h>
103 #endif
104
105 extern inthand_t IDTVEC(bpt), IDTVEC(bpt_pti), IDTVEC(dbg),
106     IDTVEC(fast_syscall), IDTVEC(fast_syscall_pti), IDTVEC(fast_syscall32),
107     IDTVEC(int0x80_syscall_pti), IDTVEC(int0x80_syscall);
108
109 void __noinline trap(struct trapframe *frame);
110 void trap_check(struct trapframe *frame);
111 void dblfault_handler(struct trapframe *frame);
112
113 static int trap_pfault(struct trapframe *, bool, int *, int *);
114 static void trap_fatal(struct trapframe *, vm_offset_t);
115 #ifdef KDTRACE_HOOKS
116 static bool trap_user_dtrace(struct trapframe *,
117     int (**hook)(struct trapframe *));
118 #endif
119
120 static const char UNKNOWN[] = "unknown";
121 static const char *const trap_msg[] = {
122         [0] =                   UNKNOWN,                        /* unused */
123         [T_PRIVINFLT] =         "privileged instruction fault",
124         [2] =                   UNKNOWN,                        /* unused */
125         [T_BPTFLT] =            "breakpoint instruction fault",
126         [4] =                   UNKNOWN,                        /* unused */
127         [5] =                   UNKNOWN,                        /* unused */
128         [T_ARITHTRAP] =         "arithmetic trap",
129         [7] =                   UNKNOWN,                        /* unused */
130         [8] =                   UNKNOWN,                        /* unused */
131         [T_PROTFLT] =           "general protection fault",
132         [T_TRCTRAP] =           "debug exception",
133         [11] =                  UNKNOWN,                        /* unused */
134         [T_PAGEFLT] =           "page fault",
135         [13] =                  UNKNOWN,                        /* unused */
136         [T_ALIGNFLT] =          "alignment fault",
137         [15] =                  UNKNOWN,                        /* unused */
138         [16] =                  UNKNOWN,                        /* unused */
139         [17] =                  UNKNOWN,                        /* unused */
140         [T_DIVIDE] =            "integer divide fault",
141         [T_NMI] =               "non-maskable interrupt trap",
142         [T_OFLOW] =             "overflow trap",
143         [T_BOUND] =             "FPU bounds check fault",
144         [T_DNA] =               "FPU device not available",
145         [T_DOUBLEFLT] =         "double fault",
146         [T_FPOPFLT] =           "FPU operand fetch fault",
147         [T_TSSFLT] =            "invalid TSS fault",
148         [T_SEGNPFLT] =          "segment not present fault",
149         [T_STKFLT] =            "stack fault",
150         [T_MCHK] =              "machine check trap",
151         [T_XMMFLT] =            "SIMD floating-point exception",
152         [T_RESERVED] =          "reserved (unknown) fault",
153         [31] =                  UNKNOWN,                        /* reserved */
154         [T_DTRACE_RET] =        "DTrace pid return trap",
155 };
156
157 static int uprintf_signal;
158 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RWTUN,
159     &uprintf_signal, 0,
160     "Print debugging information on trap signal to ctty");
161
162 /*
163  * Control L1D flush on return from NMI.
164  *
165  * Tunable  can be set to the following values:
166  * 0 - only enable flush on return from NMI if required by vmm.ko (default)
167  * >1 - always flush on return from NMI.
168  *
169  * Post-boot, the sysctl indicates if flushing is currently enabled.
170  */
171 int nmi_flush_l1d_sw;
172 SYSCTL_INT(_machdep, OID_AUTO, nmi_flush_l1d_sw, CTLFLAG_RWTUN,
173     &nmi_flush_l1d_sw, 0,
174     "Flush L1 Data Cache on NMI exit, software bhyve L1TF mitigation assist");
175
176 /*
177  * Exception, fault, and trap interface to the FreeBSD kernel.
178  * This common code is called from assembly language IDT gate entry
179  * routines that prepare a suitable stack frame, and restore this
180  * frame after the exception has been processed.
181  */
182
183 void
184 trap(struct trapframe *frame)
185 {
186         ksiginfo_t ksi;
187         struct thread *td;
188         struct proc *p;
189         register_t addr, dr6;
190         int pf, signo, ucode;
191         u_int type;
192
193         td = curthread;
194         p = td->td_proc;
195         dr6 = 0;
196
197         VM_CNT_INC(v_trap);
198         type = frame->tf_trapno;
199
200 #ifdef SMP
201         /* Handler for NMI IPIs used for stopping CPUs. */
202         if (type == T_NMI && ipi_nmi_handler() == 0)
203                 return;
204 #endif
205
206 #ifdef KDB
207         if (kdb_active) {
208                 kdb_reenter();
209                 return;
210         }
211 #endif
212
213         if (type == T_RESERVED) {
214                 trap_fatal(frame, 0);
215                 return;
216         }
217
218         if (type == T_NMI) {
219 #ifdef HWPMC_HOOKS
220                 /*
221                  * CPU PMCs interrupt using an NMI.  If the PMC module is
222                  * active, pass the 'rip' value to the PMC module's interrupt
223                  * handler.  A non-zero return value from the handler means that
224                  * the NMI was consumed by it and we can return immediately.
225                  */
226                 if (pmc_intr != NULL &&
227                     (*pmc_intr)(frame) != 0)
228                         return;
229 #endif
230         }
231
232         if ((frame->tf_rflags & PSL_I) == 0) {
233                 /*
234                  * Buggy application or kernel code has disabled
235                  * interrupts and then trapped.  Enabling interrupts
236                  * now is wrong, but it is better than running with
237                  * interrupts disabled until they are accidentally
238                  * enabled later.
239                  */
240                 if (TRAPF_USERMODE(frame))
241                         uprintf(
242                             "pid %ld (%s): trap %d with interrupts disabled\n",
243                             (long)curproc->p_pid, curthread->td_name, type);
244                 else if (type != T_NMI && type != T_BPTFLT &&
245                     type != T_TRCTRAP) {
246                         /*
247                          * XXX not quite right, since this may be for a
248                          * multiple fault in user mode.
249                          */
250                         printf("kernel trap %d with interrupts disabled\n",
251                             type);
252
253                         /*
254                          * We shouldn't enable interrupts while holding a
255                          * spin lock.
256                          */
257                         if (td->td_md.md_spinlock_count == 0)
258                                 enable_intr();
259                 }
260         }
261
262         if (TRAPF_USERMODE(frame)) {
263                 /* user trap */
264
265                 td->td_pticks = 0;
266                 td->td_frame = frame;
267                 addr = frame->tf_rip;
268                 if (td->td_cowgen != p->p_cowgen)
269                         thread_cow_update(td);
270
271                 switch (type) {
272                 case T_PRIVINFLT:       /* privileged instruction fault */
273                         signo = SIGILL;
274                         ucode = ILL_PRVOPC;
275                         break;
276
277                 case T_BPTFLT:          /* bpt instruction fault */
278 #ifdef KDTRACE_HOOKS
279                         if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
280                                 return;
281 #else
282                         enable_intr();
283 #endif
284                         signo = SIGTRAP;
285                         ucode = TRAP_BRKPT;
286                         break;
287
288                 case T_TRCTRAP:         /* debug exception */
289                         enable_intr();
290                         signo = SIGTRAP;
291                         ucode = TRAP_TRACE;
292                         dr6 = rdr6();
293                         if ((dr6 & DBREG_DR6_BS) != 0) {
294                                 PROC_LOCK(td->td_proc);
295                                 if ((td->td_dbgflags & TDB_STEP) != 0) {
296                                         td->td_frame->tf_rflags &= ~PSL_T;
297                                         td->td_dbgflags &= ~TDB_STEP;
298                                 }
299                                 PROC_UNLOCK(td->td_proc);
300                         }
301                         break;
302
303                 case T_ARITHTRAP:       /* arithmetic trap */
304                         ucode = fputrap_x87();
305                         if (ucode == -1)
306                                 return;
307                         signo = SIGFPE;
308                         break;
309
310                 case T_PROTFLT:         /* general protection fault */
311                         signo = SIGBUS;
312                         ucode = BUS_OBJERR;
313                         break;
314                 case T_STKFLT:          /* stack fault */
315                 case T_SEGNPFLT:        /* segment not present fault */
316                         signo = SIGBUS;
317                         ucode = BUS_ADRERR;
318                         break;
319                 case T_TSSFLT:          /* invalid TSS fault */
320                         signo = SIGBUS;
321                         ucode = BUS_OBJERR;
322                         break;
323                 case T_ALIGNFLT:
324                         signo = SIGBUS;
325                         ucode = BUS_ADRALN;
326                         break;
327                 case T_DOUBLEFLT:       /* double fault */
328                 default:
329                         signo = SIGBUS;
330                         ucode = BUS_OBJERR;
331                         break;
332
333                 case T_PAGEFLT:         /* page fault */
334                         /*
335                          * Can emulator handle this trap?
336                          */
337                         if (*p->p_sysent->sv_trap != NULL &&
338                             (*p->p_sysent->sv_trap)(td) == 0)
339                                 return;
340
341                         pf = trap_pfault(frame, true, &signo, &ucode);
342                         if (pf == -1)
343                                 return;
344                         if (pf == 0)
345                                 goto userret;
346                         addr = frame->tf_addr;
347                         break;
348
349                 case T_DIVIDE:          /* integer divide fault */
350                         ucode = FPE_INTDIV;
351                         signo = SIGFPE;
352                         break;
353
354 #ifdef DEV_ISA
355                 case T_NMI:
356                         nmi_handle_intr(type, frame);
357                         return;
358 #endif
359
360                 case T_OFLOW:           /* integer overflow fault */
361                         ucode = FPE_INTOVF;
362                         signo = SIGFPE;
363                         break;
364
365                 case T_BOUND:           /* bounds check fault */
366                         ucode = FPE_FLTSUB;
367                         signo = SIGFPE;
368                         break;
369
370                 case T_DNA:
371                         /* transparent fault (due to context switch "late") */
372                         KASSERT(PCB_USER_FPU(td->td_pcb),
373                             ("kernel FPU ctx has leaked"));
374                         fpudna();
375                         return;
376
377                 case T_FPOPFLT:         /* FPU operand fetch fault */
378                         ucode = ILL_COPROC;
379                         signo = SIGILL;
380                         break;
381
382                 case T_XMMFLT:          /* SIMD floating-point exception */
383                         ucode = fputrap_sse();
384                         if (ucode == -1)
385                                 return;
386                         signo = SIGFPE;
387                         break;
388 #ifdef KDTRACE_HOOKS
389                 case T_DTRACE_RET:
390                         (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
391                         return;
392 #endif
393                 }
394         } else {
395                 /* kernel trap */
396
397                 KASSERT(cold || td->td_ucred != NULL,
398                     ("kernel trap doesn't have ucred"));
399                 switch (type) {
400                 case T_PAGEFLT:                 /* page fault */
401                         (void)trap_pfault(frame, false, NULL, NULL);
402                         return;
403
404                 case T_DNA:
405                         if (PCB_USER_FPU(td->td_pcb))
406                                 panic("Unregistered use of FPU in kernel");
407                         fpudna();
408                         return;
409
410                 case T_ARITHTRAP:       /* arithmetic trap */
411                 case T_XMMFLT:          /* SIMD floating-point exception */
412                 case T_FPOPFLT:         /* FPU operand fetch fault */
413                         /*
414                          * For now, supporting kernel handler
415                          * registration for FPU traps is overkill.
416                          */
417                         trap_fatal(frame, 0);
418                         return;
419
420                 case T_STKFLT:          /* stack fault */
421                 case T_PROTFLT:         /* general protection fault */
422                 case T_SEGNPFLT:        /* segment not present fault */
423                         if (td->td_intr_nesting_level != 0)
424                                 break;
425
426                         /*
427                          * Invalid segment selectors and out of bounds
428                          * %rip's and %rsp's can be set up in user mode.
429                          * This causes a fault in kernel mode when the
430                          * kernel tries to return to user mode.  We want
431                          * to get this fault so that we can fix the
432                          * problem here and not have to check all the
433                          * selectors and pointers when the user changes
434                          * them.
435                          *
436                          * In case of PTI, the IRETQ faulted while the
437                          * kernel used the pti stack, and exception
438                          * frame records %rsp value pointing to that
439                          * stack.  If we return normally to
440                          * doreti_iret_fault, the trapframe is
441                          * reconstructed on pti stack, and calltrap()
442                          * called on it as well.  Due to the very
443                          * limited pti stack size, kernel does not
444                          * survive for too long.  Switch to the normal
445                          * thread stack for the trap handling.
446                          *
447                          * Magic '5' is the number of qwords occupied by
448                          * the hardware trap frame.
449                          */
450                         if (frame->tf_rip == (long)doreti_iret) {
451                                 frame->tf_rip = (long)doreti_iret_fault;
452                                 if ((PCPU_GET(curpmap)->pm_ucr3 !=
453                                     PMAP_NO_CR3) &&
454                                     (frame->tf_rsp == (uintptr_t)PCPU_GET(
455                                     pti_rsp0) - 5 * sizeof(register_t))) {
456                                         frame->tf_rsp = PCPU_GET(rsp0) - 5 *
457                                             sizeof(register_t);
458                                 }
459                                 return;
460                         }
461                         if (frame->tf_rip == (long)ld_ds) {
462                                 frame->tf_rip = (long)ds_load_fault;
463                                 return;
464                         }
465                         if (frame->tf_rip == (long)ld_es) {
466                                 frame->tf_rip = (long)es_load_fault;
467                                 return;
468                         }
469                         if (frame->tf_rip == (long)ld_fs) {
470                                 frame->tf_rip = (long)fs_load_fault;
471                                 return;
472                         }
473                         if (frame->tf_rip == (long)ld_gs) {
474                                 frame->tf_rip = (long)gs_load_fault;
475                                 return;
476                         }
477                         if (frame->tf_rip == (long)ld_gsbase) {
478                                 frame->tf_rip = (long)gsbase_load_fault;
479                                 return;
480                         }
481                         if (frame->tf_rip == (long)ld_fsbase) {
482                                 frame->tf_rip = (long)fsbase_load_fault;
483                                 return;
484                         }
485                         if (curpcb->pcb_onfault != NULL) {
486                                 frame->tf_rip = (long)curpcb->pcb_onfault;
487                                 return;
488                         }
489                         break;
490
491                 case T_TSSFLT:
492                         /*
493                          * PSL_NT can be set in user mode and isn't cleared
494                          * automatically when the kernel is entered.  This
495                          * causes a TSS fault when the kernel attempts to
496                          * `iret' because the TSS link is uninitialized.  We
497                          * want to get this fault so that we can fix the
498                          * problem here and not every time the kernel is
499                          * entered.
500                          */
501                         if (frame->tf_rflags & PSL_NT) {
502                                 frame->tf_rflags &= ~PSL_NT;
503                                 return;
504                         }
505                         break;
506
507                 case T_TRCTRAP:  /* debug exception */
508                         /* Clear any pending debug events. */
509                         dr6 = rdr6();
510                         load_dr6(0);
511
512                         /*
513                          * Ignore debug register exceptions due to
514                          * accesses in the user's address space, which
515                          * can happen under several conditions such as
516                          * if a user sets a watchpoint on a buffer and
517                          * then passes that buffer to a system call.
518                          * We still want to get TRCTRAPS for addresses
519                          * in kernel space because that is useful when
520                          * debugging the kernel.
521                          */
522                         if (user_dbreg_trap(dr6))
523                                 return;
524
525                         /*
526                          * Malicious user code can configure a debug
527                          * register watchpoint to trap on data access
528                          * to the top of stack and then execute 'pop
529                          * %ss; int 3'.  Due to exception deferral for
530                          * 'pop %ss', the CPU will not interrupt 'int
531                          * 3' to raise the DB# exception for the debug
532                          * register but will postpone the DB# until
533                          * execution of the first instruction of the
534                          * BP# handler (in kernel mode).  Normally the
535                          * previous check would ignore DB# exceptions
536                          * for watchpoints on user addresses raised in
537                          * kernel mode.  However, some CPU errata
538                          * include cases where DB# exceptions do not
539                          * properly set bits in %dr6, e.g. Haswell
540                          * HSD23 and Skylake-X SKZ24.
541                          *
542                          * A deferred DB# can also be raised on the
543                          * first instructions of system call entry
544                          * points or single-step traps via similar use
545                          * of 'pop %ss' or 'mov xxx, %ss'.
546                          */
547                         if (pti) {
548                                 if (frame->tf_rip ==
549                                     (uintptr_t)IDTVEC(fast_syscall_pti) ||
550 #ifdef COMPAT_FREEBSD32
551                                     frame->tf_rip ==
552                                     (uintptr_t)IDTVEC(int0x80_syscall_pti) ||
553 #endif
554                                     frame->tf_rip == (uintptr_t)IDTVEC(bpt_pti))
555                                         return;
556                         } else {
557                                 if (frame->tf_rip ==
558                                     (uintptr_t)IDTVEC(fast_syscall) ||
559 #ifdef COMPAT_FREEBSD32
560                                     frame->tf_rip ==
561                                     (uintptr_t)IDTVEC(int0x80_syscall) ||
562 #endif
563                                     frame->tf_rip == (uintptr_t)IDTVEC(bpt))
564                                         return;
565                         }
566                         if (frame->tf_rip == (uintptr_t)IDTVEC(dbg) ||
567                             /* Needed for AMD. */
568                             frame->tf_rip == (uintptr_t)IDTVEC(fast_syscall32))
569                                 return;
570                         /*
571                          * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
572                          */
573                 case T_BPTFLT:
574                         /*
575                          * If KDB is enabled, let it handle the debugger trap.
576                          * Otherwise, debugger traps "can't happen".
577                          */
578 #ifdef KDB
579                         if (kdb_trap(type, dr6, frame))
580                                 return;
581 #endif
582                         break;
583
584 #ifdef DEV_ISA
585                 case T_NMI:
586                         nmi_handle_intr(type, frame);
587                         return;
588 #endif
589                 }
590
591                 trap_fatal(frame, 0);
592                 return;
593         }
594
595         /* Translate fault for emulators (e.g. Linux) */
596         if (*p->p_sysent->sv_transtrap != NULL)
597                 signo = (*p->p_sysent->sv_transtrap)(signo, type);
598
599         ksiginfo_init_trap(&ksi);
600         ksi.ksi_signo = signo;
601         ksi.ksi_code = ucode;
602         ksi.ksi_trapno = type;
603         ksi.ksi_addr = (void *)addr;
604         if (uprintf_signal) {
605                 uprintf("pid %d comm %s: signal %d err %lx code %d type %d "
606                     "addr 0x%lx rsp 0x%lx rip 0x%lx "
607                     "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
608                     p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
609                     addr, frame->tf_rsp, frame->tf_rip,
610                     fubyte((void *)(frame->tf_rip + 0)),
611                     fubyte((void *)(frame->tf_rip + 1)),
612                     fubyte((void *)(frame->tf_rip + 2)),
613                     fubyte((void *)(frame->tf_rip + 3)),
614                     fubyte((void *)(frame->tf_rip + 4)),
615                     fubyte((void *)(frame->tf_rip + 5)),
616                     fubyte((void *)(frame->tf_rip + 6)),
617                     fubyte((void *)(frame->tf_rip + 7)));
618         }
619         KASSERT((read_rflags() & PSL_I) != 0, ("interrupts disabled"));
620         trapsignal(td, &ksi);
621
622 userret:
623         userret(td, frame);
624         KASSERT(PCB_USER_FPU(td->td_pcb),
625             ("Return from trap with kernel FPU ctx leaked"));
626 }
627
628 /*
629  * Ensure that we ignore any DTrace-induced faults. This function cannot
630  * be instrumented, so it cannot generate such faults itself.
631  */
632 void
633 trap_check(struct trapframe *frame)
634 {
635
636 #ifdef KDTRACE_HOOKS
637         if (dtrace_trap_func != NULL &&
638             (*dtrace_trap_func)(frame, frame->tf_trapno) != 0)
639                 return;
640 #endif
641         trap(frame);
642 }
643
644 static bool
645 trap_is_smap(struct trapframe *frame)
646 {
647
648         /*
649          * A page fault on a userspace address is classified as
650          * SMAP-induced if:
651          * - SMAP is supported;
652          * - kernel mode accessed present data page;
653          * - rflags.AC was cleared.
654          * Kernel must never access user space with rflags.AC cleared
655          * if SMAP is enabled.
656          */
657         return ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
658             (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) ==
659             PGEX_P && (frame->tf_rflags & PSL_AC) == 0);
660 }
661
662 static bool
663 trap_is_pti(struct trapframe *frame)
664 {
665
666         return (PCPU_GET(curpmap)->pm_ucr3 != PMAP_NO_CR3 &&
667             pg_nx != 0 && (frame->tf_err & (PGEX_P | PGEX_W |
668             PGEX_U | PGEX_I)) == (PGEX_P | PGEX_U | PGEX_I) &&
669             (curpcb->pcb_saved_ucr3 & ~CR3_PCID_MASK) ==
670             (PCPU_GET(curpmap)->pm_cr3 & ~CR3_PCID_MASK));
671 }
672
673 /*
674  * Handle all details of a page fault.
675  * Returns:
676  * -1 if this fault was fatal, typically from kernel mode
677  *    (cannot happen, but we need to return something).
678  * 0  if this fault was handled by updating either the user or kernel
679  *    page table, execution can continue.
680  * 1  if this fault was from usermode and it was not handled, a synchronous
681  *    signal should be delivered to the thread.  *signo returns the signal
682  *    number, *ucode gives si_code.
683  */
684 static int
685 trap_pfault(struct trapframe *frame, bool usermode, int *signo, int *ucode)
686 {
687         struct thread *td;
688         struct proc *p;
689         vm_map_t map;
690         vm_offset_t eva;
691         int rv;
692         vm_prot_t ftype;
693
694         MPASS(!usermode || (signo != NULL && ucode != NULL));
695
696         td = curthread;
697         p = td->td_proc;
698         eva = frame->tf_addr;
699
700         if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
701                 /*
702                  * Due to both processor errata and lazy TLB invalidation when
703                  * access restrictions are removed from virtual pages, memory
704                  * accesses that are allowed by the physical mapping layer may
705                  * nonetheless cause one spurious page fault per virtual page. 
706                  * When the thread is executing a "no faulting" section that
707                  * is bracketed by vm_fault_{disable,enable}_pagefaults(),
708                  * every page fault is treated as a spurious page fault,
709                  * unless it accesses the same virtual address as the most
710                  * recent page fault within the same "no faulting" section.
711                  */
712                 if (td->td_md.md_spurflt_addr != eva ||
713                     (td->td_pflags & TDP_RESETSPUR) != 0) {
714                         /*
715                          * Do nothing to the TLB.  A stale TLB entry is
716                          * flushed automatically by a page fault.
717                          */
718                         td->td_md.md_spurflt_addr = eva;
719                         td->td_pflags &= ~TDP_RESETSPUR;
720                         return (0);
721                 }
722         } else {
723                 /*
724                  * If we get a page fault while in a critical section, then
725                  * it is most likely a fatal kernel page fault.  The kernel
726                  * is already going to panic trying to get a sleep lock to
727                  * do the VM lookup, so just consider it a fatal trap so the
728                  * kernel can print out a useful trap message and even get
729                  * to the debugger.
730                  *
731                  * If we get a page fault while holding a non-sleepable
732                  * lock, then it is most likely a fatal kernel page fault.
733                  * If WITNESS is enabled, then it's going to whine about
734                  * bogus LORs with various VM locks, so just skip to the
735                  * fatal trap handling directly.
736                  */
737                 if (td->td_critnest != 0 ||
738                     WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
739                     "Kernel page fault") != 0) {
740                         trap_fatal(frame, eva);
741                         return (-1);
742                 }
743         }
744         if (eva >= VM_MIN_KERNEL_ADDRESS) {
745                 /*
746                  * Don't allow user-mode faults in kernel address space.
747                  */
748                 if (usermode) {
749                         *signo = SIGSEGV;
750                         *ucode = SEGV_MAPERR;
751                         return (1);
752                 }
753
754                 map = kernel_map;
755         } else {
756                 map = &p->p_vmspace->vm_map;
757
758                 /*
759                  * When accessing a usermode address, kernel must be
760                  * ready to accept the page fault, and provide a
761                  * handling routine.  Since accessing the address
762                  * without the handler is a bug, do not try to handle
763                  * it normally, and panic immediately.
764                  *
765                  * If SMAP is enabled, filter SMAP faults also,
766                  * because illegal access might occur to the mapped
767                  * user address, causing infinite loop.
768                  */
769                 if (!usermode && (td->td_intr_nesting_level != 0 ||
770                     trap_is_smap(frame) || curpcb->pcb_onfault == NULL)) {
771                         trap_fatal(frame, eva);
772                         return (-1);
773                 }
774         }
775
776         /*
777          * If the trap was caused by errant bits in the PTE then panic.
778          */
779         if (frame->tf_err & PGEX_RSV) {
780                 trap_fatal(frame, eva);
781                 return (-1);
782         }
783
784         /*
785          * User-mode protection key violation (PKU).  May happen
786          * either from usermode or from kernel if copyin accessed
787          * key-protected mapping.
788          */
789         if ((frame->tf_err & PGEX_PK) != 0) {
790                 if (eva > VM_MAXUSER_ADDRESS) {
791                         trap_fatal(frame, eva);
792                         return (-1);
793                 }
794                 if (usermode) {
795                         *signo = SIGSEGV;
796                         *ucode = SEGV_PKUERR;
797                         return (1);
798                 }
799                 goto after_vmfault;
800         }
801
802         /*
803          * If nx protection of the usermode portion of kernel page
804          * tables caused trap, panic.
805          */
806         if (usermode && trap_is_pti(frame))
807                 panic("PTI: pid %d comm %s tf_err %#lx", p->p_pid,
808                     p->p_comm, frame->tf_err);
809
810         /*
811          * PGEX_I is defined only if the execute disable bit capability is
812          * supported and enabled.
813          */
814         if (frame->tf_err & PGEX_W)
815                 ftype = VM_PROT_WRITE;
816         else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
817                 ftype = VM_PROT_EXECUTE;
818         else
819                 ftype = VM_PROT_READ;
820
821         /* Fault in the page. */
822         rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
823         if (rv == KERN_SUCCESS) {
824 #ifdef HWPMC_HOOKS
825                 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
826                         PMC_SOFT_CALL_TF( , , page_fault, all, frame);
827                         if (ftype == VM_PROT_READ)
828                                 PMC_SOFT_CALL_TF( , , page_fault, read,
829                                     frame);
830                         else
831                                 PMC_SOFT_CALL_TF( , , page_fault, write,
832                                     frame);
833                 }
834 #endif
835                 return (0);
836         }
837
838         if (usermode)
839                 return (1);
840 after_vmfault:
841         if (td->td_intr_nesting_level == 0 &&
842             curpcb->pcb_onfault != NULL) {
843                 frame->tf_rip = (long)curpcb->pcb_onfault;
844                 return (0);
845         }
846         trap_fatal(frame, eva);
847         return (-1);
848 }
849
850 static void
851 trap_fatal(frame, eva)
852         struct trapframe *frame;
853         vm_offset_t eva;
854 {
855         int code, ss;
856         u_int type;
857         struct soft_segment_descriptor softseg;
858         struct user_segment_descriptor *gdt;
859 #ifdef KDB
860         bool handled;
861 #endif
862
863         code = frame->tf_err;
864         type = frame->tf_trapno;
865         gdt = *PCPU_PTR(gdt);
866         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
867
868         printf("\n\nFatal trap %d: %s while in %s mode\n", type,
869             type < nitems(trap_msg) ? trap_msg[type] : UNKNOWN,
870             TRAPF_USERMODE(frame) ? "user" : "kernel");
871 #ifdef SMP
872         /* two separate prints in case of a trap on an unmapped page */
873         printf("cpuid = %d; ", PCPU_GET(cpuid));
874         printf("apic id = %02x\n", PCPU_GET(apic_id));
875 #endif
876         if (type == T_PAGEFLT) {
877                 printf("fault virtual address   = 0x%lx\n", eva);
878                 printf("fault code              = %s %s %s%s%s, %s\n",
879                         code & PGEX_U ? "user" : "supervisor",
880                         code & PGEX_W ? "write" : "read",
881                         code & PGEX_I ? "instruction" : "data",
882                         code & PGEX_PK ? " prot key" : "",
883                         code & PGEX_SGX ? " SGX" : "",
884                         code & PGEX_RSV ? "reserved bits in PTE" :
885                         code & PGEX_P ? "protection violation" : "page not present");
886         }
887         printf("instruction pointer     = 0x%lx:0x%lx\n",
888                frame->tf_cs & 0xffff, frame->tf_rip);
889         ss = frame->tf_ss & 0xffff;
890         printf("stack pointer           = 0x%x:0x%lx\n", ss, frame->tf_rsp);
891         printf("frame pointer           = 0x%x:0x%lx\n", ss, frame->tf_rbp);
892         printf("code segment            = base 0x%lx, limit 0x%lx, type 0x%x\n",
893                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
894         printf("                        = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
895                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
896                softseg.ssd_gran);
897         printf("processor eflags        = ");
898         if (frame->tf_rflags & PSL_T)
899                 printf("trace trap, ");
900         if (frame->tf_rflags & PSL_I)
901                 printf("interrupt enabled, ");
902         if (frame->tf_rflags & PSL_NT)
903                 printf("nested task, ");
904         if (frame->tf_rflags & PSL_RF)
905                 printf("resume, ");
906         printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
907         printf("current process         = %d (%s)\n",
908             curproc->p_pid, curthread->td_name);
909
910 #ifdef KDB
911         if (debugger_on_trap) {
912                 kdb_why = KDB_WHY_TRAP;
913                 handled = kdb_trap(type, 0, frame);
914                 kdb_why = KDB_WHY_UNSET;
915                 if (handled)
916                         return;
917         }
918 #endif
919         printf("trap number             = %d\n", type);
920         panic("%s", type < nitems(trap_msg) ? trap_msg[type] :
921             "unknown/reserved trap");
922 }
923
924 #ifdef KDTRACE_HOOKS
925 /*
926  * Invoke a userspace DTrace hook.  The hook pointer is cleared when no
927  * userspace probes are enabled, so we must synchronize with DTrace to ensure
928  * that a trapping thread is able to call the hook before it is cleared.
929  */
930 static bool
931 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
932 {
933         int (*hook)(struct trapframe *);
934
935         hook = (int (*)(struct trapframe *))atomic_load_ptr(hookp);
936         enable_intr();
937         if (hook != NULL)
938                 return ((hook)(frame) == 0);
939         return (false);
940 }
941 #endif
942
943 /*
944  * Double fault handler. Called when a fault occurs while writing
945  * a frame for a trap/exception onto the stack. This usually occurs
946  * when the stack overflows (such is the case with infinite recursion,
947  * for example).
948  */
949 void
950 dblfault_handler(struct trapframe *frame)
951 {
952 #ifdef KDTRACE_HOOKS
953         if (dtrace_doubletrap_func != NULL)
954                 (*dtrace_doubletrap_func)();
955 #endif
956         printf("\nFatal double fault\n"
957             "rip %#lx rsp %#lx rbp %#lx\n"
958             "rax %#lx rdx %#lx rbx %#lx\n"
959             "rcx %#lx rsi %#lx rdi %#lx\n"
960             "r8 %#lx r9 %#lx r10 %#lx\n"
961             "r11 %#lx r12 %#lx r13 %#lx\n"
962             "r14 %#lx r15 %#lx rflags %#lx\n"
963             "cs %#lx ss %#lx ds %#hx es %#hx fs %#hx gs %#hx\n"
964             "fsbase %#lx gsbase %#lx kgsbase %#lx\n",
965             frame->tf_rip, frame->tf_rsp, frame->tf_rbp,
966             frame->tf_rax, frame->tf_rdx, frame->tf_rbx,
967             frame->tf_rcx, frame->tf_rdi, frame->tf_rsi,
968             frame->tf_r8, frame->tf_r9, frame->tf_r10,
969             frame->tf_r11, frame->tf_r12, frame->tf_r13,
970             frame->tf_r14, frame->tf_r15, frame->tf_rflags,
971             frame->tf_cs, frame->tf_ss, frame->tf_ds, frame->tf_es,
972             frame->tf_fs, frame->tf_gs,
973             rdmsr(MSR_FSBASE), rdmsr(MSR_GSBASE), rdmsr(MSR_KGSBASE));
974 #ifdef SMP
975         /* two separate prints in case of a trap on an unmapped page */
976         printf("cpuid = %d; ", PCPU_GET(cpuid));
977         printf("apic id = %02x\n", PCPU_GET(apic_id));
978 #endif
979         panic("double fault");
980 }
981
982 static int __noinline
983 cpu_fetch_syscall_args_fallback(struct thread *td, struct syscall_args *sa)
984 {
985         struct proc *p;
986         struct trapframe *frame;
987         register_t *argp;
988         caddr_t params;
989         int reg, regcnt, error;
990
991         p = td->td_proc;
992         frame = td->td_frame;
993         reg = 0;
994         regcnt = NARGREGS;
995
996         sa->code = frame->tf_rax;
997
998         if (sa->code == SYS_syscall || sa->code == SYS___syscall) {
999                 sa->code = frame->tf_rdi;
1000                 reg++;
1001                 regcnt--;
1002         }
1003
1004         if (sa->code >= p->p_sysent->sv_size)
1005                 sa->callp = &p->p_sysent->sv_table[0];
1006         else
1007                 sa->callp = &p->p_sysent->sv_table[sa->code];
1008
1009         sa->narg = sa->callp->sy_narg;
1010         KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1011         argp = &frame->tf_rdi;
1012         argp += reg;
1013         memcpy(sa->args, argp, sizeof(sa->args[0]) * NARGREGS);
1014         if (sa->narg > regcnt) {
1015                 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1016                 error = copyin(params, &sa->args[regcnt],
1017                     (sa->narg - regcnt) * sizeof(sa->args[0]));
1018                 if (__predict_false(error != 0))
1019                         return (error);
1020         }
1021
1022         td->td_retval[0] = 0;
1023         td->td_retval[1] = frame->tf_rdx;
1024
1025         return (0);
1026 }
1027
1028 int
1029 cpu_fetch_syscall_args(struct thread *td)
1030 {
1031         struct proc *p;
1032         struct trapframe *frame;
1033         struct syscall_args *sa;
1034
1035         p = td->td_proc;
1036         frame = td->td_frame;
1037         sa = &td->td_sa;
1038
1039         sa->code = frame->tf_rax;
1040
1041         if (__predict_false(sa->code == SYS_syscall ||
1042             sa->code == SYS___syscall ||
1043             sa->code >= p->p_sysent->sv_size))
1044                 return (cpu_fetch_syscall_args_fallback(td, sa));
1045
1046         sa->callp = &p->p_sysent->sv_table[sa->code];
1047         sa->narg = sa->callp->sy_narg;
1048         KASSERT(sa->narg <= nitems(sa->args), ("Too many syscall arguments!"));
1049
1050         if (__predict_false(sa->narg > NARGREGS))
1051                 return (cpu_fetch_syscall_args_fallback(td, sa));
1052
1053         memcpy(sa->args, &frame->tf_rdi, sizeof(sa->args[0]) * NARGREGS);
1054
1055         td->td_retval[0] = 0;
1056         td->td_retval[1] = frame->tf_rdx;
1057
1058         return (0);
1059 }
1060
1061 #include "../../kern/subr_syscall.c"
1062
1063 static void (*syscall_ret_l1d_flush)(void);
1064 int syscall_ret_l1d_flush_mode;
1065
1066 static void
1067 flush_l1d_hw(void)
1068 {
1069
1070         wrmsr(MSR_IA32_FLUSH_CMD, IA32_FLUSH_CMD_L1D);
1071 }
1072
1073 static void __inline
1074 amd64_syscall_ret_flush_l1d_inline(int error)
1075 {
1076         void (*p)(void);
1077
1078         if (error != 0 && error != EEXIST && error != EAGAIN &&
1079             error != EXDEV && error != ENOENT && error != ENOTCONN &&
1080             error != EINPROGRESS) {
1081                 p = syscall_ret_l1d_flush;
1082                 if (p != NULL)
1083                         p();
1084         }
1085 }
1086
1087 void
1088 amd64_syscall_ret_flush_l1d(int error)
1089 {
1090
1091         amd64_syscall_ret_flush_l1d_inline(error);
1092 }
1093
1094 void
1095 amd64_syscall_ret_flush_l1d_recalc(void)
1096 {
1097         bool l1d_hw;
1098
1099         l1d_hw = (cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) != 0;
1100 again:
1101         switch (syscall_ret_l1d_flush_mode) {
1102         case 0:
1103                 syscall_ret_l1d_flush = NULL;
1104                 break;
1105         case 1:
1106                 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw :
1107                     flush_l1d_sw_abi;
1108                 break;
1109         case 2:
1110                 syscall_ret_l1d_flush = l1d_hw ? flush_l1d_hw : NULL;
1111                 break;
1112         case 3:
1113                 syscall_ret_l1d_flush = flush_l1d_sw_abi;
1114                 break;
1115         default:
1116                 syscall_ret_l1d_flush_mode = 1;
1117                 goto again;
1118         }
1119 }
1120
1121 static int
1122 machdep_syscall_ret_flush_l1d(SYSCTL_HANDLER_ARGS)
1123 {
1124         int error, val;
1125
1126         val = syscall_ret_l1d_flush_mode;
1127         error = sysctl_handle_int(oidp, &val, 0, req);
1128         if (error != 0 || req->newptr == NULL)
1129                 return (error);
1130         syscall_ret_l1d_flush_mode = val;
1131         amd64_syscall_ret_flush_l1d_recalc();
1132         return (0);
1133 }
1134 SYSCTL_PROC(_machdep, OID_AUTO, syscall_ret_flush_l1d, CTLTYPE_INT |
1135     CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, NULL, 0,
1136     machdep_syscall_ret_flush_l1d, "I",
1137     "Flush L1D on syscall return with error (0 - off, 1 - on, "
1138     "2 - use hw only, 3 - use sw only");
1139
1140
1141 /*
1142  * System call handler for native binaries.  The trap frame is already
1143  * set up by the assembler trampoline and a pointer to it is saved in
1144  * td_frame.
1145  */
1146 void
1147 amd64_syscall(struct thread *td, int traced)
1148 {
1149         ksiginfo_t ksi;
1150
1151 #ifdef DIAGNOSTIC
1152         if (!TRAPF_USERMODE(td->td_frame)) {
1153                 panic("syscall");
1154                 /* NOT REACHED */
1155         }
1156 #endif
1157         syscallenter(td);
1158
1159         /*
1160          * Traced syscall.
1161          */
1162         if (__predict_false(traced)) {
1163                 td->td_frame->tf_rflags &= ~PSL_T;
1164                 ksiginfo_init_trap(&ksi);
1165                 ksi.ksi_signo = SIGTRAP;
1166                 ksi.ksi_code = TRAP_TRACE;
1167                 ksi.ksi_addr = (void *)td->td_frame->tf_rip;
1168                 trapsignal(td, &ksi);
1169         }
1170
1171         KASSERT(PCB_USER_FPU(td->td_pcb),
1172             ("System call %s returning with kernel FPU ctx leaked",
1173              syscallname(td->td_proc, td->td_sa.code)));
1174         KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1175             ("System call %s returning with mangled pcb_save",
1176              syscallname(td->td_proc, td->td_sa.code)));
1177         KASSERT(pmap_not_in_di(),
1178             ("System call %s returning with leaked invl_gen %lu",
1179             syscallname(td->td_proc, td->td_sa.code),
1180             td->td_md.md_invl_gen.gen));
1181
1182         syscallret(td);
1183
1184         /*
1185          * If the user-supplied value of %rip is not a canonical
1186          * address, then some CPUs will trigger a ring 0 #GP during
1187          * the sysret instruction.  However, the fault handler would
1188          * execute in ring 0 with the user's %gs and %rsp which would
1189          * not be safe.  Instead, use the full return path which
1190          * catches the problem safely.
1191          */
1192         if (__predict_false(td->td_frame->tf_rip >= VM_MAXUSER_ADDRESS))
1193                 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
1194
1195         amd64_syscall_ret_flush_l1d_inline(td->td_errno);
1196 }