]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/i386/i386/trap.c
MFC r368207,368607:
[FreeBSD/stable/10.git] / sys / i386 / i386 / trap.c
1 /*-
2  * Copyright (C) 1994, David Greenman
3  * Copyright (c) 1990, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * the University of Utah, and William Jolitz.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      from: @(#)trap.c        7.4 (Berkeley) 5/13/91
38  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
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_kdtrace.h"
53 #include "opt_npx.h"
54 #include "opt_trap.h"
55
56 #include <sys/param.h>
57 #include <sys/bus.h>
58 #include <sys/systm.h>
59 #include <sys/proc.h>
60 #include <sys/pioctl.h>
61 #include <sys/ptrace.h>
62 #include <sys/kdb.h>
63 #include <sys/kernel.h>
64 #include <sys/ktr.h>
65 #include <sys/lock.h>
66 #include <sys/mutex.h>
67 #include <sys/resourcevar.h>
68 #include <sys/signalvar.h>
69 #include <sys/syscall.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysent.h>
72 #include <sys/uio.h>
73 #include <sys/vmmeter.h>
74 #ifdef HWPMC_HOOKS
75 #include <sys/pmckern.h>
76 PMC_SOFT_DEFINE( , , page_fault, all);
77 PMC_SOFT_DEFINE( , , page_fault, read);
78 PMC_SOFT_DEFINE( , , page_fault, write);
79 #endif
80 #include <security/audit/audit.h>
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/tss.h>
99 #include <machine/vm86.h>
100
101 #ifdef POWERFAIL_NMI
102 #include <sys/syslog.h>
103 #include <machine/clock.h>
104 #endif
105
106 #ifdef KDTRACE_HOOKS
107 #include <sys/dtrace_bsd.h>
108 #endif
109
110 extern void trap(struct trapframe *frame);
111 extern void syscall(struct trapframe *frame);
112
113 static int trap_pfault(struct trapframe *, int, vm_offset_t);
114 static void trap_fatal(struct trapframe *, vm_offset_t);
115 void dblfault_handler(void);
116
117 extern inthand_t IDTVEC(lcall_syscall);
118
119 extern inthand_t IDTVEC(bpt), IDTVEC(dbg), IDTVEC(int0x80_syscall);
120
121 #define MAX_TRAP_MSG            32
122 static char *trap_msg[] = {
123         "",                                     /*  0 unused */
124         "privileged instruction fault",         /*  1 T_PRIVINFLT */
125         "",                                     /*  2 unused */
126         "breakpoint instruction fault",         /*  3 T_BPTFLT */
127         "",                                     /*  4 unused */
128         "",                                     /*  5 unused */
129         "arithmetic trap",                      /*  6 T_ARITHTRAP */
130         "",                                     /*  7 unused */
131         "",                                     /*  8 unused */
132         "general protection fault",             /*  9 T_PROTFLT */
133         "trace trap",                           /* 10 T_TRCTRAP */
134         "",                                     /* 11 unused */
135         "page fault",                           /* 12 T_PAGEFLT */
136         "",                                     /* 13 unused */
137         "alignment fault",                      /* 14 T_ALIGNFLT */
138         "",                                     /* 15 unused */
139         "",                                     /* 16 unused */
140         "",                                     /* 17 unused */
141         "integer divide fault",                 /* 18 T_DIVIDE */
142         "non-maskable interrupt trap",          /* 19 T_NMI */
143         "overflow trap",                        /* 20 T_OFLOW */
144         "FPU bounds check fault",               /* 21 T_BOUND */
145         "FPU device not available",             /* 22 T_DNA */
146         "double fault",                         /* 23 T_DOUBLEFLT */
147         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
148         "invalid TSS fault",                    /* 25 T_TSSFLT */
149         "segment not present fault",            /* 26 T_SEGNPFLT */
150         "stack fault",                          /* 27 T_STKFLT */
151         "machine check trap",                   /* 28 T_MCHK */
152         "SIMD floating-point exception",        /* 29 T_XMMFLT */
153         "reserved (unknown) fault",             /* 30 T_RESERVED */
154         "",                                     /* 31 unused (reserved) */
155         "DTrace pid return trap",               /* 32 T_DTRACE_RET */
156 };
157
158 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
159 int has_f00f_bug = 0;           /* Initialized so that it can be patched. */
160 #endif
161
162 #ifdef KDB
163 static int kdb_on_nmi = 1;
164 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RW,
165         &kdb_on_nmi, 0, "Go to KDB on NMI");
166 TUNABLE_INT("machdep.kdb_on_nmi", &kdb_on_nmi);
167 #endif
168 static int panic_on_nmi = 1;
169 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
170         &panic_on_nmi, 0, "Panic on NMI");
171 TUNABLE_INT("machdep.panic_on_nmi", &panic_on_nmi);
172 static int prot_fault_translation = 0;
173 SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RW,
174         &prot_fault_translation, 0, "Select signal to deliver on protection fault");
175 static int uprintf_signal;
176 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RW,
177     &uprintf_signal, 0,
178     "Print debugging information on trap signal to ctty");
179
180 /*
181  * Exception, fault, and trap interface to the FreeBSD kernel.
182  * This common code is called from assembly language IDT gate entry
183  * routines that prepare a suitable stack frame, and restore this
184  * frame after the exception has been processed.
185  */
186
187 void
188 trap(struct trapframe *frame)
189 {
190 #ifdef KDTRACE_HOOKS
191         struct reg regs;
192 #endif
193         struct thread *td = curthread;
194         struct proc *p = td->td_proc;
195         int i = 0, ucode = 0, code;
196         u_int type;
197         register_t addr = 0;
198         vm_offset_t eva;
199         ksiginfo_t ksi;
200 #ifdef POWERFAIL_NMI
201         static int lastalert = 0;
202 #endif
203
204         PCPU_INC(cnt.v_trap);
205         type = frame->tf_trapno;
206
207 #ifdef SMP
208         /* Handler for NMI IPIs used for stopping CPUs. */
209         if (type == T_NMI) {
210                  if (ipi_nmi_handler() == 0)
211                            goto out;
212         }
213 #endif /* SMP */
214
215 #ifdef KDB
216         if (kdb_active) {
217                 kdb_reenter();
218                 goto out;
219         }
220 #endif
221
222         if (type == T_RESERVED) {
223                 trap_fatal(frame, 0);
224                 goto out;
225         }
226
227 #ifdef  HWPMC_HOOKS
228         /*
229          * CPU PMCs interrupt using an NMI so we check for that first.
230          * If the HWPMC module is active, 'pmc_hook' will point to
231          * the function to be called.  A return value of '1' from the
232          * hook means that the NMI was handled by it and that we can
233          * return immediately.
234          */
235         if (type == T_NMI && pmc_intr &&
236             (*pmc_intr)(PCPU_GET(cpuid), frame))
237             goto out;
238 #endif
239
240         if (type == T_MCHK) {
241                 mca_intr();
242                 goto out;
243         }
244
245 #ifdef KDTRACE_HOOKS
246         /*
247          * A trap can occur while DTrace executes a probe. Before
248          * executing the probe, DTrace blocks re-scheduling and sets
249          * a flag in its per-cpu flags to indicate that it doesn't
250          * want to fault. On returning from the probe, the no-fault
251          * flag is cleared and finally re-scheduling is enabled.
252          */
253         if ((type == T_PROTFLT || type == T_PAGEFLT) &&
254             dtrace_trap_func != NULL && (*dtrace_trap_func)(frame, type))
255                 goto out;
256 #endif
257
258         if ((frame->tf_eflags & PSL_I) == 0) {
259                 /*
260                  * Buggy application or kernel code has disabled
261                  * interrupts and then trapped.  Enabling interrupts
262                  * now is wrong, but it is better than running with
263                  * interrupts disabled until they are accidentally
264                  * enabled later.
265                  */
266                 if (ISPL(frame->tf_cs) == SEL_UPL || (frame->tf_eflags & PSL_VM))
267                         uprintf(
268                             "pid %ld (%s): trap %d with interrupts disabled\n",
269                             (long)curproc->p_pid, curthread->td_name, type);
270                 else if (type != T_NMI && type != T_BPTFLT &&
271                     type != T_TRCTRAP &&
272                     frame->tf_eip != (int)cpu_switch_load_gs) {
273                         /*
274                          * XXX not quite right, since this may be for a
275                          * multiple fault in user mode.
276                          */
277                         printf("kernel trap %d with interrupts disabled\n",
278                             type);
279                         /*
280                          * Page faults need interrupts disabled until later,
281                          * and we shouldn't enable interrupts while holding
282                          * a spin lock.
283                          */
284                         if (type != T_PAGEFLT &&
285                             td->td_md.md_spinlock_count == 0)
286                                 enable_intr();
287                 }
288         }
289         eva = 0;
290         code = frame->tf_err;
291         if (type == T_PAGEFLT) {
292                 /*
293                  * For some Cyrix CPUs, %cr2 is clobbered by
294                  * interrupts.  This problem is worked around by using
295                  * an interrupt gate for the pagefault handler.  We
296                  * are finally ready to read %cr2 and conditionally
297                  * reenable interrupts.  If we hold a spin lock, then
298                  * we must not reenable interrupts.  This might be a
299                  * spurious page fault.
300                  */
301                 eva = rcr2();
302                 if (td->td_md.md_spinlock_count == 0)
303                         enable_intr();
304         }
305
306         if ((ISPL(frame->tf_cs) == SEL_UPL) ||
307             ((frame->tf_eflags & PSL_VM) && 
308                 !(curpcb->pcb_flags & PCB_VM86CALL))) {
309                 /* user trap */
310
311                 td->td_pticks = 0;
312                 td->td_frame = frame;
313                 addr = frame->tf_eip;
314                 if (td->td_ucred != p->p_ucred) 
315                         cred_update_thread(td);
316
317                 switch (type) {
318                 case T_PRIVINFLT:       /* privileged instruction fault */
319                         i = SIGILL;
320                         ucode = ILL_PRVOPC;
321                         break;
322
323                 case T_BPTFLT:          /* bpt instruction fault */
324                 case T_TRCTRAP:         /* trace trap */
325                         enable_intr();
326 #ifdef KDTRACE_HOOKS
327                         if (type == T_BPTFLT) {
328                                 fill_frame_regs(frame, &regs);
329                                 if (dtrace_pid_probe_ptr != NULL &&
330                                     dtrace_pid_probe_ptr(&regs) == 0)
331                                         goto out;
332                         }
333 #endif
334                         frame->tf_eflags &= ~PSL_T;
335                         i = SIGTRAP;
336                         ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
337                         break;
338
339                 case T_ARITHTRAP:       /* arithmetic trap */
340 #ifdef DEV_NPX
341                         ucode = npxtrap_x87();
342                         if (ucode == -1)
343                                 goto userout;
344 #else
345                         ucode = 0;
346 #endif
347                         i = SIGFPE;
348                         break;
349
350                         /*
351                          * The following two traps can happen in
352                          * vm86 mode, and, if so, we want to handle
353                          * them specially.
354                          */
355                 case T_PROTFLT:         /* general protection fault */
356                 case T_STKFLT:          /* stack fault */
357                         if (frame->tf_eflags & PSL_VM) {
358                                 i = vm86_emulate((struct vm86frame *)frame);
359                                 if (i == 0)
360                                         goto user;
361                                 break;
362                         }
363                         i = SIGBUS;
364                         ucode = (type == T_PROTFLT) ? BUS_OBJERR : BUS_ADRERR;
365                         break;
366                 case T_SEGNPFLT:        /* segment not present fault */
367                         i = SIGBUS;
368                         ucode = BUS_ADRERR;
369                         break;
370                 case T_TSSFLT:          /* invalid TSS fault */
371                         i = SIGBUS;
372                         ucode = BUS_OBJERR;
373                         break;
374                 case T_ALIGNFLT:
375                         i = SIGBUS;
376                         ucode = BUS_ADRALN;
377                         break;
378                 case T_DOUBLEFLT:       /* double fault */
379                 default:
380                         i = SIGBUS;
381                         ucode = BUS_OBJERR;
382                         break;
383
384                 case T_PAGEFLT:         /* page fault */
385
386                         i = trap_pfault(frame, TRUE, eva);
387 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
388                         if (i == -2) {
389                                 /*
390                                  * The f00f hack workaround has triggered, so
391                                  * treat the fault as an illegal instruction 
392                                  * (T_PRIVINFLT) instead of a page fault.
393                                  */
394                                 type = frame->tf_trapno = T_PRIVINFLT;
395
396                                 /* Proceed as in that case. */
397                                 ucode = ILL_PRVOPC;
398                                 i = SIGILL;
399                                 break;
400                         }
401 #endif
402                         if (i == -1)
403                                 goto userout;
404                         if (i == 0)
405                                 goto user;
406
407                         if (i == SIGSEGV)
408                                 ucode = SEGV_MAPERR;
409                         else {
410                                 if (prot_fault_translation == 0) {
411                                         /*
412                                          * Autodetect.
413                                          * This check also covers the images
414                                          * without the ABI-tag ELF note.
415                                          */
416                                         if (SV_CURPROC_ABI() == SV_ABI_FREEBSD
417                                             && p->p_osrel >= P_OSREL_SIGSEGV) {
418                                                 i = SIGSEGV;
419                                                 ucode = SEGV_ACCERR;
420                                         } else {
421                                                 i = SIGBUS;
422                                                 ucode = BUS_PAGE_FAULT;
423                                         }
424                                 } else if (prot_fault_translation == 1) {
425                                         /*
426                                          * Always compat mode.
427                                          */
428                                         i = SIGBUS;
429                                         ucode = BUS_PAGE_FAULT;
430                                 } else {
431                                         /*
432                                          * Always SIGSEGV mode.
433                                          */
434                                         i = SIGSEGV;
435                                         ucode = SEGV_ACCERR;
436                                 }
437                         }
438                         addr = eva;
439                         break;
440
441                 case T_DIVIDE:          /* integer divide fault */
442                         ucode = FPE_INTDIV;
443                         i = SIGFPE;
444                         break;
445
446 #ifdef DEV_ISA
447                 case T_NMI:
448 #ifdef POWERFAIL_NMI
449 #ifndef TIMER_FREQ
450 #  define TIMER_FREQ 1193182
451 #endif
452                         if (time_second - lastalert > 10) {
453                                 log(LOG_WARNING, "NMI: power fail\n");
454                                 sysbeep(880, hz);
455                                 lastalert = time_second;
456                         }
457                         goto userout;
458 #else /* !POWERFAIL_NMI */
459                         /* machine/parity/power fail/"kitchen sink" faults */
460                         if (isa_nmi(code) == 0) {
461 #ifdef KDB
462                                 /*
463                                  * NMI can be hooked up to a pushbutton
464                                  * for debugging.
465                                  */
466                                 if (kdb_on_nmi) {
467                                         printf ("NMI ... going to debugger\n");
468                                         kdb_trap(type, 0, frame);
469                                 }
470 #endif /* KDB */
471                                 goto userout;
472                         } else if (panic_on_nmi)
473                                 panic("NMI indicates hardware failure");
474                         goto out;
475 #endif /* POWERFAIL_NMI */
476 #endif /* DEV_ISA */
477
478                 case T_OFLOW:           /* integer overflow fault */
479                         ucode = FPE_INTOVF;
480                         i = SIGFPE;
481                         break;
482
483                 case T_BOUND:           /* bounds check fault */
484                         ucode = FPE_FLTSUB;
485                         i = SIGFPE;
486                         break;
487
488                 case T_DNA:
489 #ifdef DEV_NPX
490                         KASSERT(PCB_USER_FPU(td->td_pcb),
491                             ("kernel FPU ctx has leaked"));
492                         /* transparent fault (due to context switch "late") */
493                         if (npxdna())
494                                 goto userout;
495 #endif
496                         uprintf("pid %d killed due to lack of floating point\n",
497                                 p->p_pid);
498                         i = SIGKILL;
499                         ucode = 0;
500                         break;
501
502                 case T_FPOPFLT:         /* FPU operand fetch fault */
503                         ucode = ILL_COPROC;
504                         i = SIGILL;
505                         break;
506
507                 case T_XMMFLT:          /* SIMD floating-point exception */
508 #if defined(DEV_NPX) && !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
509                         ucode = npxtrap_sse();
510                         if (ucode == -1)
511                                 goto userout;
512 #else
513                         ucode = 0;
514 #endif
515                         i = SIGFPE;
516                         break;
517 #ifdef KDTRACE_HOOKS
518                 case T_DTRACE_RET:
519                         enable_intr();
520                         fill_frame_regs(frame, &regs);
521                         if (dtrace_return_probe_ptr != NULL &&
522                             dtrace_return_probe_ptr(&regs) == 0)
523                                 goto out;
524                         goto userout;
525 #endif
526                 }
527         } else {
528                 /* kernel trap */
529
530                 KASSERT(cold || td->td_ucred != NULL,
531                     ("kernel trap doesn't have ucred"));
532                 switch (type) {
533                 case T_PAGEFLT:                 /* page fault */
534                         (void) trap_pfault(frame, FALSE, eva);
535                         goto out;
536
537                 case T_DNA:
538 #ifdef DEV_NPX
539                         if (PCB_USER_FPU(td->td_pcb))
540                                 panic("Unregistered use of FPU in kernel");
541                         if (npxdna())
542                                 goto out;
543 #endif
544                         break;
545
546                 case T_ARITHTRAP:       /* arithmetic trap */
547                 case T_XMMFLT:          /* SIMD floating-point exception */
548                 case T_FPOPFLT:         /* FPU operand fetch fault */
549                         /*
550                          * XXXKIB for now disable any FPU traps in kernel
551                          * handler registration seems to be overkill
552                          */
553                         trap_fatal(frame, 0);
554                         goto out;
555
556                         /*
557                          * The following two traps can happen in
558                          * vm86 mode, and, if so, we want to handle
559                          * them specially.
560                          */
561                 case T_PROTFLT:         /* general protection fault */
562                 case T_STKFLT:          /* stack fault */
563                         if (frame->tf_eflags & PSL_VM) {
564                                 i = vm86_emulate((struct vm86frame *)frame);
565                                 if (i != 0)
566                                         /*
567                                          * returns to original process
568                                          */
569                                         vm86_trap((struct vm86frame *)frame);
570                                 goto out;
571                         }
572                         /* FALL THROUGH */
573                 case T_SEGNPFLT:        /* segment not present fault */
574                         if (curpcb->pcb_flags & PCB_VM86CALL)
575                                 break;
576
577                         /*
578                          * Invalid %fs's and %gs's can be created using
579                          * procfs or PT_SETREGS or by invalidating the
580                          * underlying LDT entry.  This causes a fault
581                          * in kernel mode when the kernel attempts to
582                          * switch contexts.  Lose the bad context
583                          * (XXX) so that we can continue, and generate
584                          * a signal.
585                          */
586                         if (frame->tf_eip == (int)cpu_switch_load_gs) {
587                                 curpcb->pcb_gs = 0;
588 #if 0                           
589                                 PROC_LOCK(p);
590                                 kern_psignal(p, SIGBUS);
591                                 PROC_UNLOCK(p);
592 #endif                          
593                                 goto out;
594                         }
595
596                         if (td->td_intr_nesting_level != 0)
597                                 break;
598
599                         /*
600                          * Invalid segment selectors and out of bounds
601                          * %eip's and %esp's can be set up in user mode.
602                          * This causes a fault in kernel mode when the
603                          * kernel tries to return to user mode.  We want
604                          * to get this fault so that we can fix the
605                          * problem here and not have to check all the
606                          * selectors and pointers when the user changes
607                          * them.
608                          */
609                         if (frame->tf_eip == (int)doreti_iret) {
610                                 frame->tf_eip = (int)doreti_iret_fault;
611                                 goto out;
612                         }
613                         if (type == T_STKFLT)
614                                 break;
615
616                         if (frame->tf_eip == (int)doreti_popl_ds) {
617                                 frame->tf_eip = (int)doreti_popl_ds_fault;
618                                 goto out;
619                         }
620                         if (frame->tf_eip == (int)doreti_popl_es) {
621                                 frame->tf_eip = (int)doreti_popl_es_fault;
622                                 goto out;
623                         }
624                         if (frame->tf_eip == (int)doreti_popl_fs) {
625                                 frame->tf_eip = (int)doreti_popl_fs_fault;
626                                 goto out;
627                         }
628                         if (curpcb->pcb_onfault != NULL) {
629                                 frame->tf_eip =
630                                     (int)curpcb->pcb_onfault;
631                                 goto out;
632                         }
633                         break;
634
635                 case T_TSSFLT:
636                         /*
637                          * PSL_NT can be set in user mode and isn't cleared
638                          * automatically when the kernel is entered.  This
639                          * causes a TSS fault when the kernel attempts to
640                          * `iret' because the TSS link is uninitialized.  We
641                          * want to get this fault so that we can fix the
642                          * problem here and not every time the kernel is
643                          * entered.
644                          */
645                         if (frame->tf_eflags & PSL_NT) {
646                                 frame->tf_eflags &= ~PSL_NT;
647                                 goto out;
648                         }
649                         break;
650
651                 case T_TRCTRAP:  /* trace trap */
652                         if (frame->tf_eip == (int)IDTVEC(lcall_syscall)) {
653                                 /*
654                                  * We've just entered system mode via the
655                                  * syscall lcall.  Continue single stepping
656                                  * silently until the syscall handler has
657                                  * saved the flags.
658                                  */
659                                 goto out;
660                         }
661                         if (frame->tf_eip == (int)IDTVEC(lcall_syscall) + 1) {
662                                 /*
663                                  * The syscall handler has now saved the
664                                  * flags.  Stop single stepping it.
665                                  */
666                                 frame->tf_eflags &= ~PSL_T;
667                                 goto out;
668                         }
669                         /*
670                          * Ignore debug register trace traps due to
671                          * accesses in the user's address space, which
672                          * can happen under several conditions such as
673                          * if a user sets a watchpoint on a buffer and
674                          * then passes that buffer to a system call.
675                          * We still want to get TRCTRAPS for addresses
676                          * in kernel space because that is useful when
677                          * debugging the kernel.
678                          */
679                         if (user_dbreg_trap() && 
680                            !(curpcb->pcb_flags & PCB_VM86CALL)) {
681                                 /*
682                                  * Reset breakpoint bits because the
683                                  * processor doesn't
684                                  */
685                                 load_dr6(rdr6() & 0xfffffff0);
686                                 goto out;
687                         }
688
689                         /*
690                          * Malicious user code can configure a debug
691                          * register watchpoint to trap on data access
692                          * to the top of stack and then execute 'pop
693                          * %ss; int 3'.  Due to exception deferral for
694                          * 'pop %ss', the CPU will not interrupt 'int
695                          * 3' to raise the DB# exception for the debug
696                          * register but will postpone the DB# until
697                          * execution of the first instruction of the
698                          * BP# handler (in kernel mode).  Normally the
699                          * previous check would ignore DB# exceptions
700                          * for watchpoints on user addresses raised in
701                          * kernel mode.  However, some CPU errata
702                          * include cases where DB# exceptions do not
703                          * properly set bits in %dr6, e.g. Haswell
704                          * HSD23 and Skylake-X SKZ24.
705                          *
706                          * A deferred DB# can also be raised on the
707                          * first instructions of system call entry
708                          * points or single-step traps via similar use
709                          * of 'pop %ss' or 'mov xxx, %ss'.
710                          */
711                         if (frame->tf_eip ==
712                             (uintptr_t)IDTVEC(int0x80_syscall) ||
713                             frame->tf_eip == (uintptr_t)IDTVEC(bpt) ||
714                             frame->tf_eip == (uintptr_t)IDTVEC(dbg))
715                                 return;
716                         /*
717                          * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
718                          */
719                 case T_BPTFLT:
720                         /*
721                          * If KDB is enabled, let it handle the debugger trap.
722                          * Otherwise, debugger traps "can't happen".
723                          */
724 #ifdef KDB
725                         if (kdb_trap(type, 0, frame))
726                                 goto out;
727 #endif
728                         break;
729
730 #ifdef DEV_ISA
731                 case T_NMI:
732 #ifdef POWERFAIL_NMI
733                         if (time_second - lastalert > 10) {
734                                 log(LOG_WARNING, "NMI: power fail\n");
735                                 sysbeep(880, hz);
736                                 lastalert = time_second;
737                         }
738                         goto out;
739 #else /* !POWERFAIL_NMI */
740                         /* machine/parity/power fail/"kitchen sink" faults */
741                         if (isa_nmi(code) == 0) {
742 #ifdef KDB
743                                 /*
744                                  * NMI can be hooked up to a pushbutton
745                                  * for debugging.
746                                  */
747                                 if (kdb_on_nmi) {
748                                         printf ("NMI ... going to debugger\n");
749                                         kdb_trap(type, 0, frame);
750                                 }
751 #endif /* KDB */
752                                 goto out;
753                         } else if (panic_on_nmi == 0)
754                                 goto out;
755                         /* FALLTHROUGH */
756 #endif /* POWERFAIL_NMI */
757 #endif /* DEV_ISA */
758                 }
759
760                 trap_fatal(frame, eva);
761                 goto out;
762         }
763
764         /* Translate fault for emulators (e.g. Linux) */
765         if (*p->p_sysent->sv_transtrap)
766                 i = (*p->p_sysent->sv_transtrap)(i, type);
767
768         ksiginfo_init_trap(&ksi);
769         ksi.ksi_signo = i;
770         ksi.ksi_code = ucode;
771         ksi.ksi_addr = (void *)addr;
772         ksi.ksi_trapno = type;
773         if (uprintf_signal) {
774                 uprintf("pid %d comm %s: signal %d err %x code %d type %d "
775                     "addr 0x%x esp 0x%08x eip 0x%08x "
776                     "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
777                     p->p_pid, p->p_comm, i, frame->tf_err, ucode, type, addr,
778                     frame->tf_esp, frame->tf_eip,
779                     fubyte((void *)(frame->tf_eip + 0)),
780                     fubyte((void *)(frame->tf_eip + 1)),
781                     fubyte((void *)(frame->tf_eip + 2)),
782                     fubyte((void *)(frame->tf_eip + 3)),
783                     fubyte((void *)(frame->tf_eip + 4)),
784                     fubyte((void *)(frame->tf_eip + 5)),
785                     fubyte((void *)(frame->tf_eip + 6)),
786                     fubyte((void *)(frame->tf_eip + 7)));
787         }
788         KASSERT((read_eflags() & PSL_I) != 0, ("interrupts disabled"));
789         trapsignal(td, &ksi);
790
791 #ifdef DEBUG
792         if (type <= MAX_TRAP_MSG) {
793                 uprintf("fatal process exception: %s",
794                         trap_msg[type]);
795                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
796                         uprintf(", fault VA = 0x%lx", (u_long)eva);
797                 uprintf("\n");
798         }
799 #endif
800
801 user:
802         userret(td, frame);
803         KASSERT(PCB_USER_FPU(td->td_pcb),
804             ("Return from trap with kernel FPU ctx leaked"));
805 userout:
806 out:
807         return;
808 }
809
810 static int
811 trap_pfault(frame, usermode, eva)
812         struct trapframe *frame;
813         int usermode;
814         vm_offset_t eva;
815 {
816         vm_offset_t va;
817         struct vmspace *vm;
818         vm_map_t map;
819         int rv = 0;
820         vm_prot_t ftype;
821         struct thread *td = curthread;
822         struct proc *p = td->td_proc;
823
824         if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
825                 /*
826                  * Due to both processor errata and lazy TLB invalidation when
827                  * access restrictions are removed from virtual pages, memory
828                  * accesses that are allowed by the physical mapping layer may
829                  * nonetheless cause one spurious page fault per virtual page. 
830                  * When the thread is executing a "no faulting" section that
831                  * is bracketed by vm_fault_{disable,enable}_pagefaults(),
832                  * every page fault is treated as a spurious page fault,
833                  * unless it accesses the same virtual address as the most
834                  * recent page fault within the same "no faulting" section.
835                  */
836                 if (td->td_md.md_spurflt_addr != eva ||
837                     (td->td_pflags & TDP_RESETSPUR) != 0) {
838                         /*
839                          * Do nothing to the TLB.  A stale TLB entry is
840                          * flushed automatically by a page fault.
841                          */
842                         td->td_md.md_spurflt_addr = eva;
843                         td->td_pflags &= ~TDP_RESETSPUR;
844                         return (0);
845                 }
846         } else {
847                 /*
848                  * If we get a page fault while in a critical section, then
849                  * it is most likely a fatal kernel page fault.  The kernel
850                  * is already going to panic trying to get a sleep lock to
851                  * do the VM lookup, so just consider it a fatal trap so the
852                  * kernel can print out a useful trap message and even get
853                  * to the debugger.
854                  *
855                  * If we get a page fault while holding a non-sleepable
856                  * lock, then it is most likely a fatal kernel page fault.
857                  * If WITNESS is enabled, then it's going to whine about
858                  * bogus LORs with various VM locks, so just skip to the
859                  * fatal trap handling directly.
860                  */
861                 if (td->td_critnest != 0 ||
862                     WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
863                     "Kernel page fault") != 0) {
864                         trap_fatal(frame, eva);
865                         return (-1);
866                 }
867         }
868         va = trunc_page(eva);
869         if (va >= KERNBASE) {
870                 /*
871                  * Don't allow user-mode faults in kernel address space.
872                  * An exception:  if the faulting address is the invalid
873                  * instruction entry in the IDT, then the Intel Pentium
874                  * F00F bug workaround was triggered, and we need to
875                  * treat it is as an illegal instruction, and not a page
876                  * fault.
877                  */
878 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
879                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug)
880                         return (-2);
881 #endif
882                 if (usermode)
883                         goto nogo;
884
885                 map = kernel_map;
886         } else {
887                 /*
888                  * This is a fault on non-kernel virtual memory.  If either
889                  * p or p->p_vmspace is NULL, then the fault is fatal.
890                  */
891                 if (p == NULL || (vm = p->p_vmspace) == NULL)
892                         goto nogo;
893
894                 map = &vm->vm_map;
895
896                 /*
897                  * When accessing a user-space address, kernel must be
898                  * ready to accept the page fault, and provide a
899                  * handling routine.  Since accessing the address
900                  * without the handler is a bug, do not try to handle
901                  * it normally, and panic immediately.
902                  */
903                 if (!usermode && (td->td_intr_nesting_level != 0 ||
904                     curpcb->pcb_onfault == NULL)) {
905                         trap_fatal(frame, eva);
906                         return (-1);
907                 }
908         }
909
910         /*
911          * If the trap was caused by errant bits in the PTE then panic.
912          */
913         if (frame->tf_err & PGEX_RSV) {
914                 trap_fatal(frame, eva);
915                 return (-1);
916         }
917
918         /*
919          * PGEX_I is defined only if the execute disable bit capability is
920          * supported and enabled.
921          */
922         if (frame->tf_err & PGEX_W)
923                 ftype = VM_PROT_WRITE;
924 #if defined(PAE) || defined(PAE_TABLES)
925         else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
926                 ftype = VM_PROT_EXECUTE;
927 #endif
928         else
929                 ftype = VM_PROT_READ;
930
931         if (map != kernel_map) {
932                 /*
933                  * Keep swapout from messing with us during this
934                  *      critical time.
935                  */
936                 PROC_LOCK(p);
937                 ++p->p_lock;
938                 PROC_UNLOCK(p);
939
940                 /* Fault in the user page: */
941                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
942
943                 PROC_LOCK(p);
944                 --p->p_lock;
945                 PROC_UNLOCK(p);
946         } else {
947                 /*
948                  * Don't have to worry about process locking or stacks in the
949                  * kernel.
950                  */
951                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
952         }
953         if (rv == KERN_SUCCESS) {
954 #ifdef HWPMC_HOOKS
955                 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
956                         PMC_SOFT_CALL_TF( , , page_fault, all, frame);
957                         if (ftype == VM_PROT_READ)
958                                 PMC_SOFT_CALL_TF( , , page_fault, read,
959                                     frame);
960                         else
961                                 PMC_SOFT_CALL_TF( , , page_fault, write,
962                                     frame);
963                 }
964 #endif
965                 return (0);
966         }
967 nogo:
968         if (!usermode) {
969                 if (td->td_intr_nesting_level == 0 &&
970                     curpcb->pcb_onfault != NULL) {
971                         frame->tf_eip = (int)curpcb->pcb_onfault;
972                         return (0);
973                 }
974                 trap_fatal(frame, eva);
975                 return (-1);
976         }
977         return ((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
978 }
979
980 static void
981 trap_fatal(frame, eva)
982         struct trapframe *frame;
983         vm_offset_t eva;
984 {
985         int code, ss, esp;
986         u_int type;
987         struct soft_segment_descriptor softseg;
988         char *msg;
989 #ifdef KDB
990         bool handled;
991 #endif
992
993         code = frame->tf_err;
994         type = frame->tf_trapno;
995         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
996
997         if (type <= MAX_TRAP_MSG)
998                 msg = trap_msg[type];
999         else
1000                 msg = "UNKNOWN";
1001         printf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
1002             frame->tf_eflags & PSL_VM ? "vm86" :
1003             ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
1004 #ifdef SMP
1005         /* two separate prints in case of a trap on an unmapped page */
1006         printf("cpuid = %d; ", PCPU_GET(cpuid));
1007         printf("apic id = %02x\n", PCPU_GET(apic_id));
1008 #endif
1009         if (type == T_PAGEFLT) {
1010                 printf("fault virtual address   = 0x%x\n", eva);
1011                 printf("fault code              = %s %s%s, %s\n",
1012                         code & PGEX_U ? "user" : "supervisor",
1013                         code & PGEX_W ? "write" : "read",
1014 #if defined(PAE) || defined(PAE_TABLES)
1015                         pg_nx != 0 ?
1016                         (code & PGEX_I ? " instruction" : " data") :
1017 #endif
1018                         "",
1019                         code & PGEX_RSV ? "reserved bits in PTE" :
1020                         code & PGEX_P ? "protection violation" : "page not present");
1021         }
1022         printf("instruction pointer     = 0x%x:0x%x\n",
1023                frame->tf_cs & 0xffff, frame->tf_eip);
1024         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
1025                 ss = frame->tf_ss & 0xffff;
1026                 esp = frame->tf_esp;
1027         } else {
1028                 ss = GSEL(GDATA_SEL, SEL_KPL);
1029                 esp = (int)&frame->tf_esp;
1030         }
1031         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
1032         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
1033         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
1034                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1035         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
1036                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
1037                softseg.ssd_gran);
1038         printf("processor eflags        = ");
1039         if (frame->tf_eflags & PSL_T)
1040                 printf("trace trap, ");
1041         if (frame->tf_eflags & PSL_I)
1042                 printf("interrupt enabled, ");
1043         if (frame->tf_eflags & PSL_NT)
1044                 printf("nested task, ");
1045         if (frame->tf_eflags & PSL_RF)
1046                 printf("resume, ");
1047         if (frame->tf_eflags & PSL_VM)
1048                 printf("vm86, ");
1049         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1050         printf("current process         = %d (%s)\n",
1051             curproc->p_pid, curthread->td_name);
1052
1053 #ifdef KDB
1054         if (debugger_on_panic) {
1055                 kdb_why = KDB_WHY_TRAP;
1056                 frame->tf_err = eva;    /* smuggle fault address to ddb */
1057                 handled = kdb_trap(type, 0, frame);
1058                 frame->tf_err = code;   /* restore error code */
1059                 kdb_why = KDB_WHY_UNSET;
1060                 if (handled)
1061                         return;
1062         }
1063 #endif
1064         printf("trap number             = %d\n", type);
1065         if (type <= MAX_TRAP_MSG)
1066                 panic("%s", trap_msg[type]);
1067         else
1068                 panic("unknown/reserved trap");
1069 }
1070
1071 /*
1072  * Double fault handler. Called when a fault occurs while writing
1073  * a frame for a trap/exception onto the stack. This usually occurs
1074  * when the stack overflows (such is the case with infinite recursion,
1075  * for example).
1076  *
1077  * XXX Note that the current PTD gets replaced by IdlePTD when the
1078  * task switch occurs. This means that the stack that was active at
1079  * the time of the double fault is not available at <kstack> unless
1080  * the machine was idle when the double fault occurred. The downside
1081  * of this is that "trace <ebp>" in ddb won't work.
1082  */
1083 void
1084 dblfault_handler()
1085 {
1086 #ifdef KDTRACE_HOOKS
1087         if (dtrace_doubletrap_func != NULL)
1088                 (*dtrace_doubletrap_func)();
1089 #endif
1090         printf("\nFatal double fault:\n");
1091         printf("eip = 0x%x\n", PCPU_GET(common_tss.tss_eip));
1092         printf("esp = 0x%x\n", PCPU_GET(common_tss.tss_esp));
1093         printf("ebp = 0x%x\n", PCPU_GET(common_tss.tss_ebp));
1094 #ifdef SMP
1095         /* two separate prints in case of a trap on an unmapped page */
1096         printf("cpuid = %d; ", PCPU_GET(cpuid));
1097         printf("apic id = %02x\n", PCPU_GET(apic_id));
1098 #endif
1099         panic("double fault");
1100 }
1101
1102 int
1103 cpu_fetch_syscall_args(struct thread *td, struct syscall_args *sa)
1104 {
1105         struct proc *p;
1106         struct trapframe *frame;
1107         caddr_t params;
1108         long tmp;
1109         int error;
1110
1111         p = td->td_proc;
1112         frame = td->td_frame;
1113
1114         params = (caddr_t)frame->tf_esp + sizeof(int);
1115         sa->code = frame->tf_eax;
1116
1117         /*
1118          * Need to check if this is a 32 bit or 64 bit syscall.
1119          */
1120         if (sa->code == SYS_syscall) {
1121                 /*
1122                  * Code is first argument, followed by actual args.
1123                  */
1124                 error = fueword(params, &tmp);
1125                 if (error == -1)
1126                         return (EFAULT);
1127                 sa->code = tmp;
1128                 params += sizeof(int);
1129         } else if (sa->code == SYS___syscall) {
1130                 /*
1131                  * Like syscall, but code is a quad, so as to maintain
1132                  * quad alignment for the rest of the arguments.
1133                  */
1134                 error = fueword(params, &tmp);
1135                 if (error == -1)
1136                         return (EFAULT);
1137                 sa->code = tmp;
1138                 params += sizeof(quad_t);
1139         }
1140
1141         if (p->p_sysent->sv_mask)
1142                 sa->code &= p->p_sysent->sv_mask;
1143         if (sa->code >= p->p_sysent->sv_size)
1144                 sa->callp = &p->p_sysent->sv_table[0];
1145         else
1146                 sa->callp = &p->p_sysent->sv_table[sa->code];
1147         sa->narg = sa->callp->sy_narg;
1148
1149         if (params != NULL && sa->narg != 0)
1150                 error = copyin(params, (caddr_t)sa->args,
1151                     (u_int)(sa->narg * sizeof(int)));
1152         else
1153                 error = 0;
1154
1155         if (error == 0) {
1156                 td->td_retval[0] = 0;
1157                 td->td_retval[1] = frame->tf_edx;
1158         }
1159                 
1160         return (error);
1161 }
1162
1163 #include "../../kern/subr_syscall.c"
1164
1165 /*
1166  * syscall - system call request C handler.  A system call is
1167  * essentially treated as a trap by reusing the frame layout.
1168  */
1169 void
1170 syscall(struct trapframe *frame)
1171 {
1172         struct thread *td;
1173         struct syscall_args sa;
1174         register_t orig_tf_eflags;
1175         int error;
1176         ksiginfo_t ksi;
1177
1178 #ifdef DIAGNOSTIC
1179         if (ISPL(frame->tf_cs) != SEL_UPL) {
1180                 panic("syscall");
1181                 /* NOT REACHED */
1182         }
1183 #endif
1184         orig_tf_eflags = frame->tf_eflags;
1185
1186         td = curthread;
1187         td->td_frame = frame;
1188
1189         error = syscallenter(td, &sa);
1190
1191         /*
1192          * Traced syscall.
1193          */
1194         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1195                 frame->tf_eflags &= ~PSL_T;
1196                 ksiginfo_init_trap(&ksi);
1197                 ksi.ksi_signo = SIGTRAP;
1198                 ksi.ksi_code = TRAP_TRACE;
1199                 ksi.ksi_addr = (void *)frame->tf_eip;
1200                 trapsignal(td, &ksi);
1201         }
1202
1203         KASSERT(PCB_USER_FPU(td->td_pcb),
1204             ("System call %s returning with kernel FPU ctx leaked",
1205              syscallname(td->td_proc, sa.code)));
1206         KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1207             ("System call %s returning with mangled pcb_save",
1208              syscallname(td->td_proc, sa.code)));
1209
1210         syscallret(td, error, &sa);
1211 }