2 * Copyright (C) 1994, David Greenman
3 * Copyright (c) 1990, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * the University of Utah, and William Jolitz.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
37 * from: @(#)trap.c 7.4 (Berkeley) 5/13/91
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
44 * AMD64 Trap and System call handling
47 #include "opt_clock.h"
49 #include "opt_hwpmc_hooks.h"
52 #include "opt_ktrace.h"
54 #include <sys/param.h>
56 #include <sys/systm.h>
58 #include <sys/pioctl.h>
59 #include <sys/ptrace.h>
61 #include <sys/kernel.h>
64 #include <sys/mutex.h>
65 #include <sys/resourcevar.h>
66 #include <sys/signalvar.h>
67 #include <sys/syscall.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysent.h>
71 #include <sys/vmmeter.h>
73 #include <sys/ktrace.h>
76 #include <sys/pmckern.h>
78 #include <security/audit/audit.h>
81 #include <vm/vm_param.h>
83 #include <vm/vm_kern.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_extern.h>
88 #include <machine/cpu.h>
89 #include <machine/intr_machdep.h>
90 #include <machine/md_var.h>
91 #include <machine/pcb.h>
93 #include <machine/smp.h>
95 #include <machine/tss.h>
97 extern void trap(struct trapframe *frame);
98 extern void syscall(struct trapframe *frame);
100 static int trap_pfault(struct trapframe *, int);
101 static void trap_fatal(struct trapframe *, vm_offset_t);
102 void dblfault_handler(void);
104 #define MAX_TRAP_MSG 30
105 static char *trap_msg[] = {
107 "privileged instruction fault", /* 1 T_PRIVINFLT */
109 "breakpoint instruction fault", /* 3 T_BPTFLT */
112 "arithmetic trap", /* 6 T_ARITHTRAP */
115 "general protection fault", /* 9 T_PROTFLT */
116 "trace trap", /* 10 T_TRCTRAP */
118 "page fault", /* 12 T_PAGEFLT */
120 "alignment fault", /* 14 T_ALIGNFLT */
124 "integer divide fault", /* 18 T_DIVIDE */
125 "non-maskable interrupt trap", /* 19 T_NMI */
126 "overflow trap", /* 20 T_OFLOW */
127 "FPU bounds check fault", /* 21 T_BOUND */
128 "FPU device not available", /* 22 T_DNA */
129 "double fault", /* 23 T_DOUBLEFLT */
130 "FPU operand fetch fault", /* 24 T_FPOPFLT */
131 "invalid TSS fault", /* 25 T_TSSFLT */
132 "segment not present fault", /* 26 T_SEGNPFLT */
133 "stack fault", /* 27 T_STKFLT */
134 "machine check trap", /* 28 T_MCHK */
135 "SIMD floating-point exception", /* 29 T_XMMFLT */
136 "reserved (unknown) fault", /* 30 T_RESERVED */
140 static int kdb_on_nmi = 1;
141 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RW,
142 &kdb_on_nmi, 0, "Go to KDB on NMI");
144 static int panic_on_nmi = 1;
145 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
146 &panic_on_nmi, 0, "Panic on NMI");
148 extern char *syscallnames[];
151 * Exception, fault, and trap interface to the FreeBSD kernel.
152 * This common code is called from assembly language IDT gate entry
153 * routines that prepare a suitable stack frame, and restore this
154 * frame after the exception has been processed.
158 trap(struct trapframe *frame)
160 struct thread *td = curthread;
161 struct proc *p = td->td_proc;
162 int i = 0, ucode = 0, code;
167 PCPU_INC(cnt.v_trap);
168 type = frame->tf_trapno;
172 /* Handler for NMI IPIs used for stopping CPUs. */
174 if (ipi_nmi_handler() == 0)
177 #endif /* STOP_NMI */
189 * CPU PMCs interrupt using an NMI. If the PMC module is
190 * active, pass the 'rip' value to the PMC module's interrupt
191 * handler. A return value of '1' from the handler means that
192 * the NMI was handled by it and we can return immediately.
194 if (type == T_NMI && pmc_intr &&
195 (*pmc_intr)(PCPU_GET(cpuid), (uintptr_t) frame->tf_rip,
196 TRAPF_USERMODE(frame)))
200 if ((frame->tf_rflags & PSL_I) == 0) {
202 * Buggy application or kernel code has disabled
203 * interrupts and then trapped. Enabling interrupts
204 * now is wrong, but it is better than running with
205 * interrupts disabled until they are accidentally
208 if (ISPL(frame->tf_cs) == SEL_UPL)
210 "pid %ld (%s): trap %d with interrupts disabled\n",
211 (long)curproc->p_pid, curproc->p_comm, type);
212 else if (type != T_NMI && type != T_BPTFLT &&
215 * XXX not quite right, since this may be for a
216 * multiple fault in user mode.
218 printf("kernel trap %d with interrupts disabled\n",
221 * We shouldn't enable interrupts while holding a
222 * spin lock or servicing an NMI.
224 if (type != T_NMI && td->td_md.md_spinlock_count == 0)
229 code = frame->tf_err;
230 if (type == T_PAGEFLT) {
232 * If we get a page fault while in a critical section, then
233 * it is most likely a fatal kernel page fault. The kernel
234 * is already going to panic trying to get a sleep lock to
235 * do the VM lookup, so just consider it a fatal trap so the
236 * kernel can print out a useful trap message and even get
239 * If we get a page fault while holding a non-sleepable
240 * lock, then it is most likely a fatal kernel page fault.
241 * If WITNESS is enabled, then it's going to whine about
242 * bogus LORs with various VM locks, so just skip to the
243 * fatal trap handling directly.
245 if (td->td_critnest != 0 ||
246 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
247 "Kernel page fault") != 0)
248 trap_fatal(frame, frame->tf_addr);
251 if (ISPL(frame->tf_cs) == SEL_UPL) {
255 td->td_frame = frame;
256 addr = frame->tf_rip;
257 if (td->td_ucred != p->p_ucred)
258 cred_update_thread(td);
261 case T_PRIVINFLT: /* privileged instruction fault */
266 case T_BPTFLT: /* bpt instruction fault */
267 case T_TRCTRAP: /* trace trap */
269 frame->tf_rflags &= ~PSL_T;
271 ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
274 case T_ARITHTRAP: /* arithmetic trap */
281 case T_PROTFLT: /* general protection fault */
285 case T_STKFLT: /* stack fault */
286 case T_SEGNPFLT: /* segment not present fault */
290 case T_TSSFLT: /* invalid TSS fault */
294 case T_DOUBLEFLT: /* double fault */
300 case T_PAGEFLT: /* page fault */
301 addr = frame->tf_addr;
303 if (td->td_pflags & TDP_SA)
304 thread_user_enter(td);
306 i = trap_pfault(frame, TRUE);
315 i = SIGSEGV; /* XXX hack */
320 case T_DIVIDE: /* integer divide fault */
327 /* machine/parity/power fail/"kitchen sink" faults */
329 if (isa_nmi(code) == 0) {
332 * NMI can be hooked up to a pushbutton
336 printf ("NMI ... going to debugger\n");
337 kdb_trap(type, 0, frame);
341 } else if (panic_on_nmi)
342 panic("NMI indicates hardware failure");
346 case T_OFLOW: /* integer overflow fault */
351 case T_BOUND: /* bounds check fault */
357 /* transparent fault (due to context switch "late") */
360 printf("pid %d killed due to lack of floating point\n",
366 case T_FPOPFLT: /* FPU operand fetch fault */
371 case T_XMMFLT: /* SIMD floating-point exception */
379 KASSERT(cold || td->td_ucred != NULL,
380 ("kernel trap doesn't have ucred"));
382 case T_PAGEFLT: /* page fault */
383 (void) trap_pfault(frame, FALSE);
388 * The kernel is apparently using fpu for copying.
389 * XXX this should be fatal unless the kernel has
390 * registered such use.
393 printf("fpudna in kernel mode!\n");
398 case T_STKFLT: /* stack fault */
401 case T_PROTFLT: /* general protection fault */
402 case T_SEGNPFLT: /* segment not present fault */
403 if (td->td_intr_nesting_level != 0)
407 * Invalid segment selectors and out of bounds
408 * %rip's and %rsp's can be set up in user mode.
409 * This causes a fault in kernel mode when the
410 * kernel tries to return to user mode. We want
411 * to get this fault so that we can fix the
412 * problem here and not have to check all the
413 * selectors and pointers when the user changes
416 if (frame->tf_rip == (long)doreti_iret) {
417 frame->tf_rip = (long)doreti_iret_fault;
420 if (PCPU_GET(curpcb)->pcb_onfault != NULL) {
422 (long)PCPU_GET(curpcb)->pcb_onfault;
429 * PSL_NT can be set in user mode and isn't cleared
430 * automatically when the kernel is entered. This
431 * causes a TSS fault when the kernel attempts to
432 * `iret' because the TSS link is uninitialized. We
433 * want to get this fault so that we can fix the
434 * problem here and not every time the kernel is
437 if (frame->tf_rflags & PSL_NT) {
438 frame->tf_rflags &= ~PSL_NT;
443 case T_TRCTRAP: /* trace trap */
445 * Ignore debug register trace traps due to
446 * accesses in the user's address space, which
447 * can happen under several conditions such as
448 * if a user sets a watchpoint on a buffer and
449 * then passes that buffer to a system call.
450 * We still want to get TRCTRAPS for addresses
451 * in kernel space because that is useful when
452 * debugging the kernel.
454 if (user_dbreg_trap()) {
456 * Reset breakpoint bits because the
459 /* XXX check upper bits here */
460 load_dr6(rdr6() & 0xfffffff0);
464 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
468 * If KDB is enabled, let it handle the debugger trap.
469 * Otherwise, debugger traps "can't happen".
472 if (kdb_trap(type, 0, frame))
480 /* machine/parity/power fail/"kitchen sink" faults */
481 if (isa_nmi(code) == 0) {
484 * NMI can be hooked up to a pushbutton
488 printf ("NMI ... going to debugger\n");
489 kdb_trap(type, 0, frame);
493 } else if (panic_on_nmi == 0)
499 trap_fatal(frame, 0);
503 /* Translate fault for emulators (e.g. Linux) */
504 if (*p->p_sysent->sv_transtrap)
505 i = (*p->p_sysent->sv_transtrap)(i, type);
507 ksiginfo_init_trap(&ksi);
509 ksi.ksi_code = ucode;
510 ksi.ksi_trapno = type;
511 ksi.ksi_addr = (void *)addr;
512 trapsignal(td, &ksi);
515 if (type <= MAX_TRAP_MSG) {
516 uprintf("fatal process exception: %s",
518 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
519 uprintf(", fault VA = 0x%lx", frame->tf_addr);
526 mtx_assert(&Giant, MA_NOTOWNED);
533 trap_pfault(frame, usermode)
534 struct trapframe *frame;
538 struct vmspace *vm = NULL;
542 struct thread *td = curthread;
543 struct proc *p = td->td_proc;
544 vm_offset_t eva = frame->tf_addr;
546 va = trunc_page(eva);
547 if (va >= KERNBASE) {
549 * Don't allow user-mode faults in kernel address space.
557 * This is a fault on non-kernel virtual memory.
558 * vm is initialized above to NULL. If curproc is NULL
559 * or curproc->p_vmspace is NULL the fault is fatal.
571 * PGEX_I is defined only if the execute disable bit capability is
572 * supported and enabled.
574 if (frame->tf_err & PGEX_W)
575 ftype = VM_PROT_WRITE;
576 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
577 ftype = VM_PROT_EXECUTE;
579 ftype = VM_PROT_READ;
581 if (map != kernel_map) {
583 * Keep swapout from messing with us during this
590 /* Fault in the user page: */
591 rv = vm_fault(map, va, ftype,
592 (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
600 * Don't have to worry about process locking or stacks in the
603 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
605 if (rv == KERN_SUCCESS)
609 if (td->td_intr_nesting_level == 0 &&
610 PCPU_GET(curpcb)->pcb_onfault != NULL) {
611 frame->tf_rip = (long)PCPU_GET(curpcb)->pcb_onfault;
614 trap_fatal(frame, eva);
618 return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
622 trap_fatal(frame, eva)
623 struct trapframe *frame;
629 struct soft_segment_descriptor softseg;
632 code = frame->tf_err;
633 type = frame->tf_trapno;
634 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
636 if (type <= MAX_TRAP_MSG)
637 msg = trap_msg[type];
640 printf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
641 ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
643 /* two separate prints in case of a trap on an unmapped page */
644 printf("cpuid = %d; ", PCPU_GET(cpuid));
645 printf("apic id = %02x\n", PCPU_GET(apic_id));
647 if (type == T_PAGEFLT) {
648 printf("fault virtual address = 0x%lx\n", eva);
649 printf("fault code = %s %s %s, %s\n",
650 code & PGEX_U ? "user" : "supervisor",
651 code & PGEX_W ? "write" : "read",
652 code & PGEX_I ? "instruction" : "data",
653 code & PGEX_P ? "protection violation" : "page not present");
655 printf("instruction pointer = 0x%lx:0x%lx\n",
656 frame->tf_cs & 0xffff, frame->tf_rip);
657 if (ISPL(frame->tf_cs) == SEL_UPL) {
658 ss = frame->tf_ss & 0xffff;
661 ss = GSEL(GDATA_SEL, SEL_KPL);
662 esp = (long)&frame->tf_rsp;
664 printf("stack pointer = 0x%x:0x%lx\n", ss, esp);
665 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
666 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
667 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
668 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
669 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
671 printf("processor eflags = ");
672 if (frame->tf_rflags & PSL_T)
673 printf("trace trap, ");
674 if (frame->tf_rflags & PSL_I)
675 printf("interrupt enabled, ");
676 if (frame->tf_rflags & PSL_NT)
677 printf("nested task, ");
678 if (frame->tf_rflags & PSL_RF)
680 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
681 printf("current process = ");
684 (u_long)curproc->p_pid, curproc->p_comm ?
685 curproc->p_comm : "");
691 if (debugger_on_panic || kdb_active)
692 if (kdb_trap(type, 0, frame))
695 printf("trap number = %d\n", type);
696 if (type <= MAX_TRAP_MSG)
697 panic("%s", trap_msg[type]);
699 panic("unknown/reserved trap");
703 * Double fault handler. Called when a fault occurs while writing
704 * a frame for a trap/exception onto the stack. This usually occurs
705 * when the stack overflows (such is the case with infinite recursion,
711 printf("\nFatal double fault\n");
713 /* two separate prints in case of a trap on an unmapped page */
714 printf("cpuid = %d; ", PCPU_GET(cpuid));
715 printf("apic id = %02x\n", PCPU_GET(apic_id));
717 panic("double fault");
721 * syscall - system call request C handler
723 * A system call is essentially treated as a trap.
726 syscall(struct trapframe *frame)
729 struct sysent *callp;
730 struct thread *td = curthread;
731 struct proc *p = td->td_proc;
732 register_t orig_tf_rflags;
741 PCPU_INC(cnt.v_syscall);
744 if (ISPL(frame->tf_cs) != SEL_UPL) {
753 td->td_frame = frame;
754 if (td->td_ucred != p->p_ucred)
755 cred_update_thread(td);
757 if (p->p_flag & P_SA)
758 thread_user_enter(td);
760 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
761 code = frame->tf_rax;
762 orig_tf_rflags = frame->tf_rflags;
764 if (p->p_sysent->sv_prepsyscall) {
766 * The prep code is MP aware.
768 (*p->p_sysent->sv_prepsyscall)(frame, (int *)args, &code, ¶ms);
770 if (code == SYS_syscall || code == SYS___syscall) {
771 code = frame->tf_rdi;
777 if (p->p_sysent->sv_mask)
778 code &= p->p_sysent->sv_mask;
780 if (code >= p->p_sysent->sv_size)
781 callp = &p->p_sysent->sv_table[0];
783 callp = &p->p_sysent->sv_table[code];
785 narg = callp->sy_narg;
788 * copyin and the ktrsyscall()/ktrsysret() code is MP-aware
790 KASSERT(narg <= sizeof(args) / sizeof(args[0]),
791 ("Too many syscall arguments!"));
793 argp = &frame->tf_rdi;
795 bcopy(argp, args, sizeof(args[0]) * regcnt);
797 KASSERT(params != NULL, ("copyin args with no params!"));
798 error = copyin(params, &args[regcnt],
799 (narg - regcnt) * sizeof(args[0]));
804 if (KTRPOINT(td, KTR_SYSCALL))
805 ktrsyscall(code, narg, argp);
808 CTR4(KTR_SYSC, "syscall enter thread %p pid %d proc %s code %d", td,
809 td->td_proc->p_pid, td->td_proc->p_comm, code);
814 td->td_retval[0] = 0;
815 td->td_retval[1] = frame->tf_rdx;
817 STOPEVENT(p, S_SCE, narg);
819 PTRACESTOP_SC(p, td, S_PT_SCE);
821 AUDIT_SYSCALL_ENTER(code, td);
822 error = (*callp->sy_call)(td, argp);
823 AUDIT_SYSCALL_EXIT(error, td);
828 frame->tf_rax = td->td_retval[0];
829 frame->tf_rdx = td->td_retval[1];
830 frame->tf_rflags &= ~PSL_C;
835 * Reconstruct pc, we know that 'syscall' is 2 bytes.
836 * We have to do a full context restore so that %r10
837 * (which was holding the value of %rcx) is restored for
838 * the next iteration.
840 frame->tf_rip -= frame->tf_err;
841 frame->tf_r10 = frame->tf_rcx;
842 td->td_pcb->pcb_flags |= PCB_FULLCTX;
849 if (p->p_sysent->sv_errsize) {
850 if (error >= p->p_sysent->sv_errsize)
851 error = -1; /* XXX */
853 error = p->p_sysent->sv_errtbl[error];
855 frame->tf_rax = error;
856 frame->tf_rflags |= PSL_C;
863 if (orig_tf_rflags & PSL_T) {
864 frame->tf_rflags &= ~PSL_T;
865 ksiginfo_init_trap(&ksi);
866 ksi.ksi_signo = SIGTRAP;
867 ksi.ksi_code = TRAP_TRACE;
868 ksi.ksi_addr = (void *)frame->tf_rip;
869 trapsignal(td, &ksi);
873 * Check for misbehavior.
875 WITNESS_WARN(WARN_PANIC, NULL, "System call %s returning",
876 (code >= 0 && code < SYS_MAXSYSCALL) ? syscallnames[code] : "???");
877 KASSERT(td->td_critnest == 0,
878 ("System call %s returning in a critical section",
879 (code >= 0 && code < SYS_MAXSYSCALL) ? syscallnames[code] : "???"));
880 KASSERT(td->td_locks == 0,
881 ("System call %s returning with %d locks held",
882 (code >= 0 && code < SYS_MAXSYSCALL) ? syscallnames[code] : "???",
886 * Handle reschedule and other end-of-syscall issues
890 CTR4(KTR_SYSC, "syscall exit thread %p pid %d proc %s code %d", td,
891 td->td_proc->p_pid, td->td_proc->p_comm, code);
894 if (KTRPOINT(td, KTR_SYSRET))
895 ktrsysret(code, error, td->td_retval[0]);
899 * This works because errno is findable through the
900 * register set. If we ever support an emulation where this
901 * is not the case, this code will need to be revisited.
903 STOPEVENT(p, S_SCX, code);
905 PTRACESTOP_SC(p, td, S_PT_SCX);