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