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>
80 #include <vm/vm_param.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>
87 #include <machine/cpu.h>
88 #include <machine/intr_machdep.h>
89 #include <machine/md_var.h>
90 #include <machine/pcb.h>
92 #include <machine/smp.h>
94 #include <machine/tss.h>
96 extern void trap(struct trapframe frame);
97 extern void syscall(struct trapframe frame);
99 static int trap_pfault(struct trapframe *, int);
100 static void trap_fatal(struct trapframe *, vm_offset_t);
101 void dblfault_handler(void);
103 #define MAX_TRAP_MSG 30
104 static char *trap_msg[] = {
106 "privileged instruction fault", /* 1 T_PRIVINFLT */
108 "breakpoint instruction fault", /* 3 T_BPTFLT */
111 "arithmetic trap", /* 6 T_ARITHTRAP */
114 "general protection fault", /* 9 T_PROTFLT */
115 "trace trap", /* 10 T_TRCTRAP */
117 "page fault", /* 12 T_PAGEFLT */
119 "alignment fault", /* 14 T_ALIGNFLT */
123 "integer divide fault", /* 18 T_DIVIDE */
124 "non-maskable interrupt trap", /* 19 T_NMI */
125 "overflow trap", /* 20 T_OFLOW */
126 "FPU bounds check fault", /* 21 T_BOUND */
127 "FPU device not available", /* 22 T_DNA */
128 "double fault", /* 23 T_DOUBLEFLT */
129 "FPU operand fetch fault", /* 24 T_FPOPFLT */
130 "invalid TSS fault", /* 25 T_TSSFLT */
131 "segment not present fault", /* 26 T_SEGNPFLT */
132 "stack fault", /* 27 T_STKFLT */
133 "machine check trap", /* 28 T_MCHK */
134 "SIMD floating-point exception", /* 29 T_XMMFLT */
135 "reserved (unknown) fault", /* 30 T_RESERVED */
139 static int kdb_on_nmi = 1;
140 SYSCTL_INT(_machdep, OID_AUTO, kdb_on_nmi, CTLFLAG_RW,
141 &kdb_on_nmi, 0, "Go to KDB on NMI");
143 static int panic_on_nmi = 1;
144 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
145 &panic_on_nmi, 0, "Panic on NMI");
148 extern char *syscallnames[];
152 * Exception, fault, and trap interface to the FreeBSD kernel.
153 * This common code is called from assembly language IDT gate entry
154 * routines that prepare a suitable stack frame, and restore this
155 * frame after the exception has been processed.
160 struct trapframe frame;
162 struct thread *td = curthread;
163 struct proc *p = td->td_proc;
165 int i = 0, ucode = 0, type, code;
169 PCPU_LAZY_INC(cnt.v_trap);
170 type = frame.tf_trapno;
174 /* Handler for NMI IPIs used for stopping CPUs. */
176 if (ipi_nmi_handler() == 0)
179 #endif /* STOP_NMI */
191 * CPU PMCs interrupt using an NMI. If the PMC module is
192 * active, pass the 'rip' value to the PMC module's interrupt
193 * handler. A return value of '1' from the handler means that
194 * the NMI was handled by it and we can return immediately.
196 if (type == T_NMI && pmc_intr &&
197 (*pmc_intr)(PCPU_GET(cpuid), (uintptr_t) frame.tf_rip,
198 TRAPF_USERMODE(&frame)))
202 if ((frame.tf_rflags & PSL_I) == 0) {
204 * Buggy application or kernel code has disabled
205 * interrupts and then trapped. Enabling interrupts
206 * now is wrong, but it is better than running with
207 * interrupts disabled until they are accidentally
210 if (ISPL(frame.tf_cs) == SEL_UPL)
212 "pid %ld (%s): trap %d with interrupts disabled\n",
213 (long)curproc->p_pid, curproc->p_comm, type);
214 else if (type != T_NMI && type != T_BPTFLT &&
217 * XXX not quite right, since this may be for a
218 * multiple fault in user mode.
220 printf("kernel trap %d with interrupts disabled\n",
223 * We shouldn't enable interrupts while in a critical
224 * section or servicing an NMI.
226 if (type != T_NMI && td->td_critnest == 0)
232 if (type == T_PAGEFLT) {
234 * If we get a page fault while in a critical section, then
235 * it is most likely a fatal kernel page fault. The kernel
236 * is already going to panic trying to get a sleep lock to
237 * do the VM lookup, so just consider it a fatal trap so the
238 * kernel can print out a useful trap message and even get
241 if (td->td_critnest != 0)
242 trap_fatal(&frame, frame.tf_addr);
245 if (ISPL(frame.tf_cs) == SEL_UPL) {
248 sticks = td->td_sticks;
249 td->td_frame = &frame;
251 if (td->td_ucred != p->p_ucred)
252 cred_update_thread(td);
255 case T_PRIVINFLT: /* privileged instruction fault */
260 case T_BPTFLT: /* bpt instruction fault */
261 case T_TRCTRAP: /* trace trap */
263 frame.tf_rflags &= ~PSL_T;
265 ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
268 case T_ARITHTRAP: /* arithmetic trap */
275 case T_PROTFLT: /* general protection fault */
279 case T_STKFLT: /* stack fault */
280 case T_SEGNPFLT: /* segment not present fault */
284 case T_TSSFLT: /* invalid TSS fault */
288 case T_DOUBLEFLT: /* double fault */
294 case T_PAGEFLT: /* page fault */
295 addr = frame.tf_addr;
296 if (td->td_pflags & TDP_SA)
297 thread_user_enter(td);
298 i = trap_pfault(&frame, TRUE);
307 i = SIGSEGV; /* XXX hack */
312 case T_DIVIDE: /* integer divide fault */
319 /* machine/parity/power fail/"kitchen sink" faults */
321 if (isa_nmi(code) == 0) {
324 * NMI can be hooked up to a pushbutton
328 printf ("NMI ... going to debugger\n");
329 kdb_trap(type, 0, &frame);
333 } else if (panic_on_nmi)
334 panic("NMI indicates hardware failure");
338 case T_OFLOW: /* integer overflow fault */
343 case T_BOUND: /* bounds check fault */
349 /* transparent fault (due to context switch "late") */
352 printf("pid %d killed due to lack of floating point\n",
358 case T_FPOPFLT: /* FPU operand fetch fault */
363 case T_XMMFLT: /* SIMD floating-point exception */
371 KASSERT(cold || td->td_ucred != NULL,
372 ("kernel trap doesn't have ucred"));
374 case T_PAGEFLT: /* page fault */
375 (void) trap_pfault(&frame, FALSE);
380 * The kernel is apparently using fpu for copying.
381 * XXX this should be fatal unless the kernel has
382 * registered such use.
385 printf("fpudna in kernel mode!\n");
390 case T_STKFLT: /* stack fault */
393 case T_PROTFLT: /* general protection fault */
394 case T_SEGNPFLT: /* segment not present fault */
395 if (td->td_intr_nesting_level != 0)
399 * Invalid segment selectors and out of bounds
400 * %rip's and %rsp's can be set up in user mode.
401 * This causes a fault in kernel mode when the
402 * kernel tries to return to user mode. We want
403 * to get this fault so that we can fix the
404 * problem here and not have to check all the
405 * selectors and pointers when the user changes
408 if (frame.tf_rip == (long)doreti_iret) {
409 frame.tf_rip = (long)doreti_iret_fault;
412 if (PCPU_GET(curpcb)->pcb_onfault != NULL) {
414 (long)PCPU_GET(curpcb)->pcb_onfault;
421 * PSL_NT can be set in user mode and isn't cleared
422 * automatically when the kernel is entered. This
423 * causes a TSS fault when the kernel attempts to
424 * `iret' because the TSS link is uninitialized. We
425 * want to get this fault so that we can fix the
426 * problem here and not every time the kernel is
429 if (frame.tf_rflags & PSL_NT) {
430 frame.tf_rflags &= ~PSL_NT;
435 case T_TRCTRAP: /* trace trap */
437 * Ignore debug register trace traps due to
438 * accesses in the user's address space, which
439 * can happen under several conditions such as
440 * if a user sets a watchpoint on a buffer and
441 * then passes that buffer to a system call.
442 * We still want to get TRCTRAPS for addresses
443 * in kernel space because that is useful when
444 * debugging the kernel.
446 if (user_dbreg_trap()) {
448 * Reset breakpoint bits because the
451 /* XXX check upper bits here */
452 load_dr6(rdr6() & 0xfffffff0);
456 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
460 * If KDB is enabled, let it handle the debugger trap.
461 * Otherwise, debugger traps "can't happen".
465 if (kdb_trap(type, 0, &frame))
473 /* machine/parity/power fail/"kitchen sink" faults */
474 if (isa_nmi(code) == 0) {
477 * NMI can be hooked up to a pushbutton
481 printf ("NMI ... going to debugger\n");
482 kdb_trap(type, 0, &frame);
486 } else if (panic_on_nmi == 0)
492 trap_fatal(&frame, 0);
496 /* Translate fault for emulators (e.g. Linux) */
497 if (*p->p_sysent->sv_transtrap)
498 i = (*p->p_sysent->sv_transtrap)(i, type);
500 ksiginfo_init_trap(&ksi);
502 ksi.ksi_code = ucode;
503 ksi.ksi_trapno = type;
504 ksi.ksi_addr = (void *)addr;
505 trapsignal(td, &ksi);
508 if (type <= MAX_TRAP_MSG) {
509 uprintf("fatal process exception: %s",
511 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
512 uprintf(", fault VA = 0x%lx", frame.tf_addr);
518 userret(td, &frame, sticks);
519 mtx_assert(&Giant, MA_NOTOWNED);
526 trap_pfault(frame, usermode)
527 struct trapframe *frame;
531 struct vmspace *vm = NULL;
535 struct thread *td = curthread;
536 struct proc *p = td->td_proc;
537 vm_offset_t eva = frame->tf_addr;
539 va = trunc_page(eva);
540 if (va >= KERNBASE) {
542 * Don't allow user-mode faults in kernel address space.
550 * This is a fault on non-kernel virtual memory.
551 * vm is initialized above to NULL. If curproc is NULL
552 * or curproc->p_vmspace is NULL the fault is fatal.
563 if (frame->tf_err & PGEX_W)
564 ftype = VM_PROT_WRITE;
566 ftype = VM_PROT_READ;
568 if (map != kernel_map) {
570 * Keep swapout from messing with us during this
577 /* Fault in the user page: */
578 rv = vm_fault(map, va, ftype,
579 (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
587 * Don't have to worry about process locking or stacks in the
590 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
592 if (rv == KERN_SUCCESS)
596 if (td->td_intr_nesting_level == 0 &&
597 PCPU_GET(curpcb)->pcb_onfault != NULL) {
598 frame->tf_rip = (long)PCPU_GET(curpcb)->pcb_onfault;
601 trap_fatal(frame, eva);
605 return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
609 trap_fatal(frame, eva)
610 struct trapframe *frame;
615 struct soft_segment_descriptor softseg;
618 code = frame->tf_err;
619 type = frame->tf_trapno;
620 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
622 if (type <= MAX_TRAP_MSG)
623 msg = trap_msg[type];
626 printf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
627 ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
629 /* two separate prints in case of a trap on an unmapped page */
630 printf("cpuid = %d; ", PCPU_GET(cpuid));
631 printf("apic id = %02x\n", PCPU_GET(apic_id));
633 if (type == T_PAGEFLT) {
634 printf("fault virtual address = 0x%lx\n", eva);
635 printf("fault code = %s %s, %s\n",
636 code & PGEX_U ? "user" : "supervisor",
637 code & PGEX_W ? "write" : "read",
638 code & PGEX_P ? "protection violation" : "page not present");
640 printf("instruction pointer = 0x%lx:0x%lx\n",
641 frame->tf_cs & 0xffff, frame->tf_rip);
642 if (ISPL(frame->tf_cs) == SEL_UPL) {
643 ss = frame->tf_ss & 0xffff;
646 ss = GSEL(GDATA_SEL, SEL_KPL);
647 esp = (long)&frame->tf_rsp;
649 printf("stack pointer = 0x%x:0x%lx\n", ss, esp);
650 printf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
651 printf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
652 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
653 printf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
654 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
656 printf("processor eflags = ");
657 if (frame->tf_rflags & PSL_T)
658 printf("trace trap, ");
659 if (frame->tf_rflags & PSL_I)
660 printf("interrupt enabled, ");
661 if (frame->tf_rflags & PSL_NT)
662 printf("nested task, ");
663 if (frame->tf_rflags & PSL_RF)
665 printf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
666 printf("current process = ");
669 (u_long)curproc->p_pid, curproc->p_comm ?
670 curproc->p_comm : "");
676 if (debugger_on_panic || kdb_active) {
678 rflags = intr_disable();
679 if (kdb_trap(type, 0, frame)) {
680 intr_restore(rflags);
683 intr_restore(rflags);
686 printf("trap number = %d\n", type);
687 if (type <= MAX_TRAP_MSG)
688 panic("%s", trap_msg[type]);
690 panic("unknown/reserved trap");
694 * Double fault handler. Called when a fault occurs while writing
695 * a frame for a trap/exception onto the stack. This usually occurs
696 * when the stack overflows (such is the case with infinite recursion,
702 printf("\nFatal double fault\n");
704 /* two separate prints in case of a trap on an unmapped page */
705 printf("cpuid = %d; ", PCPU_GET(cpuid));
706 printf("apic id = %02x\n", PCPU_GET(apic_id));
708 panic("double fault");
712 * syscall - system call request C handler
714 * A system call is essentially treated as a trap.
718 struct trapframe frame;
721 struct sysent *callp;
722 struct thread *td = curthread;
723 struct proc *p = td->td_proc;
724 register_t orig_tf_rflags;
735 * note: PCPU_LAZY_INC() can only be used if we can afford
736 * occassional inaccuracy in the count.
738 PCPU_LAZY_INC(cnt.v_syscall);
741 if (ISPL(frame.tf_cs) != SEL_UPL) {
742 mtx_lock(&Giant); /* try to stabilize the system XXX */
751 sticks = td->td_sticks;
752 td->td_frame = &frame;
753 if (td->td_ucred != p->p_ucred)
754 cred_update_thread(td);
755 if (p->p_flag & P_SA)
756 thread_user_enter(td);
757 params = (caddr_t)frame.tf_rsp + sizeof(register_t);
759 orig_tf_rflags = frame.tf_rflags;
761 if (p->p_sysent->sv_prepsyscall) {
763 * The prep code is MP aware.
765 (*p->p_sysent->sv_prepsyscall)(&frame, (int *)args, &code, ¶ms);
767 if (code == SYS_syscall || code == SYS___syscall) {
774 if (p->p_sysent->sv_mask)
775 code &= p->p_sysent->sv_mask;
777 if (code >= p->p_sysent->sv_size)
778 callp = &p->p_sysent->sv_table[0];
780 callp = &p->p_sysent->sv_table[code];
782 narg = callp->sy_narg & SYF_ARGMASK;
785 * copyin and the ktrsyscall()/ktrsysret() code is MP-aware
787 KASSERT(narg <= sizeof(args) / sizeof(args[0]),
788 ("Too many syscall arguments!"));
790 argp = &frame.tf_rdi;
792 bcopy(argp, args, sizeof(args[0]) * regcnt);
794 KASSERT(params != NULL, ("copyin args with no params!"));
795 error = copyin(params, &args[regcnt],
796 (narg - regcnt) * sizeof(args[0]));
801 if (KTRPOINT(td, KTR_SYSCALL))
802 ktrsyscall(code, narg, argp);
805 CTR4(KTR_SYSC, "syscall enter thread %p pid %d proc %s code %d", td,
806 td->td_proc->p_pid, td->td_proc->p_comm, code);
809 td->td_retval[0] = 0;
810 td->td_retval[1] = frame.tf_rdx;
812 STOPEVENT(p, S_SCE, narg);
814 PTRACESTOP_SC(p, td, S_PT_SCE);
816 if ((callp->sy_narg & SYF_MPSAFE) == 0) {
818 error = (*callp->sy_call)(td, argp);
821 error = (*callp->sy_call)(td, argp);
826 frame.tf_rax = td->td_retval[0];
827 frame.tf_rdx = td->td_retval[1];
828 frame.tf_rflags &= ~PSL_C;
833 * Reconstruct pc, we know that 'syscall' is 2 bytes.
834 * We have to do a full context restore so that %r10
835 * (which was holding the value of %rcx) is restored for
836 * the next iteration.
838 frame.tf_rip -= frame.tf_err;
839 frame.tf_r10 = frame.tf_rcx;
840 td->td_pcb->pcb_flags |= PCB_FULLCTX;
847 if (p->p_sysent->sv_errsize) {
848 if (error >= p->p_sysent->sv_errsize)
849 error = -1; /* XXX */
851 error = p->p_sysent->sv_errtbl[error];
853 frame.tf_rax = error;
854 frame.tf_rflags |= PSL_C;
861 if (orig_tf_rflags & PSL_T) {
862 frame.tf_rflags &= ~PSL_T;
864 ksiginfo_init_trap(&ksi);
865 ksi.ksi_signo = SIGTRAP;
866 ksi.ksi_code = TRAP_TRACE;
867 ksi.ksi_addr = (void *)frame.tf_rip;
868 trapsignal(td, &ksi);
872 * Handle reschedule and other end-of-syscall issues
874 userret(td, &frame, sticks);
876 CTR4(KTR_SYSC, "syscall exit thread %p pid %d proc %s code %d", td,
877 td->td_proc->p_pid, td->td_proc->p_comm, code);
880 if (KTRPOINT(td, KTR_SYSRET))
881 ktrsysret(code, error, td->td_retval[0]);
885 * This works because errno is findable through the
886 * register set. If we ever support an emulation where this
887 * is not the case, this code will need to be revisited.
889 STOPEVENT(p, S_SCX, code);
891 PTRACESTOP_SC(p, td, S_PT_SCX);
893 WITNESS_WARN(WARN_PANIC, NULL, "System call %s returning",
894 (code >= 0 && code < SYS_MAXSYSCALL) ? syscallnames[code] : "???");
895 mtx_assert(&sched_lock, MA_NOTOWNED);
896 mtx_assert(&Giant, MA_NOTOWNED);