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