Fix panics which can occur when killing a threaded program. lwp_exit()
[dragonfly.git] / sys / platform / pc32 / i386 / trap.c
1 /*-
2  * Copyright (C) 1994, David Greenman
3  * Copyright (c) 1990, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * the University of Utah, and William Jolitz.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
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.
24  *
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
35  * SUCH DAMAGE.
36  *
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 $
39  * $DragonFly: src/sys/platform/pc32/i386/trap.c,v 1.111 2008/04/24 08:53:01 dillon Exp $
40  */
41
42 /*
43  * 386 Trap and System call handling
44  */
45
46 #include "use_isa.h"
47 #include "use_npx.h"
48
49 #include "opt_cpu.h"
50 #include "opt_ddb.h"
51 #include "opt_ktrace.h"
52 #include "opt_clock.h"
53 #include "opt_trap.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/proc.h>
58 #include <sys/pioctl.h>
59 #include <sys/kernel.h>
60 #include <sys/resourcevar.h>
61 #include <sys/signalvar.h>
62 #include <sys/signal2.h>
63 #include <sys/syscall.h>
64 #include <sys/sysctl.h>
65 #include <sys/sysent.h>
66 #include <sys/uio.h>
67 #include <sys/vmmeter.h>
68 #include <sys/malloc.h>
69 #ifdef KTRACE
70 #include <sys/ktrace.h>
71 #endif
72 #include <sys/upcall.h>
73 #include <sys/vkernel.h>
74 #include <sys/sysproto.h>
75 #include <sys/sysunion.h>
76
77 #include <vm/vm.h>
78 #include <vm/vm_param.h>
79 #include <sys/lock.h>
80 #include <vm/pmap.h>
81 #include <vm/vm_kern.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_page.h>
84 #include <vm/vm_extern.h>
85
86 #include <machine/cpu.h>
87 #include <machine/md_var.h>
88 #include <machine/pcb.h>
89 #include <machine/smp.h>
90 #include <machine/tss.h>
91 #include <machine/specialreg.h>
92 #include <machine/globaldata.h>
93
94 #include <machine_base/isa/intr_machdep.h>
95
96 #ifdef POWERFAIL_NMI
97 #include <sys/syslog.h>
98 #include <machine/clock.h>
99 #endif
100
101 #include <machine/vm86.h>
102
103 #include <ddb/ddb.h>
104 #include <sys/msgport2.h>
105 #include <sys/thread2.h>
106
107 #ifdef SMP
108
109 #define MAKEMPSAFE(have_mplock)                 \
110         if (have_mplock == 0) {                 \
111                 get_mplock();                   \
112                 have_mplock = 1;                \
113         }
114
115 #else
116
117 #define MAKEMPSAFE(have_mplock)
118
119 #endif
120
121 int (*pmath_emulate) (struct trapframe *);
122
123 extern void trap (struct trapframe *frame);
124 extern int trapwrite (unsigned addr);
125 extern void syscall2 (struct trapframe *frame);
126
127 static int trap_pfault (struct trapframe *, int, vm_offset_t);
128 static void trap_fatal (struct trapframe *, vm_offset_t);
129 void dblfault_handler (void);
130
131 extern inthand_t IDTVEC(syscall);
132
133 #define MAX_TRAP_MSG            28
134 static char *trap_msg[] = {
135         "",                                     /*  0 unused */
136         "privileged instruction fault",         /*  1 T_PRIVINFLT */
137         "",                                     /*  2 unused */
138         "breakpoint instruction fault",         /*  3 T_BPTFLT */
139         "",                                     /*  4 unused */
140         "",                                     /*  5 unused */
141         "arithmetic trap",                      /*  6 T_ARITHTRAP */
142         "system forced exception",              /*  7 T_ASTFLT */
143         "",                                     /*  8 unused */
144         "general protection fault",             /*  9 T_PROTFLT */
145         "trace trap",                           /* 10 T_TRCTRAP */
146         "",                                     /* 11 unused */
147         "page fault",                           /* 12 T_PAGEFLT */
148         "",                                     /* 13 unused */
149         "alignment fault",                      /* 14 T_ALIGNFLT */
150         "",                                     /* 15 unused */
151         "",                                     /* 16 unused */
152         "",                                     /* 17 unused */
153         "integer divide fault",                 /* 18 T_DIVIDE */
154         "non-maskable interrupt trap",          /* 19 T_NMI */
155         "overflow trap",                        /* 20 T_OFLOW */
156         "FPU bounds check fault",               /* 21 T_BOUND */
157         "FPU device not available",             /* 22 T_DNA */
158         "double fault",                         /* 23 T_DOUBLEFLT */
159         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
160         "invalid TSS fault",                    /* 25 T_TSSFLT */
161         "segment not present fault",            /* 26 T_SEGNPFLT */
162         "stack fault",                          /* 27 T_STKFLT */
163         "machine check trap",                   /* 28 T_MCHK */
164 };
165
166 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
167 extern int has_f00f_bug;
168 #endif
169
170 #ifdef DDB
171 static int ddb_on_nmi = 1;
172 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
173         &ddb_on_nmi, 0, "Go to DDB on NMI");
174 #endif
175 static int panic_on_nmi = 1;
176 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
177         &panic_on_nmi, 0, "Panic on NMI");
178 static int fast_release;
179 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
180         &fast_release, 0, "Passive Release was optimal");
181 static int slow_release;
182 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
183         &slow_release, 0, "Passive Release was nonoptimal");
184 #ifdef SMP
185 static int syscall_mpsafe = 1;
186 SYSCTL_INT(_kern, OID_AUTO, syscall_mpsafe, CTLFLAG_RW,
187         &syscall_mpsafe, 0, "Allow MPSAFE marked syscalls to run without BGL");
188 TUNABLE_INT("kern.syscall_mpsafe", &syscall_mpsafe);
189 static int trap_mpsafe = 1;
190 SYSCTL_INT(_kern, OID_AUTO, trap_mpsafe, CTLFLAG_RW,
191         &trap_mpsafe, 0, "Allow traps to mostly run without the BGL");
192 TUNABLE_INT("kern.trap_mpsafe", &trap_mpsafe);
193 #endif
194
195 MALLOC_DEFINE(M_SYSMSG, "sysmsg", "sysmsg structure");
196 extern int max_sysmsg;
197
198 /*
199  * Passive USER->KERNEL transition.  This only occurs if we block in the
200  * kernel while still holding our userland priority.  We have to fixup our
201  * priority in order to avoid potential deadlocks before we allow the system
202  * to switch us to another thread.
203  */
204 static void
205 passive_release(struct thread *td)
206 {
207         struct lwp *lp = td->td_lwp;
208
209         td->td_release = NULL;
210         lwkt_setpri_self(TDPRI_KERN_USER);
211         lp->lwp_proc->p_usched->release_curproc(lp);
212 }
213
214 /*
215  * userenter() passively intercepts the thread switch function to increase
216  * the thread priority from a user priority to a kernel priority, reducing
217  * syscall and trap overhead for the case where no switch occurs.
218  */
219
220 static __inline void
221 userenter(struct thread *curtd)
222 {
223         curtd->td_release = passive_release;
224 }
225
226 /*
227  * Handle signals, upcalls, profiling, and other AST's and/or tasks that
228  * must be completed before we can return to or try to return to userland.
229  *
230  * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
231  * arithmatic on the delta calculation so the absolute tick values are
232  * truncated to an integer.
233  */
234 static void
235 userret(struct lwp *lp, struct trapframe *frame, int sticks)
236 {
237         struct proc *p = lp->lwp_proc;
238         int sig;
239
240         /*
241          * Charge system time if profiling.  Note: times are in microseconds.
242          * This may do a copyout and block, so do it first even though it
243          * means some system time will be charged as user time.
244          */
245         if (p->p_flag & P_PROFIL) {
246                 addupc_task(p, frame->tf_eip, 
247                         (u_int)((int)lp->lwp_thread->td_sticks - sticks));
248         }
249
250 recheck:
251         /*
252          * If the jungle wants us dead, so be it.
253          */
254         if (lp->lwp_flag & LWP_WEXIT) {
255                 get_mplock();
256                 lwp_exit(0);
257                 rel_mplock(); /* NOT REACHED */
258         }
259
260         /*
261          * Block here if we are in a stopped state.
262          */
263         if (p->p_stat == SSTOP) {
264                 get_mplock();
265                 tstop();
266                 rel_mplock();
267                 goto recheck;
268         }
269
270         /*
271          * Post any pending upcalls.  If running a virtual kernel be sure
272          * to restore the virtual kernel's vmspace before posting the upcall.
273          */
274         if (p->p_flag & P_UPCALLPEND) {
275                 p->p_flag &= ~P_UPCALLPEND;
276                 get_mplock();
277                 postupcall(lp);
278                 rel_mplock();
279                 goto recheck;
280         }
281
282         /*
283          * Post any pending signals.  If running a virtual kernel be sure
284          * to restore the virtual kernel's vmspace before posting the signal.
285          */
286         if ((sig = CURSIG(lp)) != 0) {
287                 get_mplock();
288                 postsig(sig);
289                 rel_mplock();
290                 goto recheck;
291         }
292
293         /*
294          * block here if we are swapped out, but still process signals
295          * (such as SIGKILL).  proc0 (the swapin scheduler) is already
296          * aware of our situation, we do not have to wake it up.
297          */
298         if (p->p_flag & P_SWAPPEDOUT) {
299                 get_mplock();
300                 p->p_flag |= P_SWAPWAIT;
301                 swapin_request();
302                 if (p->p_flag & P_SWAPWAIT)
303                         tsleep(p, PCATCH, "SWOUT", 0);
304                 p->p_flag &= ~P_SWAPWAIT;
305                 rel_mplock();
306                 goto recheck;
307         }
308
309         /*
310          * Make sure postsig() handled request to restore old signal mask after
311          * running signal handler.
312          */
313         KKASSERT((lp->lwp_flag & LWP_OLDMASK) == 0);
314 }
315
316 /*
317  * Cleanup from userenter and any passive release that might have occured.
318  * We must reclaim the current-process designation before we can return
319  * to usermode.  We also handle both LWKT and USER reschedule requests.
320  */
321 static __inline void
322 userexit(struct lwp *lp)
323 {
324         struct thread *td = lp->lwp_thread;
325         globaldata_t gd = td->td_gd;
326
327 #if 0
328         /*
329          * If a user reschedule is requested force a new process to be
330          * chosen by releasing the current process.  Our process will only
331          * be chosen again if it has a considerably better priority.
332          */
333         if (user_resched_wanted())
334                 lp->lwp_proc->p_usched->release_curproc(lp);
335 #endif
336
337         /*
338          * Handle a LWKT reschedule request first.  Since our passive release
339          * is still in place we do not have to do anything special.
340          */
341         if (lwkt_resched_wanted())
342                 lwkt_switch();
343
344         /*
345          * Acquire the current process designation for this user scheduler
346          * on this cpu.  This will also handle any user-reschedule requests.
347          */
348         lp->lwp_proc->p_usched->acquire_curproc(lp);
349         /* We may have switched cpus on acquisition */
350         gd = td->td_gd;
351
352         /*
353          * Reduce our priority in preparation for a return to userland.  If
354          * our passive release function was still in place, our priority was
355          * never raised and does not need to be reduced.
356          */
357         if (td->td_release == NULL)
358                 lwkt_setpri_self(TDPRI_USER_NORM);
359         td->td_release = NULL;
360
361         /*
362          * After reducing our priority there might be other kernel-level
363          * LWKTs that now have a greater priority.  Run them as necessary.
364          * We don't have to worry about losing cpu to userland because
365          * we still control the current-process designation and we no longer
366          * have a passive release function installed.
367          */
368         if (lwkt_checkpri_self())
369                 lwkt_switch();
370 }
371
372 /*
373  * Exception, fault, and trap interface to the kernel.
374  * This common code is called from assembly language IDT gate entry
375  * routines that prepare a suitable stack frame, and restore this
376  * frame after the exception has been processed.
377  *
378  * This function is also called from doreti in an interlock to handle ASTs.
379  * For example:  hardwareint->INTROUTINE->(set ast)->doreti->trap
380  *
381  * NOTE!  We have to retrieve the fault address prior to obtaining the
382  * MP lock because get_mplock() may switch out.  YYY cr2 really ought
383  * to be retrieved by the assembly code, not here.
384  *
385  * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
386  * if an attempt is made to switch from a fast interrupt or IPI.  This is
387  * necessary to properly take fatal kernel traps on SMP machines if 
388  * get_mplock() has to block.
389  */
390
391 void
392 trap(struct trapframe *frame)
393 {
394         struct globaldata *gd = mycpu;
395         struct thread *td = gd->gd_curthread;
396         struct lwp *lp = td->td_lwp;
397         struct proc *p;
398         int sticks = 0;
399         int i = 0, ucode = 0, type, code;
400 #ifdef SMP
401         int have_mplock = 0;
402 #endif
403 #ifdef INVARIANTS
404         int crit_count = td->td_pri & ~TDPRI_MASK;
405 #endif
406         vm_offset_t eva;
407
408         p = td->td_proc;
409 #ifdef DDB
410         if (db_active) {
411                 eva = (frame->tf_trapno == T_PAGEFLT ? rcr2() : 0);
412                 ++gd->gd_trap_nesting_level;
413                 MAKEMPSAFE(have_mplock);
414                 trap_fatal(frame, eva);
415                 --gd->gd_trap_nesting_level;
416                 goto out2;
417         }
418 #endif
419
420         eva = 0;
421         ++gd->gd_trap_nesting_level;
422         if (frame->tf_trapno == T_PAGEFLT) {
423                 /*
424                  * For some Cyrix CPUs, %cr2 is clobbered by interrupts.
425                  * This problem is worked around by using an interrupt
426                  * gate for the pagefault handler.  We are finally ready
427                  * to read %cr2 and then must reenable interrupts.
428                  *
429                  * XXX this should be in the switch statement, but the
430                  * NO_FOOF_HACK and VM86 goto and ifdefs obfuscate the
431                  * flow of control too much for this to be obviously
432                  * correct.
433                  */
434                 eva = rcr2();
435                 cpu_enable_intr();
436         }
437 #ifdef SMP
438         if (trap_mpsafe == 0)
439                 MAKEMPSAFE(have_mplock);
440 #endif
441
442         --gd->gd_trap_nesting_level;
443
444         if (!(frame->tf_eflags & PSL_I)) {
445                 /*
446                  * Buggy application or kernel code has disabled interrupts
447                  * and then trapped.  Enabling interrupts now is wrong, but
448                  * it is better than running with interrupts disabled until
449                  * they are accidentally enabled later.
450                  */
451                 type = frame->tf_trapno;
452                 if (ISPL(frame->tf_cs)==SEL_UPL || (frame->tf_eflags & PSL_VM)) {
453                         MAKEMPSAFE(have_mplock);
454                         kprintf(
455                             "pid %ld (%s): trap %d with interrupts disabled\n",
456                             (long)curproc->p_pid, curproc->p_comm, type);
457                 } else if (type != T_BPTFLT && type != T_TRCTRAP) {
458                         /*
459                          * XXX not quite right, since this may be for a
460                          * multiple fault in user mode.
461                          */
462                         MAKEMPSAFE(have_mplock);
463                         kprintf("kernel trap %d with interrupts disabled\n",
464                             type);
465                 }
466                 cpu_enable_intr();
467         }
468
469 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
470 restart:
471 #endif
472         type = frame->tf_trapno;
473         code = frame->tf_err;
474
475         if (in_vm86call) {
476                 if (frame->tf_eflags & PSL_VM &&
477                     (type == T_PROTFLT || type == T_STKFLT)) {
478 #ifdef SMP
479                         KKASSERT(td->td_mpcount > 0);
480 #endif
481                         i = vm86_emulate((struct vm86frame *)frame);
482 #ifdef SMP
483                         KKASSERT(td->td_mpcount > 0);
484 #endif
485                         if (i != 0) {
486                                 /*
487                                  * returns to original process
488                                  */
489 #ifdef SMP
490                                 vm86_trap((struct vm86frame *)frame,
491                                           have_mplock);
492 #else
493                                 vm86_trap((struct vm86frame *)frame, 0);
494 #endif
495                                 KKASSERT(0); /* NOT REACHED */
496                         }
497                         goto out2;
498                 }
499                 switch (type) {
500                         /*
501                          * these traps want either a process context, or
502                          * assume a normal userspace trap.
503                          */
504                 case T_PROTFLT:
505                 case T_SEGNPFLT:
506                         trap_fatal(frame, eva);
507                         goto out2;
508                 case T_TRCTRAP:
509                         type = T_BPTFLT;        /* kernel breakpoint */
510                         /* FALL THROUGH */
511                 }
512                 goto kernel_trap;       /* normal kernel trap handling */
513         }
514
515         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
516                 /* user trap */
517
518                 userenter(td);
519
520                 sticks = (int)td->td_sticks;
521                 lp->lwp_md.md_regs = frame;
522
523                 switch (type) {
524                 case T_PRIVINFLT:       /* privileged instruction fault */
525                         ucode = type;
526                         i = SIGILL;
527                         break;
528
529                 case T_BPTFLT:          /* bpt instruction fault */
530                 case T_TRCTRAP:         /* trace trap */
531                         frame->tf_eflags &= ~PSL_T;
532                         i = SIGTRAP;
533                         break;
534
535                 case T_ARITHTRAP:       /* arithmetic trap */
536                         ucode = code;
537                         i = SIGFPE;
538                         break;
539
540                 case T_ASTFLT:          /* Allow process switch */
541                         mycpu->gd_cnt.v_soft++;
542                         if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
543                                 atomic_clear_int_nonlocked(&mycpu->gd_reqflags,
544                                             RQF_AST_OWEUPC);
545                                 addupc_task(p, p->p_prof.pr_addr,
546                                             p->p_prof.pr_ticks);
547                         }
548                         goto out;
549
550                         /*
551                          * The following two traps can happen in
552                          * vm86 mode, and, if so, we want to handle
553                          * them specially.
554                          */
555                 case T_PROTFLT:         /* general protection fault */
556                 case T_STKFLT:          /* stack fault */
557                         if (frame->tf_eflags & PSL_VM) {
558                                 i = vm86_emulate((struct vm86frame *)frame);
559                                 if (i == 0)
560                                         goto out;
561                                 break;
562                         }
563                         /* FALL THROUGH */
564
565                 case T_SEGNPFLT:        /* segment not present fault */
566                 case T_TSSFLT:          /* invalid TSS fault */
567                 case T_DOUBLEFLT:       /* double fault */
568                 default:
569                         ucode = code + BUS_SEGM_FAULT ;
570                         i = SIGBUS;
571                         break;
572
573                 case T_PAGEFLT:         /* page fault */
574                         MAKEMPSAFE(have_mplock);
575                         i = trap_pfault(frame, TRUE, eva);
576                         if (i == -1)
577                                 goto out;
578 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
579                         if (i == -2)
580                                 goto restart;
581 #endif
582                         if (i == 0)
583                                 goto out;
584
585                         ucode = T_PAGEFLT;
586                         break;
587
588                 case T_DIVIDE:          /* integer divide fault */
589                         ucode = FPE_INTDIV;
590                         i = SIGFPE;
591                         break;
592
593 #if NISA > 0
594                 case T_NMI:
595                         MAKEMPSAFE(have_mplock);
596 #ifdef POWERFAIL_NMI
597                         goto handle_powerfail;
598 #else /* !POWERFAIL_NMI */
599                         /* machine/parity/power fail/"kitchen sink" faults */
600                         if (isa_nmi(code) == 0) {
601 #ifdef DDB
602                                 /*
603                                  * NMI can be hooked up to a pushbutton
604                                  * for debugging.
605                                  */
606                                 if (ddb_on_nmi) {
607                                         kprintf ("NMI ... going to debugger\n");
608                                         kdb_trap (type, 0, frame);
609                                 }
610 #endif /* DDB */
611                                 goto out2;
612                         } else if (panic_on_nmi)
613                                 panic("NMI indicates hardware failure");
614                         break;
615 #endif /* POWERFAIL_NMI */
616 #endif /* NISA > 0 */
617
618                 case T_OFLOW:           /* integer overflow fault */
619                         ucode = FPE_INTOVF;
620                         i = SIGFPE;
621                         break;
622
623                 case T_BOUND:           /* bounds check fault */
624                         ucode = FPE_FLTSUB;
625                         i = SIGFPE;
626                         break;
627
628                 case T_DNA:
629                         /*
630                          * Virtual kernel intercept - pass the DNA exception
631                          * to the virtual kernel if it asked to handle it.
632                          * This occurs when the virtual kernel is holding
633                          * onto the FP context for a different emulated
634                          * process then the one currently running.
635                          *
636                          * We must still call npxdna() since we may have
637                          * saved FP state that the virtual kernel needs
638                          * to hand over to a different emulated process.
639                          */
640                         if (lp->lwp_vkernel && lp->lwp_vkernel->ve &&
641                             (td->td_pcb->pcb_flags & FP_VIRTFP)
642                         ) {
643                                 npxdna();
644                                 break;
645                         }
646
647 #if NNPX > 0
648                         /* 
649                          * The kernel may have switched out the FP unit's
650                          * state, causing the user process to take a fault
651                          * when it tries to use the FP unit.  Restore the
652                          * state here
653                          */
654                         if (npxdna())
655                                 goto out;
656 #endif
657                         if (!pmath_emulate) {
658                                 i = SIGFPE;
659                                 ucode = FPE_FPU_NP_TRAP;
660                                 break;
661                         }
662                         i = (*pmath_emulate)(frame);
663                         if (i == 0) {
664                                 if (!(frame->tf_eflags & PSL_T))
665                                         goto out2;
666                                 frame->tf_eflags &= ~PSL_T;
667                                 i = SIGTRAP;
668                         }
669                         /* else ucode = emulator_only_knows() XXX */
670                         break;
671
672                 case T_FPOPFLT:         /* FPU operand fetch fault */
673                         ucode = T_FPOPFLT;
674                         i = SIGILL;
675                         break;
676
677                 case T_XMMFLT:          /* SIMD floating-point exception */
678                         ucode = 0; /* XXX */
679                         i = SIGFPE;
680                         break;
681                 }
682         } else {
683 kernel_trap:
684                 /* kernel trap */
685
686                 switch (type) {
687                 case T_PAGEFLT:                 /* page fault */
688                         MAKEMPSAFE(have_mplock);
689                         trap_pfault(frame, FALSE, eva);
690                         goto out2;
691
692                 case T_DNA:
693 #if NNPX > 0
694                         /*
695                          * The kernel may be using npx for copying or other
696                          * purposes.
697                          */
698                         if (npxdna())
699                                 goto out2;
700 #endif
701                         break;
702
703                 case T_PROTFLT:         /* general protection fault */
704                 case T_SEGNPFLT:        /* segment not present fault */
705                         /*
706                          * Invalid segment selectors and out of bounds
707                          * %eip's and %esp's can be set up in user mode.
708                          * This causes a fault in kernel mode when the
709                          * kernel tries to return to user mode.  We want
710                          * to get this fault so that we can fix the
711                          * problem here and not have to check all the
712                          * selectors and pointers when the user changes
713                          * them.
714                          */
715 #define MAYBE_DORETI_FAULT(where, whereto)                              \
716         do {                                                            \
717                 if (frame->tf_eip == (int)where) {                      \
718                         frame->tf_eip = (int)whereto;                   \
719                         goto out2;                                      \
720                 }                                                       \
721         } while (0)
722                         if (mycpu->gd_intr_nesting_level == 0) {
723                                 /*
724                                  * Invalid %fs's and %gs's can be created using
725                                  * procfs or PT_SETREGS or by invalidating the
726                                  * underlying LDT entry.  This causes a fault
727                                  * in kernel mode when the kernel attempts to
728                                  * switch contexts.  Lose the bad context
729                                  * (XXX) so that we can continue, and generate
730                                  * a signal.
731                                  */
732                                 MAYBE_DORETI_FAULT(doreti_iret,
733                                                    doreti_iret_fault);
734                                 MAYBE_DORETI_FAULT(doreti_popl_ds,
735                                                    doreti_popl_ds_fault);
736                                 MAYBE_DORETI_FAULT(doreti_popl_es,
737                                                    doreti_popl_es_fault);
738                                 MAYBE_DORETI_FAULT(doreti_popl_fs,
739                                                    doreti_popl_fs_fault);
740                                 MAYBE_DORETI_FAULT(doreti_popl_gs,
741                                                    doreti_popl_gs_fault);
742                                 if (td->td_pcb->pcb_onfault) {
743                                         frame->tf_eip = 
744                                             (register_t)td->td_pcb->pcb_onfault;
745                                         goto out2;
746                                 }
747                         }
748                         break;
749
750                 case T_TSSFLT:
751                         /*
752                          * PSL_NT can be set in user mode and isn't cleared
753                          * automatically when the kernel is entered.  This
754                          * causes a TSS fault when the kernel attempts to
755                          * `iret' because the TSS link is uninitialized.  We
756                          * want to get this fault so that we can fix the
757                          * problem here and not every time the kernel is
758                          * entered.
759                          */
760                         if (frame->tf_eflags & PSL_NT) {
761                                 frame->tf_eflags &= ~PSL_NT;
762                                 goto out2;
763                         }
764                         break;
765
766                 case T_TRCTRAP:  /* trace trap */
767                         if (frame->tf_eip == (int)IDTVEC(syscall)) {
768                                 /*
769                                  * We've just entered system mode via the
770                                  * syscall lcall.  Continue single stepping
771                                  * silently until the syscall handler has
772                                  * saved the flags.
773                                  */
774                                 goto out2;
775                         }
776                         if (frame->tf_eip == (int)IDTVEC(syscall) + 1) {
777                                 /*
778                                  * The syscall handler has now saved the
779                                  * flags.  Stop single stepping it.
780                                  */
781                                 frame->tf_eflags &= ~PSL_T;
782                                 goto out2;
783                         }
784                         /*
785                          * Ignore debug register trace traps due to
786                          * accesses in the user's address space, which
787                          * can happen under several conditions such as
788                          * if a user sets a watchpoint on a buffer and
789                          * then passes that buffer to a system call.
790                          * We still want to get TRCTRAPS for addresses
791                          * in kernel space because that is useful when
792                          * debugging the kernel.
793                          */
794                         if (user_dbreg_trap()) {
795                                 /*
796                                  * Reset breakpoint bits because the
797                                  * processor doesn't
798                                  */
799                                 load_dr6(rdr6() & 0xfffffff0);
800                                 goto out2;
801                         }
802                         /*
803                          * Fall through (TRCTRAP kernel mode, kernel address)
804                          */
805                 case T_BPTFLT:
806                         /*
807                          * If DDB is enabled, let it handle the debugger trap.
808                          * Otherwise, debugger traps "can't happen".
809                          */
810 #ifdef DDB
811                         MAKEMPSAFE(have_mplock);
812                         if (kdb_trap (type, 0, frame))
813                                 goto out2;
814 #endif
815                         break;
816
817 #if NISA > 0
818                 case T_NMI:
819                         MAKEMPSAFE(have_mplock);
820 #ifdef POWERFAIL_NMI
821 #ifndef TIMER_FREQ
822 #  define TIMER_FREQ 1193182
823 #endif
824         handle_powerfail:
825                 {
826                   static unsigned lastalert = 0;
827
828                   if(time_second - lastalert > 10)
829                     {
830                       log(LOG_WARNING, "NMI: power fail\n");
831                       sysbeep(TIMER_FREQ/880, hz);
832                       lastalert = time_second;
833                     }
834                     /* YYY mp count */
835                   goto out2;
836                 }
837 #else /* !POWERFAIL_NMI */
838                         /* machine/parity/power fail/"kitchen sink" faults */
839                         if (isa_nmi(code) == 0) {
840 #ifdef DDB
841                                 /*
842                                  * NMI can be hooked up to a pushbutton
843                                  * for debugging.
844                                  */
845                                 if (ddb_on_nmi) {
846                                         kprintf ("NMI ... going to debugger\n");
847                                         kdb_trap (type, 0, frame);
848                                 }
849 #endif /* DDB */
850                                 goto out2;
851                         } else if (panic_on_nmi == 0)
852                                 goto out2;
853                         /* FALL THROUGH */
854 #endif /* POWERFAIL_NMI */
855 #endif /* NISA > 0 */
856                 }
857
858                 MAKEMPSAFE(have_mplock);
859                 trap_fatal(frame, eva);
860                 goto out2;
861         }
862
863         /*
864          * Virtual kernel intercept - if the fault is directly related to a
865          * VM context managed by a virtual kernel then let the virtual kernel
866          * handle it.
867          */
868         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
869                 vkernel_trap(lp, frame);
870                 goto out;
871         }
872
873         /*
874          * Translate fault for emulators (e.g. Linux) 
875          */
876         if (*p->p_sysent->sv_transtrap)
877                 i = (*p->p_sysent->sv_transtrap)(i, type);
878
879         MAKEMPSAFE(have_mplock);
880         trapsignal(lp, i, ucode);
881
882 #ifdef DEBUG
883         if (type <= MAX_TRAP_MSG) {
884                 uprintf("fatal process exception: %s",
885                         trap_msg[type]);
886                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
887                         uprintf(", fault VA = 0x%lx", (u_long)eva);
888                 uprintf("\n");
889         }
890 #endif
891
892 out:
893 #ifdef SMP
894         if (ISPL(frame->tf_cs) == SEL_UPL)
895                 KASSERT(td->td_mpcount == have_mplock, ("badmpcount trap/end from %p", (void *)frame->tf_eip));
896 #endif
897         userret(lp, frame, sticks);
898         userexit(lp);
899 out2:   ;
900 #ifdef SMP
901         if (have_mplock)
902                 rel_mplock();
903 #endif
904 #ifdef INVARIANTS
905         KASSERT(crit_count == (td->td_pri & ~TDPRI_MASK),
906                 ("syscall: critical section count mismatch! %d/%d",
907                 crit_count / TDPRI_CRIT, td->td_pri / TDPRI_CRIT));
908 #endif
909 }
910
911 int
912 trap_pfault(struct trapframe *frame, int usermode, vm_offset_t eva)
913 {
914         vm_offset_t va;
915         struct vmspace *vm = NULL;
916         vm_map_t map = 0;
917         int rv = 0;
918         vm_prot_t ftype;
919         thread_t td = curthread;
920         struct lwp *lp = td->td_lwp;
921
922         va = trunc_page(eva);
923         if (va >= KERNBASE) {
924                 /*
925                  * Don't allow user-mode faults in kernel address space.
926                  * An exception:  if the faulting address is the invalid
927                  * instruction entry in the IDT, then the Intel Pentium
928                  * F00F bug workaround was triggered, and we need to
929                  * treat it is as an illegal instruction, and not a page
930                  * fault.
931                  */
932 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
933                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
934                         frame->tf_trapno = T_PRIVINFLT;
935                         return -2;
936                 }
937 #endif
938                 if (usermode)
939                         goto nogo;
940
941                 map = &kernel_map;
942         } else {
943                 /*
944                  * This is a fault on non-kernel virtual memory.
945                  * vm is initialized above to NULL. If curproc is NULL
946                  * or curproc->p_vmspace is NULL the fault is fatal.
947                  */
948                 if (lp != NULL)
949                         vm = lp->lwp_vmspace;
950
951                 if (vm == NULL)
952                         goto nogo;
953
954                 map = &vm->vm_map;
955         }
956
957         if (frame->tf_err & PGEX_W)
958                 ftype = VM_PROT_WRITE;
959         else
960                 ftype = VM_PROT_READ;
961
962         if (map != &kernel_map) {
963                 /*
964                  * Keep swapout from messing with us during this
965                  *      critical time.
966                  */
967                 PHOLD(lp->lwp_proc);
968
969                 /*
970                  * Grow the stack if necessary
971                  */
972                 /* grow_stack returns false only if va falls into
973                  * a growable stack region and the stack growth
974                  * fails.  It returns true if va was not within
975                  * a growable stack region, or if the stack 
976                  * growth succeeded.
977                  */
978                 if (!grow_stack(lp->lwp_proc, va)) {
979                         rv = KERN_FAILURE;
980                         PRELE(lp->lwp_proc);
981                         goto nogo;
982                 }
983
984                 /* Fault in the user page: */
985                 rv = vm_fault(map, va, ftype,
986                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
987                                                       : VM_FAULT_NORMAL);
988
989                 PRELE(lp->lwp_proc);
990         } else {
991                 /*
992                  * Don't have to worry about process locking or stacks in the kernel.
993                  */
994                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
995         }
996
997         if (rv == KERN_SUCCESS)
998                 return (0);
999 nogo:
1000         if (!usermode) {
1001                 if (td->td_gd->gd_intr_nesting_level == 0 &&
1002                     td->td_pcb->pcb_onfault) {
1003                         frame->tf_eip = (register_t)td->td_pcb->pcb_onfault;
1004                         return (0);
1005                 }
1006                 trap_fatal(frame, eva);
1007                 return (-1);
1008         }
1009
1010         /* kludge to pass faulting virtual address to sendsig */
1011         frame->tf_xflags = frame->tf_err;
1012         frame->tf_err = eva;
1013
1014         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
1015 }
1016
1017 static void
1018 trap_fatal(struct trapframe *frame, vm_offset_t eva)
1019 {
1020         int code, type, ss, esp;
1021         struct soft_segment_descriptor softseg;
1022
1023         code = frame->tf_err;
1024         type = frame->tf_trapno;
1025         sdtossd(&gdt[mycpu->gd_cpuid * NGDT + IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
1026
1027         if (type <= MAX_TRAP_MSG)
1028                 kprintf("\n\nFatal trap %d: %s while in %s mode\n",
1029                         type, trap_msg[type],
1030                         frame->tf_eflags & PSL_VM ? "vm86" :
1031                         ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
1032 #ifdef SMP
1033         /* three separate prints in case of a trap on an unmapped page */
1034         kprintf("mp_lock = %08x; ", mp_lock);
1035         kprintf("cpuid = %d; ", mycpu->gd_cpuid);
1036         kprintf("lapic.id = %08x\n", lapic.id);
1037 #endif
1038         if (type == T_PAGEFLT) {
1039                 kprintf("fault virtual address  = 0x%x\n", eva);
1040                 kprintf("fault code             = %s %s, %s\n",
1041                         code & PGEX_U ? "user" : "supervisor",
1042                         code & PGEX_W ? "write" : "read",
1043                         code & PGEX_P ? "protection violation" : "page not present");
1044         }
1045         kprintf("instruction pointer    = 0x%x:0x%x\n",
1046                frame->tf_cs & 0xffff, frame->tf_eip);
1047         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
1048                 ss = frame->tf_ss & 0xffff;
1049                 esp = frame->tf_esp;
1050         } else {
1051                 ss = GSEL(GDATA_SEL, SEL_KPL);
1052                 esp = (int)&frame->tf_esp;
1053         }
1054         kprintf("stack pointer          = 0x%x:0x%x\n", ss, esp);
1055         kprintf("frame pointer          = 0x%x:0x%x\n", ss, frame->tf_ebp);
1056         kprintf("code segment           = base 0x%x, limit 0x%x, type 0x%x\n",
1057                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1058         kprintf("                       = DPL %d, pres %d, def32 %d, gran %d\n",
1059                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
1060                softseg.ssd_gran);
1061         kprintf("processor eflags       = ");
1062         if (frame->tf_eflags & PSL_T)
1063                 kprintf("trace trap, ");
1064         if (frame->tf_eflags & PSL_I)
1065                 kprintf("interrupt enabled, ");
1066         if (frame->tf_eflags & PSL_NT)
1067                 kprintf("nested task, ");
1068         if (frame->tf_eflags & PSL_RF)
1069                 kprintf("resume, ");
1070         if (frame->tf_eflags & PSL_VM)
1071                 kprintf("vm86, ");
1072         kprintf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1073         kprintf("current process                = ");
1074         if (curproc) {
1075                 kprintf("%lu (%s)\n",
1076                     (u_long)curproc->p_pid, curproc->p_comm ?
1077                     curproc->p_comm : "");
1078         } else {
1079                 kprintf("Idle\n");
1080         }
1081         kprintf("current thread          = pri %d ", curthread->td_pri);
1082         if (curthread->td_pri >= TDPRI_CRIT)
1083                 kprintf("(CRIT)");
1084         kprintf("\n");
1085 #ifdef SMP
1086 /**
1087  *  XXX FIXME:
1088  *      we probably SHOULD have stopped the other CPUs before now!
1089  *      another CPU COULD have been touching cpl at this moment...
1090  */
1091         kprintf(" <- SMP: XXX");
1092 #endif
1093         kprintf("\n");
1094
1095 #ifdef KDB
1096         if (kdb_trap(&psl))
1097                 return;
1098 #endif
1099 #ifdef DDB
1100         if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1101                 return;
1102 #endif
1103         kprintf("trap number            = %d\n", type);
1104         if (type <= MAX_TRAP_MSG)
1105                 panic("%s", trap_msg[type]);
1106         else
1107                 panic("unknown/reserved trap");
1108 }
1109
1110 /*
1111  * Double fault handler. Called when a fault occurs while writing
1112  * a frame for a trap/exception onto the stack. This usually occurs
1113  * when the stack overflows (such is the case with infinite recursion,
1114  * for example).
1115  *
1116  * XXX Note that the current PTD gets replaced by IdlePTD when the
1117  * task switch occurs. This means that the stack that was active at
1118  * the time of the double fault is not available at <kstack> unless
1119  * the machine was idle when the double fault occurred. The downside
1120  * of this is that "trace <ebp>" in ddb won't work.
1121  */
1122 void
1123 dblfault_handler(void)
1124 {
1125         struct mdglobaldata *gd = mdcpu;
1126
1127         kprintf("\nFatal double fault:\n");
1128         kprintf("eip = 0x%x\n", gd->gd_common_tss.tss_eip);
1129         kprintf("esp = 0x%x\n", gd->gd_common_tss.tss_esp);
1130         kprintf("ebp = 0x%x\n", gd->gd_common_tss.tss_ebp);
1131 #ifdef SMP
1132         /* three separate prints in case of a trap on an unmapped page */
1133         kprintf("mp_lock = %08x; ", mp_lock);
1134         kprintf("cpuid = %d; ", mycpu->gd_cpuid);
1135         kprintf("lapic.id = %08x\n", lapic.id);
1136 #endif
1137         panic("double fault");
1138 }
1139
1140 /*
1141  * Compensate for 386 brain damage (missing URKR).
1142  * This is a little simpler than the pagefault handler in trap() because
1143  * it the page tables have already been faulted in and high addresses
1144  * are thrown out early for other reasons.
1145  */
1146 int
1147 trapwrite(unsigned addr)
1148 {
1149         struct lwp *lp;
1150         vm_offset_t va;
1151         struct vmspace *vm;
1152         int rv;
1153
1154         va = trunc_page((vm_offset_t)addr);
1155         /*
1156          * XXX - MAX is END.  Changed > to >= for temp. fix.
1157          */
1158         if (va >= VM_MAX_USER_ADDRESS)
1159                 return (1);
1160
1161         lp = curthread->td_lwp;
1162         vm = lp->lwp_vmspace;
1163
1164         PHOLD(lp->lwp_proc);
1165
1166         if (!grow_stack(lp->lwp_proc, va)) {
1167                 PRELE(lp->lwp_proc);
1168                 return (1);
1169         }
1170
1171         /*
1172          * fault the data page
1173          */
1174         rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1175
1176         PRELE(lp->lwp_proc);
1177
1178         if (rv != KERN_SUCCESS)
1179                 return 1;
1180
1181         return (0);
1182 }
1183
1184 /*
1185  *      syscall2 -      MP aware system call request C handler
1186  *
1187  *      A system call is essentially treated as a trap except that the
1188  *      MP lock is not held on entry or return.  We are responsible for
1189  *      obtaining the MP lock if necessary and for handling ASTs
1190  *      (e.g. a task switch) prior to return.
1191  *
1192  *      In general, only simple access and manipulation of curproc and
1193  *      the current stack is allowed without having to hold MP lock.
1194  *
1195  *      MPSAFE - note that large sections of this routine are run without
1196  *               the MP lock.
1197  */
1198
1199 void
1200 syscall2(struct trapframe *frame)
1201 {
1202         struct thread *td = curthread;
1203         struct proc *p = td->td_proc;
1204         struct lwp *lp = td->td_lwp;
1205         caddr_t params;
1206         struct sysent *callp;
1207         register_t orig_tf_eflags;
1208         int sticks;
1209         int error;
1210         int narg;
1211 #ifdef INVARIANTS
1212         int crit_count = td->td_pri & ~TDPRI_MASK;
1213 #endif
1214 #ifdef SMP
1215         int have_mplock = 0;
1216 #endif
1217         u_int code;
1218         union sysunion args;
1219
1220 #ifdef DIAGNOSTIC
1221         if (ISPL(frame->tf_cs) != SEL_UPL) {
1222                 get_mplock();
1223                 panic("syscall");
1224                 /* NOT REACHED */
1225         }
1226 #endif
1227
1228 #ifdef SMP
1229         KASSERT(td->td_mpcount == 0, ("badmpcount syscall2 from %p", (void *)frame->tf_eip));
1230         if (syscall_mpsafe == 0)
1231                 MAKEMPSAFE(have_mplock);
1232 #endif
1233         userenter(td);          /* lazy raise our priority */
1234
1235         /*
1236          * Misc
1237          */
1238         sticks = (int)td->td_sticks;
1239         orig_tf_eflags = frame->tf_eflags;
1240
1241         /*
1242          * Virtual kernel intercept - if a VM context managed by a virtual
1243          * kernel issues a system call the virtual kernel handles it, not us.
1244          * Restore the virtual kernel context and return from its system
1245          * call.  The current frame is copied out to the virtual kernel.
1246          */
1247         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
1248                 error = vkernel_trap(lp, frame);
1249                 frame->tf_eax = error;
1250                 if (error)
1251                         frame->tf_eflags |= PSL_C;
1252                 error = EJUSTRETURN;
1253                 goto out;
1254         }
1255
1256         /*
1257          * Get the system call parameters and account for time
1258          */
1259         lp->lwp_md.md_regs = frame;
1260         params = (caddr_t)frame->tf_esp + sizeof(int);
1261         code = frame->tf_eax;
1262
1263         if (p->p_sysent->sv_prepsyscall) {
1264                 (*p->p_sysent->sv_prepsyscall)(
1265                         frame, (int *)(&args.nosys.sysmsg + 1),
1266                         &code, &params);
1267         } else {
1268                 /*
1269                  * Need to check if this is a 32 bit or 64 bit syscall.
1270                  * fuword is MP aware.
1271                  */
1272                 if (code == SYS_syscall) {
1273                         /*
1274                          * Code is first argument, followed by actual args.
1275                          */
1276                         code = fuword(params);
1277                         params += sizeof(int);
1278                 } else if (code == SYS___syscall) {
1279                         /*
1280                          * Like syscall, but code is a quad, so as to maintain
1281                          * quad alignment for the rest of the arguments.
1282                          */
1283                         code = fuword(params);
1284                         params += sizeof(quad_t);
1285                 }
1286         }
1287
1288         code &= p->p_sysent->sv_mask;
1289         if (code >= p->p_sysent->sv_size)
1290                 callp = &p->p_sysent->sv_table[0];
1291         else
1292                 callp = &p->p_sysent->sv_table[code];
1293
1294         narg = callp->sy_narg & SYF_ARGMASK;
1295
1296         /*
1297          * copyin is MP aware, but the tracing code is not
1298          */
1299         if (narg && params) {
1300                 error = copyin(params, (caddr_t)(&args.nosys.sysmsg + 1),
1301                                 narg * sizeof(register_t));
1302                 if (error) {
1303 #ifdef KTRACE
1304                         if (KTRPOINT(td, KTR_SYSCALL)) {
1305                                 MAKEMPSAFE(have_mplock);
1306                                 
1307                                 ktrsyscall(lp, code, narg,
1308                                         (void *)(&args.nosys.sysmsg + 1));
1309                         }
1310 #endif
1311                         goto bad;
1312                 }
1313         }
1314
1315 #ifdef KTRACE
1316         if (KTRPOINT(td, KTR_SYSCALL)) {
1317                 MAKEMPSAFE(have_mplock);
1318                 ktrsyscall(lp, code, narg, (void *)(&args.nosys.sysmsg + 1));
1319         }
1320 #endif
1321
1322         /*
1323          * For traditional syscall code edx is left untouched when 32 bit
1324          * results are returned.  Since edx is loaded from fds[1] when the 
1325          * system call returns we pre-set it here.
1326          */
1327         args.sysmsg_fds[0] = 0;
1328         args.sysmsg_fds[1] = frame->tf_edx;
1329
1330         /*
1331          * The syscall might manipulate the trap frame. If it does it
1332          * will probably return EJUSTRETURN.
1333          */
1334         args.sysmsg_frame = frame;
1335
1336         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1337
1338 #ifdef SMP
1339         /*
1340          * Try to run the syscall without the MP lock if the syscall
1341          * is MP safe.  We have to obtain the MP lock no matter what if 
1342          * we are ktracing
1343          */
1344         if ((callp->sy_narg & SYF_MPSAFE) == 0)
1345                 MAKEMPSAFE(have_mplock);
1346 #endif
1347
1348         error = (*callp->sy_call)(&args);
1349
1350 out:
1351         /*
1352          * MP SAFE (we may or may not have the MP lock at this point)
1353          */
1354         switch (error) {
1355         case 0:
1356                 /*
1357                  * Reinitialize proc pointer `p' as it may be different
1358                  * if this is a child returning from fork syscall.
1359                  */
1360                 p = curproc;
1361                 lp = curthread->td_lwp;
1362                 frame->tf_eax = args.sysmsg_fds[0];
1363                 frame->tf_edx = args.sysmsg_fds[1];
1364                 frame->tf_eflags &= ~PSL_C;
1365                 break;
1366         case ERESTART:
1367                 /*
1368                  * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1369                  * int 0x80 is 2 bytes. We saved this in tf_err.
1370                  */
1371                 frame->tf_eip -= frame->tf_err;
1372                 break;
1373         case EJUSTRETURN:
1374                 break;
1375         case EASYNC:
1376                 panic("Unexpected EASYNC return value (for now)");
1377         default:
1378 bad:
1379                 if (p->p_sysent->sv_errsize) {
1380                         if (error >= p->p_sysent->sv_errsize)
1381                                 error = -1;     /* XXX */
1382                         else
1383                                 error = p->p_sysent->sv_errtbl[error];
1384                 }
1385                 frame->tf_eax = error;
1386                 frame->tf_eflags |= PSL_C;
1387                 break;
1388         }
1389
1390         /*
1391          * Traced syscall.  trapsignal() is not MP aware.
1392          */
1393         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1394                 MAKEMPSAFE(have_mplock);
1395                 frame->tf_eflags &= ~PSL_T;
1396                 trapsignal(lp, SIGTRAP, 0);
1397         }
1398
1399         /*
1400          * Handle reschedule and other end-of-syscall issues
1401          */
1402         userret(lp, frame, sticks);
1403
1404 #ifdef KTRACE
1405         if (KTRPOINT(td, KTR_SYSRET)) {
1406                 MAKEMPSAFE(have_mplock);
1407                 ktrsysret(lp, code, error, args.sysmsg_result);
1408         }
1409 #endif
1410
1411         /*
1412          * This works because errno is findable through the
1413          * register set.  If we ever support an emulation where this
1414          * is not the case, this code will need to be revisited.
1415          */
1416         STOPEVENT(p, S_SCX, code);
1417
1418         userexit(lp);
1419 #ifdef SMP
1420         /*
1421          * Release the MP lock if we had to get it
1422          */
1423         KASSERT(td->td_mpcount == have_mplock, 
1424                 ("badmpcount syscall2/end from %p", (void *)frame->tf_eip));
1425         if (have_mplock)
1426                 rel_mplock();
1427 #endif
1428 #ifdef INVARIANTS
1429         KASSERT(crit_count == (td->td_pri & ~TDPRI_MASK), 
1430                 ("syscall: critical section count mismatch! %d/%d",
1431                 crit_count / TDPRI_CRIT, td->td_pri / TDPRI_CRIT));
1432 #endif
1433 }
1434
1435 void
1436 fork_return(struct lwp *lp, struct trapframe *frame)
1437 {
1438         frame->tf_eax = 0;              /* Child returns zero */
1439         frame->tf_eflags &= ~PSL_C;     /* success */
1440         frame->tf_edx = 1;
1441
1442         generic_lwp_return(lp, frame);
1443 }
1444
1445 /*
1446  * Simplified back end of syscall(), used when returning from fork()
1447  * directly into user mode.  MP lock is held on entry and should be
1448  * released on return.  This code will return back into the fork
1449  * trampoline code which then runs doreti.
1450  */
1451 void
1452 generic_lwp_return(struct lwp *lp, struct trapframe *frame)
1453 {
1454         struct proc *p = lp->lwp_proc;
1455
1456         /*
1457          * Newly forked processes are given a kernel priority.  We have to
1458          * adjust the priority to a normal user priority and fake entry
1459          * into the kernel (call userenter()) to install a passive release
1460          * function just in case userret() decides to stop the process.  This
1461          * can occur when ^Z races a fork.  If we do not install the passive
1462          * release function the current process designation will not be
1463          * released when the thread goes to sleep.
1464          */
1465         lwkt_setpri_self(TDPRI_USER_NORM);
1466         userenter(lp->lwp_thread);
1467         userret(lp, frame, 0);
1468 #ifdef KTRACE
1469         if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1470                 ktrsysret(lp, SYS_fork, 0, 0);
1471 #endif
1472         p->p_flag |= P_PASSIVE_ACQ;
1473         userexit(lp);
1474         p->p_flag &= ~P_PASSIVE_ACQ;
1475 #ifdef SMP
1476         KKASSERT(lp->lwp_thread->td_mpcount == 1);
1477         rel_mplock();
1478 #endif
1479 }
1480
1481 /*
1482  * If PGEX_FPFAULT is set then set FP_VIRTFP in the PCB to force a T_DNA
1483  * fault (which is then passed back to the virtual kernel) if an attempt is
1484  * made to use the FP unit.
1485  *
1486  * XXX this is a fairly big hack.
1487  */
1488 void
1489 set_vkernel_fp(struct trapframe *frame)
1490 {
1491         struct thread *td = curthread;
1492
1493         if (frame->tf_xflags & PGEX_FPFAULT) {
1494                 td->td_pcb->pcb_flags |= FP_VIRTFP;
1495                 if (mdcpu->gd_npxthread == td)
1496                         npxexit();
1497         } else {
1498                 td->td_pcb->pcb_flags &= ~FP_VIRTFP;
1499         }
1500 }
1501