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