]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/i386/i386/trap.c
o Call vm_map_growstack() from vm_fault() if vm_map_lookup() has failed
[FreeBSD/FreeBSD.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$
39  */
40
41 /*
42  * 386 Trap and System call handling
43  */
44
45 #include "opt_clock.h"
46 #include "opt_cpu.h"
47 #include "opt_ddb.h"
48 #include "opt_isa.h"
49 #include "opt_ktrace.h"
50 #include "opt_npx.h"
51 #include "opt_trap.h"
52
53 #include <sys/param.h>
54 #include <sys/bus.h>
55 #include <sys/systm.h>
56 #include <sys/proc.h>
57 #include <sys/pioctl.h>
58 #include <sys/kernel.h>
59 #include <sys/ktr.h>
60 #include <sys/lock.h>
61 #include <sys/mutex.h>
62 #include <sys/resourcevar.h>
63 #include <sys/signalvar.h>
64 #include <sys/syscall.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/uio.h>
68 #include <sys/vmmeter.h>
69 #ifdef KTRACE
70 #include <sys/ktrace.h>
71 #endif
72
73 #include <vm/vm.h>
74 #include <vm/vm_param.h>
75 #include <vm/pmap.h>
76 #include <vm/vm_kern.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_page.h>
79 #include <vm/vm_extern.h>
80
81 #include <machine/cpu.h>
82 #include <machine/md_var.h>
83 #include <machine/pcb.h>
84 #ifdef SMP
85 #include <machine/smp.h>
86 #endif
87 #include <machine/tss.h>
88
89 #include <i386/isa/icu.h>
90 #include <i386/isa/intr_machdep.h>
91
92 #ifdef POWERFAIL_NMI
93 #include <sys/syslog.h>
94 #include <machine/clock.h>
95 #endif
96
97 #include <machine/vm86.h>
98
99 #include <ddb/ddb.h>
100
101 #include <sys/sysctl.h>
102
103 int (*pmath_emulate)(struct trapframe *);
104
105 extern void trap(struct trapframe frame);
106 #ifdef I386_CPU
107 extern int trapwrite(unsigned addr);
108 #endif
109 extern void syscall(struct trapframe frame);
110
111 static int trap_pfault(struct trapframe *, int, vm_offset_t);
112 static void trap_fatal(struct trapframe *, vm_offset_t);
113 void dblfault_handler(void);
114
115 extern inthand_t IDTVEC(lcall_syscall);
116
117 #define MAX_TRAP_MSG            28
118 static char *trap_msg[] = {
119         "",                                     /*  0 unused */
120         "privileged instruction fault",         /*  1 T_PRIVINFLT */
121         "",                                     /*  2 unused */
122         "breakpoint instruction fault",         /*  3 T_BPTFLT */
123         "",                                     /*  4 unused */
124         "",                                     /*  5 unused */
125         "arithmetic trap",                      /*  6 T_ARITHTRAP */
126         "",                                     /*  7 unused */
127         "",                                     /*  8 unused */
128         "general protection fault",             /*  9 T_PROTFLT */
129         "trace trap",                           /* 10 T_TRCTRAP */
130         "",                                     /* 11 unused */
131         "page fault",                           /* 12 T_PAGEFLT */
132         "",                                     /* 13 unused */
133         "alignment fault",                      /* 14 T_ALIGNFLT */
134         "",                                     /* 15 unused */
135         "",                                     /* 16 unused */
136         "",                                     /* 17 unused */
137         "integer divide fault",                 /* 18 T_DIVIDE */
138         "non-maskable interrupt trap",          /* 19 T_NMI */
139         "overflow trap",                        /* 20 T_OFLOW */
140         "FPU bounds check fault",               /* 21 T_BOUND */
141         "FPU device not available",             /* 22 T_DNA */
142         "double fault",                         /* 23 T_DOUBLEFLT */
143         "FPU operand fetch fault",              /* 24 T_FPOPFLT */
144         "invalid TSS fault",                    /* 25 T_TSSFLT */
145         "segment not present fault",            /* 26 T_SEGNPFLT */
146         "stack fault",                          /* 27 T_STKFLT */
147         "machine check trap",                   /* 28 T_MCHK */
148 };
149
150 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
151 extern int has_f00f_bug;
152 #endif
153
154 #ifdef DDB
155 static int ddb_on_nmi = 1;
156 SYSCTL_INT(_machdep, OID_AUTO, ddb_on_nmi, CTLFLAG_RW,
157         &ddb_on_nmi, 0, "Go to DDB on NMI");
158 #endif
159 static int panic_on_nmi = 1;
160 SYSCTL_INT(_machdep, OID_AUTO, panic_on_nmi, CTLFLAG_RW,
161         &panic_on_nmi, 0, "Panic on NMI");
162
163 #ifdef WITNESS
164 extern char *syscallnames[];
165 #endif
166
167 #ifdef DEVICE_POLLING
168 extern u_int32_t poll_in_trap;
169 extern int ether_poll(int count);
170 #endif /* DEVICE_POLLING */
171
172 /*
173  * Exception, fault, and trap interface to the FreeBSD kernel.
174  * This common code is called from assembly language IDT gate entry
175  * routines that prepare a suitable stack frame, and restore this
176  * frame after the exception has been processed.
177  */
178
179 void
180 trap(frame)
181         struct trapframe frame;
182 {
183         struct thread *td = curthread;
184         struct proc *p = td->td_proc;
185         u_int sticks = 0;
186         int i = 0, ucode = 0, type, code;
187         vm_offset_t eva;
188 #ifdef POWERFAIL_NMI
189         static int lastalert = 0;
190 #endif
191
192         atomic_add_int(&cnt.v_trap, 1);
193
194         if ((frame.tf_eflags & PSL_I) == 0) {
195                 /*
196                  * Buggy application or kernel code has disabled
197                  * interrupts and then trapped.  Enabling interrupts
198                  * now is wrong, but it is better than running with
199                  * interrupts disabled until they are accidentally
200                  * enabled later.
201                  */
202                 type = frame.tf_trapno;
203                 if (ISPL(frame.tf_cs) == SEL_UPL || (frame.tf_eflags & PSL_VM))
204                         printf(
205                             "pid %ld (%s): trap %d with interrupts disabled\n",
206                             (long)curproc->p_pid, curproc->p_comm, type);
207                 else if (type != T_BPTFLT && type != T_TRCTRAP) {
208                         /*
209                          * XXX not quite right, since this may be for a
210                          * multiple fault in user mode.
211                          */
212                         printf("kernel trap %d with interrupts disabled\n",
213                             type);
214                         /*
215                          * Page faults need interrupts diasabled until later,
216                          * and we shouldn't enable interrupts while holding a
217                          * spin lock.
218                          */
219                         if (type != T_PAGEFLT && PCPU_GET(spinlocks) == NULL)
220                                 enable_intr();
221                 }
222         }
223
224         eva = 0;
225         type = frame.tf_trapno;
226         code = frame.tf_err;
227         if (type == T_PAGEFLT) {
228                 /*
229                  * For some Cyrix CPUs, %cr2 is clobbered by
230                  * interrupts.  This problem is worked around by using
231                  * an interrupt gate for the pagefault handler.  We
232                  * are finally ready to read %cr2 and then must
233                  * reenable interrupts.
234                  *
235                  * If we get a page fault while holding a spin lock, then
236                  * it is most likely a fatal kernel page fault.  The kernel
237                  * is already going to panic trying to get a sleep lock to
238                  * do the VM lookup, so just consider it a fatal trap so the
239                  * kernel can print out a useful trap message and even get
240                  * to the debugger.
241                  */
242                 eva = rcr2();
243                 if (PCPU_GET(spinlocks) == NULL)
244                         enable_intr();
245                 else
246                         trap_fatal(&frame, eva);
247         }
248
249 #ifdef  DEVICE_POLLING
250         if (poll_in_trap)
251                 ether_poll(poll_in_trap);
252 #endif  /* DEVICE_POLLING */
253
254         if ((ISPL(frame.tf_cs) == SEL_UPL) ||
255             ((frame.tf_eflags & PSL_VM) && !in_vm86call)) {
256                 /* user trap */
257
258                 sticks = td->td_kse->ke_sticks;
259                 td->td_frame = &frame;
260                 if (td->td_ucred != p->p_ucred) 
261                         cred_update_thread(td);
262
263                 switch (type) {
264                 case T_PRIVINFLT:       /* privileged instruction fault */
265                         ucode = type;
266                         i = SIGILL;
267                         break;
268
269                 case T_BPTFLT:          /* bpt instruction fault */
270                 case T_TRCTRAP:         /* trace trap */
271                         frame.tf_eflags &= ~PSL_T;
272                         i = SIGTRAP;
273                         break;
274
275                 case T_ARITHTRAP:       /* arithmetic trap */
276 #ifdef DEV_NPX
277                         ucode = npxtrap();
278                         if (ucode == -1)
279                                 goto userout;
280 #else
281                         ucode = code;
282 #endif
283                         i = SIGFPE;
284                         break;
285
286                         /*
287                          * The following two traps can happen in
288                          * vm86 mode, and, if so, we want to handle
289                          * them specially.
290                          */
291                 case T_PROTFLT:         /* general protection fault */
292                 case T_STKFLT:          /* stack fault */
293                         if (frame.tf_eflags & PSL_VM) {
294                                 mtx_lock(&Giant);
295                                 i = vm86_emulate((struct vm86frame *)&frame);
296                                 mtx_unlock(&Giant);
297                                 if (i == 0)
298                                         goto user;
299                                 break;
300                         }
301                         /* FALL THROUGH */
302
303                 case T_SEGNPFLT:        /* segment not present fault */
304                 case T_TSSFLT:          /* invalid TSS fault */
305                 case T_DOUBLEFLT:       /* double fault */
306                 default:
307                         ucode = code + BUS_SEGM_FAULT ;
308                         i = SIGBUS;
309                         break;
310
311                 case T_PAGEFLT:         /* page fault */
312                         i = trap_pfault(&frame, TRUE, eva);
313 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
314                         if (i == -2) {
315                                 /*
316                                  * The f00f hack workaround has triggered, so
317                                  * treat the fault as an illegal instruction 
318                                  * (T_PRIVINFLT) instead of a page fault.
319                                  */
320                                 type = frame.tf_trapno = T_PRIVINFLT;
321
322                                 /* Proceed as in that case. */
323                                 ucode = type;
324                                 i = SIGILL;
325                                 break;
326                         }
327 #endif
328                         if (i == -1)
329                                 goto userout;
330                         if (i == 0)
331                                 goto user;
332
333                         ucode = T_PAGEFLT;
334                         break;
335
336                 case T_DIVIDE:          /* integer divide fault */
337                         ucode = FPE_INTDIV;
338                         i = SIGFPE;
339                         break;
340
341 #ifdef DEV_ISA
342                 case T_NMI:
343 #ifdef POWERFAIL_NMI
344 #ifndef TIMER_FREQ
345 #  define TIMER_FREQ 1193182
346 #endif
347                         mtx_lock(&Giant);
348                         if (time_second - lastalert > 10) {
349                                 log(LOG_WARNING, "NMI: power fail\n");
350                                 sysbeep(TIMER_FREQ/880, hz);
351                                 lastalert = time_second;
352                         }
353                         mtx_unlock(&Giant);
354                         goto userout;
355 #else /* !POWERFAIL_NMI */
356                         /* machine/parity/power fail/"kitchen sink" faults */
357                         /* XXX Giant */
358                         if (isa_nmi(code) == 0) {
359 #ifdef DDB
360                                 /*
361                                  * NMI can be hooked up to a pushbutton
362                                  * for debugging.
363                                  */
364                                 if (ddb_on_nmi) {
365                                         printf ("NMI ... going to debugger\n");
366                                         kdb_trap (type, 0, &frame);
367                                 }
368 #endif /* DDB */
369                                 goto userout;
370                         } else if (panic_on_nmi)
371                                 panic("NMI indicates hardware failure");
372                         break;
373 #endif /* POWERFAIL_NMI */
374 #endif /* DEV_ISA */
375
376                 case T_OFLOW:           /* integer overflow fault */
377                         ucode = FPE_INTOVF;
378                         i = SIGFPE;
379                         break;
380
381                 case T_BOUND:           /* bounds check fault */
382                         ucode = FPE_FLTSUB;
383                         i = SIGFPE;
384                         break;
385
386                 case T_DNA:
387 #ifdef DEV_NPX
388                         /* transparent fault (due to context switch "late") */
389                         if (npxdna())
390                                 goto userout;
391 #endif
392                         if (!pmath_emulate) {
393                                 i = SIGFPE;
394                                 ucode = FPE_FPU_NP_TRAP;
395                                 break;
396                         }
397                         mtx_lock(&Giant);
398                         i = (*pmath_emulate)(&frame);
399                         mtx_unlock(&Giant);
400                         if (i == 0) {
401                                 if (!(frame.tf_eflags & PSL_T))
402                                         goto userout;
403                                 frame.tf_eflags &= ~PSL_T;
404                                 i = SIGTRAP;
405                         }
406                         /* else ucode = emulator_only_knows() XXX */
407                         break;
408
409                 case T_FPOPFLT:         /* FPU operand fetch fault */
410                         ucode = T_FPOPFLT;
411                         i = SIGILL;
412                         break;
413
414                 case T_XMMFLT:          /* SIMD floating-point exception */
415                         ucode = 0; /* XXX */
416                         i = SIGFPE;
417                         break;
418                 }
419         } else {
420                 /* kernel trap */
421
422                 KASSERT(cold || td->td_ucred != NULL,
423                     ("kernel trap doesn't have ucred"));
424                 switch (type) {
425                 case T_PAGEFLT:                 /* page fault */
426                         (void) trap_pfault(&frame, FALSE, eva);
427                         goto out;
428
429                 case T_DNA:
430 #ifdef DEV_NPX
431                         /*
432                          * The kernel is apparently using npx for copying.
433                          * XXX this should be fatal unless the kernel has
434                          * registered such use.
435                          */
436                         if (npxdna())
437                                 goto out;
438 #endif
439                         break;
440
441                         /*
442                          * The following two traps can happen in
443                          * vm86 mode, and, if so, we want to handle
444                          * them specially.
445                          */
446                 case T_PROTFLT:         /* general protection fault */
447                 case T_STKFLT:          /* stack fault */
448                         if (frame.tf_eflags & PSL_VM) {
449                                 mtx_lock(&Giant);
450                                 i = vm86_emulate((struct vm86frame *)&frame);
451                                 mtx_unlock(&Giant);
452                                 if (i != 0)
453                                         /*
454                                          * returns to original process
455                                          */
456                                         vm86_trap((struct vm86frame *)&frame);
457                                 goto out;
458                         }
459                         if (type == T_STKFLT)
460                                 break;
461
462                         /* FALL THROUGH */
463
464                 case T_SEGNPFLT:        /* segment not present fault */
465                         if (in_vm86call)
466                                 break;
467
468                         if (td->td_intr_nesting_level != 0)
469                                 break;
470
471                         /*
472                          * Invalid %fs's and %gs's can be created using
473                          * procfs or PT_SETREGS or by invalidating the
474                          * underlying LDT entry.  This causes a fault
475                          * in kernel mode when the kernel attempts to
476                          * switch contexts.  Lose the bad context
477                          * (XXX) so that we can continue, and generate
478                          * a signal.
479                          */
480                         if (frame.tf_eip == (int)cpu_switch_load_gs) {
481                                 PCPU_GET(curpcb)->pcb_gs = 0;
482                                 PROC_LOCK(p);
483                                 psignal(p, SIGBUS);
484                                 PROC_UNLOCK(p);
485                                 goto out;
486                         }
487
488                         /*
489                          * Invalid segment selectors and out of bounds
490                          * %eip's and %esp's can be set up in user mode.
491                          * This causes a fault in kernel mode when the
492                          * kernel tries to return to user mode.  We want
493                          * to get this fault so that we can fix the
494                          * problem here and not have to check all the
495                          * selectors and pointers when the user changes
496                          * them.
497                          */
498                         if (frame.tf_eip == (int)doreti_iret) {
499                                 frame.tf_eip = (int)doreti_iret_fault;
500                                 goto out;
501                         }
502                         if (frame.tf_eip == (int)doreti_popl_ds) {
503                                 frame.tf_eip = (int)doreti_popl_ds_fault;
504                                 goto out;
505                         }
506                         if (frame.tf_eip == (int)doreti_popl_es) {
507                                 frame.tf_eip = (int)doreti_popl_es_fault;
508                                 goto out;
509                         }
510                         if (frame.tf_eip == (int)doreti_popl_fs) {
511                                 frame.tf_eip = (int)doreti_popl_fs_fault;
512                                 goto out;
513                         }
514                         if (PCPU_GET(curpcb) != NULL &&
515                             PCPU_GET(curpcb)->pcb_onfault != NULL) {
516                                 frame.tf_eip =
517                                     (int)PCPU_GET(curpcb)->pcb_onfault;
518                                 goto out;
519                         }
520                         break;
521
522                 case T_TSSFLT:
523                         /*
524                          * PSL_NT can be set in user mode and isn't cleared
525                          * automatically when the kernel is entered.  This
526                          * causes a TSS fault when the kernel attempts to
527                          * `iret' because the TSS link is uninitialized.  We
528                          * want to get this fault so that we can fix the
529                          * problem here and not every time the kernel is
530                          * entered.
531                          */
532                         if (frame.tf_eflags & PSL_NT) {
533                                 frame.tf_eflags &= ~PSL_NT;
534                                 goto out;
535                         }
536                         break;
537
538                 case T_TRCTRAP:  /* trace trap */
539                         if (frame.tf_eip == (int)IDTVEC(lcall_syscall)) {
540                                 /*
541                                  * We've just entered system mode via the
542                                  * syscall lcall.  Continue single stepping
543                                  * silently until the syscall handler has
544                                  * saved the flags.
545                                  */
546                                 goto out;
547                         }
548                         if (frame.tf_eip == (int)IDTVEC(lcall_syscall) + 1) {
549                                 /*
550                                  * The syscall handler has now saved the
551                                  * flags.  Stop single stepping it.
552                                  */
553                                 frame.tf_eflags &= ~PSL_T;
554                                 goto out;
555                         }
556                         /*
557                          * Ignore debug register trace traps due to
558                          * accesses in the user's address space, which
559                          * can happen under several conditions such as
560                          * if a user sets a watchpoint on a buffer and
561                          * then passes that buffer to a system call.
562                          * We still want to get TRCTRAPS for addresses
563                          * in kernel space because that is useful when
564                          * debugging the kernel.
565                          */
566                         /* XXX Giant */
567                         if (user_dbreg_trap() && !in_vm86call) {
568                                 /*
569                                  * Reset breakpoint bits because the
570                                  * processor doesn't
571                                  */
572                                 load_dr6(rdr6() & 0xfffffff0);
573                                 goto out;
574                         }
575                         /*
576                          * Fall through (TRCTRAP kernel mode, kernel address)
577                          */
578                 case T_BPTFLT:
579                         /*
580                          * If DDB is enabled, let it handle the debugger trap.
581                          * Otherwise, debugger traps "can't happen".
582                          */
583 #ifdef DDB
584                         /* XXX Giant */
585                         if (kdb_trap (type, 0, &frame))
586                                 goto out;
587 #endif
588                         break;
589
590 #ifdef DEV_ISA
591                 case T_NMI:
592 #ifdef POWERFAIL_NMI
593                         mtx_lock(&Giant);
594                         if (time_second - lastalert > 10) {
595                                 log(LOG_WARNING, "NMI: power fail\n");
596                                 sysbeep(TIMER_FREQ/880, hz);
597                                 lastalert = time_second;
598                         }
599                         mtx_unlock(&Giant);
600                         goto out;
601 #else /* !POWERFAIL_NMI */
602                         /* XXX Giant */
603                         /* machine/parity/power fail/"kitchen sink" faults */
604                         if (isa_nmi(code) == 0) {
605 #ifdef DDB
606                                 /*
607                                  * NMI can be hooked up to a pushbutton
608                                  * for debugging.
609                                  */
610                                 if (ddb_on_nmi) {
611                                         printf ("NMI ... going to debugger\n");
612                                         kdb_trap (type, 0, &frame);
613                                 }
614 #endif /* DDB */
615                                 goto out;
616                         } else if (panic_on_nmi == 0)
617                                 goto out;
618                         /* FALL THROUGH */
619 #endif /* POWERFAIL_NMI */
620 #endif /* DEV_ISA */
621                 }
622
623                 trap_fatal(&frame, eva);
624                 goto out;
625         }
626
627         /* Translate fault for emulators (e.g. Linux) */
628         if (*p->p_sysent->sv_transtrap)
629                 i = (*p->p_sysent->sv_transtrap)(i, type);
630
631         trapsignal(p, i, ucode);
632
633 #ifdef DEBUG
634         if (type <= MAX_TRAP_MSG) {
635                 uprintf("fatal process exception: %s",
636                         trap_msg[type]);
637                 if ((type == T_PAGEFLT) || (type == T_PROTFLT))
638                         uprintf(", fault VA = 0x%lx", (u_long)eva);
639                 uprintf("\n");
640         }
641 #endif
642
643 user:
644         userret(td, &frame, sticks);
645         mtx_assert(&Giant, MA_NOTOWNED);
646 userout:
647 #ifdef DIAGNOSTIC
648         cred_free_thread(td);
649 #endif
650 out:
651         return;
652 }
653
654 int
655 trap_pfault(frame, usermode, eva)
656         struct trapframe *frame;
657         int usermode;
658         vm_offset_t eva;
659 {
660         vm_offset_t va;
661         struct vmspace *vm = NULL;
662         vm_map_t map = 0;
663         int rv = 0;
664         vm_prot_t ftype;
665         struct thread *td = curthread;
666         struct proc *p = td->td_proc;
667
668         va = trunc_page(eva);
669         if (va >= KERNBASE) {
670                 /*
671                  * Don't allow user-mode faults in kernel address space.
672                  * An exception:  if the faulting address is the invalid
673                  * instruction entry in the IDT, then the Intel Pentium
674                  * F00F bug workaround was triggered, and we need to
675                  * treat it is as an illegal instruction, and not a page
676                  * fault.
677                  */
678 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
679                 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug)
680                         return -2;
681 #endif
682                 if (usermode)
683                         goto nogo;
684
685                 map = kernel_map;
686         } else {
687                 /*
688                  * This is a fault on non-kernel virtual memory.
689                  * vm is initialized above to NULL. If curproc is NULL
690                  * or curproc->p_vmspace is NULL the fault is fatal.
691                  */
692                 if (p != NULL)
693                         vm = p->p_vmspace;
694
695                 if (vm == NULL)
696                         goto nogo;
697
698                 map = &vm->vm_map;
699         }
700
701         if (frame->tf_err & PGEX_W)
702                 ftype = VM_PROT_WRITE;
703         else
704                 ftype = VM_PROT_READ;
705
706         if (map != kernel_map) {
707                 /*
708                  * Keep swapout from messing with us during this
709                  *      critical time.
710                  */
711                 PROC_LOCK(p);
712                 ++p->p_lock;
713                 PROC_UNLOCK(p);
714
715                 /* Fault in the user page: */
716                 rv = vm_fault(map, va, ftype,
717                               (ftype & VM_PROT_WRITE) ? VM_FAULT_DIRTY
718                                                       : VM_FAULT_NORMAL);
719
720                 PROC_LOCK(p);
721                 --p->p_lock;
722                 PROC_UNLOCK(p);
723         } else {
724                 /*
725                  * Don't have to worry about process locking or stacks in the
726                  * kernel.
727                  */
728                 rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
729         }
730         if (rv == KERN_SUCCESS)
731                 return (0);
732 nogo:
733         if (!usermode) {
734                 if (td->td_intr_nesting_level == 0 &&
735                     PCPU_GET(curpcb) != NULL &&
736                     PCPU_GET(curpcb)->pcb_onfault != NULL) {
737                         frame->tf_eip = (int)PCPU_GET(curpcb)->pcb_onfault;
738                         return (0);
739                 }
740                 trap_fatal(frame, eva);
741                 return (-1);
742         }
743
744         /* kludge to pass faulting virtual address to sendsig */
745         frame->tf_err = eva;
746
747         return((rv == KERN_PROTECTION_FAILURE) ? SIGBUS : SIGSEGV);
748 }
749
750 static void
751 trap_fatal(frame, eva)
752         struct trapframe *frame;
753         vm_offset_t eva;
754 {
755         int code, type, ss, esp;
756         struct soft_segment_descriptor softseg;
757
758         code = frame->tf_err;
759         type = frame->tf_trapno;
760         sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
761
762         if (type <= MAX_TRAP_MSG)
763                 printf("\n\nFatal trap %d: %s while in %s mode\n",
764                         type, trap_msg[type],
765                         frame->tf_eflags & PSL_VM ? "vm86" :
766                         ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
767 #ifdef SMP
768         /* two separate prints in case of a trap on an unmapped page */
769         printf("cpuid = %d; ", PCPU_GET(cpuid));
770         printf("lapic.id = %08x\n", lapic.id);
771 #endif
772         if (type == T_PAGEFLT) {
773                 printf("fault virtual address   = 0x%x\n", eva);
774                 printf("fault code              = %s %s, %s\n",
775                         code & PGEX_U ? "user" : "supervisor",
776                         code & PGEX_W ? "write" : "read",
777                         code & PGEX_P ? "protection violation" : "page not present");
778         }
779         printf("instruction pointer     = 0x%x:0x%x\n",
780                frame->tf_cs & 0xffff, frame->tf_eip);
781         if ((ISPL(frame->tf_cs) == SEL_UPL) || (frame->tf_eflags & PSL_VM)) {
782                 ss = frame->tf_ss & 0xffff;
783                 esp = frame->tf_esp;
784         } else {
785                 ss = GSEL(GDATA_SEL, SEL_KPL);
786                 esp = (int)&frame->tf_esp;
787         }
788         printf("stack pointer           = 0x%x:0x%x\n", ss, esp);
789         printf("frame pointer           = 0x%x:0x%x\n", ss, frame->tf_ebp);
790         printf("code segment            = base 0x%x, limit 0x%x, type 0x%x\n",
791                softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
792         printf("                        = DPL %d, pres %d, def32 %d, gran %d\n",
793                softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
794                softseg.ssd_gran);
795         printf("processor eflags        = ");
796         if (frame->tf_eflags & PSL_T)
797                 printf("trace trap, ");
798         if (frame->tf_eflags & PSL_I)
799                 printf("interrupt enabled, ");
800         if (frame->tf_eflags & PSL_NT)
801                 printf("nested task, ");
802         if (frame->tf_eflags & PSL_RF)
803                 printf("resume, ");
804         if (frame->tf_eflags & PSL_VM)
805                 printf("vm86, ");
806         printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
807         printf("current process         = ");
808         if (curproc) {
809                 printf("%lu (%s)\n",
810                     (u_long)curproc->p_pid, curproc->p_comm ?
811                     curproc->p_comm : "");
812         } else {
813                 printf("Idle\n");
814         }
815
816 #ifdef KDB
817         if (kdb_trap(&psl))
818                 return;
819 #endif
820 #ifdef DDB
821         if ((debugger_on_panic || db_active) && kdb_trap(type, 0, frame))
822                 return;
823 #endif
824         printf("trap number             = %d\n", type);
825         if (type <= MAX_TRAP_MSG)
826                 panic("%s", trap_msg[type]);
827         else
828                 panic("unknown/reserved trap");
829 }
830
831 /*
832  * Double fault handler. Called when a fault occurs while writing
833  * a frame for a trap/exception onto the stack. This usually occurs
834  * when the stack overflows (such is the case with infinite recursion,
835  * for example).
836  *
837  * XXX Note that the current PTD gets replaced by IdlePTD when the
838  * task switch occurs. This means that the stack that was active at
839  * the time of the double fault is not available at <kstack> unless
840  * the machine was idle when the double fault occurred. The downside
841  * of this is that "trace <ebp>" in ddb won't work.
842  */
843 void
844 dblfault_handler()
845 {
846         printf("\nFatal double fault:\n");
847         printf("eip = 0x%x\n", PCPU_GET(common_tss.tss_eip));
848         printf("esp = 0x%x\n", PCPU_GET(common_tss.tss_esp));
849         printf("ebp = 0x%x\n", PCPU_GET(common_tss.tss_ebp));
850 #ifdef SMP
851         /* two separate prints in case of a trap on an unmapped page */
852         printf("cpuid = %d; ", PCPU_GET(cpuid));
853         printf("lapic.id = %08x\n", lapic.id);
854 #endif
855         panic("double fault");
856 }
857
858 #ifdef I386_CPU
859 /*
860  * Compensate for 386 brain damage (missing URKR).
861  * This is a little simpler than the pagefault handler in trap() because
862  * it the page tables have already been faulted in and high addresses
863  * are thrown out early for other reasons.
864  */
865 int trapwrite(addr)
866         unsigned addr;
867 {
868         struct thread *td;
869         struct proc *p;
870         vm_offset_t va;
871         struct vmspace *vm;
872         int rv;
873
874         va = trunc_page((vm_offset_t)addr);
875         /*
876          * XXX - MAX is END.  Changed > to >= for temp. fix.
877          */
878         if (va >= VM_MAXUSER_ADDRESS)
879                 return (1);
880
881         td = curthread;
882         p = td->td_proc;
883         vm = p->p_vmspace;
884
885         PROC_LOCK(p);
886         ++p->p_lock;
887         PROC_UNLOCK(p);
888
889         if (vm_map_growstack(p, va) != KERN_SUCCESS)
890                 rv = KERN_FAILURE;
891         else
892                 /*
893                  * fault the data page
894                  */
895                 rv = vm_fault(&vm->vm_map, va, VM_PROT_WRITE, VM_FAULT_DIRTY);
896
897         PROC_LOCK(p);
898         --p->p_lock;
899         PROC_UNLOCK(p);
900
901         if (rv != KERN_SUCCESS)
902                 return 1;
903
904         return (0);
905 }
906 #endif
907
908 /*
909  *      syscall -       system call request C handler
910  *
911  *      A system call is essentially treated as a trap.
912  */
913 void
914 syscall(frame)
915         struct trapframe frame;
916 {
917         caddr_t params;
918         int i;
919         struct sysent *callp;
920         struct thread *td = curthread;
921         struct proc *p = td->td_proc;
922         register_t orig_tf_eflags;
923         u_int sticks;
924         int error;
925         int narg;
926         int args[8];
927         u_int code;
928
929         /*
930          * note: PCPU_LAZY_INC() can only be used if we can afford
931          * occassional inaccuracy in the count.
932          */
933         PCPU_LAZY_INC(cnt.v_syscall);
934
935 #ifdef DIAGNOSTIC
936         if (ISPL(frame.tf_cs) != SEL_UPL) {
937                 mtx_lock(&Giant);       /* try to stabilize the system XXX */
938                 panic("syscall");
939                 /* NOT REACHED */
940                 mtx_unlock(&Giant);
941         }
942 #endif
943
944         sticks = td->td_kse->ke_sticks;
945         td->td_frame = &frame;
946         if (td->td_ucred != p->p_ucred) 
947                 cred_update_thread(td);
948         params = (caddr_t)frame.tf_esp + sizeof(int);
949         code = frame.tf_eax;
950         orig_tf_eflags = frame.tf_eflags;
951
952         if (p->p_sysent->sv_prepsyscall) {
953                 /*
954                  * The prep code is MP aware.
955                  */
956                 (*p->p_sysent->sv_prepsyscall)(&frame, args, &code, &params);
957         } else {
958                 /*
959                  * Need to check if this is a 32 bit or 64 bit syscall.
960                  * fuword is MP aware.
961                  */
962                 if (code == SYS_syscall) {
963                         /*
964                          * Code is first argument, followed by actual args.
965                          */
966                         code = fuword(params);
967                         params += sizeof(int);
968                 } else if (code == SYS___syscall) {
969                         /*
970                          * Like syscall, but code is a quad, so as to maintain
971                          * quad alignment for the rest of the arguments.
972                          */
973                         code = fuword(params);
974                         params += sizeof(quad_t);
975                 }
976         }
977
978         if (p->p_sysent->sv_mask)
979                 code &= p->p_sysent->sv_mask;
980
981         if (code >= p->p_sysent->sv_size)
982                 callp = &p->p_sysent->sv_table[0];
983         else
984                 callp = &p->p_sysent->sv_table[code];
985
986         narg = callp->sy_narg & SYF_ARGMASK;
987
988         /*
989          * copyin and the ktrsyscall()/ktrsysret() code is MP-aware
990          */
991         if (params && (i = narg * sizeof(int)) &&
992             (error = copyin(params, (caddr_t)args, (u_int)i))) {
993 #ifdef KTRACE
994                 if (KTRPOINT(p, KTR_SYSCALL))
995                         ktrsyscall(p->p_tracep, code, narg, args);
996 #endif
997                 goto bad;
998         }
999
1000         /*
1001          * Try to run the syscall without Giant if the syscall
1002          * is MP safe.
1003          */
1004         if ((callp->sy_narg & SYF_MPSAFE) == 0) {
1005                 mtx_lock(&Giant);
1006         }
1007
1008 #ifdef KTRACE
1009         /*
1010          * We have to obtain Giant no matter what if 
1011          * we are ktracing
1012          */
1013         if (KTRPOINT(p, KTR_SYSCALL)) {
1014                 ktrsyscall(p->p_tracep, code, narg, args);
1015         }
1016 #endif
1017         td->td_retval[0] = 0;
1018         td->td_retval[1] = frame.tf_edx;
1019
1020         STOPEVENT(p, S_SCE, narg);
1021
1022         error = (*callp->sy_call)(td, args);
1023
1024         switch (error) {
1025         case 0:
1026                 frame.tf_eax = td->td_retval[0];
1027                 frame.tf_edx = td->td_retval[1];
1028                 frame.tf_eflags &= ~PSL_C;
1029                 break;
1030
1031         case ERESTART:
1032                 /*
1033                  * Reconstruct pc, assuming lcall $X,y is 7 bytes,
1034                  * int 0x80 is 2 bytes. We saved this in tf_err.
1035                  */
1036                 frame.tf_eip -= frame.tf_err;
1037                 break;
1038
1039         case EJUSTRETURN:
1040                 break;
1041
1042         default:
1043 bad:
1044                 if (p->p_sysent->sv_errsize) {
1045                         if (error >= p->p_sysent->sv_errsize)
1046                                 error = -1;     /* XXX */
1047                         else
1048                                 error = p->p_sysent->sv_errtbl[error];
1049                 }
1050                 frame.tf_eax = error;
1051                 frame.tf_eflags |= PSL_C;
1052                 break;
1053         }
1054
1055         /*
1056          * Traced syscall.
1057          */
1058         if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1059                 frame.tf_eflags &= ~PSL_T;
1060                 trapsignal(p, SIGTRAP, 0);
1061         }
1062
1063         /*
1064          * Handle reschedule and other end-of-syscall issues
1065          */
1066         userret(td, &frame, sticks);
1067
1068 #ifdef KTRACE
1069         if (KTRPOINT(p, KTR_SYSRET)) {
1070                 ktrsysret(p->p_tracep, code, error, td->td_retval[0]);
1071         }
1072 #endif
1073
1074         /*
1075          * Release Giant if we previously set it.  Do not
1076          * release based on mtx_owned() - we want to catch
1077          * broken syscalls.
1078          */
1079         if ((callp->sy_narg & SYF_MPSAFE) == 0) {
1080                 mtx_unlock(&Giant);
1081         }
1082
1083         /*
1084          * This works because errno is findable through the
1085          * register set.  If we ever support an emulation where this
1086          * is not the case, this code will need to be revisited.
1087          */
1088         STOPEVENT(p, S_SCX, code);
1089
1090 #ifdef DIAGNOSTIC
1091         cred_free_thread(td);
1092 #endif
1093
1094 #ifdef WITNESS
1095         if (witness_list(td)) {
1096                 panic("system call %s returning with mutex(s) held\n",
1097                     syscallnames[code]);
1098         }
1099 #endif
1100         mtx_assert(&sched_lock, MA_NOTOWNED);
1101         mtx_assert(&Giant, MA_NOTOWNED);
1102 }
1103