1:1 Userland threading stage 2.8/4:
[dragonfly.git] / sys / i386 / 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/i386/i386/Attic/trap.c,v 1.64 2005/10/11 09:59:56 corecode 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/syscall.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/uio.h>
66 #include <sys/vmmeter.h>
67 #include <sys/malloc.h>
68 #ifdef KTRACE
69 #include <sys/ktrace.h>
70 #endif
71 #include <sys/upcall.h>
72 #include <sys/sysproto.h>
73 #include <sys/sysunion.h>
74
75 #include <vm/vm.h>
76 #include <vm/vm_param.h>
77 #include <sys/lock.h>
78 #include <vm/pmap.h>
79 #include <vm/vm_kern.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_extern.h>
83
84 #include <machine/cpu.h>
85 #include <machine/ipl.h>
86 #include <machine/md_var.h>
87 #include <machine/pcb.h>
88 #ifdef SMP
89 #include <machine/smp.h>
90 #endif
91 #include <machine/tss.h>
92 #include <machine/globaldata.h>
93
94 #include <i386/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 int (*pmath_emulate) (struct trapframe *);
108
109 extern void trap (struct trapframe frame);
110 extern int trapwrite (unsigned addr);
111 extern void syscall2 (struct trapframe frame);
112 extern void sendsys2 (struct trapframe frame);
113 extern void waitsys2 (struct trapframe frame);
114
115 static int trap_pfault (struct trapframe *, int, vm_offset_t);
116 static void trap_fatal (struct trapframe *, vm_offset_t);
117 void dblfault_handler (void);
118
119 extern inthand_t IDTVEC(syscall);
120
121 #define MAX_TRAP_MSG            28
122 static char *trap_msg[] = {
123         "",                                     /*  0 unused */
124         "privileged instruction fault",         /*  1 T_PRIVINFLT */
125         "",                                     /*  2 unused */
126         "breakpoint instruction fault",         /*  3 T_BPTFLT */
127         "",                                     /*  4 unused */
128         "",                                     /*  5 unused */
129         "arithmetic trap",                      /*  6 T_ARITHTRAP */
130         "system forced exception",              /*  7 T_ASTFLT */
131         "",                                     /*  8 unused */
132         "general protection fault",             /*  9 T_PROTFLT */
133         "trace trap",                           /* 10 T_TRCTRAP */
134         "",                                     /* 11 unused */
135         "page fault",                           /* 12 T_PAGEFLT */
136         "",                                     /* 13 unused */
137         "alignment fault",                      /* 14 T_ALIGNFLT */
138         "",                                     /* 15 unused */
139         "",                                     /* 16 unused */
140         "",                                     /* 17 unused */
141         "integer divide fault",                 /* 18 T_DIVIDE */
142         "non-maskable interrupt trap",          /* 19 T_NMI */
143         "overflow trap",                        /* 20 T_OFLOW */
144         "FPU bounds check fault",               /* 21 T_BOUND */
145         "FPU device not available",             /* 22 T_DNA */
146         "double fault",                         /* 23 T_DOUBLEFLT */
147         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
148         "invalid TSS fault",                    /* 25 T_TSSFLT */
149         "segment not present fault",            /* 26 T_SEGNPFLT */
150         "stack fault",                          /* 27 T_STKFLT */
151         "machine check trap",                   /* 28 T_MCHK */
152 };
153
154 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
155 extern int has_f00f_bug;
156 #endif
157
158 #ifdef DDB
159 static int ddb_on_nmi = 1;
160 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
161         &ddb_on_nmi, 0, "Go to DDB on NMI");
162 #endif
163 static int panic_on_nmi = 1;
164 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
165         &panic_on_nmi, 0, "Panic on NMI");
166 static int fast_release;
167 SYSCTL_INT(_machdep, OID_AUTO, fast_release, CTLFLAG_RW,
168         &fast_release, 0, "Passive Release was optimal");
169 static int slow_release;
170 SYSCTL_INT(_machdep, OID_AUTO, slow_release, CTLFLAG_RW,
171         &slow_release, 0, "Passive Release was nonoptimal");
172
173 MALLOC_DEFINE(M_SYSMSG, "sysmsg", "sysmsg structure");
174 extern int max_sysmsg;
175
176 /*
177  * Passive USER->KERNEL transition.  This only occurs if we block in the
178  * kernel while still holding our userland priority.  We have to fixup our
179  * priority in order to avoid potential deadlocks before we allow the system
180  * to switch us to another thread.
181  */
182 static void
183 passive_release(struct thread *td)
184 {
185         struct lwp *lp = td->td_lwp;
186
187         td->td_release = NULL;
188         lwkt_setpri_self(TDPRI_KERN_USER);
189         lp->lwp_proc->p_usched->release_curproc(lp);
190 }
191
192 /*
193  * userenter() passively intercepts the thread switch function to increase
194  * the thread priority from a user priority to a kernel priority, reducing
195  * syscall and trap overhead for the case where no switch occurs.
196  */
197
198 static __inline void
199 userenter(struct thread *curtd)
200 {
201         curtd->td_release = passive_release;
202 }
203
204 /*
205  * Handle signals, upcalls, profiling, and other AST's and/or tasks that
206  * must be completed before we can return to or try to return to userland.
207  *
208  * Note that td_sticks is a 64 bit quantity, but there's no point doing 64
209  * arithmatic on the delta calculation so the absolute tick values are
210  * truncated to an integer.
211  */
212 static void
213 userret(struct lwp *lp, struct trapframe *frame, int sticks)
214 {
215         struct proc *p = lp->lwp_proc;
216         int sig;
217
218         /*
219          * Post any pending upcalls
220          */
221         if (p->p_flag & P_UPCALLPEND) {
222                 p->p_flag &= ~P_UPCALLPEND;
223                 postupcall(lp);
224         }
225
226         /*
227          * Post any pending signals
228          */
229         while ((sig = CURSIG(p)) != 0) {
230                 postsig(sig);
231         }
232
233         /*
234          * Charge system time if profiling.  Note: times are in microseconds.
235          */
236         if (p->p_flag & P_PROFIL) {
237                 addupc_task(p, frame->tf_eip, 
238                         (u_int)((int)p->p_thread->td_sticks - sticks));
239         }
240
241         /*
242          * Post any pending signals XXX
243          */
244         while ((sig = CURSIG(p)) != 0)
245                 postsig(sig);
246 }
247
248 /*
249  * Cleanup from userenter and any passive release that might have occured.
250  * We must reclaim the current-process designation before we can return
251  * to usermode.  We also handle both LWKT and USER reschedule requests.
252  */
253 static __inline void
254 userexit(struct lwp *lp)
255 {
256         struct thread *td = lp->lwp_thread;
257         globaldata_t gd = td->td_gd;
258
259 #if 0
260         /*
261          * If a user reschedule is requested force a new process to be
262          * chosen by releasing the current process.  Our process will only
263          * be chosen again if it has a considerably better priority.
264          */
265         if (user_resched_wanted())
266                 lp->lwp_proc->p_usched->release_curproc(lp);
267 #endif
268
269 again:
270         /*
271          * Handle a LWKT reschedule request first.  Since our passive release
272          * is still in place we do not have to do anything special.
273          */
274         if (lwkt_resched_wanted())
275                 lwkt_switch();
276
277         /*
278          * Acquire the current process designation if we do not own it.
279          * Note that acquire_curproc() does not reset the user reschedule
280          * bit on purpose, because we may need to accumulate over several
281          * threads waking up at the same time.
282          *
283          * NOTE: userland scheduler cruft: because processes are removed
284          * from the userland scheduler's queue we run through loops to try
285          * to figure out which is the best of [ existing, waking-up ]
286          * threads.
287          */
288         if (lp != gd->gd_uschedcp) {
289                 ++slow_release;
290                 lp->lwp_proc->p_usched->acquire_curproc(lp);
291                 /* We may have switched cpus on acquisition */
292                 gd = td->td_gd;
293         } else {
294                 ++fast_release;
295         }
296
297         /*
298          * Reduce our priority in preparation for a return to userland.  If
299          * our passive release function was still in place, our priority was
300          * never raised and does not need to be reduced.
301          */
302         if (td->td_release == NULL)
303                 lwkt_setpri_self(TDPRI_USER_NORM);
304         td->td_release = NULL;
305
306         /*
307          * After reducing our priority there might be other kernel-level
308          * LWKTs that now have a greater priority.  Run them as necessary.
309          * We don't have to worry about losing cpu to userland because
310          * we still control the current-process designation and we no longer
311          * have a passive release function installed.
312          */
313         if (lwkt_checkpri_self())
314                 lwkt_switch();
315
316         /*
317          * If a userland reschedule is [still] pending we may not be the best
318          * selected process.  Select a better one.  If another LWKT resched
319          * is pending the trap will be re-entered.
320          */
321         if (user_resched_wanted()) {
322                 lp->lwp_proc->p_usched->select_curproc(gd);
323                 if (lp != gd->gd_uschedcp) {
324                         lwkt_setpri_self(TDPRI_KERN_USER);
325                         goto again;
326                 }
327         }
328 }
329
330 /*
331  * Exception, fault, and trap interface to the kernel.
332  * This common code is called from assembly language IDT gate entry
333  * routines that prepare a suitable stack frame, and restore this
334  * frame after the exception has been processed.
335  *
336  * This function is also called from doreti in an interlock to handle ASTs.
337  * For example:  hardwareint->INTROUTINE->(set ast)->doreti->trap
338  *
339  * NOTE!  We have to retrieve the fault address prior to obtaining the
340  * MP lock because get_mplock() may switch out.  YYY cr2 really ought
341  * to be retrieved by the assembly code, not here.
342  *
343  * XXX gd_trap_nesting_level currently prevents lwkt_switch() from panicing
344  * if an attempt is made to switch from a fast interrupt or IPI.  This is
345  * necessary to properly take fatal kernel traps on SMP machines if 
346  * get_mplock() has to block.
347  */
348 void
349 trap(frame)
350         struct trapframe frame;
351 {
352         struct globaldata *gd = mycpu;
353         struct thread *td = gd->gd_curthread;
354         struct lwp *lp = td->td_lwp;
355         struct proc *p;
356         int sticks = 0;
357         int i = 0, ucode = 0, type, code;
358         vm_offset_t eva;
359
360         p = td->td_proc;
361 #ifdef DDB
362         if (db_active) {
363                 eva = (frame.tf_trapno == T_PAGEFLT ? rcr2() : 0);
364                 ++gd->gd_trap_nesting_level;
365                 get_mplock();
366                 trap_fatal(&frame, eva);
367                 --gd->gd_trap_nesting_level;
368                 goto out2;
369         }
370 #endif
371
372         eva = 0;
373         ++gd->gd_trap_nesting_level;
374         if (frame.tf_trapno == T_PAGEFLT) {
375                 /*
376                  * For some Cyrix CPUs, %cr2 is clobbered by interrupts.
377                  * This problem is worked around by using an interrupt
378                  * gate for the pagefault handler.  We are finally ready
379                  * to read %cr2 and then must reenable interrupts.
380                  *
381                  * XXX this should be in the switch statement, but the
382                  * NO_FOOF_HACK and VM86 goto and ifdefs obfuscate the
383                  * flow of control too much for this to be obviously
384                  * correct.
385                  */
386                 eva = rcr2();
387                 get_mplock();
388                 cpu_enable_intr();
389         } else {
390                 get_mplock();
391         }
392         --gd->gd_trap_nesting_level;
393         /*
394          * MP lock is held at this point
395          */
396
397         if (!(frame.tf_eflags & PSL_I)) {
398                 /*
399                  * Buggy application or kernel code has disabled interrupts
400                  * and then trapped.  Enabling interrupts now is wrong, but
401                  * it is better than running with interrupts disabled until
402                  * they are accidentally enabled later.
403                  */
404                 type = frame.tf_trapno;
405                 if (ISPL(frame.tf_cs)==SEL_UPL || (frame.tf_eflags & PSL_VM)) {
406                         printf(
407                             "pid %ld (%s): trap %d with interrupts disabled\n",
408                             (long)curproc->p_pid, curproc->p_comm, type);
409                 } else if (type != T_BPTFLT && type != T_TRCTRAP) {
410                         /*
411                          * XXX not quite right, since this may be for a
412                          * multiple fault in user mode.
413                          */
414                         printf("kernel trap %d with interrupts disabled\n",
415                             type);
416                 }
417                 cpu_enable_intr();
418         }
419
420 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
421 restart:
422 #endif
423         type = frame.tf_trapno;
424         code = frame.tf_err;
425
426         if (in_vm86call) {
427                 if (frame.tf_eflags & PSL_VM &&
428                     (type == T_PROTFLT || type == T_STKFLT)) {
429 #ifdef SMP
430                         KKASSERT(td->td_mpcount > 0);
431 #endif
432                         i = vm86_emulate((struct vm86frame *)&frame);
433 #ifdef SMP
434                         KKASSERT(td->td_mpcount > 0);
435 #endif
436                         if (i != 0) {
437                                 /*
438                                  * returns to original process
439                                  */
440                                 vm86_trap((struct vm86frame *)&frame);
441                                 KKASSERT(0);
442                         }
443                         goto out2;
444                 }
445                 switch (type) {
446                         /*
447                          * these traps want either a process context, or
448                          * assume a normal userspace trap.
449                          */
450                 case T_PROTFLT:
451                 case T_SEGNPFLT:
452                         trap_fatal(&frame, eva);
453                         goto out2;
454                 case T_TRCTRAP:
455                         type = T_BPTFLT;        /* kernel breakpoint */
456                         /* FALL THROUGH */
457                 }
458                 goto kernel_trap;       /* normal kernel trap handling */
459         }
460
461         if ((ISPL(frame.tf_cs) == SEL_UPL) || (frame.tf_eflags & PSL_VM)) {
462                 /* user trap */
463
464                 userenter(td);
465
466                 sticks = (int)td->td_sticks;
467                 lp->lwp_md.md_regs = &frame;
468
469                 switch (type) {
470                 case T_PRIVINFLT:       /* privileged instruction fault */
471                         ucode = type;
472                         i = SIGILL;
473                         break;
474
475                 case T_BPTFLT:          /* bpt instruction fault */
476                 case T_TRCTRAP:         /* trace trap */
477                         frame.tf_eflags &= ~PSL_T;
478                         i = SIGTRAP;
479                         break;
480
481                 case T_ARITHTRAP:       /* arithmetic trap */
482                         ucode = code;
483                         i = SIGFPE;
484                         break;
485
486                 case T_ASTFLT:          /* Allow process switch */
487                         mycpu->gd_cnt.v_soft++;
488                         if (mycpu->gd_reqflags & RQF_AST_OWEUPC) {
489                                 atomic_clear_int_nonlocked(&mycpu->gd_reqflags,
490                                             RQF_AST_OWEUPC);
491                                 addupc_task(p, p->p_prof.pr_addr,
492                                             p->p_prof.pr_ticks);
493                         }
494                         goto out;
495
496                         /*
497                          * The following two traps can happen in
498                          * vm86 mode, and, if so, we want to handle
499                          * them specially.
500                          */
501                 case T_PROTFLT:         /* general protection fault */
502                 case T_STKFLT:          /* stack fault */
503                         if (frame.tf_eflags & PSL_VM) {
504                                 i = vm86_emulate((struct vm86frame *)&frame);
505                                 if (i == 0)
506                                         goto out;
507                                 break;
508                         }
509                         /* FALL THROUGH */
510
511                 case T_SEGNPFLT:        /* segment not present fault */
512                 case T_TSSFLT:          /* invalid TSS fault */
513                 case T_DOUBLEFLT:       /* double fault */
514                 default:
515                         ucode = code + BUS_SEGM_FAULT ;
516                         i = SIGBUS;
517                         break;
518
519                 case T_PAGEFLT:         /* page fault */
520                         i = trap_pfault(&frame, TRUE, eva);
521                         if (i == -1)
522                                 goto out;
523 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
524                         if (i == -2)
525                                 goto restart;
526 #endif
527                         if (i == 0)
528                                 goto out;
529
530                         ucode = T_PAGEFLT;
531                         break;
532
533                 case T_DIVIDE:          /* integer divide fault */
534                         ucode = FPE_INTDIV;
535                         i = SIGFPE;
536                         break;
537
538 #if NISA > 0
539                 case T_NMI:
540 #ifdef POWERFAIL_NMI
541                         goto handle_powerfail;
542 #else /* !POWERFAIL_NMI */
543                         /* machine/parity/power fail/"kitchen sink" faults */
544                         if (isa_nmi(code) == 0) {
545 #ifdef DDB
546                                 /*
547                                  * NMI can be hooked up to a pushbutton
548                                  * for debugging.
549                                  */
550                                 if (ddb_on_nmi) {
551                                         printf ("NMI ... going to debugger\n");
552                                         kdb_trap (type, 0, &frame);
553                                 }
554 #endif /* DDB */
555                                 goto out2;
556                         } else if (panic_on_nmi)
557                                 panic("NMI indicates hardware failure");
558                         break;
559 #endif /* POWERFAIL_NMI */
560 #endif /* NISA > 0 */
561
562                 case T_OFLOW:           /* integer overflow fault */
563                         ucode = FPE_INTOVF;
564                         i = SIGFPE;
565                         break;
566
567                 case T_BOUND:           /* bounds check fault */
568                         ucode = FPE_FLTSUB;
569                         i = SIGFPE;
570                         break;
571
572                 case T_DNA:
573 #if NNPX > 0
574                         /* 
575                          * The kernel may have switched out the FP unit's
576                          * state, causing the user process to take a fault
577                          * when it tries to use the FP unit.  Restore the
578                          * state here
579                          */
580                         if (npxdna())
581                                 goto out;
582 #endif
583                         if (!pmath_emulate) {
584                                 i = SIGFPE;
585                                 ucode = FPE_FPU_NP_TRAP;
586                                 break;
587                         }
588                         i = (*pmath_emulate)(&frame);
589                         if (i == 0) {
590                                 if (!(frame.tf_eflags & PSL_T))
591                                         goto out2;
592                                 frame.tf_eflags &= ~PSL_T;
593                                 i = SIGTRAP;
594                         }
595                         /* else ucode = emulator_only_knows() XXX */
596                         break;
597
598                 case T_FPOPFLT:         /* FPU operand fetch fault */
599                         ucode = T_FPOPFLT;
600                         i = SIGILL;
601                         break;
602
603                 case T_XMMFLT:          /* SIMD floating-point exception */
604                         ucode = 0; /* XXX */
605                         i = SIGFPE;
606                         break;
607                 }
608         } else {
609 kernel_trap:
610                 /* kernel trap */
611
612                 switch (type) {
613                 case T_PAGEFLT:                 /* page fault */
614                         (void) trap_pfault(&frame, FALSE, eva);
615                         goto out2;
616
617                 case T_DNA:
618 #if NNPX > 0
619                         /*
620                          * The kernel may be using npx for copying or other
621                          * purposes.
622                          */
623                         if (npxdna())
624                                 goto out2;
625 #endif
626                         break;
627
628                 case T_PROTFLT:         /* general protection fault */
629                 case T_SEGNPFLT:        /* segment not present fault */
630                         /*
631                          * Invalid segment selectors and out of bounds
632                          * %eip's and %esp's can be set up in user mode.
633                          * This causes a fault in kernel mode when the
634                          * kernel tries to return to user mode.  We want
635                          * to get this fault so that we can fix the
636                          * problem here and not have to check all the
637                          * selectors and pointers when the user changes
638                          * them.
639                          */
640 #define MAYBE_DORETI_FAULT(where, whereto)                              \
641         do {                                                            \
642                 if (frame.tf_eip == (int)where) {                       \
643                         frame.tf_eip = (int)whereto;                    \
644                         goto out2;                                      \
645                 }                                                       \
646         } while (0)
647                         /*
648                          * Since we don't save %gs across an interrupt
649                          * frame this check must occur outside the intr
650                          * nesting level check.
651                          */
652                         if (frame.tf_eip == (int)cpu_switch_load_gs) {
653                                 td->td_pcb->pcb_gs = 0;
654                                 psignal(p, SIGBUS);
655                                 goto out2;
656                         }
657                         if (mycpu->gd_intr_nesting_level == 0) {
658                                 /*
659                                  * Invalid %fs's and %gs's can be created using
660                                  * procfs or PT_SETREGS or by invalidating the
661                                  * underlying LDT entry.  This causes a fault
662                                  * in kernel mode when the kernel attempts to
663                                  * switch contexts.  Lose the bad context
664                                  * (XXX) so that we can continue, and generate
665                                  * a signal.
666                                  */
667                                 MAYBE_DORETI_FAULT(doreti_iret,
668                                                    doreti_iret_fault);
669                                 MAYBE_DORETI_FAULT(doreti_popl_ds,
670                                                    doreti_popl_ds_fault);
671                                 MAYBE_DORETI_FAULT(doreti_popl_es,
672                                                    doreti_popl_es_fault);
673                                 MAYBE_DORETI_FAULT(doreti_popl_fs,
674                                                    doreti_popl_fs_fault);
675                                 if (td->td_pcb->pcb_onfault) {
676                                         frame.tf_eip = 
677                                             (register_t)td->td_pcb->pcb_onfault;
678                                         goto out2;
679                                 }
680                         }
681                         break;
682
683                 case T_TSSFLT:
684                         /*
685                          * PSL_NT can be set in user mode and isn't cleared
686                          * automatically when the kernel is entered.  This
687                          * causes a TSS fault when the kernel attempts to
688                          * `iret' because the TSS link is uninitialized.  We
689                          * want to get this fault so that we can fix the
690                          * problem here and not every time the kernel is
691                          * entered.
692                          */
693                         if (frame.tf_eflags & PSL_NT) {
694                                 frame.tf_eflags &= ~PSL_NT;
695                                 goto out2;
696                         }
697                         break;
698
699                 case T_TRCTRAP:  /* trace trap */
700                         if (frame.tf_eip == (int)IDTVEC(syscall)) {
701                                 /*
702                                  * We've just entered system mode via the
703                                  * syscall lcall.  Continue single stepping
704                                  * silently until the syscall handler has
705                                  * saved the flags.
706                                  */
707                                 goto out2;
708                         }
709                         if (frame.tf_eip == (int)IDTVEC(syscall) + 1) {
710                                 /*
711                                  * The syscall handler has now saved the
712                                  * flags.  Stop single stepping it.
713                                  */
714                                 frame.tf_eflags &= ~PSL_T;
715                                 goto out2;
716                         }
717                         /*
718                          * Ignore debug register trace traps due to
719                          * accesses in the user's address space, which
720                          * can happen under several conditions such as
721                          * if a user sets a watchpoint on a buffer and
722                          * then passes that buffer to a system call.
723                          * We still want to get TRCTRAPS for addresses
724                          * in kernel space because that is useful when
725                          * debugging the kernel.
726                          */
727                         if (user_dbreg_trap()) {
728                                 /*
729                                  * Reset breakpoint bits because the
730                                  * processor doesn't
731                                  */
732                                 load_dr6(rdr6() & 0xfffffff0);
733                                 goto out2;
734                         }
735                         /*
736                          * Fall through (TRCTRAP kernel mode, kernel address)
737                          */
738                 case T_BPTFLT:
739                         /*
740                          * If DDB is enabled, let it handle the debugger trap.
741                          * Otherwise, debugger traps "can't happen".
742                          */
743 #ifdef DDB
744                         if (kdb_trap (type, 0, &frame))
745                                 goto out2;
746 #endif
747                         break;
748
749 #if NISA > 0
750                 case T_NMI:
751 #ifdef POWERFAIL_NMI
752 #ifndef TIMER_FREQ
753 #  define TIMER_FREQ 1193182
754 #endif
755         handle_powerfail:
756                 {
757                   static unsigned lastalert = 0;
758
759                   if(time_second - lastalert > 10)
760                     {
761                       log(LOG_WARNING, "NMI: power fail\n");
762                       sysbeep(TIMER_FREQ/880, hz);
763                       lastalert = time_second;
764                     }
765                     /* YYY mp count */
766                   goto out2;
767                 }
768 #else /* !POWERFAIL_NMI */
769                         /* machine/parity/power fail/"kitchen sink" faults */
770                         if (isa_nmi(code) == 0) {
771 #ifdef DDB
772                                 /*
773                                  * NMI can be hooked up to a pushbutton
774                                  * for debugging.
775                                  */
776                                 if (ddb_on_nmi) {
777                                         printf ("NMI ... going to debugger\n");
778                                         kdb_trap (type, 0, &frame);
779                                 }
780 #endif /* DDB */
781                                 goto out2;
782                         } else if (panic_on_nmi == 0)
783                                 goto out2;
784                         /* FALL THROUGH */
785 #endif /* POWERFAIL_NMI */
786 #endif /* NISA > 0 */
787                 }
788
789                 trap_fatal(&frame, eva);
790                 goto out2;
791         }
792
793         /* Translate fault for emulators (e.g. Linux) */
794         if (*p->p_sysent->sv_transtrap)
795                 i = (*p->p_sysent->sv_transtrap)(i, type);
796
797         trapsignal(p, i, ucode);
798
799 #ifdef DEBUG
800         if (type <= MAX_TRAP_MSG) {
801                 uprintf("fatal process exception: %s",
802                         trap_msg[type]);
803                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
804                         uprintf(", fault VA = 0x%lx", (u_long)eva);
805                 uprintf("\n");
806         }
807 #endif
808
809 out:
810 #ifdef SMP
811         if (ISPL(frame.tf_cs) == SEL_UPL)
812                 KASSERT(td->td_mpcount == 1, ("badmpcount trap from %p", (void *)frame.tf_eip));
813 #endif
814         userret(lp, &frame, sticks);
815         userexit(lp);
816 out2:
817 #ifdef SMP
818         KKASSERT(td->td_mpcount > 0);
819 #endif
820         rel_mplock();
821 }
822
823 #ifdef notyet
824 /*
825  * This version doesn't allow a page fault to user space while
826  * in the kernel. The rest of the kernel needs to be made "safe"
827  * before this can be used. I think the only things remaining
828  * to be made safe are the iBCS2 code and the process tracing/
829  * debugging code.
830  */
831 static int
832 trap_pfault(frame, usermode, eva)
833         struct trapframe *frame;
834         int usermode;
835         vm_offset_t eva;
836 {
837         vm_offset_t va;
838         struct vmspace *vm = NULL;
839         vm_map_t map = 0;
840         int rv = 0;
841         vm_prot_t ftype;
842         thread_t td = curthread;
843         struct proc *p = td->td_proc;   /* may be NULL */
844
845         if (frame->tf_err & PGEX_W)
846                 ftype = VM_PROT_WRITE;
847         else
848                 ftype = VM_PROT_READ;
849
850         va = trunc_page(eva);
851         if (va < VM_MIN_KERNEL_ADDRESS) {
852                 vm_offset_t v;
853                 vm_page_t mpte;
854
855                 if (p == NULL ||
856                     (!usermode && va < VM_MAXUSER_ADDRESS &&
857                      (td->td_gd->gd_intr_nesting_level != 0 || 
858                       td->td_pcb->pcb_onfault == NULL))) {
859                         trap_fatal(frame, eva);
860                         return (-1);
861                 }
862
863                 /*
864                  * This is a fault on non-kernel virtual memory.
865                  * vm is initialized above to NULL. If curproc is NULL
866                  * or curproc->p_vmspace is NULL the fault is fatal.
867                  */
868                 vm = p->p_vmspace;
869                 if (vm == NULL)
870                         goto nogo;
871
872                 map = &vm->vm_map;
873
874                 /*
875                  * Keep swapout from messing with us during this
876                  *      critical time.
877                  */
878                 ++p->p_lock;
879
880                 /*
881                  * Grow the stack if necessary
882                  */
883                 /* grow_stack returns false only if va falls into
884                  * a growable stack region and the stack growth
885                  * fails.  It returns true if va was not within
886                  * a growable stack region, or if the stack 
887                  * growth succeeded.
888                  */
889                 if (!grow_stack (p, va)) {
890                         rv = KERN_FAILURE;
891                         --p->p_lock;
892                         goto nogo;
893                 }
894                 
895                 /* Fault in the user page: */
896                 rv = vm_fault(map, va, ftype,
897                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
898                                                       : VM_FAULT_NORMAL);
899
900                 --p->p_lock;
901         } else {
902                 /*
903                  * Don't allow user-mode faults in kernel address space.
904                  */
905                 if (usermode)
906                         goto nogo;
907
908                 /*
909                  * Since we know that kernel virtual address addresses
910                  * always have pte pages mapped, we just have to fault
911                  * the page.
912                  */
913                 rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
914         }
915
916         if (rv == KERN_SUCCESS)
917                 return (0);
918 nogo:
919         if (!usermode) {
920                 if (mtd->td_gd->gd_intr_nesting_level == 0 && 
921                     td->td_pcb->pcb_onfault) {
922                         frame->tf_eip = (register_t)td->td_pcb->pcb_onfault;
923                         return (0);
924                 }
925                 trap_fatal(frame, eva);
926                 return (-1);
927         }
928
929         /* kludge to pass faulting virtual address to sendsig */
930         frame->tf_err = eva;
931
932         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
933 }
934 #endif
935
936 int
937 trap_pfault(frame, usermode, eva)
938         struct trapframe *frame;
939         int usermode;
940         vm_offset_t eva;
941 {
942         vm_offset_t va;
943         struct vmspace *vm = NULL;
944         vm_map_t map = 0;
945         int rv = 0;
946         vm_prot_t ftype;
947         thread_t td = curthread;
948         struct proc *p = td->td_proc;
949
950         va = trunc_page(eva);
951         if (va >= KERNBASE) {
952                 /*
953                  * Don't allow user-mode faults in kernel address space.
954                  * An exception:  if the faulting address is the invalid
955                  * instruction entry in the IDT, then the Intel Pentium
956                  * F00F bug workaround was triggered, and we need to
957                  * treat it is as an illegal instruction, and not a page
958                  * fault.
959                  */
960 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
961                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
962                         frame->tf_trapno = T_PRIVINFLT;
963                         return -2;
964                 }
965 #endif
966                 if (usermode)
967                         goto nogo;
968
969                 map = kernel_map;
970         } else {
971                 /*
972                  * This is a fault on non-kernel virtual memory.
973                  * vm is initialized above to NULL. If curproc is NULL
974                  * or curproc->p_vmspace is NULL the fault is fatal.
975                  */
976                 if (p != NULL)
977                         vm = p->p_vmspace;
978
979                 if (vm == NULL)
980                         goto nogo;
981
982                 map = &vm->vm_map;
983         }
984
985         if (frame->tf_err & PGEX_W)
986                 ftype = VM_PROT_WRITE;
987         else
988                 ftype = VM_PROT_READ;
989
990         if (map != kernel_map) {
991                 /*
992                  * Keep swapout from messing with us during this
993                  *      critical time.
994                  */
995                 ++p->p_lock;
996
997                 /*
998                  * Grow the stack if necessary
999                  */
1000                 /* grow_stack returns false only if va falls into
1001                  * a growable stack region and the stack growth
1002                  * fails.  It returns true if va was not within
1003                  * a growable stack region, or if the stack 
1004                  * growth succeeded.
1005                  */
1006                 if (!grow_stack (p, va)) {
1007                         rv = KERN_FAILURE;
1008                         --p->p_lock;
1009                         goto nogo;
1010                 }
1011
1012                 /* Fault in the user page: */
1013                 rv = vm_fault(map, va, ftype,
1014                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
1015                                                       : VM_FAULT_NORMAL);
1016
1017                 --p->p_lock;
1018         } else {
1019                 /*
1020                  * Don't have to worry about process locking or stacks in the kernel.
1021                  */
1022                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
1023         }
1024
1025         if (rv == KERN_SUCCESS)
1026                 return (0);
1027 nogo:
1028         if (!usermode) {
1029                 if (td->td_gd->gd_intr_nesting_level == 0 &&
1030                     td->td_pcb->pcb_onfault) {
1031                         frame->tf_eip = (register_t)td->td_pcb->pcb_onfault;
1032                         return (0);
1033                 }
1034                 trap_fatal(frame, eva);
1035                 return (-1);
1036         }
1037
1038         /* kludge to pass faulting virtual address to sendsig */
1039         frame->tf_err = eva;
1040
1041         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
1042 }
1043
1044 static void
1045 trap_fatal(frame, eva)
1046         struct trapframe *frame;
1047         vm_offset_t eva;
1048 {
1049         int code, type, ss, esp;
1050         struct soft_segment_descriptor softseg;
1051
1052         code = frame->tf_err;
1053         type = frame->tf_trapno;
1054         sdtossd(&gdt[mycpu->gd_cpuid * NGDT + IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
1055
1056         if (type <= MAX_TRAP_MSG)
1057                 printf("\n\nFatal trap %d: %s while in %s mode\n",
1058                         type, trap_msg[type],
1059                         frame->tf_eflags & PSL_VM ? "vm86" :
1060                         ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
1061 #ifdef SMP
1062         /* three separate prints in case of a trap on an unmapped page */
1063         printf("mp_lock = %08x; ", mp_lock);
1064         printf("cpuid = %d; ", mycpu->gd_cpuid);
1065         printf("lapic.id = %08x\n", lapic.id);
1066 #endif
1067         if (type == T_PAGEFLT) {
1068                 printf("fault virtual address   = 0x%x\n", eva);
1069                 printf("fault code              = %s %s, %s\n",
1070                         code & PGEX_U ? "user" : "supervisor",
1071                         code & PGEX_W ? "write" : "read",
1072                         code & PGEX_P ? "protection violation" : "page not present");
1073         }
1074         printf("instruction pointer     = 0x%x:0x%x\n",
1075                frame->tf_cs & 0xffff, frame->tf_eip);
1076         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
1077                 ss = frame->tf_ss & 0xffff;
1078                 esp = frame->tf_esp;
1079         } else {
1080                 ss = GSEL(GDATA_SEL, SEL_KPL);
1081                 esp = (int)&frame->tf_esp;
1082         }
1083         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
1084         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
1085         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
1086                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
1087         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
1088                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
1089                softseg.ssd_gran);
1090         printf("processor eflags        = ");
1091         if (frame->tf_eflags & PSL_T)
1092                 printf("trace trap, ");
1093         if (frame->tf_eflags & PSL_I)
1094                 printf("interrupt enabled, ");
1095         if (frame->tf_eflags & PSL_NT)
1096                 printf("nested task, ");
1097         if (frame->tf_eflags & PSL_RF)
1098                 printf("resume, ");
1099         if (frame->tf_eflags & PSL_VM)
1100                 printf("vm86, ");
1101         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1102         printf("current process         = ");
1103         if (curproc) {
1104                 printf("%lu (%s)\n",
1105                     (u_long)curproc->p_pid, curproc->p_comm ?
1106                     curproc->p_comm : "");
1107         } else {
1108                 printf("Idle\n");
1109         }
1110         printf("current thread          = pri %d ", curthread->td_pri);
1111         if (curthread->td_pri >= TDPRI_CRIT)
1112                 printf("(CRIT)");
1113         printf("\n");
1114 #ifdef SMP
1115 /**
1116  *  XXX FIXME:
1117  *      we probably SHOULD have stopped the other CPUs before now!
1118  *      another CPU COULD have been touching cpl at this moment...
1119  */
1120         printf(" <- SMP: XXX");
1121 #endif
1122         printf("\n");
1123
1124 #ifdef KDB
1125         if (kdb_trap(&psl))
1126                 return;
1127 #endif
1128 #ifdef DDB
1129         if ((debugger_on_panic || db_active) && kdb_trap(type, code, frame))
1130                 return;
1131 #endif
1132         printf("trap number             = %d\n", type);
1133         if (type <= MAX_TRAP_MSG)
1134                 panic("%s", trap_msg[type]);
1135         else
1136                 panic("unknown/reserved trap");
1137 }
1138
1139 /*
1140  * Double fault handler. Called when a fault occurs while writing
1141  * a frame for a trap/exception onto the stack. This usually occurs
1142  * when the stack overflows (such is the case with infinite recursion,
1143  * for example).
1144  *
1145  * XXX Note that the current PTD gets replaced by IdlePTD when the
1146  * task switch occurs. This means that the stack that was active at
1147  * the time of the double fault is not available at <kstack> unless
1148  * the machine was idle when the double fault occurred. The downside
1149  * of this is that "trace <ebp>" in ddb won't work.
1150  */
1151 void
1152 dblfault_handler()
1153 {
1154         struct mdglobaldata *gd = mdcpu;
1155
1156         printf("\nFatal double fault:\n");
1157         printf("eip = 0x%x\n", gd->gd_common_tss.tss_eip);
1158         printf("esp = 0x%x\n", gd->gd_common_tss.tss_esp);
1159         printf("ebp = 0x%x\n", gd->gd_common_tss.tss_ebp);
1160 #ifdef SMP
1161         /* three separate prints in case of a trap on an unmapped page */
1162         printf("mp_lock = %08x; ", mp_lock);
1163         printf("cpuid = %d; ", mycpu->gd_cpuid);
1164         printf("lapic.id = %08x\n", lapic.id);
1165 #endif
1166         panic("double fault");
1167 }
1168
1169 /*
1170  * Compensate for 386 brain damage (missing URKR).
1171  * This is a little simpler than the pagefault handler in trap() because
1172  * it the page tables have already been faulted in and high addresses
1173  * are thrown out early for other reasons.
1174  */
1175 int trapwrite(addr)
1176         unsigned addr;
1177 {
1178         struct proc *p;
1179         vm_offset_t va;
1180         struct vmspace *vm;
1181         int rv;
1182
1183         va = trunc_page((vm_offset_t)addr);
1184         /*
1185          * XXX - MAX is END.  Changed > to >= for temp. fix.
1186          */
1187         if (va >= VM_MAXUSER_ADDRESS)
1188                 return (1);
1189
1190         p = curproc;
1191         vm = p->p_vmspace;
1192
1193         ++p->p_lock;
1194
1195         if (!grow_stack (p, va)) {
1196                 --p->p_lock;
1197                 return (1);
1198         }
1199
1200         /*
1201          * fault the data page
1202          */
1203         rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1204
1205         --p->p_lock;
1206
1207         if (rv != KERN_SUCCESS)
1208                 return 1;
1209
1210         return (0);
1211 }
1212
1213 /*
1214  *      syscall2 -      MP aware system call request C handler
1215  *
1216  *      A system call is essentially treated as a trap except that the
1217  *      MP lock is not held on entry or return.  We are responsible for
1218  *      obtaining the MP lock if necessary and for handling ASTs
1219  *      (e.g. a task switch) prior to return.
1220  *
1221  *      In general, only simple access and manipulation of curproc and
1222  *      the current stack is allowed without having to hold MP lock.
1223  */
1224 void
1225 syscall2(struct trapframe frame)
1226 {
1227         struct thread *td = curthread;
1228         struct proc *p = td->td_proc;
1229         struct lwp *lp = td->td_lwp;
1230         caddr_t params;
1231         struct sysent *callp;
1232         register_t orig_tf_eflags;
1233         int sticks;
1234         int error;
1235         int narg;
1236         u_int code;
1237         union sysunion args;
1238
1239 #ifdef DIAGNOSTIC
1240         if (ISPL(frame.tf_cs) != SEL_UPL) {
1241                 get_mplock();
1242                 panic("syscall");
1243                 /* NOT REACHED */
1244         }
1245 #endif
1246
1247 #ifdef SMP
1248         KASSERT(td->td_mpcount == 0, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1249         get_mplock();
1250 #endif
1251         userenter(td);          /* lazy raise our priority */
1252
1253         sticks = (int)td->td_sticks;
1254
1255         lp->lwp_md.md_regs = &frame;
1256         params = (caddr_t)frame.tf_esp + sizeof(int);
1257         code = frame.tf_eax;
1258         orig_tf_eflags = frame.tf_eflags;
1259
1260         if (p->p_sysent->sv_prepsyscall) {
1261                 /*
1262                  * The prep code is not MP aware.
1263                  */
1264                 (*p->p_sysent->sv_prepsyscall)(&frame, (int *)(&args.nosys.usrmsg + 1), &code, &params);
1265         } else {
1266                 /*
1267                  * Need to check if this is a 32 bit or 64 bit syscall.
1268                  * fuword is MP aware.
1269                  */
1270                 if (code == SYS_syscall) {
1271                         /*
1272                          * Code is first argument, followed by actual args.
1273                          */
1274                         code = fuword(params);
1275                         params += sizeof(int);
1276                 } else if (code == SYS___syscall) {
1277                         /*
1278                          * Like syscall, but code is a quad, so as to maintain
1279                          * quad alignment for the rest of the arguments.
1280                          */
1281                         code = fuword(params);
1282                         params += sizeof(quad_t);
1283                 }
1284         }
1285
1286         code &= p->p_sysent->sv_mask;
1287         if (code >= p->p_sysent->sv_size)
1288                 callp = &p->p_sysent->sv_table[0];
1289         else
1290                 callp = &p->p_sysent->sv_table[code];
1291
1292         narg = callp->sy_narg & SYF_ARGMASK;
1293
1294         /*
1295          * copyin is MP aware, but the tracing code is not
1296          */
1297         if (narg && params) {
1298                 error = copyin(params, (caddr_t)(&args.nosys.usrmsg + 1),
1299                                 narg * sizeof(register_t));
1300                 if (error) {
1301 #ifdef KTRACE
1302                         if (KTRPOINT(td, KTR_SYSCALL))
1303                                 ktrsyscall(p->p_tracep, code, narg,
1304                                         (void *)(&args.nosys.usrmsg + 1));
1305 #endif
1306                         goto bad;
1307                 }
1308         }
1309
1310 #if 0
1311         /*
1312          * Try to run the syscall without the MP lock if the syscall
1313          * is MP safe.  We have to obtain the MP lock no matter what if 
1314          * we are ktracing
1315          */
1316         if ((callp->sy_narg & SYF_MPSAFE) == 0) {
1317                 get_mplock();
1318                 have_mplock = 1;
1319         }
1320 #endif
1321
1322 #ifdef KTRACE
1323         if (KTRPOINT(td, KTR_SYSCALL)) {
1324                 ktrsyscall(p->p_tracep, code, narg, (void *)(&args.nosys.usrmsg + 1));
1325         }
1326 #endif
1327
1328         /*
1329          * For traditional syscall code edx is left untouched when 32 bit
1330          * results are returned.  Since edx is loaded from fds[1] when the 
1331          * system call returns we pre-set it here.
1332          */
1333         lwkt_initmsg(&args.lmsg, &td->td_msgport, 0,
1334                         lwkt_cmd_op(code), lwkt_cmd_op_none);
1335         args.sysmsg_copyout = NULL;
1336         args.sysmsg_fds[0] = 0;
1337         args.sysmsg_fds[1] = frame.tf_edx;
1338
1339         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1340
1341         error = (*callp->sy_call)(&args);
1342
1343         /*
1344          * MP SAFE (we may or may not have the MP lock at this point)
1345          */
1346         switch (error) {
1347         case 0:
1348                 /*
1349                  * Reinitialize proc pointer `p' as it may be different
1350                  * if this is a child returning from fork syscall.
1351                  */
1352                 p = curproc;
1353                 lp = curthread->td_lwp;
1354                 frame.tf_eax = args.sysmsg_fds[0];
1355                 frame.tf_edx = args.sysmsg_fds[1];
1356                 frame.tf_eflags &= ~PSL_C;
1357                 break;
1358         case ERESTART:
1359                 /*
1360                  * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1361                  * int 0x80 is 2 bytes. We saved this in tf_err.
1362                  */
1363                 frame.tf_eip -= frame.tf_err;
1364                 break;
1365         case EJUSTRETURN:
1366                 break;
1367         case EASYNC:
1368                 panic("Unexpected EASYNC return value (for now)");
1369         default:
1370 bad:
1371                 if (p->p_sysent->sv_errsize) {
1372                         if (error >= p->p_sysent->sv_errsize)
1373                                 error = -1;     /* XXX */
1374                         else
1375                                 error = p->p_sysent->sv_errtbl[error];
1376                 }
1377                 frame.tf_eax = error;
1378                 frame.tf_eflags |= PSL_C;
1379                 break;
1380         }
1381
1382         /*
1383          * Traced syscall.  trapsignal() is not MP aware.
1384          */
1385         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1386                 frame.tf_eflags &= ~PSL_T;
1387                 trapsignal(p, SIGTRAP, 0);
1388         }
1389
1390         /*
1391          * Handle reschedule and other end-of-syscall issues
1392          */
1393         userret(lp, &frame, sticks);
1394
1395 #ifdef KTRACE
1396         if (KTRPOINT(td, KTR_SYSRET)) {
1397                 ktrsysret(p->p_tracep, code, error, args.sysmsg_result);
1398         }
1399 #endif
1400
1401         /*
1402          * This works because errno is findable through the
1403          * register set.  If we ever support an emulation where this
1404          * is not the case, this code will need to be revisited.
1405          */
1406         STOPEVENT(p, S_SCX, code);
1407
1408         userexit(lp);
1409 #ifdef SMP
1410         /*
1411          * Release the MP lock if we had to get it
1412          */
1413         KASSERT(td->td_mpcount == 1, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1414         rel_mplock();
1415 #endif
1416 }
1417
1418 /*
1419  *      free_sysun -    Put an unused sysun on the free list.
1420  */
1421 static __inline void
1422 free_sysun(struct thread *td, union sysunion *sysun)
1423 {
1424         struct globaldata *gd = td->td_gd;
1425
1426         crit_enter_quick(td);
1427         sysun->lmsg.opaque.ms_sysunnext = gd->gd_freesysun;
1428         gd->gd_freesysun = sysun;
1429         crit_exit_quick(td);
1430 }
1431
1432 /*
1433  *      sendsys2 -      MP aware system message request C handler
1434  */
1435 void
1436 sendsys2(struct trapframe frame)
1437 {
1438         struct globaldata *gd;
1439         struct thread *td = curthread;
1440         struct proc *p = td->td_proc;
1441         struct lwp *lp = td->td_lwp;
1442         register_t orig_tf_eflags;
1443         struct sysent *callp;
1444         union sysunion *sysun = NULL;
1445         lwkt_msg_t umsg;
1446         int sticks;
1447         int error;
1448         int narg;
1449         u_int code = 0;
1450         int msgsize;
1451         int result;
1452
1453 #ifdef DIAGNOSTIC
1454         if (ISPL(frame.tf_cs) != SEL_UPL) {
1455                 get_mplock();
1456                 panic("sendsys");
1457                 /* NOT REACHED */
1458         }
1459 #endif
1460
1461 #ifdef SMP
1462         KASSERT(td->td_mpcount == 0, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1463         get_mplock();
1464 #endif
1465         /*
1466          * access non-atomic field from critical section.  p_sticks is
1467          * updated by the clock interrupt.  Also use this opportunity
1468          * to lazy-raise our LWKT priority.
1469          */
1470         userenter(td);
1471         sticks = td->td_sticks;
1472
1473         lp->lwp_md.md_regs = &frame;
1474         orig_tf_eflags = frame.tf_eflags;
1475         result = 0;
1476
1477         /*
1478          * Extract the system call message.  If msgsize is zero we are 
1479          * blocking on a message and/or message port.  If msgsize is -1 
1480          * we are testing a message for completion or a message port for
1481          * activity.
1482          *
1483          * The userland system call message size includes the size of the
1484          * userland lwkt_msg plus arguments.  We load it into the userland
1485          * portion of our sysunion structure then we initialize the kerneland
1486          * portion and go.
1487          */
1488
1489         /*
1490          * Bad message size
1491          */
1492         if ((msgsize = frame.tf_edx) < sizeof(struct lwkt_msg) ||
1493             msgsize > sizeof(union sysunion) - sizeof(struct sysmsg)) {
1494                 error = ENOSYS;
1495                 goto bad2;
1496         }
1497
1498         /*
1499          * Obtain a sysun from our per-cpu cache or allocate a new one.  Use
1500          * the opaque field to store the original (user) message pointer.
1501          * A critical section is necessary to interlock against interrupts
1502          * returning system messages to the thread cache.
1503          */
1504         gd = td->td_gd;
1505         crit_enter_quick(td);
1506         if ((sysun = gd->gd_freesysun) != NULL)
1507                 gd->gd_freesysun = sysun->lmsg.opaque.ms_sysunnext;
1508         else
1509                 sysun = malloc(sizeof(union sysunion), M_SYSMSG, M_WAITOK);
1510         crit_exit_quick(td);
1511
1512         /*
1513          * Copy the user request into the kernel copy of the user request.
1514          */
1515         umsg = (void *)frame.tf_ecx;
1516         error = copyin(umsg, &sysun->nosys.usrmsg, msgsize);
1517         if (error)
1518                 goto bad1;
1519         if ((sysun->nosys.usrmsg.umsg.ms_flags & MSGF_ASYNC)) {
1520                 error = suser(td);
1521                 if (error) {
1522                         goto bad1;
1523                 }
1524                 if (max_sysmsg > 0 && lp->lwp_nsysmsg >= max_sysmsg) {
1525                         error = E2BIG;
1526                         goto bad1;
1527                 }
1528         }
1529
1530         /*
1531          * Initialize the kernel message from the copied-in data and
1532          * pull in appropriate flags from the userland message.
1533          *
1534          * ms_abort_port is usually initialized in sendmsg/domsg, but since
1535          * we are not calling those functions (yet), we have to do it manually.
1536          */
1537         lwkt_initmsg(&sysun->lmsg, &td->td_msgport, 0,
1538                         sysun->nosys.usrmsg.umsg.ms_cmd,
1539                         lwkt_cmd_op_none);
1540         sysun->lmsg.ms_abort_port = sysun->lmsg.ms_reply_port;
1541         sysun->sysmsg_copyout = NULL;
1542         sysun->lmsg.opaque.ms_umsg = umsg;
1543         sysun->lmsg.ms_flags |= sysun->nosys.usrmsg.umsg.ms_flags & MSGF_ASYNC;
1544
1545         /*
1546          * Extract the system call number, lookup the system call, and
1547          * set the default return value.
1548          */
1549         code = (u_int)sysun->lmsg.ms_cmd.cm_op;
1550         /* We don't handle the syscall() syscall yet */
1551         if (code == 0) {
1552                 error = ENOTSUP;
1553                 free_sysun(td, sysun);
1554                 goto bad2;
1555         }
1556         if (code >= p->p_sysent->sv_size) {
1557                 error = ENOSYS;
1558                 free_sysun(td, sysun);
1559                 goto bad1;
1560         }
1561
1562         callp = &p->p_sysent->sv_table[code];
1563
1564         narg = (msgsize - sizeof(struct lwkt_msg)) / sizeof(register_t);
1565
1566 #ifdef KTRACE
1567         if (KTRPOINT(td, KTR_SYSCALL)) {
1568                 ktrsyscall(p->p_tracep, code, narg, (void *)(&sysun->nosys.usrmsg + 1));
1569         }
1570 #endif
1571         sysun->lmsg.u.ms_fds[0] = 0;
1572         sysun->lmsg.u.ms_fds[1] = 0;
1573
1574         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1575
1576         /*
1577          * Make the system call.  An error code is always returned, results
1578          * are copied back via ms_result32 or ms_result64.  YYY temporary
1579          * stage copy p_retval[] into ms_result32/64
1580          *
1581          * NOTE!  XXX if this is a child returning from a fork curproc
1582          * might be different.  YYY huh? a child returning from a fork
1583          * should never 'return' from this call, it should go right to the
1584          * fork_trampoline function.
1585          */
1586         error = (*callp->sy_call)(sysun);
1587         gd = td->td_gd; /* RELOAD, might have switched cpus */
1588
1589 bad1:
1590         /*
1591          * If a synchronous return copy p_retval to ms_result64 and return
1592          * the sysmsg to the free pool.
1593          *
1594          * YYY Don't writeback message if execve() YYY
1595          */
1596         sysun->nosys.usrmsg.umsg.ms_error = error;
1597         sysun->nosys.usrmsg.umsg.u.ms_fds[0] = sysun->lmsg.u.ms_fds[0];
1598         sysun->nosys.usrmsg.umsg.u.ms_fds[1] = sysun->lmsg.u.ms_fds[1];
1599         result = sysun->nosys.usrmsg.umsg.u.ms_fds[0]; /* for ktrace */
1600         if (error != 0 || code != SYS_execve) {
1601                 int error2;
1602                 error2 = copyout(&sysun->nosys.usrmsg.umsg.ms_copyout_start,
1603                                 &umsg->ms_copyout_start,
1604                                 ms_copyout_size);
1605                 if (error2 != 0)
1606                         error = error2;
1607         }
1608         if (error == EASYNC) {
1609                 /*
1610                  * Since only the current process ever messes with msgq,
1611                  * we can safely manipulate it in parallel with the async
1612                  * operation.
1613                  */
1614                 TAILQ_INSERT_TAIL(&lp->lwp_sysmsgq, &sysun->sysmsg, msgq);
1615                 lp->lwp_nsysmsg++;
1616                 error = (int)&sysun->sysmsg;
1617         }
1618         else {
1619                 free_sysun(td, sysun);
1620         }
1621 bad2:
1622         frame.tf_eax = (register_t)error;
1623
1624         /*
1625          * Traced syscall.  trapsignal() is not MP aware.
1626          */
1627         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1628                 frame.tf_eflags &= ~PSL_T;
1629                 trapsignal(p, SIGTRAP, 0);
1630         }
1631
1632         /*
1633          * Handle reschedule and other end-of-syscall issues
1634          */
1635         userret(lp, &frame, sticks);
1636
1637 #ifdef KTRACE
1638         if (KTRPOINT(td, KTR_SYSRET)) {
1639                 ktrsysret(p->p_tracep, code, error, result);
1640         }
1641 #endif
1642
1643         /*
1644          * This works because errno is findable through the
1645          * register set.  If we ever support an emulation where this
1646          * is not the case, this code will need to be revisited.
1647          */
1648         STOPEVENT(p, S_SCX, code);
1649
1650         userexit(lp);
1651 #ifdef SMP
1652         /*
1653          * Release the MP lock if we had to get it
1654          */
1655         KASSERT(td->td_mpcount == 1, ("badmpcount syscall from %p", (void *)frame.tf_eip));
1656         rel_mplock();
1657 #endif
1658 }
1659
1660 /*
1661  *      waitsys2 -      MP aware system message wait C handler
1662  */
1663 void
1664 waitsys2(struct trapframe frame)
1665 {
1666         struct globaldata *gd;
1667         struct thread *td = curthread;
1668         struct proc *p = td->td_proc;
1669         struct lwp *lp = td->td_lwp;
1670         union sysunion *sysun = NULL;
1671         lwkt_msg_t umsg;
1672         register_t orig_tf_eflags;
1673         int error = 0, result, sticks;
1674         u_int code = 0;
1675
1676 #ifdef DIAGNOSTIC
1677         if (ISPL(frame.tf_cs) != SEL_UPL) {
1678                 get_mplock();
1679                 panic("waitsys2");
1680                 /* NOT REACHED */
1681         }
1682 #endif
1683
1684 #ifdef SMP
1685         KASSERT(td->td_mpcount == 0, ("badmpcount syscall from %p",
1686                 (void *)frame.tf_eip));
1687         get_mplock();
1688 #endif
1689
1690         /*
1691          * access non-atomic field from critical section.  p_sticks is
1692          * updated by the clock interrupt.  Also use this opportunity
1693          * to lazy-raise our LWKT priority.
1694          */
1695         userenter(td);
1696         sticks = td->td_sticks;
1697
1698         lp->lwp_md.md_regs = &frame;
1699         orig_tf_eflags = frame.tf_eflags;
1700         result = 0;
1701
1702         if (frame.tf_ecx) {
1703                 struct sysmsg *ptr;
1704                 int found = 0;
1705                 TAILQ_FOREACH(ptr, &lp->lwp_sysmsgq, msgq) {
1706                         if ((void *)ptr == (void *)frame.tf_ecx) {
1707                                 sysun = (void *)sysmsg_wait(lp,
1708                                              (void *)frame.tf_ecx, 1);
1709                                 found = 1;
1710                                 break;
1711                         }
1712                 }
1713                 if (!found) {
1714                         error = ENOENT;
1715                         goto bad;
1716                 }
1717         }
1718         else if (frame.tf_eax) {
1719                 printf("waitport/checkport only the default port is supported at the moment\n");
1720                 error = ENOTSUP;
1721                 goto bad;
1722         }
1723         else {
1724                 switch(frame.tf_edx) {
1725                 case 0:
1726                         sysun = (void *)sysmsg_wait(lp, NULL, 0);
1727                         break;
1728                 case -1:
1729                         sysun = (void *)sysmsg_wait(lp, NULL, 1);
1730                         break;
1731                 default:
1732                         error = ENOSYS;
1733                         goto bad;
1734                 }
1735         }
1736         if (sysun) {
1737                 gd = td->td_gd;
1738                 umsg = sysun->lmsg.opaque.ms_umsg;
1739                 frame.tf_eax = (register_t)sysun;
1740                 sysun->nosys.usrmsg.umsg.u.ms_fds[0] = sysun->lmsg.u.ms_fds[0];
1741                 sysun->nosys.usrmsg.umsg.u.ms_fds[1] = sysun->lmsg.u.ms_fds[1];
1742                 sysun->nosys.usrmsg.umsg.ms_error = sysun->lmsg.ms_error;
1743                 error = sysun->lmsg.ms_error;
1744                 result = sysun->lmsg.u.ms_fds[0]; /* for ktrace */
1745                 error = copyout(&sysun->nosys.usrmsg.umsg.ms_copyout_start,
1746                                 &umsg->ms_copyout_start, ms_copyout_size);
1747                 free_sysun(td, sysun);
1748                 frame.tf_edx = 0;
1749                 code = (u_int)sysun->lmsg.ms_cmd.cm_op;
1750         }
1751 bad:
1752         if (error)
1753                 frame.tf_eax = error;
1754         /*
1755          * Traced syscall.  trapsignal() is not MP aware.
1756          */
1757         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1758                 frame.tf_eflags &= ~PSL_T;
1759                 trapsignal(p, SIGTRAP, 0);
1760         }
1761
1762         /*
1763          * Handle reschedule and other end-of-syscall issues
1764          */
1765         userret(lp, &frame, sticks);
1766
1767 #ifdef KTRACE
1768         if (KTRPOINT(td, KTR_SYSRET)) {
1769                 ktrsysret(p->p_tracep, code, error, result);
1770         }
1771 #endif
1772
1773         /*
1774          * This works because errno is findable through the
1775          * register set.  If we ever support an emulation where this
1776          * is not the case, this code will need to be revisited.
1777          */
1778         STOPEVENT(p, S_SCX, code);
1779
1780         userexit(lp);
1781 #ifdef SMP
1782         KASSERT(td->td_mpcount == 1, ("badmpcount syscall from %p",
1783                 (void *)frame.tf_eip));
1784         rel_mplock();
1785 #endif
1786 }
1787
1788 /*
1789  * Simplified back end of syscall(), used when returning from fork()
1790  * directly into user mode.  MP lock is held on entry and should be
1791  * released on return.  This code will return back into the fork
1792  * trampoline code which then runs doreti.
1793  */
1794 void
1795 fork_return(p, frame)
1796         struct proc *p;
1797         struct trapframe frame;
1798 {
1799         struct lwp *lp;
1800
1801         KKASSERT(p->p_nthreads == 1);
1802
1803         lp = LIST_FIRST(&p->p_lwps);
1804
1805         frame.tf_eax = 0;               /* Child returns zero */
1806         frame.tf_eflags &= ~PSL_C;      /* success */
1807         frame.tf_edx = 1;
1808
1809         /*
1810          * Newly forked processes are given a kernel priority.  We have to
1811          * adjust the priority to a normal user priority and fake entry
1812          * into the kernel (call userenter()) to install a passive release
1813          * function just in case userret() decides to stop the process.  This
1814          * can occur when ^Z races a fork.  If we do not install the passive
1815          * release function the current process designation will not be
1816          * released when the thread goes to sleep.
1817          */
1818         lwkt_setpri_self(TDPRI_USER_NORM);
1819         userenter(lp->lwp_thread);
1820         userret(lp, &frame, 0);
1821 #ifdef KTRACE
1822         if (KTRPOINT(lp->lwp_thread, KTR_SYSRET))
1823                 ktrsysret(p->p_tracep, SYS_fork, 0, 0);
1824 #endif
1825         p->p_flag |= P_PASSIVE_ACQ;
1826         userexit(lp);
1827         p->p_flag &= ~P_PASSIVE_ACQ;
1828 #ifdef SMP
1829         KKASSERT(lp->lwp_thread->td_mpcount == 1);
1830         rel_mplock();
1831 #endif
1832 }