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