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