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