cb0f3ba8c6bc67564187e000f73920d6cc28f425
[dragonfly.git] / sys / platform / pc64 / x86_64 / trap.c
1 /*-
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 The DragonFly Project.
6  * Copyright (c) 2008 Jordan Gordeev.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * the University of Utah, and William Jolitz.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
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.
26  *
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
37  * SUCH DAMAGE.
38  *
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 $
41  */
42
43 /*
44  * x86_64 Trap and System call handling
45  */
46
47 #include "opt_ddb.h"
48 #include "opt_ktrace.h"
49
50 #include <machine/frame.h>
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/kernel.h>
54 #include <sys/proc.h>
55 #include <sys/pioctl.h>
56 #include <sys/types.h>
57 #include <sys/signal2.h>
58 #include <sys/syscall.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
61 #include <sys/systm.h>
62 #ifdef KTRACE
63 #include <sys/ktrace.h>
64 #endif
65 #include <sys/ktr.h>
66 #include <sys/sysmsg.h>
67 #include <sys/sysproto.h>
68 #include <sys/sysunion.h>
69
70 #include <vm/pmap.h>
71 #include <vm/vm.h>
72 #include <vm/vm_extern.h>
73 #include <vm/vm_kern.h>
74 #include <vm/vm_param.h>
75 #include <machine/cpu.h>
76 #include <machine/pcb.h>
77 #include <machine/smp.h>
78 #include <machine/thread.h>
79 #include <machine/vmparam.h>
80 #include <machine/md_var.h>
81 #include <machine_base/isa/intr_machdep.h>
82
83 #include <ddb/ddb.h>
84
85 #include <sys/thread2.h>
86 #include <sys/mplock2.h>
87
88 #ifdef SMP
89
90 #define MAKEMPSAFE(have_mplock)                 \
91         if (have_mplock == 0) {                 \
92                 get_mplock();                   \
93                 have_mplock = 1;                \
94         }
95
96 #else
97
98 #define MAKEMPSAFE(have_mplock)
99
100 #endif
101
102 extern void trap(struct trapframe *frame);
103
104 static int trap_pfault(struct trapframe *, int);
105 static void trap_fatal(struct trapframe *, vm_offset_t);
106 void dblfault_handler(struct trapframe *frame);
107
108 #define MAX_TRAP_MSG            30
109 static char *trap_msg[] = {
110         "",                                     /*  0 unused */
111         "privileged instruction fault",         /*  1 T_PRIVINFLT */
112         "",                                     /*  2 unused */
113         "breakpoint instruction fault",         /*  3 T_BPTFLT */
114         "",                                     /*  4 unused */
115         "",                                     /*  5 unused */
116         "arithmetic trap",                      /*  6 T_ARITHTRAP */
117         "system forced exception",              /*  7 T_ASTFLT */
118         "",                                     /*  8 unused */
119         "general protection fault",             /*  9 T_PROTFLT */
120         "trace trap",                           /* 10 T_TRCTRAP */
121         "",                                     /* 11 unused */
122         "page fault",                           /* 12 T_PAGEFLT */
123         "",                                     /* 13 unused */
124         "alignment fault",                      /* 14 T_ALIGNFLT */
125         "",                                     /* 15 unused */
126         "",                                     /* 16 unused */
127         "",                                     /* 17 unused */
128         "integer divide fault",                 /* 18 T_DIVIDE */
129         "non-maskable interrupt trap",          /* 19 T_NMI */
130         "overflow trap",                        /* 20 T_OFLOW */
131         "FPU bounds check fault",               /* 21 T_BOUND */
132         "FPU device not available",             /* 22 T_DNA */
133         "double fault",                         /* 23 T_DOUBLEFLT */
134         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
135         "invalid TSS fault",                    /* 25 T_TSSFLT */
136         "segment not present fault",            /* 26 T_SEGNPFLT */
137         "stack fault",                          /* 27 T_STKFLT */
138         "machine check trap",                   /* 28 T_MCHK */
139         "SIMD floating-point exception",        /* 29 T_XMMFLT */
140         "reserved (unknown) fault",             /* 30 T_RESERVED */
141 };
142
143 #ifdef DDB
144 static int ddb_on_nmi = 1;
145 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
146         &ddb_on_nmi, 0, "Go to DDB on NMI");
147 #endif
148 static int panic_on_nmi = 1;
149 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
150         &panic_on_nmi, 0, "Panic on NMI");
151 static int fast_release;
152 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
153         &fast_release, 0, "Passive Release was optimal");
154 static int slow_release;
155 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
156         &slow_release, 0, "Passive Release was nonoptimal");
157
158 /*
159  * Passively intercepts the thread switch function to increase
160  * the thread priority from a user priority to a kernel priority, reducing
161  * syscall and trap overhead for the case where no switch occurs.
162  *
163  * Synchronizes td_ucred with p_ucred.  This is used by system calls,
164  * signal handling, faults, AST traps, and anything else that enters the
165  * kernel from userland and provides the kernel with a stable read-only
166  * copy of the process ucred.
167  */
168 static __inline void
169 userenter(struct thread *curtd, struct proc *curp)
170 {
171         struct ucred *ocred;
172         struct ucred *ncred;
173
174         curtd->td_release = lwkt_passive_release;
175
176         if (curtd->td_ucred != curp->p_ucred) {
177                 ncred = crhold(curp->p_ucred);
178                 ocred = curtd->td_ucred;
179                 curtd->td_ucred = ncred;
180                 if (ocred)
181                         crfree(ocred);
182         }
183 }
184
185 /*
186  * Handle signals, upcalls, profiling, and other AST's and/or tasks that
187  * must be completed before we can return to or try to return to userland.
188  *
189  * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
190  * arithmatic on the delta calculation so the absolute tick values are
191  * truncated to an integer.
192  */
193 static void
194 userret(struct lwp *lp, struct trapframe *frame, int sticks)
195 {
196         struct proc *p = lp->lwp_proc;
197         int sig;
198
199         /*
200          * Charge system time if profiling.  Note: times are in microseconds.
201          * This may do a copyout and block, so do it first even though it
202          * means some system time will be charged as user time.
203          */
204         if (p->p_flag & P_PROFIL) {
205                 addupc_task(p, frame->tf_rip, 
206                         (u_int)((int)lp->lwp_thread->td_sticks - sticks));
207         }
208
209 recheck:
210         /*
211          * If the jungle wants us dead, so be it.
212          */
213         if (lp->lwp_flag & LWP_WEXIT) {
214                 get_mplock();
215                 lwp_exit(0);
216                 rel_mplock(); /* NOT REACHED */
217         }
218
219         /*
220          * Block here if we are in a stopped state.
221          */
222         if (p->p_stat == SSTOP) {
223                 get_mplock();
224                 tstop();
225                 rel_mplock();
226                 goto recheck;
227         }
228
229         /*
230          * Post any pending upcalls.  If running a virtual kernel be sure
231          * to restore the virtual kernel's vmspace before posting the upcall.
232          */
233         if (p->p_flag & P_UPCALLPEND) {
234                 p->p_flag &= ~P_UPCALLPEND;
235                 get_mplock();
236                 postupcall(lp);
237                 rel_mplock();
238                 goto recheck;
239         }
240
241         /*
242          * Post any pending signals.  If running a virtual kernel be sure
243          * to restore the virtual kernel's vmspace before posting the signal.
244          */
245         if ((sig = CURSIG_TRACE(lp)) != 0) {
246                 get_mplock();
247                 postsig(sig);
248                 rel_mplock();
249                 goto recheck;
250         }
251
252         /*
253          * block here if we are swapped out, but still process signals
254          * (such as SIGKILL).  proc0 (the swapin scheduler) is already
255          * aware of our situation, we do not have to wake it up.
256          */
257         if (p->p_flag & P_SWAPPEDOUT) {
258                 get_mplock();
259                 p->p_flag |= P_SWAPWAIT;
260                 swapin_request();
261                 if (p->p_flag & P_SWAPWAIT)
262                         tsleep(p, PCATCH, "SWOUT", 0);
263                 p->p_flag &= ~P_SWAPWAIT;
264                 rel_mplock();
265                 goto recheck;
266         }
267
268         /*
269          * Make sure postsig() handled request to restore old signal mask after
270          * running signal handler.
271          */
272         KKASSERT((lp->lwp_flag & LWP_OLDMASK) == 0);
273 }
274
275 /*
276  * Cleanup from userenter and any passive release that might have occured.
277  * We must reclaim the current-process designation before we can return
278  * to usermode.  We also handle both LWKT and USER reschedule requests.
279  */
280 static __inline void
281 userexit(struct lwp *lp)
282 {
283         struct thread *td = lp->lwp_thread;
284 /*      globaldata_t gd = td->td_gd;*/
285
286         /*
287          * Handle stop requests at kernel priority.  Any requests queued
288          * after this loop will generate another AST.
289          */
290         while (lp->lwp_proc->p_stat == SSTOP) {
291                 get_mplock();
292                 tstop();
293                 rel_mplock();
294         }
295
296         /*
297          * Reduce our priority in preparation for a return to userland.  If
298          * our passive release function was still in place, our priority was
299          * never raised and does not need to be reduced.
300          */
301         lwkt_passive_recover(td);
302
303         /*
304          * Become the current user scheduled process if we aren't already,
305          * and deal with reschedule requests and other factors.
306          */
307         lp->lwp_proc->p_usched->acquire_curproc(lp);
308         /* WARNING: we may have migrated cpu's */
309         /* gd = td->td_gd; */
310 }
311
312 #if !defined(KTR_KERNENTRY)
313 #define KTR_KERNENTRY   KTR_ALL
314 #endif
315 KTR_INFO_MASTER(kernentry);
316 KTR_INFO(KTR_KERNENTRY, kernentry, trap, 0, "STR",
317          sizeof(long) + sizeof(long) + sizeof(long) + sizeof(vm_offset_t));
318 KTR_INFO(KTR_KERNENTRY, kernentry, trap_ret, 0, "STR",
319          sizeof(long) + sizeof(long));
320 KTR_INFO(KTR_KERNENTRY, kernentry, syscall, 0, "STR",
321          sizeof(long) + sizeof(long) + sizeof(long));
322 KTR_INFO(KTR_KERNENTRY, kernentry, syscall_ret, 0, "STR",
323          sizeof(long) + sizeof(long) + sizeof(long));
324 KTR_INFO(KTR_KERNENTRY, kernentry, fork_ret, 0, "STR",
325          sizeof(long) + sizeof(long));
326
327 /*
328  * Exception, fault, and trap interface to the kernel.
329  * This common code is called from assembly language IDT gate entry
330  * routines that prepare a suitable stack frame, and restore this
331  * frame after the exception has been processed.
332  *
333  * This function is also called from doreti in an interlock to handle ASTs.
334  * For example:  hardwareint->INTROUTINE->(set ast)->doreti->trap
335  *
336  * NOTE!  We have to retrieve the fault address prior to obtaining the
337  * MP lock because get_mplock() may switch out.  YYY cr2 really ought
338  * to be retrieved by the assembly code, not here.
339  *
340  * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
341  * if an attempt is made to switch from a fast interrupt or IPI.  This is
342  * necessary to properly take fatal kernel traps on SMP machines if 
343  * get_mplock() has to block.
344  */
345
346 void
347 trap(struct trapframe *frame)
348 {
349         struct globaldata *gd = mycpu;
350         struct thread *td = gd->gd_curthread;
351         struct lwp *lp = td->td_lwp;
352         struct proc *p;
353         int sticks = 0;
354         int i = 0, ucode = 0, type, code;
355 #ifdef SMP
356         int have_mplock = 0;
357 #endif
358 #ifdef INVARIANTS
359         int crit_count = td->td_critcount;
360 #endif
361         vm_offset_t eva;
362
363         p = td->td_proc;
364
365 #ifdef JG
366         kprintf0("TRAP ");
367         kprintf0("\"%s\" type=%ld\n",
368                 trap_msg[frame->tf_trapno], frame->tf_trapno);
369         kprintf0(" rip=%lx rsp=%lx\n", frame->tf_rip, frame->tf_rsp);
370         kprintf0(" err=%lx addr=%lx\n", frame->tf_err, frame->tf_addr);
371         kprintf0(" cs=%lx ss=%lx rflags=%lx\n", (unsigned long)frame->tf_cs, (unsigned long)frame->tf_ss, frame->tf_rflags);
372 #endif
373
374 #ifdef DDB
375         if (db_active) {
376                 ++gd->gd_trap_nesting_level;
377                 MAKEMPSAFE(have_mplock);
378                 trap_fatal(frame, frame->tf_addr);
379                 --gd->gd_trap_nesting_level;
380                 goto out2;
381         }
382 #endif
383 #ifdef DDB
384         if (db_active) {
385                 eva = (frame->tf_trapno == T_PAGEFLT ? frame->tf_addr : 0);
386                 ++gd->gd_trap_nesting_level;
387                 MAKEMPSAFE(have_mplock);
388                 trap_fatal(frame, eva);
389                 --gd->gd_trap_nesting_level;
390                 goto out2;
391         }
392 #endif
393
394         eva = 0;
395
396         if ((frame->tf_rflags & PSL_I) == 0) {
397                 /*
398                  * Buggy application or kernel code has disabled interrupts
399                  * and then trapped.  Enabling interrupts now is wrong, but
400                  * it is better than running with interrupts disabled until
401                  * they are accidentally enabled later.
402                  */
403                 type = frame->tf_trapno;
404                 if (ISPL(frame->tf_cs) == SEL_UPL) {
405                         MAKEMPSAFE(have_mplock);
406                         /* JG curproc can be NULL */
407                         kprintf(
408                             "pid %ld (%s): trap %d with interrupts disabled\n",
409                             (long)curproc->p_pid, curproc->p_comm, type);
410                 } else if (type != T_NMI && type != T_BPTFLT &&
411                     type != T_TRCTRAP) {
412                         /*
413                          * XXX not quite right, since this may be for a
414                          * multiple fault in user mode.
415                          */
416                         MAKEMPSAFE(have_mplock);
417                         kprintf("kernel trap %d with interrupts disabled\n",
418                             type);
419                 }
420                 cpu_enable_intr();
421         }
422
423         type = frame->tf_trapno;
424         code = frame->tf_err;
425
426         if (ISPL(frame->tf_cs) == SEL_UPL) {
427                 /* user trap */
428
429                 KTR_LOG(kernentry_trap, p->p_pid, lp->lwp_tid,
430                         frame->tf_trapno, eva);
431
432                 userenter(td, p);
433
434                 sticks = (int)td->td_sticks;
435                 lp->lwp_md.md_regs = frame;
436
437                 switch (type) {
438                 case T_PRIVINFLT:       /* privileged instruction fault */
439                         ucode = ILL_PRVOPC;
440                         i = SIGILL;
441                         break;
442
443                 case T_BPTFLT:          /* bpt instruction fault */
444                 case T_TRCTRAP:         /* trace trap */
445                         frame->tf_rflags &= ~PSL_T;
446                         ucode = TRAP_TRACE;
447                         i = SIGTRAP;
448                         break;
449
450                 case T_ARITHTRAP:       /* arithmetic trap */
451                         ucode = code;
452                         i = SIGFPE;
453 #if 0
454 #if JG
455                         ucode = fputrap();
456 #else
457                         ucode = code;
458 #endif
459                         i = SIGFPE;
460 #endif
461                         break;
462
463                 case T_ASTFLT:          /* Allow process switch */
464                         mycpu->gd_cnt.v_soft++;
465                         if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
466                                 atomic_clear_int_nonlocked(&mycpu->gd_reqflags,
467                                             RQF_AST_OWEUPC);
468                                 addupc_task(p, p->p_prof.pr_addr,
469                                             p->p_prof.pr_ticks);
470                         }
471                         goto out;
472
473                 case T_PROTFLT:         /* general protection fault */
474                         i = SIGBUS;
475                         ucode = BUS_OBJERR;
476                         break;
477                 case T_SEGNPFLT:        /* segment not present fault */
478                         i = SIGBUS;
479                         ucode = BUS_ADRERR;
480                         break;
481                 case T_TSSFLT:          /* invalid TSS fault */
482                 case T_DOUBLEFLT:       /* double fault */
483                         i = SIGBUS;
484                         ucode = BUS_OBJERR;
485                 default:
486 #if 0
487                         ucode = code + BUS_SEGM_FAULT ; /* XXX: ???*/
488 #endif
489                         ucode = BUS_OBJERR;
490                         i = SIGBUS;
491                         break;
492
493                 case T_PAGEFLT:         /* page fault */
494                         MAKEMPSAFE(have_mplock);
495                         i = trap_pfault(frame, TRUE);
496                         if (frame->tf_rip == 0)
497                                 kprintf("T_PAGEFLT: Warning %%rip == 0!\n");
498                         if (i == -1)
499                                 goto out;
500                         if (i == 0)
501                                 goto out;
502
503 #if 0
504                         ucode = T_PAGEFLT;
505 #endif
506                         if (i == SIGSEGV)
507                                 ucode = SEGV_MAPERR;
508                         else
509                                 ucode = BUS_ADRERR;
510                         break;
511
512                 case T_DIVIDE:          /* integer divide fault */
513                         ucode = FPE_INTDIV;
514                         i = SIGFPE;
515                         break;
516
517                 case T_NMI:
518                         MAKEMPSAFE(have_mplock);
519                         /* machine/parity/power fail/"kitchen sink" faults */
520                         if (isa_nmi(code) == 0) {
521 #ifdef DDB
522                                 /*
523                                  * NMI can be hooked up to a pushbutton
524                                  * for debugging.
525                                  */
526                                 if (ddb_on_nmi) {
527                                         kprintf ("NMI ... going to debugger\n");
528                                         kdb_trap(type, 0, frame);
529                                 }
530 #endif /* DDB */
531                                 goto out2;
532                         } else if (panic_on_nmi)
533                                 panic("NMI indicates hardware failure");
534                         break;
535
536                 case T_OFLOW:           /* integer overflow fault */
537                         ucode = FPE_INTOVF;
538                         i = SIGFPE;
539                         break;
540
541                 case T_BOUND:           /* bounds check fault */
542                         ucode = FPE_FLTSUB;
543                         i = SIGFPE;
544                         break;
545
546                 case T_DNA:
547                         /*
548                          * Virtual kernel intercept - pass the DNA exception
549                          * to the virtual kernel if it asked to handle it.
550                          * This occurs when the virtual kernel is holding
551                          * onto the FP context for a different emulated
552                          * process then the one currently running.
553                          *
554                          * We must still call npxdna() since we may have
555                          * saved FP state that the virtual kernel needs
556                          * to hand over to a different emulated process.
557                          */
558                         if (lp->lwp_vkernel && lp->lwp_vkernel->ve &&
559                             (td->td_pcb->pcb_flags & FP_VIRTFP)
560                         ) {
561                                 npxdna();
562                                 break;
563                         }
564
565                         /*
566                          * The kernel may have switched out the FP unit's
567                          * state, causing the user process to take a fault
568                          * when it tries to use the FP unit.  Restore the
569                          * state here
570                          */
571                         if (npxdna())
572                                 goto out;
573                         i = SIGFPE;
574                         ucode = FPE_FPU_NP_TRAP;
575                         break;
576
577                 case T_FPOPFLT:         /* FPU operand fetch fault */
578                         ucode = ILL_COPROC;
579                         i = SIGILL;
580                         break;
581
582                 case T_XMMFLT:          /* SIMD floating-point exception */
583                         ucode = 0; /* XXX */
584                         i = SIGFPE;
585                         break;
586                 }
587         } else {
588                 /* kernel trap */
589
590                 switch (type) {
591                 case T_PAGEFLT:                 /* page fault */
592                         MAKEMPSAFE(have_mplock);
593                         trap_pfault(frame, FALSE);
594                         goto out2;
595
596                 case T_DNA:
597                         /*
598                          * The kernel is apparently using fpu for copying.
599                          * XXX this should be fatal unless the kernel has
600                          * registered such use.
601                          */
602                         if (npxdna())
603                                 goto out2;
604                         break;
605
606                 case T_STKFLT:          /* stack fault */
607                         break;
608
609                 case T_PROTFLT:         /* general protection fault */
610                 case T_SEGNPFLT:        /* segment not present fault */
611                         /*
612                          * Invalid segment selectors and out of bounds
613                          * %rip's and %rsp's can be set up in user mode.
614                          * This causes a fault in kernel mode when the
615                          * kernel tries to return to user mode.  We want
616                          * to get this fault so that we can fix the
617                          * problem here and not have to check all the
618                          * selectors and pointers when the user changes
619                          * them.
620                          */
621                         kprintf("trap.c line %d\n", __LINE__);
622                         if (mycpu->gd_intr_nesting_level == 0) {
623                                 if (td->td_pcb->pcb_onfault) {
624                                         frame->tf_rip = (register_t)
625                                                 td->td_pcb->pcb_onfault;
626                                         goto out2;
627                                 }
628                                 if (frame->tf_rip == (long)doreti_iret) {
629                                         frame->tf_rip = (long)doreti_iret_fault;
630                                         goto out2;
631                                 }
632                         }
633                         break;
634
635                 case T_TSSFLT:
636                         /*
637                          * PSL_NT can be set in user mode and isn't cleared
638                          * automatically when the kernel is entered.  This
639                          * causes a TSS fault when the kernel attempts to
640                          * `iret' because the TSS link is uninitialized.  We
641                          * want to get this fault so that we can fix the
642                          * problem here and not every time the kernel is
643                          * entered.
644                          */
645                         if (frame->tf_rflags & PSL_NT) {
646                                 frame->tf_rflags &= ~PSL_NT;
647                                 goto out2;
648                         }
649                         break;
650
651                 case T_TRCTRAP:  /* trace trap */
652 #if 0
653                         if (frame->tf_rip == (int)IDTVEC(syscall)) {
654                                 /*
655                                  * We've just entered system mode via the
656                                  * syscall lcall.  Continue single stepping
657                                  * silently until the syscall handler has
658                                  * saved the flags.
659                                  */
660                                 goto out2;
661                         }
662                         if (frame->tf_rip == (int)IDTVEC(syscall) + 1) {
663                                 /*
664                                  * The syscall handler has now saved the
665                                  * flags.  Stop single stepping it.
666                                  */
667                                 frame->tf_rflags &= ~PSL_T;
668                                 goto out2;
669                         }
670 #endif
671
672                         /*
673                          * Ignore debug register trace traps due to
674                          * accesses in the user's address space, which
675                          * can happen under several conditions such as
676                          * if a user sets a watchpoint on a buffer and
677                          * then passes that buffer to a system call.
678                          * We still want to get TRCTRAPS for addresses
679                          * in kernel space because that is useful when
680                          * debugging the kernel.
681                          */
682 #if JG
683                         if (user_dbreg_trap()) {
684                                 /*
685                                  * Reset breakpoint bits because the
686                                  * processor doesn't
687                                  */
688                                 /* XXX check upper bits here */
689                                 load_dr6(rdr6() & 0xfffffff0);
690                                 goto out2;
691                         }
692 #endif
693                         /*
694                          * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
695                          */
696                 case T_BPTFLT:
697                         /*
698                          * If DDB is enabled, let it handle the debugger trap.
699                          * Otherwise, debugger traps "can't happen".
700                          */
701                         ucode = TRAP_BRKPT;
702 #ifdef DDB
703                         MAKEMPSAFE(have_mplock);
704                         if (kdb_trap(type, 0, frame))
705                                 goto out2;
706 #endif
707                         break;
708
709                 case T_NMI:
710                         MAKEMPSAFE(have_mplock);
711                         /* machine/parity/power fail/"kitchen sink" faults */
712 #if NISA > 0
713                         if (isa_nmi(code) == 0) {
714 #ifdef DDB
715                                 /*
716                                  * NMI can be hooked up to a pushbutton
717                                  * for debugging.
718                                  */
719                                 if (ddb_on_nmi) {
720                                         kprintf ("NMI ... going to debugger\n");
721                                         kdb_trap(type, 0, frame);
722                                 }
723 #endif /* DDB */
724                                 goto out2;
725                         } else if (panic_on_nmi == 0)
726                                 goto out2;
727                         /* FALL THROUGH */
728 #endif /* NISA > 0 */
729                 }
730                 MAKEMPSAFE(have_mplock);
731                 trap_fatal(frame, 0);
732                 goto out2;
733         }
734
735         /*
736          * Virtual kernel intercept - if the fault is directly related to a
737          * VM context managed by a virtual kernel then let the virtual kernel
738          * handle it.
739          */
740         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
741                 vkernel_trap(lp, frame);
742                 goto out;
743         }
744
745         /*
746          * Translate fault for emulators (e.g. Linux) 
747          */
748         if (*p->p_sysent->sv_transtrap)
749                 i = (*p->p_sysent->sv_transtrap)(i, type);
750
751         MAKEMPSAFE(have_mplock);
752         trapsignal(lp, i, ucode);
753
754 #ifdef DEBUG
755         if (type <= MAX_TRAP_MSG) {
756                 uprintf("fatal process exception: %s",
757                         trap_msg[type]);
758                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
759                         uprintf(", fault VA = 0x%lx", frame->tf_addr);
760                 uprintf("\n");
761         }
762 #endif
763
764 out:
765 #ifdef SMP
766         if (ISPL(frame->tf_cs) == SEL_UPL)
767                 KASSERT(td->td_mpcount == have_mplock, ("badmpcount trap/end from %p", (void *)frame->tf_rip));
768 #endif
769         userret(lp, frame, sticks);
770         userexit(lp);
771 out2:   ;
772 #ifdef SMP
773         if (have_mplock)
774                 rel_mplock();
775 #endif
776         if (p != NULL && lp != NULL)
777                 KTR_LOG(kernentry_trap_ret, p->p_pid, lp->lwp_tid);
778 #ifdef INVARIANTS
779         KASSERT(crit_count == td->td_critcount,
780                 ("syscall: critical section count mismatch! %d/%d",
781                 crit_count, td->td_pri));
782 #endif
783 }
784
785 static int
786 trap_pfault(struct trapframe *frame, int usermode)
787 {
788         vm_offset_t va;
789         struct vmspace *vm = NULL;
790         vm_map_t map;
791         int rv = 0;
792         int fault_flags;
793         vm_prot_t ftype;
794         thread_t td = curthread;
795         struct lwp *lp = td->td_lwp;
796
797         va = trunc_page(frame->tf_addr);
798         if (va >= VM_MIN_KERNEL_ADDRESS) {
799                 /*
800                  * Don't allow user-mode faults in kernel address space.
801                  */
802                 if (usermode)
803                         goto nogo;
804
805                 map = &kernel_map;
806         } else {
807                 /*
808                  * This is a fault on non-kernel virtual memory.
809                  * vm is initialized above to NULL. If curproc is NULL
810                  * or curproc->p_vmspace is NULL the fault is fatal.
811                  */
812                 if (lp != NULL)
813                         vm = lp->lwp_vmspace;
814
815                 if (vm == NULL)
816                         goto nogo;
817
818                 map = &vm->vm_map;
819         }
820
821         /*
822          * PGEX_I is defined only if the execute disable bit capability is
823          * supported and enabled.
824          */
825         if (frame->tf_err & PGEX_W)
826                 ftype = VM_PROT_WRITE;
827 #if JG
828         else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
829                 ftype = VM_PROT_EXECUTE;
830 #endif
831         else
832                 ftype = VM_PROT_READ;
833
834         if (map != &kernel_map) {
835                 /*
836                  * Keep swapout from messing with us during this
837                  *      critical time.
838                  */
839                 PHOLD(lp->lwp_proc);
840
841                 /*
842                  * Issue fault
843                  */
844                 fault_flags = 0;
845                 if (usermode)
846                         fault_flags |= VM_FAULT_BURST;
847                 if (ftype & VM_PROT_WRITE)
848                         fault_flags |= VM_FAULT_DIRTY;
849                 else
850                         fault_flags |= VM_FAULT_NORMAL;
851                 rv = vm_fault(map, va, ftype, fault_flags);
852
853                 PRELE(lp->lwp_proc);
854         } else {
855                 /*
856                  * Don't have to worry about process locking or stacks
857                  * in the kernel.
858                  */
859                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
860         }
861
862         if (rv == KERN_SUCCESS)
863                 return (0);
864 nogo:
865         if (!usermode) {
866                 if (td->td_gd->gd_intr_nesting_level == 0 &&
867                     td->td_pcb->pcb_onfault) {
868                         frame->tf_rip = (register_t)td->td_pcb->pcb_onfault;
869                         return (0);
870                 }
871                 trap_fatal(frame, frame->tf_addr);
872                 return (-1);
873         }
874
875         /*
876          * NOTE: on x86_64 we have a tf_addr field in the trapframe, no
877          * kludge is needed to pass the fault address to signal handlers.
878          */
879         struct proc *p = td->td_proc;
880         if (td->td_lwp->lwp_vkernel == NULL) {
881                 kprintf("seg-fault accessing address %p rip=%p pid=%d p_comm=%s\n",
882                         (void *)va, (void *)frame->tf_rip, p->p_pid, p->p_comm);
883         }
884         /* Debugger("seg-fault"); */
885
886         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
887 }
888
889 static void
890 trap_fatal(struct trapframe *frame, vm_offset_t eva)
891 {
892         int code, ss;
893         u_int type;
894         long rsp;
895         struct soft_segment_descriptor softseg;
896         char *msg;
897
898         code = frame->tf_err;
899         type = frame->tf_trapno;
900         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)], &softseg);
901
902         if (type <= MAX_TRAP_MSG)
903                 msg = trap_msg[type];
904         else
905                 msg = "UNKNOWN";
906         kprintf("\n\nFatal trap %d: %s while in %s mode\n", type, msg,
907             ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
908 #ifdef SMP
909         /* three separate prints in case of a trap on an unmapped page */
910         kprintf("mp_lock = %08x; ", mp_lock);
911         kprintf("cpuid = %d; ", mycpu->gd_cpuid);
912         kprintf("lapic->id = %08x\n", lapic->id);
913 #endif
914         if (type == T_PAGEFLT) {
915                 kprintf("fault virtual address  = 0x%lx\n", eva);
916                 kprintf("fault code             = %s %s %s, %s\n",
917                         code & PGEX_U ? "user" : "supervisor",
918                         code & PGEX_W ? "write" : "read",
919                         code & PGEX_I ? "instruction" : "data",
920                         code & PGEX_P ? "protection violation" : "page not present");
921         }
922         kprintf("instruction pointer    = 0x%lx:0x%lx\n",
923                frame->tf_cs & 0xffff, frame->tf_rip);
924         if (ISPL(frame->tf_cs) == SEL_UPL) {
925                 ss = frame->tf_ss & 0xffff;
926                 rsp = frame->tf_rsp;
927         } else {
928                 ss = GSEL(GDATA_SEL, SEL_KPL);
929                 rsp = (long)&frame->tf_rsp;
930         }
931         kprintf("stack pointer          = 0x%x:0x%lx\n", ss, rsp);
932         kprintf("frame pointer          = 0x%x:0x%lx\n", ss, frame->tf_rbp);
933         kprintf("code segment           = base 0x%lx, limit 0x%lx, type 0x%x\n",
934                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
935         kprintf("                       = DPL %d, pres %d, long %d, def32 %d, gran %d\n",
936                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_long, softseg.ssd_def32,
937                softseg.ssd_gran);
938         kprintf("processor eflags       = ");
939         if (frame->tf_rflags & PSL_T)
940                 kprintf("trace trap, ");
941         if (frame->tf_rflags & PSL_I)
942                 kprintf("interrupt enabled, ");
943         if (frame->tf_rflags & PSL_NT)
944                 kprintf("nested task, ");
945         if (frame->tf_rflags & PSL_RF)
946                 kprintf("resume, ");
947         kprintf("IOPL = %ld\n", (frame->tf_rflags & PSL_IOPL) >> 12);
948         kprintf("current process                = ");
949         if (curproc) {
950                 kprintf("%lu\n",
951                     (u_long)curproc->p_pid);
952         } else {
953                 kprintf("Idle\n");
954         }
955         kprintf("current thread          = pri %d ", curthread->td_pri);
956         if (curthread->td_critcount)
957                 kprintf("(CRIT)");
958         kprintf("\n");
959
960 #ifdef DDB
961         if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
962                 return;
963 #endif
964         kprintf("trap number            = %d\n", type);
965         if (type <= MAX_TRAP_MSG)
966                 panic("%s", trap_msg[type]);
967         else
968                 panic("unknown/reserved trap");
969 }
970
971 /*
972  * Double fault handler. Called when a fault occurs while writing
973  * a frame for a trap/exception onto the stack. This usually occurs
974  * when the stack overflows (such is the case with infinite recursion,
975  * for example).
976  */
977 void
978 dblfault_handler(struct trapframe *frame)
979 {
980         kprintf0("DOUBLE FAULT\n");
981         kprintf("\nFatal double fault\n");
982         kprintf("rip = 0x%lx\n", frame->tf_rip);
983         kprintf("rsp = 0x%lx\n", frame->tf_rsp);
984         kprintf("rbp = 0x%lx\n", frame->tf_rbp);
985 #ifdef SMP
986         /* three separate prints in case of a trap on an unmapped page */
987         kprintf("mp_lock = %08x; ", mp_lock);
988         kprintf("cpuid = %d; ", mycpu->gd_cpuid);
989         kprintf("lapic->id = %08x\n", lapic->id);
990 #endif
991         panic("double fault");
992 }
993
994 /*
995  * syscall2 -   MP aware system call request C handler
996  *
997  * A system call is essentially treated as a trap except that the
998  * MP lock is not held on entry or return.  We are responsible for
999  * obtaining the MP lock if necessary and for handling ASTs
1000  * (e.g. a task switch) prior to return.
1001  *
1002  * MPSAFE
1003  */
1004 void
1005 syscall2(struct trapframe *frame)
1006 {
1007         struct thread *td = curthread;
1008         struct proc *p = td->td_proc;
1009         struct lwp *lp = td->td_lwp;
1010         caddr_t params;
1011         struct sysent *callp;
1012         register_t orig_tf_rflags;
1013         int sticks;
1014         int error;
1015         int narg;
1016 #ifdef INVARIANTS
1017         int crit_count = td->td_critcount;
1018 #endif
1019 #ifdef SMP
1020         int have_mplock = 0;
1021 #endif
1022         register_t *argp;
1023         u_int code;
1024         int reg, regcnt;
1025         union sysunion args;
1026         register_t *argsdst;
1027
1028         mycpu->gd_cnt.v_syscall++;
1029
1030 #ifdef DIAGNOSTIC
1031         if (ISPL(frame->tf_cs) != SEL_UPL) {
1032                 get_mplock();
1033                 panic("syscall");
1034                 /* NOT REACHED */
1035         }
1036 #endif
1037
1038         KTR_LOG(kernentry_syscall, p->p_pid, lp->lwp_tid,
1039                 frame->tf_eax);
1040
1041 #ifdef SMP
1042         KASSERT(td->td_mpcount == 0,
1043                 ("badmpcount syscall2 from %p", (void *)frame->tf_rip));
1044 #endif
1045         userenter(td, p);       /* lazy raise our priority */
1046
1047         reg = 0;
1048         regcnt = 6;
1049         /*
1050          * Misc
1051          */
1052         sticks = (int)td->td_sticks;
1053         orig_tf_rflags = frame->tf_rflags;
1054
1055         /*
1056          * Virtual kernel intercept - if a VM context managed by a virtual
1057          * kernel issues a system call the virtual kernel handles it, not us.
1058          * Restore the virtual kernel context and return from its system
1059          * call.  The current frame is copied out to the virtual kernel.
1060          */
1061         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
1062                 vkernel_trap(lp, frame);
1063                 error = EJUSTRETURN;
1064                 goto out;
1065         }
1066
1067         /*
1068          * Get the system call parameters and account for time
1069          */
1070         lp->lwp_md.md_regs = frame;
1071         params = (caddr_t)frame->tf_rsp + sizeof(register_t);
1072         code = frame->tf_rax;
1073
1074         if (p->p_sysent->sv_prepsyscall) {
1075                 (*p->p_sysent->sv_prepsyscall)(
1076                         frame, (int *)(&args.nosys.sysmsg + 1),
1077                         &code, &params);
1078         } else {
1079                 if (code == SYS_syscall || code == SYS___syscall) {
1080                         code = frame->tf_rdi;
1081                         reg++;
1082                         regcnt--;
1083                 }
1084         }
1085
1086         if (p->p_sysent->sv_mask)
1087                 code &= p->p_sysent->sv_mask;
1088
1089         if (code >= p->p_sysent->sv_size)
1090                 callp = &p->p_sysent->sv_table[0];
1091         else
1092                 callp = &p->p_sysent->sv_table[code];
1093
1094         narg = callp->sy_narg & SYF_ARGMASK;
1095
1096         /*
1097          * On x86_64 we get up to six arguments in registers. The rest are
1098          * on the stack. The first six members of 'struct trapframe' happen
1099          * to be the registers used to pass arguments, in exactly the right
1100          * order.
1101          */
1102         argp = &frame->tf_rdi;
1103         argp += reg;
1104         argsdst = (register_t *)(&args.nosys.sysmsg + 1);
1105         /*
1106          * JG can we overflow the space pointed to by 'argsdst'
1107          * either with 'bcopy' or with 'copyin'?
1108          */
1109         bcopy(argp, argsdst, sizeof(register_t) * regcnt);
1110         /*
1111          * copyin is MP aware, but the tracing code is not
1112          */
1113         if (narg > regcnt) {
1114                 KASSERT(params != NULL, ("copyin args with no params!"));
1115                 error = copyin(params, &argsdst[regcnt],
1116                         (narg - regcnt) * sizeof(register_t));
1117                 if (error) {
1118 #ifdef KTRACE
1119                         if (KTRPOINT(td, KTR_SYSCALL)) {
1120                                 MAKEMPSAFE(have_mplock);
1121                                 
1122                                 ktrsyscall(lp, code, narg,
1123                                         (void *)(&args.nosys.sysmsg + 1));
1124                         }
1125 #endif
1126                         goto bad;
1127                 }
1128         }
1129
1130 #ifdef KTRACE
1131         if (KTRPOINT(td, KTR_SYSCALL)) {
1132                 MAKEMPSAFE(have_mplock);
1133                 ktrsyscall(lp, code, narg, (void *)(&args.nosys.sysmsg + 1));
1134         }
1135 #endif
1136
1137         /*
1138          * Default return value is 0 (will be copied to %rax).  Double-value
1139          * returns use %rax and %rdx.  %rdx is left unchanged for system
1140          * calls which return only one result.
1141          */
1142         args.sysmsg_fds[0] = 0;
1143         args.sysmsg_fds[1] = frame->tf_rdx;
1144
1145         /*
1146          * The syscall might manipulate the trap frame. If it does it
1147          * will probably return EJUSTRETURN.
1148          */
1149         args.sysmsg_frame = frame;
1150
1151         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1152
1153         /*
1154          * NOTE: All system calls run MPSAFE now.  The system call itself
1155          *       is responsible for getting the MP lock.
1156          */
1157         error = (*callp->sy_call)(&args);
1158
1159 out:
1160         /*
1161          * MP SAFE (we may or may not have the MP lock at this point)
1162          */
1163         //kprintf("SYSMSG %d ", error);
1164         switch (error) {
1165         case 0:
1166                 /*
1167                  * Reinitialize proc pointer `p' as it may be different
1168                  * if this is a child returning from fork syscall.
1169                  */
1170                 p = curproc;
1171                 lp = curthread->td_lwp;
1172                 frame->tf_rax = args.sysmsg_fds[0];
1173                 frame->tf_rdx = args.sysmsg_fds[1];
1174                 frame->tf_rflags &= ~PSL_C;
1175                 break;
1176         case ERESTART:
1177                 /*
1178                  * Reconstruct pc, we know that 'syscall' is 2 bytes.
1179                  * We have to do a full context restore so that %r10
1180                  * (which was holding the value of %rcx) is restored for
1181                  * the next iteration.
1182                  */
1183                 frame->tf_rip -= frame->tf_err;
1184                 frame->tf_r10 = frame->tf_rcx;
1185                 break;
1186         case EJUSTRETURN:
1187                 break;
1188         case EASYNC:
1189                 panic("Unexpected EASYNC return value (for now)");
1190         default:
1191 bad:
1192                 if (p->p_sysent->sv_errsize) {
1193                         if (error >= p->p_sysent->sv_errsize)
1194                                 error = -1;     /* XXX */
1195                         else
1196                                 error = p->p_sysent->sv_errtbl[error];
1197                 }
1198                 frame->tf_rax = error;
1199                 frame->tf_rflags |= PSL_C;
1200                 break;
1201         }
1202
1203         /*
1204          * Traced syscall.  trapsignal() is not MP aware.
1205          */
1206         if (orig_tf_rflags & PSL_T) {
1207                 MAKEMPSAFE(have_mplock);
1208                 frame->tf_rflags &= ~PSL_T;
1209                 trapsignal(lp, SIGTRAP, TRAP_TRACE);
1210         }
1211
1212         /*
1213          * Handle reschedule and other end-of-syscall issues
1214          */
1215         userret(lp, frame, sticks);
1216
1217 #ifdef KTRACE
1218         if (KTRPOINT(td, KTR_SYSRET)) {
1219                 MAKEMPSAFE(have_mplock);
1220                 ktrsysret(lp, code, error, args.sysmsg_result);
1221         }
1222 #endif
1223
1224         /*
1225          * This works because errno is findable through the
1226          * register set.  If we ever support an emulation where this
1227          * is not the case, this code will need to be revisited.
1228          */
1229         STOPEVENT(p, S_SCX, code);
1230
1231         userexit(lp);
1232 #ifdef SMP
1233         /*
1234          * Release the MP lock if we had to get it
1235          */
1236         KASSERT(td->td_mpcount == have_mplock, 
1237                 ("badmpcount syscall2/end from %p", (void *)frame->tf_rip));
1238         if (have_mplock)
1239                 rel_mplock();
1240 #endif
1241         KTR_LOG(kernentry_syscall_ret, p->p_pid, lp->lwp_tid, error);
1242 #ifdef INVARIANTS
1243         KASSERT(crit_count == td->td_critcount,
1244                 ("syscall: critical section count mismatch! %d/%d",
1245                 crit_count, td->td_pri));
1246 #endif
1247 }
1248
1249 /*
1250  * NOTE: mplock not held at any point
1251  */
1252 void
1253 fork_return(struct lwp *lp, struct trapframe *frame)
1254 {
1255         frame->tf_rax = 0;              /* Child returns zero */
1256         frame->tf_rflags &= ~PSL_C;     /* success */
1257         frame->tf_rdx = 1;
1258
1259         generic_lwp_return(lp, frame);
1260         KTR_LOG(kernentry_fork_ret, lp->lwp_proc->p_pid, lp->lwp_tid);
1261 }
1262
1263 /*
1264  * Simplified back end of syscall(), used when returning from fork()
1265  * directly into user mode.
1266  *
1267  * This code will return back into the fork trampoline code which then
1268  * runs doreti.
1269  *
1270  * NOTE: The mplock is not held at any point.
1271  */
1272 void
1273 generic_lwp_return(struct lwp *lp, struct trapframe *frame)
1274 {
1275         struct proc *p = lp->lwp_proc;
1276
1277         /*
1278          * Newly forked processes are given a kernel priority.  We have to
1279          * adjust the priority to a normal user priority and fake entry
1280          * into the kernel (call userenter()) to install a passive release
1281          * function just in case userret() decides to stop the process.  This
1282          * can occur when ^Z races a fork.  If we do not install the passive
1283          * release function the current process designation will not be
1284          * released when the thread goes to sleep.
1285          */
1286         lwkt_setpri_self(TDPRI_USER_NORM);
1287         userenter(lp->lwp_thread, p);
1288         userret(lp, frame, 0);
1289 #ifdef KTRACE
1290         if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1291                 ktrsysret(lp, SYS_fork, 0, 0);
1292 #endif
1293         p->p_flag |= P_PASSIVE_ACQ;
1294         userexit(lp);
1295         p->p_flag &= ~P_PASSIVE_ACQ;
1296 }
1297
1298 /*
1299  * If PGEX_FPFAULT is set then set FP_VIRTFP in the PCB to force a T_DNA
1300  * fault (which is then passed back to the virtual kernel) if an attempt is
1301  * made to use the FP unit.
1302  *
1303  * XXX this is a fairly big hack.
1304  */
1305 void
1306 set_vkernel_fp(struct trapframe *frame)
1307 {
1308         struct thread *td = curthread;
1309
1310         if (frame->tf_xflags & PGEX_FPFAULT) {
1311                 td->td_pcb->pcb_flags |= FP_VIRTFP;
1312                 if (mdcpu->gd_npxthread == td)
1313                         npxexit();
1314         } else {
1315                 td->td_pcb->pcb_flags &= ~FP_VIRTFP;
1316         }
1317 }
1318
1319 /*
1320  * Called from vkernel_trap() to fixup the vkernel's syscall
1321  * frame for vmspace_ctl() return.
1322  */
1323 void
1324 cpu_vkernel_trap(struct trapframe *frame, int error)
1325 {
1326         frame->tf_rax = error;
1327         if (error)
1328                 frame->tf_rflags |= PSL_C;
1329         else
1330                 frame->tf_rflags &= ~PSL_C;
1331 }