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