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