Enhance debugging (sync before MP work).
[dragonfly.git] / sys / platform / pc32 / i386 / trap.c
1 /*-
2  * Copyright (C) 1994, David Greenman
3  * Copyright (c) 1990, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * the University of Utah, and William Jolitz.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      from: @(#)trap.c        7.4 (Berkeley) 5/13/91
38  * $FreeBSD: src/sys/i386/i386/trap.c,v 1.147.2.11 2003/02/27 19:09:59 luoqi Exp $
39  * $DragonFly: src/sys/platform/pc32/i386/trap.c,v 1.14 2003/07/01 18:49:52 dillon Exp $
40  */
41
42 /*
43  * 386 Trap and System call handling
44  */
45
46 #include "opt_cpu.h"
47 #include "opt_ddb.h"
48 #include "opt_ktrace.h"
49 #include "opt_clock.h"
50 #include "opt_trap.h"
51
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/proc.h>
55 #include <sys/pioctl.h>
56 #include <sys/kernel.h>
57 #include <sys/resourcevar.h>
58 #include <sys/signalvar.h>
59 #include <sys/syscall.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/uio.h>
63 #include <sys/vmmeter.h>
64 #ifdef KTRACE
65 #include <sys/ktrace.h>
66 #endif
67
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <sys/lock.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_extern.h>
76
77 #include <machine/cpu.h>
78 #include <machine/ipl.h>
79 #include <machine/md_var.h>
80 #include <machine/pcb.h>
81 #ifdef SMP
82 #include <machine/smp.h>
83 #endif
84 #include <machine/tss.h>
85 #include <machine/globaldata.h>
86
87 #include <i386/isa/intr_machdep.h>
88
89 #ifdef POWERFAIL_NMI
90 #include <sys/syslog.h>
91 #include <machine/clock.h>
92 #endif
93
94 #include <machine/vm86.h>
95
96 #include <ddb/ddb.h>
97 #include <sys/thread2.h>
98
99 #include "isa.h"
100 #include "npx.h"
101
102 int (*pmath_emulate) __P((struct trapframe *));
103
104 extern void trap __P((struct trapframe frame));
105 extern int trapwrite __P((unsigned addr));
106 extern void syscall2 __P((struct trapframe frame));
107
108 static int trap_pfault __P((struct trapframe *, int, vm_offset_t));
109 static void trap_fatal __P((struct trapframe *, vm_offset_t));
110 void dblfault_handler __P((void));
111
112 extern inthand_t IDTVEC(syscall);
113
114 #define MAX_TRAP_MSG            28
115 static char *trap_msg[] = {
116         "",                                     /*  0 unused */
117         "privileged instruction fault",         /*  1 T_PRIVINFLT */
118         "",                                     /*  2 unused */
119         "breakpoint instruction fault",         /*  3 T_BPTFLT */
120         "",                                     /*  4 unused */
121         "",                                     /*  5 unused */
122         "arithmetic trap",                      /*  6 T_ARITHTRAP */
123         "system forced exception",              /*  7 T_ASTFLT */
124         "",                                     /*  8 unused */
125         "general protection fault",             /*  9 T_PROTFLT */
126         "trace trap",                           /* 10 T_TRCTRAP */
127         "",                                     /* 11 unused */
128         "page fault",                           /* 12 T_PAGEFLT */
129         "",                                     /* 13 unused */
130         "alignment fault",                      /* 14 T_ALIGNFLT */
131         "",                                     /* 15 unused */
132         "",                                     /* 16 unused */
133         "",                                     /* 17 unused */
134         "integer divide fault",                 /* 18 T_DIVIDE */
135         "non-maskable interrupt trap",          /* 19 T_NMI */
136         "overflow trap",                        /* 20 T_OFLOW */
137         "FPU bounds check fault",               /* 21 T_BOUND */
138         "FPU device not available",             /* 22 T_DNA */
139         "double fault",                         /* 23 T_DOUBLEFLT */
140         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
141         "invalid TSS fault",                    /* 25 T_TSSFLT */
142         "segment not present fault",            /* 26 T_SEGNPFLT */
143         "stack fault",                          /* 27 T_STKFLT */
144         "machine check trap",                   /* 28 T_MCHK */
145 };
146
147 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
148 extern int has_f00f_bug;
149 #endif
150
151 #ifdef DDB
152 static int ddb_on_nmi = 1;
153 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
154         &ddb_on_nmi, 0, "Go to DDB on NMI");
155 #endif
156 static int panic_on_nmi = 1;
157 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
158         &panic_on_nmi, 0, "Panic on NMI");
159
160 /*
161  * USER->KERNEL transition.  Do not transition us out of userland from the
162  * point of view of the userland scheduler unless we actually have to
163  * switch.
164  *
165  * usertdsw is called from within a critical section.
166  */
167 static void
168 usertdsw(struct thread *ntd)
169 {
170         struct thread *td = curthread;
171
172         td->td_switch = cpu_heavy_switch;
173         lwkt_setpri_self(TDPRI_KERN_USER);
174 #if 0
175         /* 
176          * This is where we might want to catch the P_CURPROC designation
177          * and fix it for *any* switchout rather then just an mi_switch()
178          * switchout (move from mi_switch()?) YYY
179          */
180         if (p->p_flag & P_CURPROC) {
181                 ...
182         }
183 #endif
184         td->td_switch(ntd);
185 }
186
187 /*
188  * Note that userenter() may be re-entered several times due to AST
189  * processing.
190  */
191 static __inline void
192 userenter(void)
193 {
194         struct thread *td = curthread;
195
196         KASSERT(td->td_switch == cpu_heavy_switch || td->td_switch == usertdsw,
197                 ("userenter: bad td_switch = %p", td->td_switch));
198         td->td_switch = usertdsw;
199 }
200
201 static int
202 userret(struct proc *p, struct trapframe *frame,
203         u_quad_t oticks, int have_mplock)
204 {
205         int sig, s;
206         struct thread *td = curthread;
207
208         /*
209          * Post any pending signals
210          */
211         crit_enter();
212         while ((sig = CURSIG(p)) != 0) {
213                 if (have_mplock == 0) {
214                         get_mplock();
215                         have_mplock = 1;
216                 }
217                 crit_exit();
218                 postsig(sig);
219                 crit_enter();
220         }
221
222         /*
223          * Set our priority properly and restore our switch function.  If
224          * we did not hit our lazy switch function in the first place we
225          * do not need to restore anything.
226          */
227         if (td->td_switch == cpu_heavy_switch) {
228                 switch(p->p_rtprio.type) {
229                 case RTP_PRIO_IDLE:
230                         lwkt_setpri_self(TDPRI_USER_IDLE);
231                         break;
232                 case RTP_PRIO_REALTIME:
233                 case RTP_PRIO_FIFO:
234                         lwkt_setpri_self(TDPRI_USER_REAL);
235                         break;
236                 default:
237                         lwkt_setpri_self(TDPRI_USER_NORM);
238                         break;
239                 }
240         } else {
241                 KKASSERT(td->td_switch == usertdsw);
242                 td->td_switch = cpu_heavy_switch;
243         }
244         crit_exit();
245
246         /*
247          * If a reschedule has been requested we call chooseproc() to locate
248          * the next runnable process.  When we wakeup from that we check
249          * for pending signals again.
250          */
251         if (resched_wanted()) {
252                 uio_yield();
253                 if (have_mplock == 0) {
254                         get_mplock();
255                         have_mplock = 1;
256                 }
257                 while ((sig = CURSIG(p)) != 0)
258                         postsig(sig);
259         }
260
261         /*
262          * Charge system time if profiling.
263          */
264         if (p->p_flag & P_PROFIL) {
265                 if (have_mplock == 0) {
266                         get_mplock();
267                         have_mplock = 1;
268                 }
269                 addupc_task(p, frame->tf_eip, 
270                     (u_int)(curthread->td_sticks - oticks) * psratio);
271         }
272
273         /*
274          * In order to return to userland we need to be the designated
275          * current (user) process on this cpu.  We have to wait for
276          * the userland scheduler to schedule as P_CURPROC.
277          */
278         s = splhigh();
279         while ((p->p_flag & P_CURPROC) == 0) {
280                 p->p_stats->p_ru.ru_nivcsw++;
281                 lwkt_deschedule_self();
282                 mi_switch();
283         }
284         splx(s);
285         KKASSERT(mycpu->gd_uprocscheduled == 1);
286
287         return(have_mplock);
288 }
289
290 #ifdef DEVICE_POLLING
291 extern u_int32_t poll_in_trap;
292 extern int ether_poll __P((int count));
293 #endif /* DEVICE_POLLING */
294
295 /*
296  * Exception, fault, and trap interface to the FreeBSD kernel.
297  * This common code is called from assembly language IDT gate entry
298  * routines that prepare a suitable stack frame, and restore this
299  * frame after the exception has been processed.
300  */
301
302 void
303 trap(frame)
304         struct trapframe frame;
305 {
306         struct proc *p = curproc;
307         u_quad_t sticks = 0;
308         int i = 0, ucode = 0, type, code;
309         vm_offset_t eva;
310
311 #ifdef DDB
312         if (db_active) {
313                 eva = (frame.tf_trapno == T_PAGEFLT ? rcr2() : 0);
314                 trap_fatal(&frame, eva);
315                 return;
316         }
317 #endif
318
319         if (!(frame.tf_eflags & PSL_I)) {
320                 /*
321                  * Buggy application or kernel code has disabled interrupts
322                  * and then trapped.  Enabling interrupts now is wrong, but
323                  * it is better than running with interrupts disabled until
324                  * they are accidentally enabled later.
325                  */
326                 type = frame.tf_trapno;
327                 if (ISPL(frame.tf_cs) == SEL_UPL || (frame.tf_eflags & PSL_VM))
328                         printf(
329                             "pid %ld (%s): trap %d with interrupts disabled\n",
330                             (long)curproc->p_pid, curproc->p_comm, type);
331                 else if (type != T_BPTFLT && type != T_TRCTRAP)
332                         /*
333                          * XXX not quite right, since this may be for a
334                          * multiple fault in user mode.
335                          */
336                         printf("kernel trap %d with interrupts disabled\n",
337                             type);
338                 enable_intr();
339         }
340
341         eva = 0;
342         if (frame.tf_trapno == T_PAGEFLT) {
343                 /*
344                  * For some Cyrix CPUs, %cr2 is clobbered by interrupts.
345                  * This problem is worked around by using an interrupt
346                  * gate for the pagefault handler.  We are finally ready
347                  * to read %cr2 and then must reenable interrupts.
348                  *
349                  * XXX this should be in the switch statement, but the
350                  * NO_FOOF_HACK and VM86 goto and ifdefs obfuscate the
351                  * flow of control too much for this to be obviously
352                  * correct.
353                  */
354                 eva = rcr2();
355                 enable_intr();
356         }
357
358 #ifdef DEVICE_POLLING
359         if (poll_in_trap)
360                 ether_poll(poll_in_trap);
361 #endif /* DEVICE_POLLING */
362
363 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
364 restart:
365 #endif
366         type = frame.tf_trapno;
367         code = frame.tf_err;
368
369         if (in_vm86call) {
370                 if (frame.tf_eflags & PSL_VM &&
371                     (type == T_PROTFLT || type == T_STKFLT)) {
372                         i = vm86_emulate((struct vm86frame *)&frame);
373                         if (i != 0)
374                                 /*
375                                  * returns to original process
376                                  */
377                                 vm86_trap((struct vm86frame *)&frame);
378                         return;
379                 }
380                 switch (type) {
381                         /*
382                          * these traps want either a process context, or
383                          * assume a normal userspace trap.
384                          */
385                 case T_PROTFLT:
386                 case T_SEGNPFLT:
387                         trap_fatal(&frame, eva);
388                         return;
389                 case T_TRCTRAP:
390                         type = T_BPTFLT;        /* kernel breakpoint */
391                         /* FALL THROUGH */
392                 }
393                 goto kernel_trap;       /* normal kernel trap handling */
394         }
395
396         if ((ISPL(frame.tf_cs) == SEL_UPL) || (frame.tf_eflags & PSL_VM)) {
397                 /* user trap */
398
399                 userenter();
400
401                 sticks = curthread->td_sticks;
402                 p->p_md.md_regs = &frame;
403
404                 switch (type) {
405                 case T_PRIVINFLT:       /* privileged instruction fault */
406                         ucode = type;
407                         i = SIGILL;
408                         break;
409
410                 case T_BPTFLT:          /* bpt instruction fault */
411                 case T_TRCTRAP:         /* trace trap */
412                         frame.tf_eflags &= ~PSL_T;
413                         i = SIGTRAP;
414                         break;
415
416                 case T_ARITHTRAP:       /* arithmetic trap */
417                         ucode = code;
418                         i = SIGFPE;
419                         break;
420
421                 case T_ASTFLT:          /* Allow process switch */
422                         astoff();
423                         cnt.v_soft++;
424                         if (p->p_flag & P_OWEUPC) {
425                                 p->p_flag &= ~P_OWEUPC;
426                                 addupc_task(p, p->p_stats->p_prof.pr_addr,
427                                             p->p_stats->p_prof.pr_ticks);
428                         }
429                         goto out;
430
431                         /*
432                          * The following two traps can happen in
433                          * vm86 mode, and, if so, we want to handle
434                          * them specially.
435                          */
436                 case T_PROTFLT:         /* general protection fault */
437                 case T_STKFLT:          /* stack fault */
438                         if (frame.tf_eflags & PSL_VM) {
439                                 i = vm86_emulate((struct vm86frame *)&frame);
440                                 if (i == 0)
441                                         goto out;
442                                 break;
443                         }
444                         /* FALL THROUGH */
445
446                 case T_SEGNPFLT:        /* segment not present fault */
447                 case T_TSSFLT:          /* invalid TSS fault */
448                 case T_DOUBLEFLT:       /* double fault */
449                 default:
450                         ucode = code + BUS_SEGM_FAULT ;
451                         i = SIGBUS;
452                         break;
453
454                 case T_PAGEFLT:         /* page fault */
455                         i = trap_pfault(&frame, TRUE, eva);
456                         if (i == -1)
457                                 return;
458 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
459                         if (i == -2)
460                                 goto restart;
461 #endif
462                         if (i == 0)
463                                 goto out;
464
465                         ucode = T_PAGEFLT;
466                         break;
467
468                 case T_DIVIDE:          /* integer divide fault */
469                         ucode = FPE_INTDIV;
470                         i = SIGFPE;
471                         break;
472
473 #if NISA > 0
474                 case T_NMI:
475 #ifdef POWERFAIL_NMI
476                         goto handle_powerfail;
477 #else /* !POWERFAIL_NMI */
478                         /* machine/parity/power fail/"kitchen sink" faults */
479                         if (isa_nmi(code) == 0) {
480 #ifdef DDB
481                                 /*
482                                  * NMI can be hooked up to a pushbutton
483                                  * for debugging.
484                                  */
485                                 if (ddb_on_nmi) {
486                                         printf ("NMI ... going to debugger\n");
487                                         kdb_trap (type, 0, &frame);
488                                 }
489 #endif /* DDB */
490                                 return;
491                         } else if (panic_on_nmi)
492                                 panic("NMI indicates hardware failure");
493                         break;
494 #endif /* POWERFAIL_NMI */
495 #endif /* NISA > 0 */
496
497                 case T_OFLOW:           /* integer overflow fault */
498                         ucode = FPE_INTOVF;
499                         i = SIGFPE;
500                         break;
501
502                 case T_BOUND:           /* bounds check fault */
503                         ucode = FPE_FLTSUB;
504                         i = SIGFPE;
505                         break;
506
507                 case T_DNA:
508 #if NNPX > 0
509                         /* if a transparent fault (due to context switch "late") */
510                         if (npxdna())
511                                 return;
512 #endif
513                         if (!pmath_emulate) {
514                                 i = SIGFPE;
515                                 ucode = FPE_FPU_NP_TRAP;
516                                 break;
517                         }
518                         i = (*pmath_emulate)(&frame);
519                         if (i == 0) {
520                                 if (!(frame.tf_eflags & PSL_T))
521                                         return;
522                                 frame.tf_eflags &= ~PSL_T;
523                                 i = SIGTRAP;
524                         }
525                         /* else ucode = emulator_only_knows() XXX */
526                         break;
527
528                 case T_FPOPFLT:         /* FPU operand fetch fault */
529                         ucode = T_FPOPFLT;
530                         i = SIGILL;
531                         break;
532
533                 case T_XMMFLT:          /* SIMD floating-point exception */
534                         ucode = 0; /* XXX */
535                         i = SIGFPE;
536                         break;
537                 }
538         } else {
539 kernel_trap:
540                 /* kernel trap */
541
542                 switch (type) {
543                 case T_PAGEFLT:                 /* page fault */
544                         (void) trap_pfault(&frame, FALSE, eva);
545                         return;
546
547                 case T_DNA:
548 #if NNPX > 0
549                         /*
550                          * The kernel is apparently using npx for copying.
551                          * XXX this should be fatal unless the kernel has
552                          * registered such use.
553                          */
554                         if (npxdna())
555                                 return;
556 #endif
557                         break;
558
559                 case T_PROTFLT:         /* general protection fault */
560                 case T_SEGNPFLT:        /* segment not present fault */
561                         /*
562                          * Invalid segment selectors and out of bounds
563                          * %eip's and %esp's can be set up in user mode.
564                          * This causes a fault in kernel mode when the
565                          * kernel tries to return to user mode.  We want
566                          * to get this fault so that we can fix the
567                          * problem here and not have to check all the
568                          * selectors and pointers when the user changes
569                          * them.
570                          */
571 #define MAYBE_DORETI_FAULT(where, whereto)                              \
572         do {                                                            \
573                 if (frame.tf_eip == (int)where) {                       \
574                         frame.tf_eip = (int)whereto;                    \
575                         return;                                         \
576                 }                                                       \
577         } while (0)
578
579                         if (mycpu->gd_intr_nesting_level == 0) {
580                                 /*
581                                  * Invalid %fs's and %gs's can be created using
582                                  * procfs or PT_SETREGS or by invalidating the
583                                  * underlying LDT entry.  This causes a fault
584                                  * in kernel mode when the kernel attempts to
585                                  * switch contexts.  Lose the bad context
586                                  * (XXX) so that we can continue, and generate
587                                  * a signal.
588                                  */
589                                 if (frame.tf_eip == (int)cpu_switch_load_gs) {
590                                         curthread->td_pcb->pcb_gs = 0;
591                                         psignal(p, SIGBUS);
592                                         return;
593                                 }
594                                 MAYBE_DORETI_FAULT(doreti_iret,
595                                                    doreti_iret_fault);
596                                 MAYBE_DORETI_FAULT(doreti_popl_ds,
597                                                    doreti_popl_ds_fault);
598                                 MAYBE_DORETI_FAULT(doreti_popl_es,
599                                                    doreti_popl_es_fault);
600                                 MAYBE_DORETI_FAULT(doreti_popl_fs,
601                                                    doreti_popl_fs_fault);
602                                 if (curthread->td_pcb->pcb_onfault) {
603                                         frame.tf_eip = (int)curthread->td_pcb->pcb_onfault;
604                                         return;
605                                 }
606                         }
607                         break;
608
609                 case T_TSSFLT:
610                         /*
611                          * PSL_NT can be set in user mode and isn't cleared
612                          * automatically when the kernel is entered.  This
613                          * causes a TSS fault when the kernel attempts to
614                          * `iret' because the TSS link is uninitialized.  We
615                          * want to get this fault so that we can fix the
616                          * problem here and not every time the kernel is
617                          * entered.
618                          */
619                         if (frame.tf_eflags & PSL_NT) {
620                                 frame.tf_eflags &= ~PSL_NT;
621                                 return;
622                         }
623                         break;
624
625                 case T_TRCTRAP:  /* trace trap */
626                         if (frame.tf_eip == (int)IDTVEC(syscall)) {
627                                 /*
628                                  * We've just entered system mode via the
629                                  * syscall lcall.  Continue single stepping
630                                  * silently until the syscall handler has
631                                  * saved the flags.
632                                  */
633                                 return;
634                         }
635                         if (frame.tf_eip == (int)IDTVEC(syscall) + 1) {
636                                 /*
637                                  * The syscall handler has now saved the
638                                  * flags.  Stop single stepping it.
639                                  */
640                                 frame.tf_eflags &= ~PSL_T;
641                                 return;
642                         }
643                         /*
644                          * Ignore debug register trace traps due to
645                          * accesses in the user's address space, which
646                          * can happen under several conditions such as
647                          * if a user sets a watchpoint on a buffer and
648                          * then passes that buffer to a system call.
649                          * We still want to get TRCTRAPS for addresses
650                          * in kernel space because that is useful when
651                          * debugging the kernel.
652                          */
653                         if (user_dbreg_trap()) {
654                                 /*
655                                  * Reset breakpoint bits because the
656                                  * processor doesn't
657                                  */
658                                 load_dr6(rdr6() & 0xfffffff0);
659                                 return;
660                         }
661                         /*
662                          * Fall through (TRCTRAP kernel mode, kernel address)
663                          */
664                 case T_BPTFLT:
665                         /*
666                          * If DDB is enabled, let it handle the debugger trap.
667                          * Otherwise, debugger traps "can't happen".
668                          */
669 #ifdef DDB
670                         if (kdb_trap (type, 0, &frame))
671                                 return;
672 #endif
673                         break;
674
675 #if NISA > 0
676                 case T_NMI:
677 #ifdef POWERFAIL_NMI
678 #ifndef TIMER_FREQ
679 #  define TIMER_FREQ 1193182
680 #endif
681         handle_powerfail:
682                 {
683                   static unsigned lastalert = 0;
684
685                   if(time_second - lastalert > 10)
686                     {
687                       log(LOG_WARNING, "NMI: power fail\n");
688                       sysbeep(TIMER_FREQ/880, hz);
689                       lastalert = time_second;
690                     }
691                   return;
692                 }
693 #else /* !POWERFAIL_NMI */
694                         /* machine/parity/power fail/"kitchen sink" faults */
695                         if (isa_nmi(code) == 0) {
696 #ifdef DDB
697                                 /*
698                                  * NMI can be hooked up to a pushbutton
699                                  * for debugging.
700                                  */
701                                 if (ddb_on_nmi) {
702                                         printf ("NMI ... going to debugger\n");
703                                         kdb_trap (type, 0, &frame);
704                                 }
705 #endif /* DDB */
706                                 return;
707                         } else if (panic_on_nmi == 0)
708                                 return;
709                         /* FALL THROUGH */
710 #endif /* POWERFAIL_NMI */
711 #endif /* NISA > 0 */
712                 }
713
714                 trap_fatal(&frame, eva);
715                 return;
716         }
717
718         /* Translate fault for emulators (e.g. Linux) */
719         if (*p->p_sysent->sv_transtrap)
720                 i = (*p->p_sysent->sv_transtrap)(i, type);
721
722         trapsignal(p, i, ucode);
723
724 #ifdef DEBUG
725         if (type <= MAX_TRAP_MSG) {
726                 uprintf("fatal process exception: %s",
727                         trap_msg[type]);
728                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
729                         uprintf(", fault VA = 0x%lx", (u_long)eva);
730                 uprintf("\n");
731         }
732 #endif
733
734 out:
735         userret(p, &frame, sticks, 1);
736 }
737
738 #ifdef notyet
739 /*
740  * This version doesn't allow a page fault to user space while
741  * in the kernel. The rest of the kernel needs to be made "safe"
742  * before this can be used. I think the only things remaining
743  * to be made safe are the iBCS2 code and the process tracing/
744  * debugging code.
745  */
746 static int
747 trap_pfault(frame, usermode, eva)
748         struct trapframe *frame;
749         int usermode;
750         vm_offset_t eva;
751 {
752         vm_offset_t va;
753         struct vmspace *vm = NULL;
754         vm_map_t map = 0;
755         int rv = 0;
756         vm_prot_t ftype;
757         struct proc *p = curproc;
758
759         if (frame->tf_err & PGEX_W)
760                 ftype = VM_PROT_WRITE;
761         else
762                 ftype = VM_PROT_READ;
763
764         va = trunc_page(eva);
765         if (va < VM_MIN_KERNEL_ADDRESS) {
766                 vm_offset_t v;
767                 vm_page_t mpte;
768
769                 if (p == NULL ||
770                     (!usermode && va < VM_MAXUSER_ADDRESS &&
771                      (mycpu->gd_intr_nesting_level != 0 || 
772                       curthread->td_pcb->pcb_onfault == NULL))) {
773                         trap_fatal(frame, eva);
774                         return (-1);
775                 }
776
777                 /*
778                  * This is a fault on non-kernel virtual memory.
779                  * vm is initialized above to NULL. If curproc is NULL
780                  * or curproc->p_vmspace is NULL the fault is fatal.
781                  */
782                 vm = p->p_vmspace;
783                 if (vm == NULL)
784                         goto nogo;
785
786                 map = &vm->vm_map;
787
788                 /*
789                  * Keep swapout from messing with us during this
790                  *      critical time.
791                  */
792                 ++p->p_lock;
793
794                 /*
795                  * Grow the stack if necessary
796                  */
797                 /* grow_stack returns false only if va falls into
798                  * a growable stack region and the stack growth
799                  * fails.  It returns true if va was not within
800                  * a growable stack region, or if the stack 
801                  * growth succeeded.
802                  */
803                 if (!grow_stack (p, va)) {
804                         rv = KERN_FAILURE;
805                         --p->p_lock;
806                         goto nogo;
807                 }
808                 
809                 /* Fault in the user page: */
810                 rv = vm_fault(map, va, ftype,
811                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
812                                                       : VM_FAULT_NORMAL);
813
814                 --p->p_lock;
815         } else {
816                 /*
817                  * Don't allow user-mode faults in kernel address space.
818                  */
819                 if (usermode)
820                         goto nogo;
821
822                 /*
823                  * Since we know that kernel virtual address addresses
824                  * always have pte pages mapped, we just have to fault
825                  * the page.
826                  */
827                 rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
828         }
829
830         if (rv == KERN_SUCCESS)
831                 return (0);
832 nogo:
833         if (!usermode) {
834                 if (mycpu->gd_intr_nesting_level == 0 && curthread->td_pcb->pcb_onfault) {
835                         frame->tf_eip = (int)curthread->td_pcb->pcb_onfault;
836                         return (0);
837                 }
838                 trap_fatal(frame, eva);
839                 return (-1);
840         }
841
842         /* kludge to pass faulting virtual address to sendsig */
843         frame->tf_err = eva;
844
845         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
846 }
847 #endif
848
849 int
850 trap_pfault(frame, usermode, eva)
851         struct trapframe *frame;
852         int usermode;
853         vm_offset_t eva;
854 {
855         vm_offset_t va;
856         struct vmspace *vm = NULL;
857         vm_map_t map = 0;
858         int rv = 0;
859         vm_prot_t ftype;
860         struct proc *p = curproc;
861
862         va = trunc_page(eva);
863         if (va >= KERNBASE) {
864                 /*
865                  * Don't allow user-mode faults in kernel address space.
866                  * An exception:  if the faulting address is the invalid
867                  * instruction entry in the IDT, then the Intel Pentium
868                  * F00F bug workaround was triggered, and we need to
869                  * treat it is as an illegal instruction, and not a page
870                  * fault.
871                  */
872 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
873                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
874                         frame->tf_trapno = T_PRIVINFLT;
875                         return -2;
876                 }
877 #endif
878                 if (usermode)
879                         goto nogo;
880
881                 map = kernel_map;
882         } else {
883                 /*
884                  * This is a fault on non-kernel virtual memory.
885                  * vm is initialized above to NULL. If curproc is NULL
886                  * or curproc->p_vmspace is NULL the fault is fatal.
887                  */
888                 if (p != NULL)
889                         vm = p->p_vmspace;
890
891                 if (vm == NULL)
892                         goto nogo;
893
894                 map = &vm->vm_map;
895         }
896
897         if (frame->tf_err & PGEX_W)
898                 ftype = VM_PROT_WRITE;
899         else
900                 ftype = VM_PROT_READ;
901
902         if (map != kernel_map) {
903                 /*
904                  * Keep swapout from messing with us during this
905                  *      critical time.
906                  */
907                 ++p->p_lock;
908
909                 /*
910                  * Grow the stack if necessary
911                  */
912                 /* grow_stack returns false only if va falls into
913                  * a growable stack region and the stack growth
914                  * fails.  It returns true if va was not within
915                  * a growable stack region, or if the stack 
916                  * growth succeeded.
917                  */
918                 if (!grow_stack (p, va)) {
919                         rv = KERN_FAILURE;
920                         --p->p_lock;
921                         goto nogo;
922                 }
923
924                 /* Fault in the user page: */
925                 rv = vm_fault(map, va, ftype,
926                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
927                                                       : VM_FAULT_NORMAL);
928
929                 --p->p_lock;
930         } else {
931                 /*
932                  * Don't have to worry about process locking or stacks in the kernel.
933                  */
934                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
935         }
936
937         if (rv == KERN_SUCCESS)
938                 return (0);
939 nogo:
940         if (!usermode) {
941                 if (mycpu->gd_intr_nesting_level == 0 && curthread->td_pcb->pcb_onfault) {
942                         frame->tf_eip = (int)curthread->td_pcb->pcb_onfault;
943                         return (0);
944                 }
945                 trap_fatal(frame, eva);
946                 return (-1);
947         }
948
949         /* kludge to pass faulting virtual address to sendsig */
950         frame->tf_err = eva;
951
952         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
953 }
954
955 static void
956 trap_fatal(frame, eva)
957         struct trapframe *frame;
958         vm_offset_t eva;
959 {
960         int code, type, ss, esp;
961         struct soft_segment_descriptor softseg;
962
963         code = frame->tf_err;
964         type = frame->tf_trapno;
965         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
966
967         if (type <= MAX_TRAP_MSG)
968                 printf("\n\nFatal trap %d: %s while in %s mode\n",
969                         type, trap_msg[type],
970                         frame->tf_eflags & PSL_VM ? "vm86" :
971                         ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
972 #ifdef SMP
973         /* three seperate prints in case of a trap on an unmapped page */
974         printf("mp_lock = %08x; ", mp_lock);
975         printf("cpuid = %d; ", cpuid);
976         printf("lapic.id = %08x\n", lapic.id);
977 #endif
978         if (type == T_PAGEFLT) {
979                 printf("fault virtual address   = 0x%x\n", eva);
980                 printf("fault code              = %s %s, %s\n",
981                         code & PGEX_U ? "user" : "supervisor",
982                         code & PGEX_W ? "write" : "read",
983                         code & PGEX_P ? "protection violation" : "page not present");
984         }
985         printf("instruction pointer     = 0x%x:0x%x\n",
986                frame->tf_cs & 0xffff, frame->tf_eip);
987         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
988                 ss = frame->tf_ss & 0xffff;
989                 esp = frame->tf_esp;
990         } else {
991                 ss = GSEL(GDATA_SEL, SEL_KPL);
992                 esp = (int)&frame->tf_esp;
993         }
994         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
995         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
996         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
997                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
998         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
999                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
1000                softseg.ssd_gran);
1001         printf("processor eflags        = ");
1002         if (frame->tf_eflags & PSL_T)
1003                 printf("trace trap, ");
1004         if (frame->tf_eflags & PSL_I)
1005                 printf("interrupt enabled, ");
1006         if (frame->tf_eflags & PSL_NT)
1007                 printf("nested task, ");
1008         if (frame->tf_eflags & PSL_RF)
1009                 printf("resume, ");
1010         if (frame->tf_eflags & PSL_VM)
1011                 printf("vm86, ");
1012         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
1013         printf("current process         = ");
1014         if (curproc) {
1015                 printf("%lu (%s)\n",
1016                     (u_long)curproc->p_pid, curproc->p_comm ?
1017                     curproc->p_comm : "");
1018         } else {
1019                 printf("Idle\n");
1020         }
1021         printf("current thread          = pri %d ", curthread->td_pri);
1022         if (curthread->td_pri >= TDPRI_CRIT)
1023                 printf("(CRIT)");
1024         printf("\n");
1025         printf("interrupt mask          = ");
1026         if ((curthread->td_cpl & net_imask) == net_imask)
1027                 printf("net ");
1028         if ((curthread->td_cpl & tty_imask) == tty_imask)
1029                 printf("tty ");
1030         if ((curthread->td_cpl & bio_imask) == bio_imask)
1031                 printf("bio ");
1032         if ((curthread->td_cpl & cam_imask) == cam_imask)
1033                 printf("cam ");
1034         if (curthread->td_cpl == 0)
1035                 printf("none");
1036 #ifdef SMP
1037 /**
1038  *  XXX FIXME:
1039  *      we probably SHOULD have stopped the other CPUs before now!
1040  *      another CPU COULD have been touching cpl at this moment...
1041  */
1042         printf(" <- SMP: XXX");
1043 #endif
1044         printf("\n");
1045
1046 #ifdef KDB
1047         if (kdb_trap(&psl))
1048                 return;
1049 #endif
1050 #ifdef DDB
1051         if ((debugger_on_panic || db_active) && kdb_trap(type, 0, frame))
1052                 return;
1053 #endif
1054         printf("trap number             = %d\n", type);
1055         if (type <= MAX_TRAP_MSG)
1056                 panic("%s", trap_msg[type]);
1057         else
1058                 panic("unknown/reserved trap");
1059 }
1060
1061 /*
1062  * Double fault handler. Called when a fault occurs while writing
1063  * a frame for a trap/exception onto the stack. This usually occurs
1064  * when the stack overflows (such is the case with infinite recursion,
1065  * for example).
1066  *
1067  * XXX Note that the current PTD gets replaced by IdlePTD when the
1068  * task switch occurs. This means that the stack that was active at
1069  * the time of the double fault is not available at <kstack> unless
1070  * the machine was idle when the double fault occurred. The downside
1071  * of this is that "trace <ebp>" in ddb won't work.
1072  */
1073 void
1074 dblfault_handler()
1075 {
1076         struct mdglobaldata *gd = mdcpu;
1077
1078         printf("\nFatal double fault:\n");
1079         printf("eip = 0x%x\n", gd->gd_common_tss.tss_eip);
1080         printf("esp = 0x%x\n", gd->gd_common_tss.tss_esp);
1081         printf("ebp = 0x%x\n", gd->gd_common_tss.tss_ebp);
1082 #ifdef SMP
1083         /* three seperate prints in case of a trap on an unmapped page */
1084         printf("mp_lock = %08x; ", mp_lock);
1085         printf("cpuid = %d; ", cpuid);
1086         printf("lapic.id = %08x\n", lapic.id);
1087 #endif
1088         panic("double fault");
1089 }
1090
1091 /*
1092  * Compensate for 386 brain damage (missing URKR).
1093  * This is a little simpler than the pagefault handler in trap() because
1094  * it the page tables have already been faulted in and high addresses
1095  * are thrown out early for other reasons.
1096  */
1097 int trapwrite(addr)
1098         unsigned addr;
1099 {
1100         struct proc *p;
1101         vm_offset_t va;
1102         struct vmspace *vm;
1103         int rv;
1104
1105         va = trunc_page((vm_offset_t)addr);
1106         /*
1107          * XXX - MAX is END.  Changed > to >= for temp. fix.
1108          */
1109         if (va >= VM_MAXUSER_ADDRESS)
1110                 return (1);
1111
1112         p = curproc;
1113         vm = p->p_vmspace;
1114
1115         ++p->p_lock;
1116
1117         if (!grow_stack (p, va)) {
1118                 --p->p_lock;
1119                 return (1);
1120         }
1121
1122         /*
1123          * fault the data page
1124          */
1125         rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
1126
1127         --p->p_lock;
1128
1129         if (rv != KERN_SUCCESS)
1130                 return 1;
1131
1132         return (0);
1133 }
1134
1135 /*
1136  *      syscall2 -      MP aware system call request C handler
1137  *
1138  *      A system call is essentially treated as a trap except that the
1139  *      MP lock is not held on entry or return.  We are responsible for
1140  *      obtaining the MP lock if necessary and for handling ASTs
1141  *      (e.g. a task switch) prior to return.
1142  *
1143  *      In general, only simple access and manipulation of curproc and
1144  *      the current stack is allowed without having to hold MP lock.
1145  */
1146 void
1147 syscall2(frame)
1148         struct trapframe frame;
1149 {
1150         struct thread *td = curthread;
1151         struct proc *p = td->td_proc;
1152         caddr_t params;
1153         int i;
1154         struct sysent *callp;
1155         register_t orig_tf_eflags;
1156         u_quad_t sticks;
1157         int error;
1158         int narg;
1159         int args[8];
1160         int have_mplock = 0;
1161         u_int code;
1162
1163 #ifdef DIAGNOSTIC
1164         if (ISPL(frame.tf_cs) != SEL_UPL) {
1165                 get_mplock();
1166                 panic("syscall");
1167                 /* NOT REACHED */
1168         }
1169 #endif
1170
1171         /*
1172          * access non-atomic field from critical section.  p_sticks is
1173          * updated by the clock interrupt.  Also use this opportunity
1174          * to raise our LWKT priority.
1175          */
1176         crit_enter();
1177         userenter();
1178         sticks = curthread->td_sticks;
1179         crit_exit();
1180
1181         p->p_md.md_regs = &frame;
1182         params = (caddr_t)frame.tf_esp + sizeof(int);
1183         code = frame.tf_eax;
1184         orig_tf_eflags = frame.tf_eflags;
1185
1186         if (p->p_sysent->sv_prepsyscall) {
1187                 /*
1188                  * The prep code is not MP aware.
1189                  */
1190                 get_mplock();
1191                 (*p->p_sysent->sv_prepsyscall)(&frame, args, &code, &params);
1192                 rel_mplock();
1193         } else {
1194                 /*
1195                  * Need to check if this is a 32 bit or 64 bit syscall.
1196                  * fuword is MP aware.
1197                  */
1198                 if (code == SYS_syscall) {
1199                         /*
1200                          * Code is first argument, followed by actual args.
1201                          */
1202                         code = fuword(params);
1203                         params += sizeof(int);
1204                 } else if (code == SYS___syscall) {
1205                         /*
1206                          * Like syscall, but code is a quad, so as to maintain
1207                          * quad alignment for the rest of the arguments.
1208                          */
1209                         code = fuword(params);
1210                         params += sizeof(quad_t);
1211                 }
1212         }
1213
1214         if (p->p_sysent->sv_mask)
1215                 code &= p->p_sysent->sv_mask;
1216
1217         if (code >= p->p_sysent->sv_size)
1218                 callp = &p->p_sysent->sv_table[0];
1219         else
1220                 callp = &p->p_sysent->sv_table[code];
1221
1222         narg = callp->sy_narg & SYF_ARGMASK;
1223
1224         /*
1225          * copyin is MP aware, but the tracing code is not
1226          */
1227         if (params && (i = narg * sizeof(int)) &&
1228             (error = copyin(params, (caddr_t)args, (u_int)i))) {
1229                 get_mplock();
1230                 have_mplock = 1;
1231 #ifdef KTRACE
1232                 if (KTRPOINT(td, KTR_SYSCALL))
1233                         ktrsyscall(p->p_tracep, code, narg, args);
1234 #endif
1235                 goto bad;
1236         }
1237
1238         /*
1239          * Try to run the syscall without the MP lock if the syscall
1240          * is MP safe.  We have to obtain the MP lock no matter what if 
1241          * we are ktracing
1242          */
1243         if ((callp->sy_narg & SYF_MPSAFE) == 0) {
1244                 get_mplock();
1245                 have_mplock = 1;
1246         }
1247
1248 #ifdef KTRACE
1249         if (KTRPOINT(td, KTR_SYSCALL)) {
1250                 if (have_mplock == 0) {
1251                         get_mplock();
1252                         have_mplock = 1;
1253                 }
1254                 ktrsyscall(p->p_tracep, code, narg, args);
1255         }
1256 #endif
1257         p->p_retval[0] = 0;
1258         p->p_retval[1] = frame.tf_edx;
1259
1260         STOPEVENT(p, S_SCE, narg);      /* MP aware */
1261
1262         error = (*callp->sy_call)(args);
1263
1264         /*
1265          * MP SAFE (we may or may not have the MP lock at this point)
1266          */
1267         switch (error) {
1268         case 0:
1269                 /*
1270                  * Reinitialize proc pointer `p' as it may be different
1271                  * if this is a child returning from fork syscall.
1272                  */
1273                 p = curproc;
1274                 frame.tf_eax = p->p_retval[0];
1275                 frame.tf_edx = p->p_retval[1];
1276                 frame.tf_eflags &= ~PSL_C;
1277                 break;
1278
1279         case ERESTART:
1280                 /*
1281                  * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1282                  * int 0x80 is 2 bytes. We saved this in tf_err.
1283                  */
1284                 frame.tf_eip -= frame.tf_err;
1285                 break;
1286
1287         case EJUSTRETURN:
1288                 break;
1289
1290         default:
1291 bad:
1292                 if (p->p_sysent->sv_errsize) {
1293                         if (error >= p->p_sysent->sv_errsize)
1294                                 error = -1;     /* XXX */
1295                         else
1296                                 error = p->p_sysent->sv_errtbl[error];
1297                 }
1298                 frame.tf_eax = error;
1299                 frame.tf_eflags |= PSL_C;
1300                 break;
1301         }
1302
1303         /*
1304          * Traced syscall.  trapsignal() is not MP aware.
1305          */
1306         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1307                 if (have_mplock == 0) {
1308                         get_mplock();
1309                         have_mplock = 1;
1310                 }
1311                 frame.tf_eflags &= ~PSL_T;
1312                 trapsignal(p, SIGTRAP, 0);
1313         }
1314
1315         /*
1316          * Handle reschedule and other end-of-syscall issues
1317          */
1318         have_mplock = userret(p, &frame, sticks, have_mplock);
1319
1320 #ifdef KTRACE
1321         if (KTRPOINT(td, KTR_SYSRET)) {
1322                 if (have_mplock == 0) {
1323                         get_mplock();
1324                         have_mplock = 1;
1325                 }
1326                 ktrsysret(p->p_tracep, code, error, p->p_retval[0]);
1327         }
1328 #endif
1329
1330         /*
1331          * This works because errno is findable through the
1332          * register set.  If we ever support an emulation where this
1333          * is not the case, this code will need to be revisited.
1334          */
1335         STOPEVENT(p, S_SCX, code);
1336
1337         /*
1338          * Release the MP lock if we had to get it
1339          */
1340         if (have_mplock)
1341                 rel_mplock();
1342 }
1343
1344 /*
1345  * Simplified back end of syscall(), used when returning from fork()
1346  * directly into user mode.  MP lock is held on entry and should be 
1347  * held on return.
1348  */
1349 void
1350 fork_return(p, frame)
1351         struct proc *p;
1352         struct trapframe frame;
1353 {
1354         frame.tf_eax = 0;               /* Child returns zero */
1355         frame.tf_eflags &= ~PSL_C;      /* success */
1356         frame.tf_edx = 1;
1357
1358         userret(p, &frame, 0, 1);
1359 #ifdef KTRACE
1360         if (KTRPOINT(p->p_thread, KTR_SYSRET))
1361                 ktrsysret(p->p_tracep, SYS_fork, 0, 0);
1362 #endif
1363 }