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
38 * $FreeBSD: src/sys/i386/i386/trap.c,v 1.147.2.11 2003/02/27 19:09:59 luoqi Exp $
42 * x86_64 Trap and System call handling
48 #include "opt_ktrace.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
53 #include <sys/pioctl.h>
54 #include <sys/kernel.h>
55 #include <sys/resourcevar.h>
56 #include <sys/signalvar.h>
57 #include <sys/signal2.h>
58 #include <sys/syscall.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
62 #include <sys/vmmeter.h>
63 #include <sys/malloc.h>
65 #include <sys/ktrace.h>
68 #include <sys/vkernel.h>
69 #include <sys/sysproto.h>
70 #include <sys/sysunion.h>
71 #include <sys/vmspace.h>
74 #include <vm/vm_param.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_extern.h>
82 #include <machine/cpu.h>
83 #include <machine/md_var.h>
84 #include <machine/pcb.h>
85 #include <machine/smp.h>
86 #include <machine/tss.h>
87 #include <machine/globaldata.h>
91 #include <sys/msgport2.h>
92 #include <sys/thread2.h>
93 #include <sys/mplock2.h>
95 #define MAKEMPSAFE(have_mplock) \
96 if (have_mplock == 0) { \
101 int (*pmath_emulate) (struct trapframe *);
103 extern int trapwrite (unsigned addr);
105 static int trap_pfault (struct trapframe *, int, vm_offset_t);
106 static void trap_fatal (struct trapframe *, int, vm_offset_t);
107 void dblfault_handler (void);
108 extern int vmm_enabled;
111 extern inthand_t IDTVEC(syscall);
114 #define MAX_TRAP_MSG 30
115 static char *trap_msg[] = {
117 "privileged instruction fault", /* 1 T_PRIVINFLT */
119 "breakpoint instruction fault", /* 3 T_BPTFLT */
122 "arithmetic trap", /* 6 T_ARITHTRAP */
123 "system forced exception", /* 7 T_ASTFLT */
125 "general protection fault", /* 9 T_PROTFLT */
126 "trace trap", /* 10 T_TRCTRAP */
128 "page fault", /* 12 T_PAGEFLT */
130 "alignment fault", /* 14 T_ALIGNFLT */
134 "integer divide fault", /* 18 T_DIVIDE */
135 "non-maskable interrupt trap", /* 19 T_NMI */
136 "overflow trap", /* 20 T_OFLOW */
137 "FPU bounds check fault", /* 21 T_BOUND */
138 "FPU device not available", /* 22 T_DNA */
139 "double fault", /* 23 T_DOUBLEFLT */
140 "FPU operand fetch fault", /* 24 T_FPOPFLT */
141 "invalid TSS fault", /* 25 T_TSSFLT */
142 "segment not present fault", /* 26 T_SEGNPFLT */
143 "stack fault", /* 27 T_STKFLT */
144 "machine check trap", /* 28 T_MCHK */
145 "SIMD floating-point exception", /* 29 T_XMMFLT */
146 "reserved (unknown) fault", /* 30 T_RESERVED */
150 static int ddb_on_nmi = 1;
151 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
152 &ddb_on_nmi, 0, "Go to DDB on NMI");
154 static int panic_on_nmi = 1;
155 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
156 &panic_on_nmi, 0, "Panic on NMI");
157 static int fast_release;
158 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
159 &fast_release, 0, "Passive Release was optimal");
160 static int slow_release;
161 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
162 &slow_release, 0, "Passive Release was nonoptimal");
165 * Passively intercepts the thread switch function to increase
166 * the thread priority from a user priority to a kernel priority, reducing
167 * syscall and trap overhead for the case where no switch occurs.
169 * Synchronizes td_ucred with p_ucred. This is used by system calls,
170 * signal handling, faults, AST traps, and anything else that enters the
171 * kernel from userland and provides the kernel with a stable read-only
172 * copy of the process ucred.
175 userenter(struct thread *curtd, struct proc *curp)
180 curtd->td_release = lwkt_passive_release;
182 if (curtd->td_ucred != curp->p_ucred) {
183 ncred = crhold(curp->p_ucred);
184 ocred = curtd->td_ucred;
185 curtd->td_ucred = ncred;
192 * Handle signals, profiling, and other AST's and/or tasks that
193 * must be completed before we can return to or try to return to userland.
195 * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
196 * arithmatic on the delta calculation so the absolute tick values are
197 * truncated to an integer.
200 userret(struct lwp *lp, struct trapframe *frame, int sticks)
202 struct proc *p = lp->lwp_proc;
206 * Charge system time if profiling. Note: times are in microseconds.
207 * This may do a copyout and block, so do it first even though it
208 * means some system time will be charged as user time.
210 if (p->p_flags & P_PROFIL) {
211 addupc_task(p, frame->tf_rip,
212 (u_int)((int)lp->lwp_thread->td_sticks - sticks));
217 * Specific on-return-to-usermode checks (LWP_MP_WEXIT,
218 * LWP_MP_VNLRU, etc).
220 if (lp->lwp_mpflags & LWP_MP_URETMASK)
224 * Block here if we are in a stopped state.
226 if (p->p_stat == SSTOP || p->p_stat == SCORE) {
227 lwkt_gettoken(&p->p_token);
229 lwkt_reltoken(&p->p_token);
234 * Post any pending upcalls. If running a virtual kernel be sure
235 * to restore the virtual kernel's vmspace before posting the upcall.
237 if (p->p_flags & (P_SIGVTALRM | P_SIGPROF)) {
238 lwkt_gettoken(&p->p_token);
239 if (p->p_flags & P_SIGVTALRM) {
240 p->p_flags &= ~P_SIGVTALRM;
241 ksignal(p, SIGVTALRM);
243 if (p->p_flags & P_SIGPROF) {
244 p->p_flags &= ~P_SIGPROF;
247 lwkt_reltoken(&p->p_token);
252 * Post any pending signals
254 * WARNING! postsig() can exit and not return.
256 if ((sig = CURSIG_TRACE(lp)) != 0) {
257 lwkt_gettoken(&p->p_token);
259 lwkt_reltoken(&p->p_token);
264 * block here if we are swapped out, but still process signals
265 * (such as SIGKILL). proc0 (the swapin scheduler) is already
266 * aware of our situation, we do not have to wake it up.
268 if (p->p_flags & P_SWAPPEDOUT) {
269 lwkt_gettoken(&p->p_token);
271 p->p_flags |= P_SWAPWAIT;
273 if (p->p_flags & P_SWAPWAIT)
274 tsleep(p, PCATCH, "SWOUT", 0);
275 p->p_flags &= ~P_SWAPWAIT;
277 lwkt_reltoken(&p->p_token);
282 * In a multi-threaded program it is possible for a thread to change
283 * signal state during a system call which temporarily changes the
284 * signal mask. In this case postsig() might not be run and we
285 * have to restore the mask ourselves.
287 if (lp->lwp_flags & LWP_OLDMASK) {
288 lp->lwp_flags &= ~LWP_OLDMASK;
289 lp->lwp_sigmask = lp->lwp_oldsigmask;
295 * Cleanup from userenter and any passive release that might have occured.
296 * We must reclaim the current-process designation before we can return
297 * to usermode. We also handle both LWKT and USER reschedule requests.
300 userexit(struct lwp *lp)
302 struct thread *td = lp->lwp_thread;
303 /* globaldata_t gd = td->td_gd; */
306 * Handle stop requests at kernel priority. Any requests queued
307 * after this loop will generate another AST.
309 while (lp->lwp_proc->p_stat == SSTOP ||
310 lp->lwp_proc->p_stat == SCORE) {
311 lwkt_gettoken(&lp->lwp_proc->p_token);
313 lwkt_reltoken(&lp->lwp_proc->p_token);
317 * Reduce our priority in preparation for a return to userland. If
318 * our passive release function was still in place, our priority was
319 * never raised and does not need to be reduced.
321 lwkt_passive_recover(td);
324 * Become the current user scheduled process if we aren't already,
325 * and deal with reschedule requests and other factors.
327 lp->lwp_proc->p_usched->acquire_curproc(lp);
328 /* WARNING: we may have migrated cpu's */
329 /* gd = td->td_gd; */
332 #if !defined(KTR_KERNENTRY)
333 #define KTR_KERNENTRY KTR_ALL
335 KTR_INFO_MASTER(kernentry);
336 KTR_INFO(KTR_KERNENTRY, kernentry, trap, 0,
337 "TRAP(pid %hd, tid %hd, trapno %ld, eva %lu)",
338 pid_t pid, lwpid_t tid, register_t trapno, vm_offset_t eva);
339 KTR_INFO(KTR_KERNENTRY, kernentry, trap_ret, 0, "TRAP_RET(pid %hd, tid %hd)",
340 pid_t pid, lwpid_t tid);
341 KTR_INFO(KTR_KERNENTRY, kernentry, syscall, 0, "SYSC(pid %hd, tid %hd, nr %ld)",
342 pid_t pid, lwpid_t tid, register_t trapno);
343 KTR_INFO(KTR_KERNENTRY, kernentry, syscall_ret, 0, "SYSRET(pid %hd, tid %hd, err %d)",
344 pid_t pid, lwpid_t tid, int err);
345 KTR_INFO(KTR_KERNENTRY, kernentry, fork_ret, 0, "FORKRET(pid %hd, tid %hd)",
346 pid_t pid, lwpid_t tid);
349 * Exception, fault, and trap interface to the kernel.
350 * This common code is called from assembly language IDT gate entry
351 * routines that prepare a suitable stack frame, and restore this
352 * frame after the exception has been processed.
354 * This function is also called from doreti in an interlock to handle ASTs.
355 * For example: hardwareint->INTROUTINE->(set ast)->doreti->trap
357 * NOTE! We have to retrieve the fault address prior to obtaining the
358 * MP lock because get_mplock() may switch out. YYY cr2 really ought
359 * to be retrieved by the assembly code, not here.
361 * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
362 * if an attempt is made to switch from a fast interrupt or IPI. This is
363 * necessary to properly take fatal kernel traps on SMP machines if
364 * get_mplock() has to block.
368 user_trap(struct trapframe *frame)
370 struct globaldata *gd = mycpu;
371 struct thread *td = gd->gd_curthread;
372 struct lwp *lp = td->td_lwp;
375 int i = 0, ucode = 0, type, code;
378 int crit_count = td->td_critcount;
379 lwkt_tokref_t curstop = td->td_toks_stop;
385 if (frame->tf_trapno == T_PAGEFLT)
386 eva = frame->tf_addr;
390 kprintf("USER_TRAP AT %08lx xflags %ld trapno %ld eva %08lx\n",
391 frame->tf_rip, frame->tf_xflags, frame->tf_trapno, eva);
395 * Everything coming from user mode runs through user_trap,
396 * including system calls.
398 if (frame->tf_trapno == T_FAST_SYSCALL) {
403 KTR_LOG(kernentry_trap, lp->lwp_proc->p_pid, lp->lwp_tid,
404 frame->tf_trapno, eva);
408 eva = (frame->tf_trapno == T_PAGEFLT ? rcr2() : 0);
409 ++gd->gd_trap_nesting_level;
410 MAKEMPSAFE(have_mplock);
411 trap_fatal(frame, TRUE, eva);
412 --gd->gd_trap_nesting_level;
417 type = frame->tf_trapno;
418 code = frame->tf_err;
422 sticks = (int)td->td_sticks;
423 lp->lwp_md.md_regs = frame;
426 case T_PRIVINFLT: /* privileged instruction fault */
431 case T_BPTFLT: /* bpt instruction fault */
432 case T_TRCTRAP: /* trace trap */
433 frame->tf_rflags &= ~PSL_T;
435 ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
438 case T_ARITHTRAP: /* arithmetic trap */
443 case T_ASTFLT: /* Allow process switch */
444 mycpu->gd_cnt.v_soft++;
445 if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
446 atomic_clear_int(&mycpu->gd_reqflags, RQF_AST_OWEUPC);
447 addupc_task(p, p->p_prof.pr_addr, p->p_prof.pr_ticks);
452 * The following two traps can happen in
453 * vm86 mode, and, if so, we want to handle
456 case T_PROTFLT: /* general protection fault */
457 case T_STKFLT: /* stack fault */
459 if (frame->tf_eflags & PSL_VM) {
460 i = vm86_emulate((struct vm86frame *)frame);
468 case T_SEGNPFLT: /* segment not present fault */
469 case T_TSSFLT: /* invalid TSS fault */
470 case T_DOUBLEFLT: /* double fault */
473 ucode = code + BUS_SEGM_FAULT ;
476 case T_PAGEFLT: /* page fault */
477 i = trap_pfault(frame, TRUE, eva);
478 if (i == -1 || i == 0)
490 case T_DIVIDE: /* integer divide fault */
497 MAKEMPSAFE(have_mplock);
498 /* machine/parity/power fail/"kitchen sink" faults */
499 if (isa_nmi(code) == 0) {
502 * NMI can be hooked up to a pushbutton
506 kprintf ("NMI ... going to debugger\n");
507 kdb_trap(type, 0, frame);
511 } else if (panic_on_nmi)
512 panic("NMI indicates hardware failure");
514 #endif /* NISA > 0 */
516 case T_OFLOW: /* integer overflow fault */
521 case T_BOUND: /* bounds check fault */
528 * Virtual kernel intercept - pass the DNA exception
529 * to the (emulated) virtual kernel if it asked to handle
530 * it. This occurs when the virtual kernel is holding
531 * onto the FP context for a different emulated
532 * process then the one currently running.
534 * We must still call npxdna() since we may have
535 * saved FP state that the (emulated) virtual kernel
536 * needs to hand over to a different emulated process.
538 if (lp->lwp_vkernel && lp->lwp_vkernel->ve &&
539 (td->td_pcb->pcb_flags & FP_VIRTFP)
546 * The kernel may have switched out the FP unit's
547 * state, causing the user process to take a fault
548 * when it tries to use the FP unit. Restore the
553 if (!pmath_emulate) {
555 ucode = FPE_FPU_NP_TRAP;
558 i = (*pmath_emulate)(frame);
560 if (!(frame->tf_rflags & PSL_T))
562 frame->tf_rflags &= ~PSL_T;
565 /* else ucode = emulator_only_knows() XXX */
568 case T_FPOPFLT: /* FPU operand fetch fault */
573 case T_XMMFLT: /* SIMD floating-point exception */
580 * Virtual kernel intercept - if the fault is directly related to a
581 * VM context managed by a virtual kernel then let the virtual kernel
584 if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
585 vkernel_trap(lp, frame);
590 * Translate fault for emulators (e.g. Linux)
592 if (*p->p_sysent->sv_transtrap)
593 i = (*p->p_sysent->sv_transtrap)(i, type);
595 MAKEMPSAFE(have_mplock);
596 trapsignal(lp, i, ucode);
599 if (type <= MAX_TRAP_MSG) {
600 uprintf("fatal process exception: %s",
602 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
603 uprintf(", fault VA = 0x%lx", (u_long)eva);
609 userret(lp, frame, sticks);
614 KTR_LOG(kernentry_trap_ret, lp->lwp_proc->p_pid, lp->lwp_tid);
616 KASSERT(crit_count == td->td_critcount,
617 ("trap: critical section count mismatch! %d/%d",
618 crit_count, td->td_pri));
619 KASSERT(curstop == td->td_toks_stop,
620 ("trap: extra tokens held after trap! %ld/%ld",
621 curstop - &td->td_toks_base,
622 td->td_toks_stop - &td->td_toks_base));
627 kern_trap(struct trapframe *frame)
629 struct globaldata *gd = mycpu;
630 struct thread *td = gd->gd_curthread;
633 int i = 0, ucode = 0, type, code;
636 int crit_count = td->td_critcount;
637 lwkt_tokref_t curstop = td->td_toks_stop;
644 if (frame->tf_trapno == T_PAGEFLT)
645 eva = frame->tf_addr;
651 ++gd->gd_trap_nesting_level;
652 MAKEMPSAFE(have_mplock);
653 trap_fatal(frame, FALSE, eva);
654 --gd->gd_trap_nesting_level;
659 type = frame->tf_trapno;
660 code = frame->tf_err;
668 case T_PAGEFLT: /* page fault */
669 trap_pfault(frame, FALSE, eva);
674 * The kernel may be using npx for copying or other
677 panic("kernel NPX should not happen");
682 case T_PROTFLT: /* general protection fault */
683 case T_SEGNPFLT: /* segment not present fault */
685 * Invalid segment selectors and out of bounds
686 * %eip's and %esp's can be set up in user mode.
687 * This causes a fault in kernel mode when the
688 * kernel tries to return to user mode. We want
689 * to get this fault so that we can fix the
690 * problem here and not have to check all the
691 * selectors and pointers when the user changes
694 if (mycpu->gd_intr_nesting_level == 0) {
695 if (td->td_pcb->pcb_onfault) {
697 (register_t)td->td_pcb->pcb_onfault;
705 * PSL_NT can be set in user mode and isn't cleared
706 * automatically when the kernel is entered. This
707 * causes a TSS fault when the kernel attempts to
708 * `iret' because the TSS link is uninitialized. We
709 * want to get this fault so that we can fix the
710 * problem here and not every time the kernel is
713 if (frame->tf_rflags & PSL_NT) {
714 frame->tf_rflags &= ~PSL_NT;
719 case T_TRCTRAP: /* trace trap */
721 if (frame->tf_eip == (int)IDTVEC(syscall)) {
723 * We've just entered system mode via the
724 * syscall lcall. Continue single stepping
725 * silently until the syscall handler has
730 if (frame->tf_eip == (int)IDTVEC(syscall) + 1) {
732 * The syscall handler has now saved the
733 * flags. Stop single stepping it.
735 frame->tf_eflags &= ~PSL_T;
741 * Ignore debug register trace traps due to
742 * accesses in the user's address space, which
743 * can happen under several conditions such as
744 * if a user sets a watchpoint on a buffer and
745 * then passes that buffer to a system call.
746 * We still want to get TRCTRAPS for addresses
747 * in kernel space because that is useful when
748 * debugging the kernel.
750 if (user_dbreg_trap()) {
752 * Reset breakpoint bits because the
755 load_dr6(rdr6() & 0xfffffff0);
760 * Fall through (TRCTRAP kernel mode, kernel address)
764 * If DDB is enabled, let it handle the debugger trap.
765 * Otherwise, debugger traps "can't happen".
768 MAKEMPSAFE(have_mplock);
769 if (kdb_trap (type, 0, frame))
774 MAKEMPSAFE(have_mplock);
775 trap_fatal(frame, FALSE, eva);
778 MAKEMPSAFE(have_mplock);
779 trap_fatal(frame, FALSE, eva);
784 * Ignore this trap generated from a spurious SIGTRAP.
786 * single stepping in / syscalls leads to spurious / SIGTRAP
789 * Haiku (c) 2007 Simon 'corecode' Schubert
795 * Translate fault for emulators (e.g. Linux)
797 if (*p->p_sysent->sv_transtrap)
798 i = (*p->p_sysent->sv_transtrap)(i, type);
800 MAKEMPSAFE(have_mplock);
801 trapsignal(lp, i, ucode);
804 if (type <= MAX_TRAP_MSG) {
805 uprintf("fatal process exception: %s",
807 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
808 uprintf(", fault VA = 0x%lx", (u_long)eva);
818 KASSERT(crit_count == td->td_critcount,
819 ("trap: critical section count mismatch! %d/%d",
820 crit_count, td->td_pri));
821 KASSERT(curstop == td->td_toks_stop,
822 ("trap: extra tokens held after trap! %ld/%ld",
823 curstop - &td->td_toks_base,
824 td->td_toks_stop - &td->td_toks_base));
829 trap_pfault(struct trapframe *frame, int usermode, vm_offset_t eva)
832 struct vmspace *vm = NULL;
836 thread_t td = curthread;
837 struct lwp *lp = td->td_lwp;
840 va = trunc_page(eva);
841 if (usermode == FALSE) {
843 * This is a fault on kernel virtual memory.
848 * This is a fault on non-kernel virtual memory.
849 * vm is initialized above to NULL. If curproc is NULL
850 * or curproc->p_vmspace is NULL the fault is fatal.
853 vm = lp->lwp_vmspace;
861 if (frame->tf_err & PGEX_W)
862 ftype = VM_PROT_READ | VM_PROT_WRITE;
864 ftype = VM_PROT_READ;
866 if (map != &kernel_map) {
868 * Keep swapout from messing with us during this
874 * Grow the stack if necessary
876 /* grow_stack returns false only if va falls into
877 * a growable stack region and the stack growth
878 * fails. It returns true if va was not within
879 * a growable stack region, or if the stack
882 if (!grow_stack (lp->lwp_proc, va)) {
890 fault_flags |= VM_FAULT_BURST;
891 if (ftype & VM_PROT_WRITE)
892 fault_flags |= VM_FAULT_DIRTY;
894 fault_flags |= VM_FAULT_NORMAL;
895 rv = vm_fault(map, va, ftype, fault_flags);
900 * Don't have to worry about process locking or stacks in the kernel.
902 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
905 if (rv == KERN_SUCCESS)
909 if (td->td_gd->gd_intr_nesting_level == 0 &&
910 td->td_pcb->pcb_onfault) {
911 frame->tf_rip = (register_t)td->td_pcb->pcb_onfault;
914 trap_fatal(frame, usermode, eva);
919 * NOTE: on x86_64 we have a tf_addr field in the trapframe, no
920 * kludge is needed to pass the fault address to signal handlers.
922 struct proc *p = td->td_proc;
923 kprintf("seg-fault accessing address %p rip=%p pid=%d p_comm=%s\n",
924 (void *)va, (void *)frame->tf_rip, p->p_pid, p->p_comm);
925 /* Debugger("seg-fault"); */
927 return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
931 trap_fatal(struct trapframe *frame, int usermode, vm_offset_t eva)
936 code = frame->tf_xflags;
937 type = frame->tf_trapno;
939 if (type <= MAX_TRAP_MSG) {
940 kprintf("\n\nFatal trap %d: %s while in %s mode\n",
941 type, trap_msg[type],
942 (usermode ? "user" : "kernel"));
944 /* two separate prints in case of a trap on an unmapped page */
945 kprintf("cpuid = %d\n", mycpu->gd_cpuid);
946 if (type == T_PAGEFLT) {
947 kprintf("fault virtual address = %p\n", (void *)eva);
948 kprintf("fault code = %s %s, %s\n",
949 usermode ? "user" : "supervisor",
950 code & PGEX_W ? "write" : "read",
951 code & PGEX_P ? "protection violation" : "page not present");
953 kprintf("instruction pointer = 0x%lx:0x%lx\n",
954 frame->tf_cs & 0xffff, frame->tf_rip);
956 ss = frame->tf_ss & 0xffff;
959 ss = GSEL(GDATA_SEL, SEL_KPL);
960 rsp = (long)&frame->tf_rsp;
962 kprintf("stack pointer = 0x%x:0x%lx\n", ss, rsp);
963 kprintf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
964 kprintf("processor eflags = ");
965 if (frame->tf_rflags & PSL_T)
966 kprintf("trace trap, ");
967 if (frame->tf_rflags & PSL_I)
968 kprintf("interrupt enabled, ");
969 if (frame->tf_rflags & PSL_NT)
970 kprintf("nested task, ");
971 if (frame->tf_rflags & PSL_RF)
974 if (frame->tf_eflags & PSL_VM)
977 kprintf("IOPL = %jd\n", (intmax_t)((frame->tf_rflags & PSL_IOPL) >> 12));
978 kprintf("current process = ");
980 kprintf("%lu (%s)\n",
981 (u_long)curproc->p_pid, curproc->p_comm ?
982 curproc->p_comm : "");
986 kprintf("current thread = pri %d ", curthread->td_pri);
987 if (curthread->td_critcount)
992 * we probably SHOULD have stopped the other CPUs before now!
993 * another CPU COULD have been touching cpl at this moment...
995 kprintf(" <- SMP: XXX");
1003 if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1006 kprintf("trap number = %d\n", type);
1007 if (type <= MAX_TRAP_MSG)
1008 panic("%s", trap_msg[type]);
1010 panic("unknown/reserved trap");
1014 * Double fault handler. Called when a fault occurs while writing
1015 * a frame for a trap/exception onto the stack. This usually occurs
1016 * when the stack overflows (such is the case with infinite recursion,
1019 * XXX Note that the current PTD gets replaced by IdlePTD when the
1020 * task switch occurs. This means that the stack that was active at
1021 * the time of the double fault is not available at <kstack> unless
1022 * the machine was idle when the double fault occurred. The downside
1023 * of this is that "trace <ebp>" in ddb won't work.
1026 dblfault_handler(void)
1029 struct mdglobaldata *gd = mdcpu;
1032 kprintf("\nFatal double fault:\n");
1034 kprintf("rip = 0x%lx\n", gd->gd_common_tss.tss_rip);
1035 kprintf("rsp = 0x%lx\n", gd->gd_common_tss.tss_rsp);
1036 kprintf("rbp = 0x%lx\n", gd->gd_common_tss.tss_rbp);
1038 /* two separate prints in case of a trap on an unmapped page */
1039 kprintf("cpuid = %d\n", mycpu->gd_cpuid);
1040 panic("double fault");
1044 * Compensate for 386 brain damage (missing URKR).
1045 * This is a little simpler than the pagefault handler in trap() because
1046 * it the page tables have already been faulted in and high addresses
1047 * are thrown out early for other reasons.
1050 trapwrite(unsigned addr)
1057 va = trunc_page((vm_offset_t)addr);
1059 * XXX - MAX is END. Changed > to >= for temp. fix.
1061 if (va >= VM_MAX_USER_ADDRESS)
1064 lp = curthread->td_lwp;
1065 vm = lp->lwp_vmspace;
1067 PHOLD(lp->lwp_proc);
1069 if (!grow_stack (lp->lwp_proc, va)) {
1070 PRELE(lp->lwp_proc);
1075 * fault the data page
1077 rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1079 PRELE(lp->lwp_proc);
1081 if (rv != KERN_SUCCESS)
1088 * syscall2 - MP aware system call request C handler
1090 * A system call is essentially treated as a trap except that the
1091 * MP lock is not held on entry or return. We are responsible for
1092 * obtaining the MP lock if necessary and for handling ASTs
1093 * (e.g. a task switch) prior to return.
1095 * In general, only simple access and manipulation of curproc and
1096 * the current stack is allowed without having to hold MP lock.
1098 * MPSAFE - note that large sections of this routine are run without
1102 syscall2(struct trapframe *frame)
1104 struct thread *td = curthread;
1105 struct proc *p = td->td_proc;
1106 struct lwp *lp = td->td_lwp;
1108 struct sysent *callp;
1109 register_t orig_tf_rflags;
1114 int crit_count = td->td_critcount;
1115 lwkt_tokref_t curstop = td->td_toks_stop;
1117 int have_mplock = 0;
1121 union sysunion args;
1122 register_t *argsdst;
1124 mycpu->gd_cnt.v_syscall++;
1126 KTR_LOG(kernentry_syscall, lp->lwp_proc->p_pid, lp->lwp_tid,
1129 userenter(td, p); /* lazy raise our priority */
1136 sticks = (int)td->td_sticks;
1137 orig_tf_rflags = frame->tf_rflags;
1140 * Virtual kernel intercept - if a VM context managed by a virtual
1141 * kernel issues a system call the virtual kernel handles it, not us.
1142 * Restore the virtual kernel context and return from its system
1143 * call. The current frame is copied out to the virtual kernel.
1145 if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
1146 vkernel_trap(lp, frame);
1147 error = EJUSTRETURN;
1152 * Get the system call parameters and account for time
1154 lp->lwp_md.md_regs = frame;
1155 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1156 code = frame->tf_rax;
1158 if (p->p_sysent->sv_prepsyscall) {
1159 (*p->p_sysent->sv_prepsyscall)(
1160 frame, (int *)(&args.nosys.sysmsg + 1),
1163 if (code == SYS_syscall || code == SYS___syscall) {
1164 code = frame->tf_rdi;
1170 if (p->p_sysent->sv_mask)
1171 code &= p->p_sysent->sv_mask;
1173 if (code >= p->p_sysent->sv_size)
1174 callp = &p->p_sysent->sv_table[0];
1176 callp = &p->p_sysent->sv_table[code];
1178 narg = callp->sy_narg & SYF_ARGMASK;
1181 * On x86_64 we get up to six arguments in registers. The rest are
1182 * on the stack. The first six members of 'struct trapframe' happen
1183 * to be the registers used to pass arguments, in exactly the right
1186 argp = &frame->tf_rdi;
1188 argsdst = (register_t *)(&args.nosys.sysmsg + 1);
1190 * JG can we overflow the space pointed to by 'argsdst'
1191 * either with 'bcopy' or with 'copyin'?
1193 bcopy(argp, argsdst, sizeof(register_t) * regcnt);
1195 * copyin is MP aware, but the tracing code is not
1197 if (narg > regcnt) {
1198 KASSERT(params != NULL, ("copyin args with no params!"));
1199 error = copyin(params, &argsdst[regcnt],
1200 (narg - regcnt) * sizeof(register_t));
1203 if (KTRPOINT(td, KTR_SYSCALL)) {
1204 MAKEMPSAFE(have_mplock);
1206 ktrsyscall(lp, code, narg,
1207 (void *)(&args.nosys.sysmsg + 1));
1215 if (KTRPOINT(td, KTR_SYSCALL)) {
1216 MAKEMPSAFE(have_mplock);
1217 ktrsyscall(lp, code, narg, (void *)(&args.nosys.sysmsg + 1));
1222 * Default return value is 0 (will be copied to %rax). Double-value
1223 * returns use %rax and %rdx. %rdx is left unchanged for system
1224 * calls which return only one result.
1226 args.sysmsg_fds[0] = 0;
1227 args.sysmsg_fds[1] = frame->tf_rdx;
1230 * The syscall might manipulate the trap frame. If it does it
1231 * will probably return EJUSTRETURN.
1233 args.sysmsg_frame = frame;
1235 STOPEVENT(p, S_SCE, narg); /* MP aware */
1238 * NOTE: All system calls run MPSAFE now. The system call itself
1239 * is responsible for getting the MP lock.
1241 error = (*callp->sy_call)(&args);
1244 kprintf("system call %d returned %d\n", code, error);
1249 * MP SAFE (we may or may not have the MP lock at this point)
1254 * Reinitialize proc pointer `p' as it may be different
1255 * if this is a child returning from fork syscall.
1258 lp = curthread->td_lwp;
1259 frame->tf_rax = args.sysmsg_fds[0];
1260 frame->tf_rdx = args.sysmsg_fds[1];
1261 frame->tf_rflags &= ~PSL_C;
1265 * Reconstruct pc, we know that 'syscall' is 2 bytes.
1266 * We have to do a full context restore so that %r10
1267 * (which was holding the value of %rcx) is restored for
1268 * the next iteration.
1270 frame->tf_rip -= frame->tf_err;
1271 frame->tf_r10 = frame->tf_rcx;
1276 panic("Unexpected EASYNC return value (for now)");
1279 if (p->p_sysent->sv_errsize) {
1280 if (error >= p->p_sysent->sv_errsize)
1281 error = -1; /* XXX */
1283 error = p->p_sysent->sv_errtbl[error];
1285 frame->tf_rax = error;
1286 frame->tf_rflags |= PSL_C;
1291 * Traced syscall. trapsignal() is not MP aware.
1293 if (orig_tf_rflags & PSL_T) {
1294 MAKEMPSAFE(have_mplock);
1295 frame->tf_rflags &= ~PSL_T;
1296 trapsignal(lp, SIGTRAP, 0);
1300 * Handle reschedule and other end-of-syscall issues
1302 userret(lp, frame, sticks);
1305 if (KTRPOINT(td, KTR_SYSRET)) {
1306 MAKEMPSAFE(have_mplock);
1307 ktrsysret(lp, code, error, args.sysmsg_result);
1312 * This works because errno is findable through the
1313 * register set. If we ever support an emulation where this
1314 * is not the case, this code will need to be revisited.
1316 STOPEVENT(p, S_SCX, code);
1320 * Release the MP lock if we had to get it
1324 KTR_LOG(kernentry_syscall_ret, lp->lwp_proc->p_pid, lp->lwp_tid, error);
1326 KASSERT(&td->td_toks_base == td->td_toks_stop,
1327 ("syscall: critical section count mismatch! %d/%d",
1328 crit_count, td->td_pri));
1329 KASSERT(curstop == td->td_toks_stop,
1330 ("syscall: extra tokens held after trap! %ld",
1331 td->td_toks_stop - &td->td_toks_base));
1336 * NOTE: mplock not held at any point
1339 fork_return(struct lwp *lp, struct trapframe *frame)
1341 frame->tf_rax = 0; /* Child returns zero */
1342 frame->tf_rflags &= ~PSL_C; /* success */
1345 generic_lwp_return(lp, frame);
1346 KTR_LOG(kernentry_fork_ret, lp->lwp_proc->p_pid, lp->lwp_tid);
1350 * Simplified back end of syscall(), used when returning from fork()
1351 * directly into user mode.
1353 * This code will return back into the fork trampoline code which then
1356 * NOTE: The mplock is not held at any point.
1359 generic_lwp_return(struct lwp *lp, struct trapframe *frame)
1361 struct proc *p = lp->lwp_proc;
1364 * Check for exit-race. If one lwp exits the process concurrent with
1365 * another lwp creating a new thread, the two operations may cross
1366 * each other resulting in the newly-created lwp not receiving a
1369 if (p->p_flags & P_WEXIT) {
1370 kprintf("pid %d (%s) exit race handled\n",
1371 p->p_pid, p->p_comm);
1372 lwpsignal(p, lp, SIGKILL);
1376 * Newly forked processes are given a kernel priority. We have to
1377 * adjust the priority to a normal user priority and fake entry
1378 * into the kernel (call userenter()) to install a passive release
1379 * function just in case userret() decides to stop the process. This
1380 * can occur when ^Z races a fork. If we do not install the passive
1381 * release function the current process designation will not be
1382 * released when the thread goes to sleep.
1384 lwkt_setpri_self(TDPRI_USER_NORM);
1385 userenter(lp->lwp_thread, p);
1386 userret(lp, frame, 0);
1388 if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1389 ktrsysret(lp, SYS_fork, 0, 0);
1391 lp->lwp_flags |= LWP_PASSIVE_ACQ;
1393 lp->lwp_flags &= ~LWP_PASSIVE_ACQ;
1397 * doreti has turned into this. The frame is directly on the stack. We
1398 * pull everything else we need (fpu and tls context) from the current
1401 * Note on fpu interactions: In a virtual kernel, the fpu context for
1402 * an emulated user mode process is not shared with the virtual kernel's
1403 * fpu context, so we only have to 'stack' fpu contexts within the virtual
1404 * kernel itself, and not even then since the signal() contexts that we care
1405 * about save and restore the FPU state (I think anyhow).
1407 * vmspace_ctl() returns an error only if it had problems instaling the
1408 * context we supplied or problems copying data to/from our VM space.
1411 go_user(struct intrframe *frame)
1413 struct trapframe *tf = (void *)&frame->if_rdi;
1418 * Interrupts may be disabled on entry, make sure all signals
1419 * can be received before beginning our loop.
1424 * Switch to the current simulated user process, then call
1425 * user_trap() when we break out of it (usually due to a signal).
1430 * Always make the FPU state correct. This should generally
1431 * be faster because the cost of taking a #NM fault through
1432 * the vkernel to the real kernel is astronomical.
1434 tf->tf_xflags &= ~PGEX_FPFAULT;
1435 if (mdcpu->gd_npxthread != curthread) {
1436 if (mdcpu->gd_npxthread)
1437 npxsave(mdcpu->gd_npxthread->td_savefpu);
1442 * Tell the real kernel whether it is ok to use the FP
1443 * unit or not, allowing us to take a T_DNA exception
1444 * if the context tries to use the FP.
1446 if (mdcpu->gd_npxthread == curthread) {
1447 tf->tf_xflags &= ~PGEX_FPFAULT;
1449 tf->tf_xflags |= PGEX_FPFAULT;
1454 * Run emulated user process context. This call interlocks
1455 * with new mailbox signals.
1457 * Set PGEX_U unconditionally, indicating a user frame (the
1458 * bit is normally set only by T_PAGEFLT).
1461 id = (void *)vtophys(curproc->p_vmspace->vm_pmap.pm_pml4);
1463 id = &curproc->p_vmspace->vm_pmap;
1465 r = vmspace_ctl(id, VMSPACE_CTL_RUN, tf, &curthread->td_savevext);
1467 frame->if_xflags |= PGEX_U;
1469 kprintf("GO USER %d trap %ld EVA %08lx RIP %08lx RSP %08lx XFLAGS %02lx/%02lx\n",
1470 r, tf->tf_trapno, tf->tf_addr, tf->tf_rip, tf->tf_rsp,
1471 tf->tf_xflags, frame->if_xflags);
1475 panic("vmspace_ctl failed error %d", errno);
1477 if (tf->tf_trapno) {
1481 if (mycpu->gd_reqflags & RQF_AST_MASK) {
1482 tf->tf_trapno = T_ASTFLT;
1490 * If PGEX_FPFAULT is set then set FP_VIRTFP in the PCB to force a T_DNA
1491 * fault (which is then passed back to the virtual kernel) if an attempt is
1492 * made to use the FP unit.
1494 * XXX this is a fairly big hack.
1497 set_vkernel_fp(struct trapframe *frame)
1499 struct thread *td = curthread;
1501 if (frame->tf_xflags & PGEX_FPFAULT) {
1502 td->td_pcb->pcb_flags |= FP_VIRTFP;
1503 if (mdcpu->gd_npxthread == td)
1506 td->td_pcb->pcb_flags &= ~FP_VIRTFP;
1511 * Called from vkernel_trap() to fixup the vkernel's syscall
1512 * frame for vmspace_ctl() return.
1515 cpu_vkernel_trap(struct trapframe *frame, int error)
1517 frame->tf_rax = error;
1519 frame->tf_rflags |= PSL_C;
1521 frame->tf_rflags &= ~PSL_C;