]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/i386/i386/trap.c
OpenSSL: update to 3.0.11
[FreeBSD/FreeBSD.git] / sys / i386 / i386 / 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 /*
44  * 386 Trap and System call handling
45  */
46
47 #include "opt_clock.h"
48 #include "opt_cpu.h"
49 #include "opt_hwpmc_hooks.h"
50 #include "opt_isa.h"
51 #include "opt_kdb.h"
52 #include "opt_trap.h"
53
54 #include <sys/param.h>
55 #include <sys/bus.h>
56 #include <sys/systm.h>
57 #include <sys/proc.h>
58 #include <sys/ptrace.h>
59 #include <sys/kdb.h>
60 #include <sys/kernel.h>
61 #include <sys/ktr.h>
62 #include <sys/lock.h>
63 #include <sys/mutex.h>
64 #include <sys/resourcevar.h>
65 #include <sys/signalvar.h>
66 #include <sys/syscall.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysent.h>
69 #include <sys/uio.h>
70 #include <sys/vmmeter.h>
71 #ifdef HWPMC_HOOKS
72 #include <sys/pmckern.h>
73 PMC_SOFT_DEFINE( , , page_fault, all);
74 PMC_SOFT_DEFINE( , , page_fault, read);
75 PMC_SOFT_DEFINE( , , page_fault, write);
76 #endif
77 #include <security/audit/audit.h>
78
79 #include <vm/vm.h>
80 #include <vm/vm_param.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_kern.h>
83 #include <vm/vm_map.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_extern.h>
86
87 #include <machine/cpu.h>
88 #include <machine/intr_machdep.h>
89 #include <x86/mca.h>
90 #include <machine/md_var.h>
91 #include <machine/pcb.h>
92 #ifdef SMP
93 #include <machine/smp.h>
94 #endif
95 #include <machine/stack.h>
96 #include <machine/trap.h>
97 #include <machine/tss.h>
98 #include <machine/vm86.h>
99
100 #ifdef POWERFAIL_NMI
101 #include <sys/syslog.h>
102 #include <machine/clock.h>
103 #endif
104
105 #ifdef KDTRACE_HOOKS
106 #include <sys/dtrace_bsd.h>
107 #endif
108
109 void trap(struct trapframe *frame);
110 void syscall(struct trapframe *frame);
111
112 static int trap_pfault(struct trapframe *, bool, vm_offset_t, int *, int *);
113 static void trap_fatal(struct trapframe *, vm_offset_t);
114 #ifdef KDTRACE_HOOKS
115 static bool trap_user_dtrace(struct trapframe *,
116     int (**hook)(struct trapframe *));
117 #endif
118 void dblfault_handler(void);
119
120 extern inthand_t IDTVEC(bpt), IDTVEC(dbg), IDTVEC(int0x80_syscall);
121 extern uint64_t pg_nx;
122
123 struct trap_data {
124         bool            ei;
125         const char      *msg;
126 };
127
128 static const struct trap_data trap_data[] = {
129         [T_PRIVINFLT] = { .ei = true,   .msg = "privileged instruction fault" },
130         [T_BPTFLT] =    { .ei = false,  .msg = "breakpoint instruction fault" },
131         [T_ARITHTRAP] = { .ei = true,   .msg = "arithmetic trap" },
132         [T_PROTFLT] =   { .ei = true,   .msg = "general protection fault" },
133         [T_TRCTRAP] =   { .ei = false,  .msg = "debug exception" },
134         [T_PAGEFLT] =   { .ei = true,   .msg = "page fault" },
135         [T_ALIGNFLT] =  { .ei = true,   .msg = "alignment fault" },
136         [T_DIVIDE] =    { .ei = true,   .msg = "integer divide fault" },
137         [T_NMI] =       { .ei = false,  .msg = "non-maskable interrupt trap" },
138         [T_OFLOW] =     { .ei = true,   .msg = "overflow trap" },
139         [T_BOUND] =     { .ei = true,   .msg = "FPU bounds check fault" },
140         [T_DNA] =       { .ei = true,   .msg = "FPU device not available" },
141         [T_DOUBLEFLT] = { .ei = false,  .msg = "double fault" },
142         [T_FPOPFLT] =   { .ei = true,   .msg = "FPU operand fetch fault" },
143         [T_TSSFLT] =    { .ei = true,   .msg = "invalid TSS fault" },
144         [T_SEGNPFLT] =  { .ei = true,   .msg = "segment not present fault" },
145         [T_STKFLT] =    { .ei = true,   .msg = "stack fault" },
146         [T_MCHK] =      { .ei = true,   .msg = "machine check trap" },
147         [T_XMMFLT] =    { .ei = true,   .msg = "SIMD floating-point exception" },
148         [T_DTRACE_RET] ={ .ei = true,   .msg = "DTrace pid return trap" },
149 };
150
151 static bool
152 trap_enable_intr(int trapno)
153 {
154
155         MPASS(trapno > 0);
156         if (trapno < nitems(trap_data) && trap_data[trapno].msg != NULL)
157                 return (trap_data[trapno].ei);
158         return (false);
159 }
160
161 static const char *
162 trap_msg(int trapno)
163 {
164         const char *res;
165         static const char unkn[] = "UNKNOWN";
166
167         res = NULL;
168         if (trapno < nitems(trap_data))
169                 res = trap_data[trapno].msg;
170         if (res == NULL)
171                 res = unkn;
172         return (res);
173 }
174
175 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
176 int has_f00f_bug = 0;           /* Initialized so that it can be patched. */
177 #endif
178
179 static int uprintf_signal;
180 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RW,
181     &uprintf_signal, 0,
182     "Print debugging information on trap signal to ctty");
183
184
185 #ifdef INVARIANTS
186 static __inline register_t
187 read_esp(void)
188 {
189         register_t res;
190
191         __asm __volatile("movl\t%%esp,%0" : "=r" (res));
192         return (res);
193 }
194
195 void
196 trap_check_kstack(void)
197 {
198         struct thread *td;
199         vm_offset_t stk;
200
201         td = curthread;
202         stk = read_esp();
203         if (stk >= PMAP_TRM_MIN_ADDRESS)
204                 panic("td %p stack %#x in trampoline", td, stk);
205         if (!kstack_contains(td, stk, 0))
206                 panic("td %p stack %#x not in kstack VA %#x %d",
207                     td, stk, td->td_kstack, td->td_kstack_pages);
208 }
209 #endif
210
211 /*
212  * Exception, fault, and trap interface to the FreeBSD kernel.
213  * This common code is called from assembly language IDT gate entry
214  * routines that prepare a suitable stack frame, and restore this
215  * frame after the exception has been processed.
216  */
217
218 void
219 trap(struct trapframe *frame)
220 {
221         ksiginfo_t ksi;
222         struct thread *td;
223         struct proc *p;
224         int pf, signo, ucode;
225         u_int type;
226         register_t addr, dr6;
227         vm_offset_t eva;
228 #ifdef POWERFAIL_NMI
229         static int lastalert = 0;
230 #endif
231
232         td = curthread;
233         p = td->td_proc;
234         dr6 = 0;
235
236         VM_CNT_INC(v_trap);
237         type = frame->tf_trapno;
238
239         KASSERT((read_eflags() & PSL_I) == 0,
240             ("trap: interrupts enabled, type %d frame %p", type, frame));
241
242 #ifdef SMP
243         /* Handler for NMI IPIs used for stopping CPUs. */
244         if (type == T_NMI && ipi_nmi_handler() == 0)
245                 return;
246 #endif /* SMP */
247
248 #ifdef KDB
249         if (kdb_active) {
250                 kdb_reenter();
251                 return;
252         }
253 #endif
254         trap_check_kstack();
255
256         if (type == T_RESERVED) {
257                 trap_fatal(frame, 0);
258                 return;
259         }
260
261         if (type == T_NMI) {
262 #ifdef HWPMC_HOOKS
263                 /*
264                  * CPU PMCs interrupt using an NMI so we check for that first.
265                  * If the HWPMC module is active, 'pmc_hook' will point to
266                  * the function to be called.  A non-zero return value from the
267                  * hook means that the NMI was consumed by it and that we can
268                  * return immediately.
269                  */
270                 if (pmc_intr != NULL &&
271                     (*pmc_intr)(frame) != 0)
272                         return;
273 #endif
274         }
275
276         if (type == T_MCHK) {
277                 mca_intr();
278                 return;
279         }
280
281 #ifdef KDTRACE_HOOKS
282         /*
283          * A trap can occur while DTrace executes a probe. Before
284          * executing the probe, DTrace blocks re-scheduling and sets
285          * a flag in its per-cpu flags to indicate that it doesn't
286          * want to fault. On returning from the probe, the no-fault
287          * flag is cleared and finally re-scheduling is enabled.
288          */
289         if ((type == T_PROTFLT || type == T_PAGEFLT) &&
290             dtrace_trap_func != NULL && (*dtrace_trap_func)(frame, type))
291                 return;
292 #endif
293
294         /*
295          * We must not allow context switches until %cr2 is read.
296          * Also, for some Cyrix CPUs, %cr2 is clobbered by interrupts.
297          * All faults use interrupt gates, so %cr2 can be safely read
298          * now, before optional enable of the interrupts below.
299          */
300         if (type == T_PAGEFLT)
301                 eva = rcr2();
302
303         /*
304          * Buggy application or kernel code has disabled interrupts
305          * and then trapped.  Enabling interrupts now is wrong, but it
306          * is better than running with interrupts disabled until they
307          * are accidentally enabled later.
308          */
309         if ((frame->tf_eflags & PSL_I) == 0 && TRAPF_USERMODE(frame) &&
310             (curpcb->pcb_flags & PCB_VM86CALL) == 0)
311                 uprintf("pid %ld (%s): usermode trap %d (%s) with "
312                     "interrupts disabled\n",
313                     (long)curproc->p_pid, curthread->td_name, type,
314                     trap_data[type].msg);
315
316         /*
317          * Conditionally reenable interrupts.  If we hold a spin lock,
318          * then we must not reenable interrupts.  This might be a
319          * spurious page fault.
320          */
321         if (trap_enable_intr(type) && td->td_md.md_spinlock_count == 0 &&
322             frame->tf_eip != (int)cpu_switch_load_gs)
323                 enable_intr();
324
325         if (TRAPF_USERMODE(frame) && (curpcb->pcb_flags & PCB_VM86CALL) == 0) {
326                 /* user trap */
327
328                 td->td_pticks = 0;
329                 td->td_frame = frame;
330                 addr = frame->tf_eip;
331                 if (td->td_cowgen != atomic_load_int(&p->p_cowgen))
332                         thread_cow_update(td);
333
334                 switch (type) {
335                 case T_PRIVINFLT:       /* privileged instruction fault */
336                         signo = SIGILL;
337                         ucode = ILL_PRVOPC;
338                         break;
339
340                 case T_BPTFLT:          /* bpt instruction fault */
341 #ifdef KDTRACE_HOOKS
342                         if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
343                                 return;
344 #else
345                         enable_intr();
346 #endif
347                         signo = SIGTRAP;
348                         ucode = TRAP_BRKPT;
349                         break;
350
351                 case T_TRCTRAP:         /* debug exception */
352                         enable_intr();
353 user_trctrap_out:
354                         signo = SIGTRAP;
355                         ucode = TRAP_TRACE;
356                         dr6 = rdr6();
357                         if ((dr6 & DBREG_DR6_BS) != 0) {
358                                 PROC_LOCK(td->td_proc);
359                                 if ((td->td_dbgflags & TDB_STEP) != 0) {
360                                         td->td_frame->tf_eflags &= ~PSL_T;
361                                         td->td_dbgflags &= ~TDB_STEP;
362                                 }
363                                 PROC_UNLOCK(td->td_proc);
364                         }
365                         break;
366
367                 case T_ARITHTRAP:       /* arithmetic trap */
368                         ucode = npxtrap_x87();
369                         if (ucode == -1)
370                                 return;
371                         signo = SIGFPE;
372                         break;
373
374                 /*
375                  * The following two traps can happen in vm86 mode,
376                  * and, if so, we want to handle them specially.
377                  */
378                 case T_PROTFLT:         /* general protection fault */
379                 case T_STKFLT:          /* stack fault */
380                         if (frame->tf_eflags & PSL_VM) {
381                                 signo = vm86_emulate((struct vm86frame *)frame);
382                                 ucode = 0;      /* XXXKIB: better code ? */
383                                 if (signo == SIGTRAP) {
384                                         load_dr6(rdr6() | 0x4000);
385                                         goto user_trctrap_out;
386                                 }
387                                 if (signo == 0)
388                                         goto user;
389                                 break;
390                         }
391                         signo = SIGBUS;
392                         ucode = (type == T_PROTFLT) ? BUS_OBJERR : BUS_ADRERR;
393                         break;
394                 case T_SEGNPFLT:        /* segment not present fault */
395                         signo = SIGBUS;
396                         ucode = BUS_ADRERR;
397                         break;
398                 case T_TSSFLT:          /* invalid TSS fault */
399                         signo = SIGBUS;
400                         ucode = BUS_OBJERR;
401                         break;
402                 case T_ALIGNFLT:
403                         signo = SIGBUS;
404                         ucode = BUS_ADRALN;
405                         break;
406                 case T_DOUBLEFLT:       /* double fault */
407                 default:
408                         signo = SIGBUS;
409                         ucode = BUS_OBJERR;
410                         break;
411
412                 case T_PAGEFLT:         /* page fault */
413                         addr = eva;
414                         pf = trap_pfault(frame, true, eva, &signo, &ucode);
415 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
416                         if (pf == -2) {
417                                 /*
418                                  * The f00f hack workaround has triggered, so
419                                  * treat the fault as an illegal instruction 
420                                  * (T_PRIVINFLT) instead of a page fault.
421                                  */
422                                 type = frame->tf_trapno = T_PRIVINFLT;
423                                 break;
424                         }
425 #endif
426                         if (pf == -1)
427                                 return;
428                         if (pf == 0)
429                                 goto user;
430                         break;
431
432                 case T_DIVIDE:          /* integer divide fault */
433                         ucode = FPE_INTDIV;
434                         signo = SIGFPE;
435                         break;
436
437                 case T_NMI:
438 #ifdef POWERFAIL_NMI
439 #ifndef TIMER_FREQ
440 #  define TIMER_FREQ 1193182
441 #endif
442                         if (time_second - lastalert > 10) {
443                                 log(LOG_WARNING, "NMI: power fail\n");
444                                 sysbeep(880, SBT_1S);
445                                 lastalert = time_second;
446                         }
447                         return;
448 #else /* !POWERFAIL_NMI */
449                         nmi_handle_intr(type, frame);
450                         return;
451 #endif /* POWERFAIL_NMI */
452
453                 case T_OFLOW:           /* integer overflow fault */
454                         ucode = FPE_INTOVF;
455                         signo = SIGFPE;
456                         break;
457
458                 case T_BOUND:           /* bounds check fault */
459                         ucode = FPE_FLTSUB;
460                         signo = SIGFPE;
461                         break;
462
463                 case T_DNA:
464                         KASSERT(PCB_USER_FPU(td->td_pcb),
465                             ("kernel FPU ctx has leaked"));
466                         /* transparent fault (due to context switch "late") */
467                         if (npxdna())
468                                 return;
469                         uprintf("pid %d killed due to lack of floating point\n",
470                                 p->p_pid);
471                         signo = SIGKILL;
472                         ucode = 0;
473                         break;
474
475                 case T_FPOPFLT:         /* FPU operand fetch fault */
476                         ucode = ILL_COPROC;
477                         signo = SIGILL;
478                         break;
479
480                 case T_XMMFLT:          /* SIMD floating-point exception */
481                         ucode = npxtrap_sse();
482                         if (ucode == -1)
483                                 return;
484                         signo = SIGFPE;
485                         break;
486 #ifdef KDTRACE_HOOKS
487                 case T_DTRACE_RET:
488                         (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
489                         return;
490 #endif
491                 }
492         } else {
493                 /* kernel trap */
494
495                 KASSERT(cold || td->td_ucred != NULL,
496                     ("kernel trap doesn't have ucred"));
497                 switch (type) {
498                 case T_PAGEFLT:                 /* page fault */
499                         (void)trap_pfault(frame, false, eva, NULL, NULL);
500                         return;
501
502                 case T_DNA:
503                         if (PCB_USER_FPU(td->td_pcb))
504                                 panic("Unregistered use of FPU in kernel");
505                         if (npxdna())
506                                 return;
507                         break;
508
509                 case T_ARITHTRAP:       /* arithmetic trap */
510                 case T_XMMFLT:          /* SIMD floating-point exception */
511                 case T_FPOPFLT:         /* FPU operand fetch fault */
512                         /*
513                          * XXXKIB for now disable any FPU traps in kernel
514                          * handler registration seems to be overkill
515                          */
516                         trap_fatal(frame, 0);
517                         return;
518
519                         /*
520                          * The following two traps can happen in
521                          * vm86 mode, and, if so, we want to handle
522                          * them specially.
523                          */
524                 case T_PROTFLT:         /* general protection fault */
525                 case T_STKFLT:          /* stack fault */
526                         if (frame->tf_eflags & PSL_VM) {
527                                 signo = vm86_emulate((struct vm86frame *)frame);
528                                 if (signo == SIGTRAP) {
529                                         type = T_TRCTRAP;
530                                         load_dr6(rdr6() | 0x4000);
531                                         goto kernel_trctrap;
532                                 }
533                                 if (signo != 0)
534                                         /*
535                                          * returns to original process
536                                          */
537                                         vm86_trap((struct vm86frame *)frame);
538                                 return;
539                         }
540                         /* FALL THROUGH */
541                 case T_SEGNPFLT:        /* segment not present fault */
542                         if (curpcb->pcb_flags & PCB_VM86CALL)
543                                 break;
544
545                         /*
546                          * Invalid %fs's and %gs's can be created using
547                          * procfs or PT_SETREGS or by invalidating the
548                          * underlying LDT entry.  This causes a fault
549                          * in kernel mode when the kernel attempts to
550                          * switch contexts.  Lose the bad context
551                          * (XXX) so that we can continue, and generate
552                          * a signal.
553                          */
554                         if (frame->tf_eip == (int)cpu_switch_load_gs) {
555                                 curpcb->pcb_gs = 0;
556 #if 0                           
557                                 PROC_LOCK(p);
558                                 kern_psignal(p, SIGBUS);
559                                 PROC_UNLOCK(p);
560 #endif                          
561                                 return;
562                         }
563
564                         if (td->td_intr_nesting_level != 0)
565                                 break;
566
567                         /*
568                          * Invalid segment selectors and out of bounds
569                          * %eip's and %esp's can be set up in user mode.
570                          * This causes a fault in kernel mode when the
571                          * kernel tries to return to user mode.  We want
572                          * to get this fault so that we can fix the
573                          * problem here and not have to check all the
574                          * selectors and pointers when the user changes
575                          * them.
576                          *
577                          * N.B. Comparing to long mode, 32-bit mode
578                          * does not push %esp on the trap frame,
579                          * because iretl faulted while in ring 0.  As
580                          * the consequence, there is no need to fixup
581                          * the stack pointer for doreti_iret_fault,
582                          * the fixup and the complimentary trap() call
583                          * are executed on the main thread stack, not
584                          * on the trampoline stack.
585                          */
586                         if (frame->tf_eip == (int)doreti_iret + setidt_disp) {
587                                 frame->tf_eip = (int)doreti_iret_fault +
588                                     setidt_disp;
589                                 return;
590                         }
591                         if (type == T_STKFLT)
592                                 break;
593
594                         if (frame->tf_eip == (int)doreti_popl_ds +
595                             setidt_disp) {
596                                 frame->tf_eip = (int)doreti_popl_ds_fault +
597                                     setidt_disp;
598                                 return;
599                         }
600                         if (frame->tf_eip == (int)doreti_popl_es +
601                             setidt_disp) {
602                                 frame->tf_eip = (int)doreti_popl_es_fault +
603                                     setidt_disp;
604                                 return;
605                         }
606                         if (frame->tf_eip == (int)doreti_popl_fs +
607                             setidt_disp) {
608                                 frame->tf_eip = (int)doreti_popl_fs_fault +
609                                     setidt_disp;
610                                 return;
611                         }
612                         if (curpcb->pcb_onfault != NULL) {
613                                 frame->tf_eip = (int)curpcb->pcb_onfault;
614                                 return;
615                         }
616                         break;
617
618                 case T_TSSFLT:
619                         /*
620                          * PSL_NT can be set in user mode and isn't cleared
621                          * automatically when the kernel is entered.  This
622                          * causes a TSS fault when the kernel attempts to
623                          * `iret' because the TSS link is uninitialized.  We
624                          * want to get this fault so that we can fix the
625                          * problem here and not every time the kernel is
626                          * entered.
627                          */
628                         if (frame->tf_eflags & PSL_NT) {
629                                 frame->tf_eflags &= ~PSL_NT;
630                                 return;
631                         }
632                         break;
633
634                 case T_TRCTRAP:  /* debug exception */
635 kernel_trctrap:
636                         /* Clear any pending debug events. */
637                         dr6 = rdr6();
638                         load_dr6(0);
639
640                         /*
641                          * Ignore debug register exceptions due to
642                          * accesses in the user's address space, which
643                          * can happen under several conditions such as
644                          * if a user sets a watchpoint on a buffer and
645                          * then passes that buffer to a system call.
646                          * We still want to get TRCTRAPS for addresses
647                          * in kernel space because that is useful when
648                          * debugging the kernel.
649                          */
650                         if (user_dbreg_trap(dr6) &&
651                            !(curpcb->pcb_flags & PCB_VM86CALL))
652                                 return;
653
654                         /*
655                          * Malicious user code can configure a debug
656                          * register watchpoint to trap on data access
657                          * to the top of stack and then execute 'pop
658                          * %ss; int 3'.  Due to exception deferral for
659                          * 'pop %ss', the CPU will not interrupt 'int
660                          * 3' to raise the DB# exception for the debug
661                          * register but will postpone the DB# until
662                          * execution of the first instruction of the
663                          * BP# handler (in kernel mode).  Normally the
664                          * previous check would ignore DB# exceptions
665                          * for watchpoints on user addresses raised in
666                          * kernel mode.  However, some CPU errata
667                          * include cases where DB# exceptions do not
668                          * properly set bits in %dr6, e.g. Haswell
669                          * HSD23 and Skylake-X SKZ24.
670                          *
671                          * A deferred DB# can also be raised on the
672                          * first instructions of system call entry
673                          * points or single-step traps via similar use
674                          * of 'pop %ss' or 'mov xxx, %ss'.
675                          */
676                         if (frame->tf_eip ==
677                             (uintptr_t)IDTVEC(int0x80_syscall) + setidt_disp ||
678                             frame->tf_eip == (uintptr_t)IDTVEC(bpt) +
679                             setidt_disp ||
680                             frame->tf_eip == (uintptr_t)IDTVEC(dbg) +
681                             setidt_disp)
682                                 return;
683                         /*
684                          * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
685                          */
686                 case T_BPTFLT:
687                         /*
688                          * If KDB is enabled, let it handle the debugger trap.
689                          * Otherwise, debugger traps "can't happen".
690                          */
691 #ifdef KDB
692                         if (kdb_trap(type, dr6, frame))
693                                 return;
694 #endif
695                         break;
696
697                 case T_NMI:
698 #ifdef POWERFAIL_NMI
699                         if (time_second - lastalert > 10) {
700                                 log(LOG_WARNING, "NMI: power fail\n");
701                                 sysbeep(880, SBT_1S);
702                                 lastalert = time_second;
703                         }
704                         return;
705 #else /* !POWERFAIL_NMI */
706                         nmi_handle_intr(type, frame);
707                         return;
708 #endif /* POWERFAIL_NMI */
709                 }
710
711                 trap_fatal(frame, eva);
712                 return;
713         }
714
715         ksiginfo_init_trap(&ksi);
716         ksi.ksi_signo = signo;
717         ksi.ksi_code = ucode;
718         ksi.ksi_addr = (void *)addr;
719         ksi.ksi_trapno = type;
720         if (uprintf_signal) {
721                 uprintf("pid %d comm %s: signal %d err %#x code %d type %d "
722                     "addr %#x ss %#04x esp %#08x cs %#04x eip %#08x eax %#08x"
723                     "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
724                     p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
725                     addr, frame->tf_ss, frame->tf_esp, frame->tf_cs,
726                     frame->tf_eip, frame->tf_eax,
727                     fubyte((void *)(frame->tf_eip + 0)),
728                     fubyte((void *)(frame->tf_eip + 1)),
729                     fubyte((void *)(frame->tf_eip + 2)),
730                     fubyte((void *)(frame->tf_eip + 3)),
731                     fubyte((void *)(frame->tf_eip + 4)),
732                     fubyte((void *)(frame->tf_eip + 5)),
733                     fubyte((void *)(frame->tf_eip + 6)),
734                     fubyte((void *)(frame->tf_eip + 7)));
735         }
736         KASSERT((read_eflags() & PSL_I) != 0, ("interrupts disabled"));
737         trapsignal(td, &ksi);
738
739 user:
740         userret(td, frame);
741         KASSERT(PCB_USER_FPU(td->td_pcb),
742             ("Return from trap with kernel FPU ctx leaked"));
743 }
744
745 /*
746  * Handle all details of a page fault.
747  * Returns:
748  * -2 if the fault was caused by triggered workaround for Intel Pentium
749  *    0xf00f bug.
750  * -1 if this fault was fatal, typically from kernel mode
751  *    (cannot happen, but we need to return something).
752  * 0  if this fault was handled by updating either the user or kernel
753  *    page table, execution can continue.
754  * 1  if this fault was from usermode and it was not handled, a synchronous
755  *    signal should be delivered to the thread.  *signo returns the signal
756  *    number, *ucode gives si_code.
757  */
758 static int
759 trap_pfault(struct trapframe *frame, bool usermode, vm_offset_t eva,
760     int *signo, int *ucode)
761 {
762         struct thread *td;
763         struct proc *p;
764         vm_map_t map;
765         int rv;
766         vm_prot_t ftype;
767
768         MPASS(!usermode || (signo != NULL && ucode != NULL));
769
770         td = curthread;
771         p = td->td_proc;
772
773         if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
774                 /*
775                  * Due to both processor errata and lazy TLB invalidation when
776                  * access restrictions are removed from virtual pages, memory
777                  * accesses that are allowed by the physical mapping layer may
778                  * nonetheless cause one spurious page fault per virtual page. 
779                  * When the thread is executing a "no faulting" section that
780                  * is bracketed by vm_fault_{disable,enable}_pagefaults(),
781                  * every page fault is treated as a spurious page fault,
782                  * unless it accesses the same virtual address as the most
783                  * recent page fault within the same "no faulting" section.
784                  */
785                 if (td->td_md.md_spurflt_addr != eva ||
786                     (td->td_pflags & TDP_RESETSPUR) != 0) {
787                         /*
788                          * Do nothing to the TLB.  A stale TLB entry is
789                          * flushed automatically by a page fault.
790                          */
791                         td->td_md.md_spurflt_addr = eva;
792                         td->td_pflags &= ~TDP_RESETSPUR;
793                         return (0);
794                 }
795         } else {
796                 /*
797                  * If we get a page fault while in a critical section, then
798                  * it is most likely a fatal kernel page fault.  The kernel
799                  * is already going to panic trying to get a sleep lock to
800                  * do the VM lookup, so just consider it a fatal trap so the
801                  * kernel can print out a useful trap message and even get
802                  * to the debugger.
803                  *
804                  * If we get a page fault while holding a non-sleepable
805                  * lock, then it is most likely a fatal kernel page fault.
806                  * If WITNESS is enabled, then it's going to whine about
807                  * bogus LORs with various VM locks, so just skip to the
808                  * fatal trap handling directly.
809                  */
810                 if (td->td_critnest != 0 ||
811                     WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
812                     "Kernel page fault") != 0) {
813                         trap_fatal(frame, eva);
814                         return (-1);
815                 }
816         }
817         if (eva >= PMAP_TRM_MIN_ADDRESS) {
818                 /*
819                  * Don't allow user-mode faults in kernel address space.
820                  * An exception:  if the faulting address is the invalid
821                  * instruction entry in the IDT, then the Intel Pentium
822                  * F00F bug workaround was triggered, and we need to
823                  * treat it is as an illegal instruction, and not a page
824                  * fault.
825                  */
826 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
827                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
828                         *ucode = ILL_PRVOPC;
829                         *signo = SIGILL;
830                         return (-2);
831                 }
832 #endif
833                 if (usermode) {
834                         *signo = SIGSEGV;
835                         *ucode = SEGV_MAPERR;
836                         return (1);
837                 }
838                 trap_fatal(frame, eva);
839                 return (-1);
840         } else {
841                 map = usermode ? &p->p_vmspace->vm_map : kernel_map;
842
843                 /*
844                  * Kernel cannot access a user-space address directly
845                  * because user pages are not mapped.  Also, page
846                  * faults must not be caused during the interrupts.
847                  */
848                 if (!usermode && td->td_intr_nesting_level != 0) {
849                         trap_fatal(frame, eva);
850                         return (-1);
851                 }
852         }
853
854         /*
855          * If the trap was caused by errant bits in the PTE then panic.
856          */
857         if (frame->tf_err & PGEX_RSV) {
858                 trap_fatal(frame, eva);
859                 return (-1);
860         }
861
862         /*
863          * PGEX_I is defined only if the execute disable bit capability is
864          * supported and enabled.
865          */
866         if (frame->tf_err & PGEX_W)
867                 ftype = VM_PROT_WRITE;
868         else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
869                 ftype = VM_PROT_EXECUTE;
870         else
871                 ftype = VM_PROT_READ;
872
873         /* Fault in the page. */
874         rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
875         if (rv == KERN_SUCCESS) {
876 #ifdef HWPMC_HOOKS
877                 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
878                         PMC_SOFT_CALL_TF( , , page_fault, all, frame);
879                         if (ftype == VM_PROT_READ)
880                                 PMC_SOFT_CALL_TF( , , page_fault, read,
881                                     frame);
882                         else
883                                 PMC_SOFT_CALL_TF( , , page_fault, write,
884                                     frame);
885                 }
886 #endif
887                 return (0);
888         }
889         if (usermode)
890                 return (1);
891         if (td->td_intr_nesting_level == 0 &&
892             curpcb->pcb_onfault != NULL) {
893                 frame->tf_eip = (int)curpcb->pcb_onfault;
894                 return (0);
895         }
896         trap_fatal(frame, eva);
897         return (-1);
898 }
899
900 static void
901 trap_fatal(struct trapframe *frame, vm_offset_t eva)
902 {
903         int code, ss, esp;
904         u_int type;
905         struct soft_segment_descriptor softseg;
906 #ifdef KDB
907         bool handled;
908 #endif
909
910         code = frame->tf_err;
911         type = frame->tf_trapno;
912         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
913
914         printf("\n\nFatal trap %d: %s while in %s mode\n", type, trap_msg(type),
915             frame->tf_eflags & PSL_VM ? "vm86" :
916             ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
917 #ifdef SMP
918         /* two separate prints in case of a trap on an unmapped page */
919         printf("cpuid = %d; ", PCPU_GET(cpuid));
920         printf("apic id = %02x\n", PCPU_GET(apic_id));
921 #endif
922         if (type == T_PAGEFLT) {
923                 printf("fault virtual address   = 0x%x\n", eva);
924                 printf("fault code              = %s %s%s, %s\n",
925                         code & PGEX_U ? "user" : "supervisor",
926                         code & PGEX_W ? "write" : "read",
927                         pg_nx != 0 ?
928                         (code & PGEX_I ? " instruction" : " data") :
929                         "",
930                         code & PGEX_RSV ? "reserved bits in PTE" :
931                         code & PGEX_P ? "protection violation" : "page not present");
932         } else {
933                 printf("error code              = %#x\n", code);
934         }
935         printf("instruction pointer     = 0x%x:0x%x\n",
936                frame->tf_cs & 0xffff, frame->tf_eip);
937         if (TF_HAS_STACKREGS(frame)) {
938                 ss = frame->tf_ss & 0xffff;
939                 esp = frame->tf_esp;
940         } else {
941                 ss = GSEL(GDATA_SEL, SEL_KPL);
942                 esp = (int)&frame->tf_esp;
943         }
944         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
945         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
946         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
947                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
948         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
949                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
950                softseg.ssd_gran);
951         printf("processor eflags        = ");
952         if (frame->tf_eflags & PSL_T)
953                 printf("trace trap, ");
954         if (frame->tf_eflags & PSL_I)
955                 printf("interrupt enabled, ");
956         if (frame->tf_eflags & PSL_NT)
957                 printf("nested task, ");
958         if (frame->tf_eflags & PSL_RF)
959                 printf("resume, ");
960         if (frame->tf_eflags & PSL_VM)
961                 printf("vm86, ");
962         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
963         printf("current process         = %d (%s)\n",
964             curproc->p_pid, curthread->td_name);
965
966 #ifdef KDB
967         if (debugger_on_trap) {
968                 kdb_why = KDB_WHY_TRAP;
969                 frame->tf_err = eva;    /* smuggle fault address to ddb */
970                 handled = kdb_trap(type, 0, frame);
971                 frame->tf_err = code;   /* restore error code */
972                 kdb_why = KDB_WHY_UNSET;
973                 if (handled)
974                         return;
975         }
976 #endif
977         printf("trap number             = %d\n", type);
978         if (trap_msg(type) != NULL)
979                 panic("%s", trap_msg(type));
980         else
981                 panic("unknown/reserved trap");
982 }
983
984 #ifdef KDTRACE_HOOKS
985 /*
986  * Invoke a userspace DTrace hook.  The hook pointer is cleared when no
987  * userspace probes are enabled, so we must synchronize with DTrace to ensure
988  * that a trapping thread is able to call the hook before it is cleared.
989  */
990 static bool
991 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
992 {
993         int (*hook)(struct trapframe *);
994
995         hook = atomic_load_ptr(hookp);
996         enable_intr();
997         if (hook != NULL)
998                 return ((hook)(frame) == 0);
999         return (false);
1000 }
1001 #endif
1002
1003 /*
1004  * Double fault handler. Called when a fault occurs while writing
1005  * a frame for a trap/exception onto the stack. This usually occurs
1006  * when the stack overflows (such is the case with infinite recursion,
1007  * for example).
1008  *
1009  * XXX Note that the current PTD gets replaced by IdlePTD when the
1010  * task switch occurs. This means that the stack that was active at
1011  * the time of the double fault is not available at <kstack> unless
1012  * the machine was idle when the double fault occurred. The downside
1013  * of this is that "trace <ebp>" in ddb won't work.
1014  */
1015 void
1016 dblfault_handler(void)
1017 {
1018         struct i386tss *t;
1019
1020 #ifdef KDTRACE_HOOKS
1021         if (dtrace_doubletrap_func != NULL)
1022                 (*dtrace_doubletrap_func)();
1023 #endif
1024         printf("\nFatal double fault:\n");
1025         t = PCPU_GET(common_tssp);
1026         printf(
1027             "eip = %#08x esp = %#08x ebp = %#08x eax = %#08x\n"
1028             "edx = %#08x ecx = %#08x edi = %#08x esi = %#08x\n"
1029             "ebx = %#08x\n"
1030             "psl = %#08x cs  = %#08x ss  = %#08x ds  = %#08x\n"
1031             "es  = %#08x fs  = %#08x gs  = %#08x cr3 = %#08x\n",
1032             t->tss_eip, t->tss_esp, t->tss_ebp, t->tss_eax,
1033             t->tss_edx, t->tss_ecx, t->tss_edi, t->tss_esi,
1034             t->tss_ebx,
1035             t->tss_eflags, t->tss_cs, t->tss_ss, t->tss_ds,
1036             t->tss_es, t->tss_fs, t->tss_gs, t->tss_cr3);
1037 #ifdef SMP
1038         printf("cpuid = %d; apic id = %02x\n", PCPU_GET(cpuid),
1039             PCPU_GET(apic_id));
1040 #endif
1041         panic("double fault");
1042 }
1043
1044 int
1045 cpu_fetch_syscall_args(struct thread *td)
1046 {
1047         struct proc *p;
1048         struct trapframe *frame;
1049         struct syscall_args *sa;
1050         caddr_t params;
1051         long tmp;
1052         int error;
1053 #ifdef COMPAT_43
1054         u_int32_t eip;
1055         int cs;
1056 #endif
1057
1058         p = td->td_proc;
1059         frame = td->td_frame;
1060         sa = &td->td_sa;
1061
1062 #ifdef COMPAT_43
1063         if (__predict_false(frame->tf_cs == 7 && frame->tf_eip == 2)) {
1064                 /*
1065                  * In lcall $7,$0 after int $0x80.  Convert the user
1066                  * frame to what it would be for a direct int 0x80 instead
1067                  * of lcall $7,$0, by popping the lcall return address.
1068                  */
1069                 error = fueword32((void *)frame->tf_esp, &eip);
1070                 if (error == -1)
1071                         return (EFAULT);
1072                 cs = fuword16((void *)(frame->tf_esp + sizeof(u_int32_t)));
1073                 if (cs == -1)
1074                         return (EFAULT);
1075
1076                 /*
1077                  * Unwind in-kernel frame after all stack frame pieces
1078                  * were successfully read.
1079                  */
1080                 frame->tf_eip = eip;
1081                 frame->tf_cs = cs;
1082                 frame->tf_esp += 2 * sizeof(u_int32_t);
1083                 frame->tf_err = 7;      /* size of lcall $7,$0 */
1084         }
1085 #endif
1086
1087         sa->code = frame->tf_eax;
1088         sa->original_code = sa->code;
1089         params = (caddr_t)frame->tf_esp + sizeof(uint32_t);
1090
1091         /*
1092          * Need to check if this is a 32 bit or 64 bit syscall.
1093          */
1094         if (sa->code == SYS_syscall) {
1095                 /*
1096                  * Code is first argument, followed by actual args.
1097                  */
1098                 error = fueword(params, &tmp);
1099                 if (error == -1)
1100                         return (EFAULT);
1101                 sa->code = tmp;
1102                 params += sizeof(uint32_t);
1103         } else if (sa->code == SYS___syscall) {
1104                 /*
1105                  * Like syscall, but code is a quad, so as to maintain
1106                  * quad alignment for the rest of the arguments.
1107                  */
1108                 error = fueword(params, &tmp);
1109                 if (error == -1)
1110                         return (EFAULT);
1111                 sa->code = tmp;
1112                 params += sizeof(quad_t);
1113         }
1114
1115         if (sa->code >= p->p_sysent->sv_size)
1116                 sa->callp = &nosys_sysent;
1117         else
1118                 sa->callp = &p->p_sysent->sv_table[sa->code];
1119
1120         if (params != NULL && sa->callp->sy_narg != 0)
1121                 error = copyin(params, (caddr_t)sa->args,
1122                     (u_int)(sa->callp->sy_narg * sizeof(uint32_t)));
1123         else
1124                 error = 0;
1125
1126         if (error == 0) {
1127                 td->td_retval[0] = 0;
1128                 td->td_retval[1] = frame->tf_edx;
1129         }
1130                 
1131         return (error);
1132 }
1133
1134 #include "../../kern/subr_syscall.c"
1135
1136 /*
1137  * syscall - system call request C handler.  A system call is
1138  * essentially treated as a trap by reusing the frame layout.
1139  */
1140 void
1141 syscall(struct trapframe *frame)
1142 {
1143         struct thread *td;
1144         register_t orig_tf_eflags;
1145         ksiginfo_t ksi;
1146
1147 #ifdef DIAGNOSTIC
1148         if (!(TRAPF_USERMODE(frame) &&
1149             (curpcb->pcb_flags & PCB_VM86CALL) == 0)) {
1150                 panic("syscall");
1151                 /* NOT REACHED */
1152         }
1153 #endif
1154         trap_check_kstack();
1155         orig_tf_eflags = frame->tf_eflags;
1156
1157         td = curthread;
1158         td->td_frame = frame;
1159
1160         syscallenter(td);
1161
1162         /*
1163          * Traced syscall.
1164          */
1165         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1166                 frame->tf_eflags &= ~PSL_T;
1167                 ksiginfo_init_trap(&ksi);
1168                 ksi.ksi_signo = SIGTRAP;
1169                 ksi.ksi_code = TRAP_TRACE;
1170                 ksi.ksi_addr = (void *)frame->tf_eip;
1171                 trapsignal(td, &ksi);
1172         }
1173
1174         KASSERT(PCB_USER_FPU(td->td_pcb),
1175             ("System call %s returning with kernel FPU ctx leaked",
1176              syscallname(td->td_proc, td->td_sa.code)));
1177         KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1178             ("System call %s returning with mangled pcb_save",
1179              syscallname(td->td_proc, td->td_sa.code)));
1180
1181         syscallret(td);
1182 }