2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (C) 1994, David Greenman
5 * Copyright (c) 2008-2018 The DragonFly Project.
6 * Copyright (c) 2008 Jordan Gordeev.
8 * This code is derived from software contributed to Berkeley by
9 * the University of Utah, and William Jolitz.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * from: @(#)trap.c 7.4 (Berkeley) 5/13/91
40 * $FreeBSD: src/sys/i386/i386/trap.c,v 1.147.2.11 2003/02/27 19:09:59 luoqi Exp $
44 * x86_64 Trap and System call handling
50 #include "opt_ktrace.h"
52 #include <machine/frame.h>
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/kernel.h>
56 #include <sys/kerneldump.h>
58 #include <sys/pioctl.h>
59 #include <sys/types.h>
60 #include <sys/signal2.h>
61 #include <sys/syscall.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysent.h>
65 #include <sys/ktrace.h>
68 #include <sys/sysmsg.h>
69 #include <sys/sysproto.h>
70 #include <sys/sysunion.h>
74 #include <vm/vm_extern.h>
75 #include <vm/vm_kern.h>
76 #include <vm/vm_param.h>
77 #include <machine/cpu.h>
78 #include <machine/pcb.h>
79 #include <machine/smp.h>
80 #include <machine/thread.h>
81 #include <machine/clock.h>
82 #include <machine/vmparam.h>
83 #include <machine/md_var.h>
84 #include <machine_base/isa/isa_intr.h>
85 #include <machine_base/apic/lapic.h>
89 #include <sys/thread2.h>
90 #include <sys/spinlock2.h>
93 * These %rip's are used to detect a historical CPU artifact on syscall or
94 * int $3 entry, if not shortcutted in exception.S via
95 * DIRECT_DISALLOW_SS_CPUBUG.
97 extern void Xbpt(void);
98 extern void Xfast_syscall(void);
99 #define IDTVEC(vec) X##vec
101 extern void trap(struct trapframe *frame);
103 static int trap_pfault(struct trapframe *, int);
104 static void trap_fatal(struct trapframe *, vm_offset_t);
105 void dblfault_handler(struct trapframe *frame);
107 #define MAX_TRAP_MSG 30
108 static char *trap_msg[] = {
110 "privileged instruction fault", /* 1 T_PRIVINFLT */
112 "breakpoint instruction fault", /* 3 T_BPTFLT */
115 "arithmetic trap", /* 6 T_ARITHTRAP */
116 "system forced exception", /* 7 T_ASTFLT */
118 "general protection fault", /* 9 T_PROTFLT */
119 "trace trap", /* 10 T_TRCTRAP */
121 "page fault", /* 12 T_PAGEFLT */
123 "alignment fault", /* 14 T_ALIGNFLT */
127 "integer divide fault", /* 18 T_DIVIDE */
128 "non-maskable interrupt trap", /* 19 T_NMI */
129 "overflow trap", /* 20 T_OFLOW */
130 "FPU bounds check fault", /* 21 T_BOUND */
131 "FPU device not available", /* 22 T_DNA */
132 "double fault", /* 23 T_DOUBLEFLT */
133 "FPU operand fetch fault", /* 24 T_FPOPFLT */
134 "invalid TSS fault", /* 25 T_TSSFLT */
135 "segment not present fault", /* 26 T_SEGNPFLT */
136 "stack fault", /* 27 T_STKFLT */
137 "machine check trap", /* 28 T_MCHK */
138 "SIMD floating-point exception", /* 29 T_XMMFLT */
139 "reserved (unknown) fault", /* 30 T_RESERVED */
143 static int ddb_on_nmi = 1;
144 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
145 &ddb_on_nmi, 0, "Go to DDB on NMI");
146 static int ddb_on_seg_fault = 0;
147 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_seg_fault, CTLFLAG_RW,
148 &ddb_on_seg_fault, 0, "Go to DDB on user seg-fault");
149 __read_mostly static int freeze_on_seg_fault = 0;
150 SYSCTL_INT(_machdep, OID_AUTO, freeze_on_seg_fault, CTLFLAG_RW,
151 &freeze_on_seg_fault, 0, "Go to DDB on user seg-fault");
153 static int panic_on_nmi = 1;
154 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
155 &panic_on_nmi, 0, "Panic on NMI");
158 * System call debugging records the worst-case system call
159 * overhead (inclusive of blocking), but may be inaccurate.
161 /*#define SYSCALL_DEBUG*/
169 uint64_t tot[SYS_MAXSYSCALL];
170 uint64_t timings[SYS_MAXSYSCALL][SCWC_MAXT];
173 struct syscallwc SysCallsWorstCase[MAXCPU];
178 * Passively intercepts the thread switch function to increase
179 * the thread priority from a user priority to a kernel priority, reducing
180 * syscall and trap overhead for the case where no switch occurs.
182 * Synchronizes td_ucred with p_ucred. This is used by system calls,
183 * signal handling, faults, AST traps, and anything else that enters the
184 * kernel from userland and provides the kernel with a stable read-only
185 * copy of the process ucred.
187 * To avoid races with another thread updating p_ucred we obtain p_spin.
188 * The other thread doing the update will obtain both p_token and p_spin.
189 * In the case where the cached cred pointer matches, we will already have
190 * the ref and we don't have to do one blessed thing.
193 userenter(struct thread *curtd, struct proc *curp)
198 curtd->td_release = lwkt_passive_release;
200 if (__predict_false(curtd->td_ucred != curp->p_ucred)) {
201 spin_lock(&curp->p_spin);
202 ncred = crhold(curp->p_ucred);
203 spin_unlock(&curp->p_spin);
204 ocred = curtd->td_ucred;
205 curtd->td_ucred = ncred;
212 * Debugging, remove top two user stack pages to catch kernel faults
214 if (__predict_false(freeze_on_seg_fault > 1 && curtd->td_lwp)) {
215 pmap_remove(vmspace_pmap(curtd->td_lwp->lwp_vmspace),
216 0x00007FFFFFFFD000LU,
217 0x0000800000000000LU);
223 * Handle signals, upcalls, profiling, and other AST's and/or tasks that
224 * must be completed before we can return to or try to return to userland.
226 * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
227 * arithmatic on the delta calculation so the absolute tick values are
228 * truncated to an integer.
231 userret(struct lwp *lp, struct trapframe *frame, int sticks)
233 struct proc *p = lp->lwp_proc;
238 * Charge system time if profiling. Note: times are in microseconds.
239 * This may do a copyout and block, so do it first even though it
240 * means some system time will be charged as user time.
242 if (__predict_false(p->p_flags & P_PROFIL)) {
243 addupc_task(p, frame->tf_rip,
244 (u_int)((int)lp->lwp_thread->td_sticks - sticks));
249 * Specific on-return-to-usermode checks (LWP_MP_WEXIT,
250 * LWP_MP_VNLRU, etc).
252 if (lp->lwp_mpflags & LWP_MP_URETMASK)
256 * Block here if we are in a stopped state.
258 if (__predict_false(STOPLWP(p, lp))) {
259 lwkt_gettoken(&p->p_token);
261 lwkt_reltoken(&p->p_token);
264 while (__predict_false(dump_stop_usertds)) {
265 tsleep(&dump_stop_usertds, 0, "dumpstp", 0);
269 * Post any pending upcalls. If running a virtual kernel be sure
270 * to restore the virtual kernel's vmspace before posting the upcall.
272 if (__predict_false(p->p_flags & (P_SIGVTALRM | P_SIGPROF))) {
273 lwkt_gettoken(&p->p_token);
274 if (p->p_flags & P_SIGVTALRM) {
275 p->p_flags &= ~P_SIGVTALRM;
276 ksignal(p, SIGVTALRM);
278 if (p->p_flags & P_SIGPROF) {
279 p->p_flags &= ~P_SIGPROF;
282 lwkt_reltoken(&p->p_token);
287 * Post any pending signals. If running a virtual kernel be sure
288 * to restore the virtual kernel's vmspace before posting the signal.
290 * WARNING! postsig() can exit and not return.
292 if (__predict_false((sig = CURSIG_LCK_TRACE(lp, &ptok)) != 0)) {
298 * block here if we are swapped out, but still process signals
299 * (such as SIGKILL). proc0 (the swapin scheduler) is already
300 * aware of our situation, we do not have to wake it up.
302 if (__predict_false(p->p_flags & P_SWAPPEDOUT)) {
303 lwkt_gettoken(&p->p_token);
304 p->p_flags |= P_SWAPWAIT;
306 if (p->p_flags & P_SWAPWAIT)
307 tsleep(p, PCATCH, "SWOUT", 0);
308 p->p_flags &= ~P_SWAPWAIT;
309 lwkt_reltoken(&p->p_token);
314 * In a multi-threaded program it is possible for a thread to change
315 * signal state during a system call which temporarily changes the
316 * signal mask. In this case postsig() might not be run and we
317 * have to restore the mask ourselves.
319 if (__predict_false(lp->lwp_flags & LWP_OLDMASK)) {
320 lp->lwp_flags &= ~LWP_OLDMASK;
321 lp->lwp_sigmask = lp->lwp_oldsigmask;
327 * Cleanup from userenter and any passive release that might have occured.
328 * We must reclaim the current-process designation before we can return
329 * to usermode. We also handle both LWKT and USER reschedule requests.
332 userexit(struct lwp *lp)
334 struct thread *td = lp->lwp_thread;
335 /* globaldata_t gd = td->td_gd; */
338 * Handle stop requests at kernel priority. Any requests queued
339 * after this loop will generate another AST.
341 while (__predict_false(STOPLWP(lp->lwp_proc, lp))) {
342 lwkt_gettoken(&lp->lwp_proc->p_token);
344 lwkt_reltoken(&lp->lwp_proc->p_token);
348 * Reduce our priority in preparation for a return to userland. If
349 * our passive release function was still in place, our priority was
350 * never raised and does not need to be reduced.
352 lwkt_passive_recover(td);
354 /* WARNING: we may have migrated cpu's */
355 /* gd = td->td_gd; */
358 * Become the current user scheduled process if we aren't already,
359 * and deal with reschedule requests and other factors.
361 * Do a silly hack to avoid RETPOLINE nonsense.
363 if (lp->lwp_proc->p_usched == &usched_dfly)
364 dfly_acquire_curproc(lp);
366 lp->lwp_proc->p_usched->acquire_curproc(lp);
370 * A page fault on a userspace address is classified as SMAP-induced
372 * - SMAP is supported
373 * - kernel mode accessed present data page
374 * - rflags.AC was cleared
377 trap_is_smap(struct trapframe *frame)
379 if ((cpu_stdext_feature & CPUID_STDEXT_SMAP) != 0 &&
380 (frame->tf_err & (PGEX_P | PGEX_U | PGEX_I | PGEX_RSV)) == PGEX_P &&
381 (frame->tf_rflags & PSL_AC) == 0) {
388 #if !defined(KTR_KERNENTRY)
389 #define KTR_KERNENTRY KTR_ALL
391 KTR_INFO_MASTER(kernentry);
392 KTR_INFO(KTR_KERNENTRY, kernentry, trap, 0,
393 "TRAP(pid %d, tid %d, trapno %ld, eva %lu)",
394 pid_t pid, lwpid_t tid, register_t trapno, vm_offset_t eva);
395 KTR_INFO(KTR_KERNENTRY, kernentry, trap_ret, 0, "TRAP_RET(pid %d, tid %d)",
396 pid_t pid, lwpid_t tid);
397 KTR_INFO(KTR_KERNENTRY, kernentry, syscall, 0, "SYSC(pid %d, tid %d, nr %ld)",
398 pid_t pid, lwpid_t tid, register_t trapno);
399 KTR_INFO(KTR_KERNENTRY, kernentry, syscall_ret, 0, "SYSRET(pid %d, tid %d, err %d)",
400 pid_t pid, lwpid_t tid, int err);
401 KTR_INFO(KTR_KERNENTRY, kernentry, fork_ret, 0, "FORKRET(pid %d, tid %d)",
402 pid_t pid, lwpid_t tid);
405 * Exception, fault, and trap interface to the kernel.
406 * This common code is called from assembly language IDT gate entry
407 * routines that prepare a suitable stack frame, and restore this
408 * frame after the exception has been processed.
410 * This function is also called from doreti in an interlock to handle ASTs.
411 * For example: hardwareint->INTROUTINE->(set ast)->doreti->trap
413 * NOTE! We have to retrieve the fault address prior to potentially
414 * blocking, including blocking on any token.
416 * NOTE! NMI and kernel DBG traps remain on their respective pcpu IST
417 * stacks if taken from a kernel RPL. trap() cannot block in this
418 * situation. DDB entry or a direct report-and-return is ok.
420 * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
421 * if an attempt is made to switch from a fast interrupt or IPI.
424 trap(struct trapframe *frame)
426 static struct krate sscpubugrate = { 1 };
427 struct globaldata *gd = mycpu;
428 struct thread *td = gd->gd_curthread;
429 struct lwp *lp = td->td_lwp;
432 int i = 0, ucode = 0, type, code;
434 int crit_count = td->td_critcount;
435 lwkt_tokref_t curstop = td->td_toks_stop;
444 * We need to allow T_DNA faults when the debugger is active since
445 * some dumping paths do large bcopy() which use the floating
446 * point registers for faster copying.
448 if (db_active && frame->tf_trapno != T_DNA) {
449 eva = (frame->tf_trapno == T_PAGEFLT ? frame->tf_addr : 0);
450 ++gd->gd_trap_nesting_level;
451 trap_fatal(frame, eva);
452 --gd->gd_trap_nesting_level;
459 if ((frame->tf_rflags & PSL_I) == 0) {
461 * Buggy application or kernel code has disabled interrupts
462 * and then trapped. Enabling interrupts now is wrong, but
463 * it is better than running with interrupts disabled until
464 * they are accidentally enabled later.
467 type = frame->tf_trapno;
468 if (ISPL(frame->tf_cs) == SEL_UPL) {
469 /* JG curproc can be NULL */
471 "pid %ld (%s): trap %d with interrupts disabled\n",
472 (long)curproc->p_pid, curproc->p_comm, type);
473 } else if ((type == T_STKFLT || type == T_PROTFLT ||
474 type == T_SEGNPFLT) &&
475 frame->tf_rip == (long)doreti_iret) {
477 * iretq fault from kernel mode during return to
480 * This situation is expected, don't complain.
482 } else if (type != T_NMI && type != T_BPTFLT &&
485 * XXX not quite right, since this may be for a
486 * multiple fault in user mode.
488 kprintf("kernel trap %d (%s @ 0x%016jx) with "
489 "interrupts disabled\n",
497 type = frame->tf_trapno;
498 code = frame->tf_err;
500 if (ISPL(frame->tf_cs) == SEL_UPL) {
503 KTR_LOG(kernentry_trap, p->p_pid, lp->lwp_tid,
504 frame->tf_trapno, eva);
508 sticks = (int)td->td_sticks;
509 KASSERT(lp->lwp_md.md_regs == frame,
510 ("Frame mismatch %p %p", lp->lwp_md.md_regs, frame));
513 case T_PRIVINFLT: /* privileged instruction fault */
518 case T_BPTFLT: /* bpt instruction fault */
519 case T_TRCTRAP: /* trace trap */
520 frame->tf_rflags &= ~PSL_T;
522 ucode = (type == T_TRCTRAP ? TRAP_TRACE : TRAP_BRKPT);
525 case T_ARITHTRAP: /* arithmetic trap */
530 case T_ASTFLT: /* Allow process switch */
531 mycpu->gd_cnt.v_soft++;
532 if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
533 atomic_clear_int(&mycpu->gd_reqflags,
535 addupc_task(p, p->p_prof.pr_addr,
540 case T_PROTFLT: /* general protection fault */
544 case T_STKFLT: /* stack fault */
545 case T_SEGNPFLT: /* segment not present fault */
549 case T_TSSFLT: /* invalid TSS fault */
550 case T_DOUBLEFLT: /* double fault */
556 case T_PAGEFLT: /* page fault */
557 i = trap_pfault(frame, TRUE);
559 if (frame->tf_rip == 0) {
560 /* used for kernel debugging only */
561 while (freeze_on_seg_fault)
562 tsleep(p, 0, "freeze", hz * 20);
565 if (i == -1 || i == 0)
575 case T_DIVIDE: /* integer divide fault */
582 /* machine/parity/power fail/"kitchen sink" faults */
583 if (isa_nmi(code) == 0) {
586 * NMI can be hooked up to a pushbutton
590 kprintf ("NMI ... going to debugger\n");
591 kdb_trap(type, 0, frame);
595 } else if (panic_on_nmi)
596 panic("NMI indicates hardware failure");
598 #endif /* NISA > 0 */
600 case T_OFLOW: /* integer overflow fault */
605 case T_BOUND: /* bounds check fault */
612 * Virtual kernel intercept - pass the DNA exception
613 * to the virtual kernel if it asked to handle it.
614 * This occurs when the virtual kernel is holding
615 * onto the FP context for a different emulated
616 * process then the one currently running.
618 * We must still call npxdna() since we may have
619 * saved FP state that the virtual kernel needs
620 * to hand over to a different emulated process.
622 if (lp->lwp_vkernel && lp->lwp_vkernel->ve &&
623 (td->td_pcb->pcb_flags & FP_VIRTFP)
630 * The kernel may have switched out the FP unit's
631 * state, causing the user process to take a fault
632 * when it tries to use the FP unit. Restore the
640 ucode = FPE_FPU_NP_TRAP;
643 case T_FPOPFLT: /* FPU operand fetch fault */
648 case T_XMMFLT: /* SIMD floating-point exception */
657 case T_PAGEFLT: /* page fault */
658 trap_pfault(frame, FALSE);
663 * The kernel is apparently using fpu for copying.
664 * XXX this should be fatal unless the kernel has
665 * registered such use.
673 case T_STKFLT: /* stack fault */
674 case T_PROTFLT: /* general protection fault */
675 case T_SEGNPFLT: /* segment not present fault */
677 * Invalid segment selectors and out of bounds
678 * %rip's and %rsp's can be set up in user mode.
679 * This causes a fault in kernel mode when the
680 * kernel tries to return to user mode. We want
681 * to get this fault so that we can fix the
682 * problem here and not have to check all the
683 * selectors and pointers when the user changes
686 if (mycpu->gd_intr_nesting_level == 0) {
688 * NOTE: in 64-bit mode traps push rsp/ss
689 * even if no ring change occurs.
691 if (td->td_pcb->pcb_onfault &&
692 td->td_pcb->pcb_onfault_sp ==
694 frame->tf_rip = (register_t)
695 td->td_pcb->pcb_onfault;
700 * If the iretq in doreti faults during
701 * return to user, it will be special-cased
702 * in IDTVEC(prot) to get here. We want
703 * to 'return' to doreti_iret_fault in
704 * ipl.s in approximately the same state we
705 * were in at the iretq.
707 if (frame->tf_rip == (long)doreti_iret) {
708 frame->tf_rip = (long)doreti_iret_fault;
716 * PSL_NT can be set in user mode and isn't cleared
717 * automatically when the kernel is entered. This
718 * causes a TSS fault when the kernel attempts to
719 * `iret' because the TSS link is uninitialized. We
720 * want to get this fault so that we can fix the
721 * problem here and not every time the kernel is
724 if (frame->tf_rflags & PSL_NT) {
725 frame->tf_rflags &= ~PSL_NT;
727 /* do we need this? */
728 if (frame->tf_rip == (long)doreti_iret)
729 frame->tf_rip = (long)doreti_iret_fault;
735 case T_TRCTRAP: /* trace trap */
737 * Detect historical CPU artifact on syscall or int $3
738 * entry (if not shortcutted in exception.s via
739 * DIRECT_DISALLOW_SS_CPUBUG).
742 if (frame->tf_rip == (register_t)IDTVEC(fast_syscall)) {
743 krateprintf(&sscpubugrate,
744 "Caught #DB at syscall cpu artifact\n");
747 if (frame->tf_rip == (register_t)IDTVEC(bpt)) {
748 krateprintf(&sscpubugrate,
749 "Caught #DB at int $N cpu artifact\n");
754 * Ignore debug register trace traps due to
755 * accesses in the user's address space, which
756 * can happen under several conditions such as
757 * if a user sets a watchpoint on a buffer and
758 * then passes that buffer to a system call.
759 * We still want to get TRCTRAPS for addresses
760 * in kernel space because that is useful when
761 * debugging the kernel.
763 if (user_dbreg_trap()) {
765 * Reset breakpoint bits because the
768 load_dr6(rdr6() & ~0xf);
772 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
776 * If DDB is enabled, let it handle the debugger trap.
777 * Otherwise, debugger traps "can't happen".
781 if (kdb_trap(type, 0, frame))
788 /* machine/parity/power fail/"kitchen sink" faults */
789 if (isa_nmi(code) == 0) {
792 * NMI can be hooked up to a pushbutton
796 kprintf ("NMI ... going to debugger\n");
797 kdb_trap(type, 0, frame);
801 } else if (panic_on_nmi == 0)
804 #endif /* NISA > 0 */
806 trap_fatal(frame, 0);
811 * Fault from user mode, virtual kernel interecept.
813 * If the fault is directly related to a VM context managed by a
814 * virtual kernel then let the virtual kernel handle it.
816 if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
817 vkernel_trap(lp, frame);
821 /* Translate fault for emulators (e.g. Linux) */
822 if (*p->p_sysent->sv_transtrap)
823 i = (*p->p_sysent->sv_transtrap)(i, type);
826 trapsignal(lp, i, ucode);
829 if (type <= MAX_TRAP_MSG) {
830 uprintf("fatal process exception: %s",
832 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
833 uprintf(", fault VA = 0x%lx", frame->tf_addr);
839 userret(lp, frame, sticks);
842 if (p != NULL && lp != NULL)
843 KTR_LOG(kernentry_trap_ret, p->p_pid, lp->lwp_tid);
845 KASSERT(crit_count == td->td_critcount,
846 ("trap: critical section count mismatch! %d/%d",
847 crit_count, td->td_pri));
848 KASSERT(curstop == td->td_toks_stop,
849 ("trap: extra tokens held after trap! %ld/%ld (%s)",
850 curstop - &td->td_toks_base,
851 td->td_toks_stop - &td->td_toks_base,
852 td->td_toks_stop[-1].tr_tok->t_desc));
857 trap_handle_userenter(struct thread *td)
859 userenter(td, td->td_proc);
863 trap_handle_userexit(struct trapframe *frame, int sticks)
865 struct lwp *lp = curthread->td_lwp;
868 userret(lp, frame, sticks);
874 trap_pfault(struct trapframe *frame, int usermode)
877 struct vmspace *vm = NULL;
882 thread_t td = curthread;
883 struct lwp *lp = td->td_lwp;
886 va = trunc_page(frame->tf_addr);
887 if (va >= VM_MIN_KERNEL_ADDRESS) {
889 * Don't allow user-mode faults in kernel address space.
900 * This is a fault on non-kernel virtual memory.
901 * vm is initialized above to NULL. If curproc is NULL
902 * or curproc->p_vmspace is NULL the fault is fatal.
905 vm = lp->lwp_vmspace;
916 * Debugging, catch kernel faults on the user address
917 * space when not inside on onfault (e.g. copyin/
920 if (td->td_pcb == NULL ||
921 td->td_pcb->pcb_onfault == NULL) {
922 if (freeze_on_seg_fault) {
923 kprintf("trap_pfault: user address "
924 "fault from kernel mode "
926 (long)frame->tf_addr);
927 while (freeze_on_seg_fault) {
928 tsleep(&freeze_on_seg_fault,
936 if (td->td_gd->gd_intr_nesting_level ||
937 trap_is_smap(frame) ||
938 td->td_pcb == NULL ||
939 td->td_pcb->pcb_onfault == NULL) {
940 kprintf("Fatal user address access "
941 "from kernel mode from %s at %016jx\n",
942 td->td_comm, frame->tf_rip);
943 trap_fatal(frame, frame->tf_addr);
951 * PGEX_I is defined only if the execute disable bit capability is
952 * supported and enabled.
954 if (frame->tf_err & PGEX_W)
955 ftype = VM_PROT_WRITE;
956 else if (frame->tf_err & PGEX_I)
957 ftype = VM_PROT_EXECUTE;
959 ftype = VM_PROT_READ;
961 lwkt_tokref_t stop = td->td_toks_stop;
963 if (map != &kernel_map) {
965 * Keep swapout from messing with us during this
975 fault_flags |= VM_FAULT_BURST | VM_FAULT_USERMODE;
976 if (ftype & VM_PROT_WRITE)
977 fault_flags |= VM_FAULT_DIRTY;
979 fault_flags |= VM_FAULT_NORMAL;
980 rv = vm_fault(map, va, ftype, fault_flags);
981 if (td->td_toks_stop != stop) {
982 stop = td->td_toks_stop - 1;
983 kprintf("A-HELD TOKENS DURING PFAULT td=%p(%s) map=%p va=%p ftype=%d fault_flags=%d\n", td, td->td_comm, map, (void *)va, ftype, fault_flags);
984 panic("held tokens");
990 * Don't have to worry about process locking or stacks in the
993 fault_flags = VM_FAULT_NORMAL;
994 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
995 if (td->td_toks_stop != stop) {
996 stop = td->td_toks_stop - 1;
997 kprintf("B-HELD TOKENS DURING PFAULT td=%p(%s) map=%p va=%p ftype=%d fault_flags=%d\n", td, td->td_comm, map, (void *)va, ftype, VM_FAULT_NORMAL);
998 panic("held tokens");
1001 if (rv == KERN_SUCCESS)
1006 * NOTE: in 64-bit mode traps push rsp/ss
1007 * even if no ring change occurs.
1009 if (td->td_pcb->pcb_onfault &&
1010 td->td_pcb->pcb_onfault_sp == frame->tf_rsp &&
1011 td->td_gd->gd_intr_nesting_level == 0) {
1012 frame->tf_rip = (register_t)td->td_pcb->pcb_onfault;
1015 trap_fatal(frame, frame->tf_addr);
1020 * NOTE: on x86_64 we have a tf_addr field in the trapframe, no
1021 * kludge is needed to pass the fault address to signal handlers.
1025 if (td->td_lwp->lwp_vkernel == NULL) {
1026 while (freeze_on_seg_fault) {
1027 tsleep(p, 0, "freeze", hz * 20);
1029 if (ddb_on_seg_fault)
1030 Debugger("ddb_on_seg_fault");
1034 return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
1038 trap_fatal(struct trapframe *frame, vm_offset_t eva)
1043 struct soft_segment_descriptor softseg;
1046 code = frame->tf_err;
1047 type = frame->tf_trapno;
1048 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
1050 if (type <= MAX_TRAP_MSG)
1051 msg = trap_msg[type];
1054 kprintf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
1055 ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
1056 /* three separate prints in case of a trap on an unmapped page */
1057 kprintf("cpuid = %d; ", mycpu->gd_cpuid);
1059 kprintf("lapic id = %u\n", LAPIC_READID);
1060 if (type == T_PAGEFLT) {
1061 kprintf("fault virtual address = 0x%lx\n", eva);
1062 kprintf("fault code = %s %s %s, %s\n",
1063 code & PGEX_U ? "user" : "supervisor",
1064 code & PGEX_W ? "write" : "read",
1065 code & PGEX_I ? "instruction" : "data",
1066 code & PGEX_P ? "protection violation" : "page not present");
1068 kprintf("instruction pointer = 0x%lx:0x%lx\n",
1069 frame->tf_cs & 0xffff, frame->tf_rip);
1070 if (ISPL(frame->tf_cs) == SEL_UPL) {
1071 ss = frame->tf_ss & 0xffff;
1072 rsp = frame->tf_rsp;
1075 * NOTE: in 64-bit mode traps push rsp/ss even if no ring
1078 ss = GSEL(GDATA_SEL, SEL_KPL);
1079 rsp = frame->tf_rsp;
1081 kprintf("stack pointer = 0x%x:0x%lx\n", ss, rsp);
1082 kprintf("frame pointer = 0x%x:0x%lx\n", ss, frame->tf_rbp);
1083 kprintf("code segment = base 0x%lx, limit 0x%lx, type 0x%x\n",
1084 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1085 kprintf(" = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
1086 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
1088 kprintf("processor eflags = ");
1089 if (frame->tf_rflags & PSL_T)
1090 kprintf("trace trap, ");
1091 if (frame->tf_rflags & PSL_I)
1092 kprintf("interrupt enabled, ");
1093 if (frame->tf_rflags & PSL_NT)
1094 kprintf("nested task, ");
1095 if (frame->tf_rflags & PSL_RF)
1096 kprintf("resume, ");
1097 if (frame->tf_rflags & PSL_AC)
1098 kprintf("smap_open, ");
1099 kprintf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
1100 kprintf("current process = ");
1103 (u_long)curproc->p_pid);
1107 kprintf("current thread = pri %d ", curthread->td_pri);
1108 if (curthread->td_critcount)
1113 if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1116 kprintf("trap number = %d\n", type);
1117 if (type <= MAX_TRAP_MSG)
1118 panic("%s", trap_msg[type]);
1120 panic("unknown/reserved trap");
1124 * Double fault handler. Called when a fault occurs while writing
1125 * a frame for a trap/exception onto the stack. This usually occurs
1126 * when the stack overflows (such is the case with infinite recursion,
1131 in_kstack_guard(register_t rptr)
1133 thread_t td = curthread;
1135 if ((char *)rptr >= td->td_kstack &&
1136 (char *)rptr < td->td_kstack + PAGE_SIZE) {
1143 dblfault_handler(struct trapframe *frame)
1145 thread_t td = curthread;
1147 if (in_kstack_guard(frame->tf_rsp) || in_kstack_guard(frame->tf_rbp)) {
1148 kprintf("DOUBLE FAULT - KERNEL STACK GUARD HIT!\n");
1149 if (in_kstack_guard(frame->tf_rsp))
1150 frame->tf_rsp = (register_t)(td->td_kstack + PAGE_SIZE);
1151 if (in_kstack_guard(frame->tf_rbp))
1152 frame->tf_rbp = (register_t)(td->td_kstack + PAGE_SIZE);
1154 kprintf("DOUBLE FAULT\n");
1156 kprintf("\nFatal double fault\n");
1157 kprintf("rip = 0x%lx\n", frame->tf_rip);
1158 kprintf("rsp = 0x%lx\n", frame->tf_rsp);
1159 kprintf("rbp = 0x%lx\n", frame->tf_rbp);
1160 /* three separate prints in case of a trap on an unmapped page */
1161 kprintf("cpuid = %d; ", mycpu->gd_cpuid);
1163 kprintf("lapic id = %u\n", LAPIC_READID);
1164 panic("double fault");
1168 * syscall2 - MP aware system call request C handler
1170 * A system call is essentially treated as a trap except that the
1171 * MP lock is not held on entry or return. We are responsible for
1172 * obtaining the MP lock if necessary and for handling ASTs
1173 * (e.g. a task switch) prior to return.
1178 syscall2(struct trapframe *frame)
1180 struct thread *td = curthread;
1181 struct proc *p = td->td_proc;
1182 struct lwp *lp = td->td_lwp;
1183 struct sysent *callp;
1184 register_t orig_tf_rflags;
1189 int crit_count = td->td_critcount;
1193 int regcnt, optimized_regcnt;
1194 union sysunion args;
1195 register_t *argsdst;
1197 mycpu->gd_cnt.v_syscall++;
1200 if (__predict_false(ISPL(frame->tf_cs) != SEL_UPL)) {
1206 KTR_LOG(kernentry_syscall, p->p_pid, lp->lwp_tid,
1209 userenter(td, p); /* lazy raise our priority */
1212 optimized_regcnt = 6;
1217 sticks = (int)td->td_sticks;
1218 orig_tf_rflags = frame->tf_rflags;
1221 * Virtual kernel intercept - if a VM context managed by a virtual
1222 * kernel issues a system call the virtual kernel handles it, not us.
1223 * Restore the virtual kernel context and return from its system
1224 * call. The current frame is copied out to the virtual kernel.
1226 if (__predict_false(lp->lwp_vkernel && lp->lwp_vkernel->ve)) {
1227 vkernel_trap(lp, frame);
1228 error = EJUSTRETURN;
1235 * Get the system call parameters and account for time
1237 KASSERT(lp->lwp_md.md_regs == frame,
1238 ("Frame mismatch %p %p", lp->lwp_md.md_regs, frame));
1239 code = (u_int)frame->tf_rax;
1241 if (__predict_false(code == SYS_syscall || code == SYS___syscall)) {
1242 code = frame->tf_rdi;
1244 argp = &frame->tf_rdi + 1;
1246 argp = &frame->tf_rdi;
1249 if (code >= p->p_sysent->sv_size)
1250 callp = &p->p_sysent->sv_table[0];
1252 callp = &p->p_sysent->sv_table[code];
1255 * On x86_64 we get up to six arguments in registers. The rest are
1256 * on the stack. The first six members of 'struct trapframe' happen
1257 * to be the registers used to pass arguments, in exactly the right
1260 argsdst = (register_t *)(&args.nosys.sysmsg + 1);
1263 * Its easier to copy up to the highest number of syscall arguments
1264 * passed in registers, which is 6, than to conditionalize it.
1266 bcopy(argp, argsdst, sizeof(register_t) * optimized_regcnt);
1269 * Any arguments beyond available argument-passing registers must
1270 * be copyin()'d from the user stack.
1272 narg = callp->sy_narg;
1273 if (__predict_false(narg > regcnt)) {
1276 params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1277 error = copyin(params, &argsdst[regcnt],
1278 (narg - regcnt) * sizeof(register_t));
1281 if (KTRPOINTP(p, td, KTR_SYSCALL)) {
1282 ktrsyscall(lp, code, narg,
1283 (void *)(&args.nosys.sysmsg + 1));
1291 if (KTRPOINTP(p, td, KTR_SYSCALL)) {
1292 ktrsyscall(lp, code, narg, (void *)(&args.nosys.sysmsg + 1));
1297 * Default return value is 0 (will be copied to %rax). Double-value
1298 * returns use %rax and %rdx. %rdx is left unchanged for system
1299 * calls which return only one result.
1301 args.sysmsg_fds[0] = 0;
1302 args.sysmsg_fds[1] = frame->tf_rdx;
1305 * The syscall might manipulate the trap frame. If it does it
1306 * will probably return EJUSTRETURN.
1308 args.sysmsg_frame = frame;
1310 STOPEVENT(p, S_SCE, narg); /* MP aware */
1313 * NOTE: All system calls run MPSAFE now. The system call itself
1314 * is responsible for getting the MP lock.
1316 #ifdef SYSCALL_DEBUG
1317 tsc_uclock_t tscval = rdtsc();
1319 error = (*callp->sy_call)(&args);
1320 #ifdef SYSCALL_DEBUG
1321 tscval = rdtsc() - tscval;
1322 tscval = tscval * 1000000 / (tsc_frequency / 1000); /* ns */
1324 struct syscallwc *scwc = &SysCallsWorstCase[mycpu->gd_cpuid];
1325 int idx = scwc->idx++ % SCWC_MAXT;
1327 scwc->tot[code] += tscval - scwc->timings[code][idx];
1328 scwc->timings[code][idx] = tscval;
1334 * MP SAFE (we may or may not have the MP lock at this point)
1336 //kprintf("SYSMSG %d ", error);
1337 if (__predict_true(error == 0)) {
1339 * Reinitialize proc pointer `p' as it may be different
1340 * if this is a child returning from fork syscall.
1343 lp = curthread->td_lwp;
1344 frame->tf_rax = args.sysmsg_fds[0];
1345 frame->tf_rdx = args.sysmsg_fds[1];
1346 frame->tf_rflags &= ~PSL_C;
1347 } else if (error == ERESTART) {
1349 * Reconstruct pc, we know that 'syscall' is 2 bytes.
1350 * We have to do a full context restore so that %r10
1351 * (which was holding the value of %rcx) is restored for
1352 * the next iteration.
1354 if (frame->tf_err != 0 && frame->tf_err != 2)
1355 kprintf("lp %s:%d frame->tf_err is weird %ld\n",
1356 td->td_comm, lp->lwp_proc->p_pid, frame->tf_err);
1357 frame->tf_rip -= frame->tf_err;
1358 frame->tf_r10 = frame->tf_rcx;
1359 } else if (error == EJUSTRETURN) {
1361 } else if (error == EASYNC) {
1362 panic("Unexpected EASYNC return value (for now)");
1365 if (p->p_sysent->sv_errsize) {
1366 if (error >= p->p_sysent->sv_errsize)
1367 error = -1; /* XXX */
1369 error = p->p_sysent->sv_errtbl[error];
1371 frame->tf_rax = error;
1372 frame->tf_rflags |= PSL_C;
1376 * Traced syscall. trapsignal() should now be MP aware
1378 if (__predict_false(orig_tf_rflags & PSL_T)) {
1379 frame->tf_rflags &= ~PSL_T;
1380 trapsignal(lp, SIGTRAP, TRAP_TRACE);
1384 * Handle reschedule and other end-of-syscall issues
1386 userret(lp, frame, sticks);
1389 if (KTRPOINTP(p, td, KTR_SYSRET)) {
1390 ktrsysret(lp, code, error, args.sysmsg_result);
1395 * This works because errno is findable through the
1396 * register set. If we ever support an emulation where this
1397 * is not the case, this code will need to be revisited.
1399 STOPEVENT(p, S_SCX, code);
1402 KTR_LOG(kernentry_syscall_ret, p->p_pid, lp->lwp_tid, error);
1404 KASSERT(crit_count == td->td_critcount,
1405 ("syscall: critical section count mismatch! %d/%d",
1406 crit_count, td->td_pri));
1407 KASSERT(&td->td_toks_base == td->td_toks_stop,
1408 ("syscall: %ld extra tokens held after trap! syscall %p",
1409 td->td_toks_stop - &td->td_toks_base,
1415 fork_return(struct lwp *lp, struct trapframe *frame)
1417 frame->tf_rax = 0; /* Child returns zero */
1418 frame->tf_rflags &= ~PSL_C; /* success */
1421 generic_lwp_return(lp, frame);
1422 KTR_LOG(kernentry_fork_ret, lp->lwp_proc->p_pid, lp->lwp_tid);
1426 * Simplified back end of syscall(), used when returning from fork()
1427 * directly into user mode.
1429 * This code will return back into the fork trampoline code which then
1433 generic_lwp_return(struct lwp *lp, struct trapframe *frame)
1435 struct proc *p = lp->lwp_proc;
1438 * Check for exit-race. If one lwp exits the process concurrent with
1439 * another lwp creating a new thread, the two operations may cross
1440 * each other resulting in the newly-created lwp not receiving a
1443 if (p->p_flags & P_WEXIT) {
1444 lwpsignal(p, lp, SIGKILL);
1448 * Newly forked processes are given a kernel priority. We have to
1449 * adjust the priority to a normal user priority and fake entry
1450 * into the kernel (call userenter()) to install a passive release
1451 * function just in case userret() decides to stop the process. This
1452 * can occur when ^Z races a fork. If we do not install the passive
1453 * release function the current process designation will not be
1454 * released when the thread goes to sleep.
1456 lwkt_setpri_self(TDPRI_USER_NORM);
1457 userenter(lp->lwp_thread, p);
1458 userret(lp, frame, 0);
1460 if (KTRPOINTP(p, lp->lwp_thread, KTR_SYSRET))
1461 ktrsysret(lp, SYS_fork, 0, 0);
1463 lp->lwp_flags |= LWP_PASSIVE_ACQ;
1465 lp->lwp_flags &= ~LWP_PASSIVE_ACQ;
1469 * If PGEX_FPFAULT is set then set FP_VIRTFP in the PCB to force a T_DNA
1470 * fault (which is then passed back to the virtual kernel) if an attempt is
1471 * made to use the FP unit.
1473 * XXX this is a fairly big hack.
1476 set_vkernel_fp(struct trapframe *frame)
1478 struct thread *td = curthread;
1480 if (frame->tf_xflags & PGEX_FPFAULT) {
1481 td->td_pcb->pcb_flags |= FP_VIRTFP;
1482 if (mdcpu->gd_npxthread == td)
1485 td->td_pcb->pcb_flags &= ~FP_VIRTFP;
1490 * Called from vkernel_trap() to fixup the vkernel's syscall
1491 * frame for vmspace_ctl() return.
1494 cpu_vkernel_trap(struct trapframe *frame, int error)
1496 frame->tf_rax = error;
1498 frame->tf_rflags |= PSL_C;
1500 frame->tf_rflags &= ~PSL_C;