1 /*-
2 * SPDX-License-Identifier: BSD-4-Clause
3 *
4 * Copyright (C) 1994, David Greenman
5 * Copyright (c) 1990, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * the University of Utah, and William Jolitz.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 */
39
40 #include <sys/cdefs.h>
41 /*
42 * 386 Trap and System call handling
43 */
44
45 #include "opt_clock.h"
46 #include "opt_cpu.h"
47 #include "opt_hwpmc_hooks.h"
48 #include "opt_isa.h"
49 #include "opt_kdb.h"
50 #include "opt_trap.h"
51
52 #include <sys/param.h>
53 #include <sys/bus.h>
54 #include <sys/systm.h>
55 #include <sys/proc.h>
56 #include <sys/ptrace.h>
57 #include <sys/kdb.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 HWPMC_HOOKS
70 #include <sys/pmckern.h>
71 PMC_SOFT_DEFINE( , , page_fault, all);
72 PMC_SOFT_DEFINE( , , page_fault, read);
73 PMC_SOFT_DEFINE( , , page_fault, write);
74 #endif
75 #include <security/audit/audit.h>
76
77 #include <vm/vm.h>
78 #include <vm/vm_param.h>
79 #include <vm/pmap.h>
80 #include <vm/vm_kern.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_page.h>
83 #include <vm/vm_extern.h>
84
85 #include <machine/cpu.h>
86 #include <machine/intr_machdep.h>
87 #include <x86/mca.h>
88 #include <machine/md_var.h>
89 #include <machine/pcb.h>
90 #ifdef SMP
91 #include <machine/smp.h>
92 #endif
93 #include <machine/stack.h>
94 #include <machine/trap.h>
95 #include <machine/tss.h>
96 #include <machine/vm86.h>
97
98 #ifdef POWERFAIL_NMI
99 #include <sys/syslog.h>
100 #include <machine/clock.h>
101 #endif
102
103 #ifdef KDTRACE_HOOKS
104 #include <sys/dtrace_bsd.h>
105 #endif
106
107 void trap(struct trapframe *frame);
108 void syscall(struct trapframe *frame);
109
110 static int trap_pfault(struct trapframe *, bool, vm_offset_t, int *, int *);
111 static void trap_fatal(struct trapframe *, vm_offset_t);
112 #ifdef KDTRACE_HOOKS
113 static bool trap_user_dtrace(struct trapframe *,
114 int (**hook)(struct trapframe *));
115 #endif
116 void dblfault_handler(void);
117
118 extern inthand_t IDTVEC(bpt), IDTVEC(dbg), IDTVEC(int0x80_syscall);
119 extern uint64_t pg_nx;
120
121 struct trap_data {
122 bool ei;
123 const char *msg;
124 };
125
126 static const struct trap_data trap_data[] = {
127 [T_PRIVINFLT] = { .ei = true, .msg = "privileged instruction fault" },
128 [T_BPTFLT] = { .ei = false, .msg = "breakpoint instruction fault" },
129 [T_ARITHTRAP] = { .ei = true, .msg = "arithmetic trap" },
130 [T_PROTFLT] = { .ei = true, .msg = "general protection fault" },
131 [T_TRCTRAP] = { .ei = false, .msg = "debug exception" },
132 [T_PAGEFLT] = { .ei = true, .msg = "page fault" },
133 [T_ALIGNFLT] = { .ei = true, .msg = "alignment fault" },
134 [T_DIVIDE] = { .ei = true, .msg = "integer divide fault" },
135 [T_NMI] = { .ei = false, .msg = "non-maskable interrupt trap" },
136 [T_OFLOW] = { .ei = true, .msg = "overflow trap" },
137 [T_BOUND] = { .ei = true, .msg = "FPU bounds check fault" },
138 [T_DNA] = { .ei = true, .msg = "FPU device not available" },
139 [T_DOUBLEFLT] = { .ei = false, .msg = "double fault" },
140 [T_FPOPFLT] = { .ei = true, .msg = "FPU operand fetch fault" },
141 [T_TSSFLT] = { .ei = true, .msg = "invalid TSS fault" },
142 [T_SEGNPFLT] = { .ei = true, .msg = "segment not present fault" },
143 [T_STKFLT] = { .ei = true, .msg = "stack fault" },
144 [T_MCHK] = { .ei = true, .msg = "machine check trap" },
145 [T_XMMFLT] = { .ei = true, .msg = "SIMD floating-point exception" },
146 [T_DTRACE_RET] ={ .ei = true, .msg = "DTrace pid return trap" },
147 };
148
149 static bool
trap_enable_intr(int trapno)150 trap_enable_intr(int trapno)
151 {
152
153 MPASS(trapno > 0);
154 if (trapno < nitems(trap_data) && trap_data[trapno].msg != NULL)
155 return (trap_data[trapno].ei);
156 return (false);
157 }
158
159 static const char *
trap_msg(int trapno)160 trap_msg(int trapno)
161 {
162 const char *res;
163 static const char unkn[] = "UNKNOWN";
164
165 res = NULL;
166 if (trapno < nitems(trap_data))
167 res = trap_data[trapno].msg;
168 if (res == NULL)
169 res = unkn;
170 return (res);
171 }
172
173 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
174 int has_f00f_bug = 0; /* Initialized so that it can be patched. */
175 #endif
176
177 static int uprintf_signal;
178 SYSCTL_INT(_machdep, OID_AUTO, uprintf_signal, CTLFLAG_RW,
179 &uprintf_signal, 0,
180 "Print debugging information on trap signal to ctty");
181
182
183 #ifdef INVARIANTS
184 static __inline register_t
read_esp(void)185 read_esp(void)
186 {
187 register_t res;
188
189 __asm __volatile("movl\t%%esp,%0" : "=r" (res));
190 return (res);
191 }
192
193 void
trap_check_kstack(void)194 trap_check_kstack(void)
195 {
196 struct thread *td;
197 vm_offset_t stk;
198
199 td = curthread;
200 stk = read_esp();
201 if (stk >= PMAP_TRM_MIN_ADDRESS)
202 panic("td %p stack %#x in trampoline", td, stk);
203 if (!kstack_contains(td, stk, 0))
204 panic("td %p stack %#x not in kstack VA %#x %d",
205 td, stk, td->td_kstack, td->td_kstack_pages);
206 }
207 #endif
208
209 /*
210 * Exception, fault, and trap interface to the FreeBSD kernel.
211 * This common code is called from assembly language IDT gate entry
212 * routines that prepare a suitable stack frame, and restore this
213 * frame after the exception has been processed.
214 */
215
216 void
trap(struct trapframe * frame)217 trap(struct trapframe *frame)
218 {
219 ksiginfo_t ksi;
220 struct thread *td;
221 struct proc *p;
222 int pf, signo, ucode;
223 u_int type;
224 register_t addr, dr6;
225 vm_offset_t eva;
226 #ifdef POWERFAIL_NMI
227 static int lastalert = 0;
228 #endif
229
230 td = curthread;
231 p = td->td_proc;
232 dr6 = 0;
233
234 VM_CNT_INC(v_trap);
235 type = frame->tf_trapno;
236
237 KASSERT((read_eflags() & PSL_I) == 0,
238 ("trap: interrupts enabled, type %d frame %p", type, frame));
239
240 #ifdef KDB
241 if (kdb_active) {
242 kdb_reenter();
243 return;
244 }
245 #endif
246 trap_check_kstack();
247
248 if (type == T_NMI) {
249 nmi_handle_intr(frame);
250 return;
251 }
252
253 if (type == T_RESERVED) {
254 trap_fatal(frame, 0);
255 return;
256 }
257
258 if (type == T_MCHK) {
259 mca_intr();
260 return;
261 }
262
263 #ifdef KDTRACE_HOOKS
264 /*
265 * A trap can occur while DTrace executes a probe. Before
266 * executing the probe, DTrace blocks re-scheduling and sets
267 * a flag in its per-cpu flags to indicate that it doesn't
268 * want to fault. On returning from the probe, the no-fault
269 * flag is cleared and finally re-scheduling is enabled.
270 */
271 if ((type == T_PROTFLT || type == T_PAGEFLT) &&
272 dtrace_trap_func != NULL && (*dtrace_trap_func)(frame, type))
273 return;
274 #endif
275
276 /*
277 * We must not allow context switches until %cr2 is read.
278 * Also, for some Cyrix CPUs, %cr2 is clobbered by interrupts.
279 * All faults use interrupt gates, so %cr2 can be safely read
280 * now, before optional enable of the interrupts below.
281 */
282 if (type == T_PAGEFLT)
283 eva = rcr2();
284
285 /*
286 * Buggy application or kernel code has disabled interrupts
287 * and then trapped. Enabling interrupts now is wrong, but it
288 * is better than running with interrupts disabled until they
289 * are accidentally enabled later.
290 */
291 if ((frame->tf_eflags & PSL_I) == 0 && TRAPF_USERMODE(frame) &&
292 (curpcb->pcb_flags & PCB_VM86CALL) == 0)
293 uprintf("pid %ld (%s): usermode trap %d (%s) with "
294 "interrupts disabled\n",
295 (long)curproc->p_pid, curthread->td_name, type,
296 trap_data[type].msg);
297
298 /*
299 * Conditionally reenable interrupts. If we hold a spin lock,
300 * then we must not reenable interrupts. This might be a
301 * spurious page fault.
302 */
303 if (trap_enable_intr(type) && td->td_md.md_spinlock_count == 0 &&
304 frame->tf_eip != (int)cpu_switch_load_gs)
305 enable_intr();
306
307 if (TRAPF_USERMODE(frame) && (curpcb->pcb_flags & PCB_VM86CALL) == 0) {
308 /* user trap */
309
310 td->td_pticks = 0;
311 td->td_frame = frame;
312 addr = frame->tf_eip;
313 if (td->td_cowgen != atomic_load_int(&p->p_cowgen))
314 thread_cow_update(td);
315
316 switch (type) {
317 case T_PRIVINFLT: /* privileged instruction fault */
318 signo = SIGILL;
319 ucode = ILL_PRVOPC;
320 break;
321
322 case T_BPTFLT: /* bpt instruction fault */
323 #ifdef KDTRACE_HOOKS
324 if (trap_user_dtrace(frame, &dtrace_pid_probe_ptr))
325 return;
326 #else
327 enable_intr();
328 #endif
329 signo = SIGTRAP;
330 ucode = TRAP_BRKPT;
331 break;
332
333 case T_TRCTRAP: /* debug exception */
334 enable_intr();
335 user_trctrap_out:
336 signo = SIGTRAP;
337 ucode = TRAP_TRACE;
338 dr6 = rdr6();
339 if ((dr6 & DBREG_DR6_BS) != 0) {
340 PROC_LOCK(td->td_proc);
341 if ((td->td_dbgflags & TDB_STEP) != 0) {
342 td->td_frame->tf_eflags &= ~PSL_T;
343 td->td_dbgflags &= ~TDB_STEP;
344 }
345 PROC_UNLOCK(td->td_proc);
346 }
347 break;
348
349 case T_ARITHTRAP: /* arithmetic trap */
350 ucode = npxtrap_x87();
351 if (ucode == -1)
352 return;
353 signo = SIGFPE;
354 break;
355
356 /*
357 * The following two traps can happen in vm86 mode,
358 * and, if so, we want to handle them specially.
359 */
360 case T_PROTFLT: /* general protection fault */
361 case T_STKFLT: /* stack fault */
362 if (frame->tf_eflags & PSL_VM) {
363 signo = vm86_emulate((struct vm86frame *)frame);
364 ucode = 0; /* XXXKIB: better code ? */
365 if (signo == SIGTRAP) {
366 load_dr6(rdr6() | 0x4000);
367 goto user_trctrap_out;
368 }
369 if (signo == 0)
370 goto user;
371 break;
372 }
373 signo = SIGBUS;
374 ucode = (type == T_PROTFLT) ? BUS_OBJERR : BUS_ADRERR;
375 break;
376 case T_SEGNPFLT: /* segment not present fault */
377 signo = SIGBUS;
378 ucode = BUS_ADRERR;
379 break;
380 case T_TSSFLT: /* invalid TSS fault */
381 signo = SIGBUS;
382 ucode = BUS_OBJERR;
383 break;
384 case T_ALIGNFLT:
385 signo = SIGBUS;
386 ucode = BUS_ADRALN;
387 break;
388 case T_DOUBLEFLT: /* double fault */
389 default:
390 signo = SIGBUS;
391 ucode = BUS_OBJERR;
392 break;
393
394 case T_PAGEFLT: /* page fault */
395 addr = eva;
396 pf = trap_pfault(frame, true, eva, &signo, &ucode);
397 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
398 if (pf == -2) {
399 /*
400 * The f00f hack workaround has triggered, so
401 * treat the fault as an illegal instruction
402 * (T_PRIVINFLT) instead of a page fault.
403 */
404 type = frame->tf_trapno = T_PRIVINFLT;
405 break;
406 }
407 #endif
408 if (pf == -1)
409 return;
410 if (pf == 0)
411 goto user;
412 break;
413
414 case T_DIVIDE: /* integer divide fault */
415 ucode = FPE_INTDIV;
416 signo = SIGFPE;
417 break;
418
419 case T_NMI:
420 #ifdef POWERFAIL_NMI
421 #ifndef TIMER_FREQ
422 # define TIMER_FREQ 1193182
423 #endif
424 if (time_second - lastalert > 10) {
425 log(LOG_WARNING, "NMI: power fail\n");
426 sysbeep(880, SBT_1S);
427 lastalert = time_second;
428 }
429 return;
430 #else /* !POWERFAIL_NMI */
431 nmi_handle_intr(frame);
432 return;
433 #endif /* POWERFAIL_NMI */
434
435 case T_OFLOW: /* integer overflow fault */
436 ucode = FPE_INTOVF;
437 signo = SIGFPE;
438 break;
439
440 case T_BOUND: /* bounds check fault */
441 ucode = FPE_FLTSUB;
442 signo = SIGFPE;
443 break;
444
445 case T_DNA:
446 KASSERT(PCB_USER_FPU(td->td_pcb),
447 ("kernel FPU ctx has leaked"));
448 /* transparent fault (due to context switch "late") */
449 if (npxdna())
450 return;
451 uprintf("pid %d killed due to lack of floating point\n",
452 p->p_pid);
453 signo = SIGKILL;
454 ucode = 0;
455 break;
456
457 case T_FPOPFLT: /* FPU operand fetch fault */
458 ucode = ILL_COPROC;
459 signo = SIGILL;
460 break;
461
462 case T_XMMFLT: /* SIMD floating-point exception */
463 ucode = npxtrap_sse();
464 if (ucode == -1)
465 return;
466 signo = SIGFPE;
467 break;
468 #ifdef KDTRACE_HOOKS
469 case T_DTRACE_RET:
470 (void)trap_user_dtrace(frame, &dtrace_return_probe_ptr);
471 return;
472 #endif
473 }
474 } else {
475 /* kernel trap */
476
477 KASSERT(cold || td->td_ucred != NULL,
478 ("kernel trap doesn't have ucred"));
479 switch (type) {
480 case T_PAGEFLT: /* page fault */
481 (void)trap_pfault(frame, false, eva, NULL, NULL);
482 return;
483
484 case T_DNA:
485 if (PCB_USER_FPU(td->td_pcb))
486 panic("Unregistered use of FPU in kernel");
487 if (npxdna())
488 return;
489 break;
490
491 case T_ARITHTRAP: /* arithmetic trap */
492 case T_XMMFLT: /* SIMD floating-point exception */
493 case T_FPOPFLT: /* FPU operand fetch fault */
494 /*
495 * XXXKIB for now disable any FPU traps in kernel
496 * handler registration seems to be overkill
497 */
498 trap_fatal(frame, 0);
499 return;
500
501 /*
502 * The following two traps can happen in
503 * vm86 mode, and, if so, we want to handle
504 * them specially.
505 */
506 case T_PROTFLT: /* general protection fault */
507 case T_STKFLT: /* stack fault */
508 if (frame->tf_eflags & PSL_VM) {
509 signo = vm86_emulate((struct vm86frame *)frame);
510 if (signo == SIGTRAP) {
511 type = T_TRCTRAP;
512 load_dr6(rdr6() | 0x4000);
513 goto kernel_trctrap;
514 }
515 if (signo != 0)
516 /*
517 * returns to original process
518 */
519 vm86_trap((struct vm86frame *)frame);
520 return;
521 }
522 /* FALL THROUGH */
523 case T_SEGNPFLT: /* segment not present fault */
524 if (curpcb->pcb_flags & PCB_VM86CALL)
525 break;
526
527 /*
528 * Invalid %fs's and %gs's can be created using
529 * procfs or PT_SETREGS or by invalidating the
530 * underlying LDT entry. This causes a fault
531 * in kernel mode when the kernel attempts to
532 * switch contexts. Lose the bad context
533 * (XXX) so that we can continue, and generate
534 * a signal.
535 */
536 if (frame->tf_eip == (int)cpu_switch_load_gs) {
537 curpcb->pcb_gs = 0;
538 #if 0
539 PROC_LOCK(p);
540 kern_psignal(p, SIGBUS);
541 PROC_UNLOCK(p);
542 #endif
543 return;
544 }
545
546 if (td->td_intr_nesting_level != 0)
547 break;
548
549 /*
550 * Invalid segment selectors and out of bounds
551 * %eip's and %esp's can be set up in user mode.
552 * This causes a fault in kernel mode when the
553 * kernel tries to return to user mode. We want
554 * to get this fault so that we can fix the
555 * problem here and not have to check all the
556 * selectors and pointers when the user changes
557 * them.
558 *
559 * N.B. Comparing to long mode, 32-bit mode
560 * does not push %esp on the trap frame,
561 * because iretl faulted while in ring 0. As
562 * the consequence, there is no need to fixup
563 * the stack pointer for doreti_iret_fault,
564 * the fixup and the complimentary trap() call
565 * are executed on the main thread stack, not
566 * on the trampoline stack.
567 */
568 if (frame->tf_eip == (int)doreti_iret + setidt_disp) {
569 frame->tf_eip = (int)doreti_iret_fault +
570 setidt_disp;
571 return;
572 }
573 if (type == T_STKFLT)
574 break;
575
576 if (frame->tf_eip == (int)doreti_popl_ds +
577 setidt_disp) {
578 frame->tf_eip = (int)doreti_popl_ds_fault +
579 setidt_disp;
580 return;
581 }
582 if (frame->tf_eip == (int)doreti_popl_es +
583 setidt_disp) {
584 frame->tf_eip = (int)doreti_popl_es_fault +
585 setidt_disp;
586 return;
587 }
588 if (frame->tf_eip == (int)doreti_popl_fs +
589 setidt_disp) {
590 frame->tf_eip = (int)doreti_popl_fs_fault +
591 setidt_disp;
592 return;
593 }
594 if (curpcb->pcb_onfault != NULL) {
595 frame->tf_eip = (int)curpcb->pcb_onfault;
596 return;
597 }
598 break;
599
600 case T_TSSFLT:
601 /*
602 * PSL_NT can be set in user mode and isn't cleared
603 * automatically when the kernel is entered. This
604 * causes a TSS fault when the kernel attempts to
605 * `iret' because the TSS link is uninitialized. We
606 * want to get this fault so that we can fix the
607 * problem here and not every time the kernel is
608 * entered.
609 */
610 if (frame->tf_eflags & PSL_NT) {
611 frame->tf_eflags &= ~PSL_NT;
612 return;
613 }
614 break;
615
616 case T_TRCTRAP: /* debug exception */
617 kernel_trctrap:
618 /* Clear any pending debug events. */
619 dr6 = rdr6();
620 load_dr6(0);
621
622 /*
623 * Ignore debug register exceptions due to
624 * accesses in the user's address space, which
625 * can happen under several conditions such as
626 * if a user sets a watchpoint on a buffer and
627 * then passes that buffer to a system call.
628 * We still want to get TRCTRAPS for addresses
629 * in kernel space because that is useful when
630 * debugging the kernel.
631 */
632 if (user_dbreg_trap(dr6) &&
633 !(curpcb->pcb_flags & PCB_VM86CALL))
634 return;
635
636 /*
637 * Malicious user code can configure a debug
638 * register watchpoint to trap on data access
639 * to the top of stack and then execute 'pop
640 * %ss; int 3'. Due to exception deferral for
641 * 'pop %ss', the CPU will not interrupt 'int
642 * 3' to raise the DB# exception for the debug
643 * register but will postpone the DB# until
644 * execution of the first instruction of the
645 * BP# handler (in kernel mode). Normally the
646 * previous check would ignore DB# exceptions
647 * for watchpoints on user addresses raised in
648 * kernel mode. However, some CPU errata
649 * include cases where DB# exceptions do not
650 * properly set bits in %dr6, e.g. Haswell
651 * HSD23 and Skylake-X SKZ24.
652 *
653 * A deferred DB# can also be raised on the
654 * first instructions of system call entry
655 * points or single-step traps via similar use
656 * of 'pop %ss' or 'mov xxx, %ss'.
657 */
658 if (frame->tf_eip ==
659 (uintptr_t)IDTVEC(int0x80_syscall) + setidt_disp ||
660 frame->tf_eip == (uintptr_t)IDTVEC(bpt) +
661 setidt_disp ||
662 frame->tf_eip == (uintptr_t)IDTVEC(dbg) +
663 setidt_disp)
664 return;
665 /*
666 * FALLTHROUGH (TRCTRAP kernel mode, kernel address)
667 */
668 case T_BPTFLT:
669 /*
670 * If KDB is enabled, let it handle the debugger trap.
671 * Otherwise, debugger traps "can't happen".
672 */
673 #ifdef KDB
674 if (kdb_trap(type, dr6, frame))
675 return;
676 #endif
677 break;
678
679 case T_NMI:
680 #ifdef POWERFAIL_NMI
681 if (time_second - lastalert > 10) {
682 log(LOG_WARNING, "NMI: power fail\n");
683 sysbeep(880, SBT_1S);
684 lastalert = time_second;
685 }
686 return;
687 #else /* !POWERFAIL_NMI */
688 nmi_handle_intr(frame);
689 return;
690 #endif /* POWERFAIL_NMI */
691 }
692
693 trap_fatal(frame, eva);
694 return;
695 }
696
697 ksiginfo_init_trap(&ksi);
698 ksi.ksi_signo = signo;
699 ksi.ksi_code = ucode;
700 ksi.ksi_addr = (void *)addr;
701 ksi.ksi_trapno = type;
702 if (uprintf_signal) {
703 uprintf("pid %d comm %s: signal %d err %#x code %d type %d "
704 "addr %#x ss %#04x esp %#08x cs %#04x eip %#08x eax %#08x"
705 "<%02x %02x %02x %02x %02x %02x %02x %02x>\n",
706 p->p_pid, p->p_comm, signo, frame->tf_err, ucode, type,
707 addr, frame->tf_ss, frame->tf_esp, frame->tf_cs,
708 frame->tf_eip, frame->tf_eax,
709 fubyte((void *)(frame->tf_eip + 0)),
710 fubyte((void *)(frame->tf_eip + 1)),
711 fubyte((void *)(frame->tf_eip + 2)),
712 fubyte((void *)(frame->tf_eip + 3)),
713 fubyte((void *)(frame->tf_eip + 4)),
714 fubyte((void *)(frame->tf_eip + 5)),
715 fubyte((void *)(frame->tf_eip + 6)),
716 fubyte((void *)(frame->tf_eip + 7)));
717 }
718 KASSERT((read_eflags() & PSL_I) != 0, ("interrupts disabled"));
719 trapsignal(td, &ksi);
720
721 user:
722 userret(td, frame);
723 KASSERT(PCB_USER_FPU(td->td_pcb),
724 ("Return from trap with kernel FPU ctx leaked"));
725 }
726
727 /*
728 * Handle all details of a page fault.
729 * Returns:
730 * -2 if the fault was caused by triggered workaround for Intel Pentium
731 * 0xf00f bug.
732 * -1 if this fault was fatal, typically from kernel mode
733 * (cannot happen, but we need to return something).
734 * 0 if this fault was handled by updating either the user or kernel
735 * page table, execution can continue.
736 * 1 if this fault was from usermode and it was not handled, a synchronous
737 * signal should be delivered to the thread. *signo returns the signal
738 * number, *ucode gives si_code.
739 */
740 static int
trap_pfault(struct trapframe * frame,bool usermode,vm_offset_t eva,int * signo,int * ucode)741 trap_pfault(struct trapframe *frame, bool usermode, vm_offset_t eva,
742 int *signo, int *ucode)
743 {
744 struct thread *td;
745 struct proc *p;
746 vm_map_t map;
747 int rv;
748 vm_prot_t ftype;
749
750 MPASS(!usermode || (signo != NULL && ucode != NULL));
751
752 td = curthread;
753 p = td->td_proc;
754
755 if (__predict_false((td->td_pflags & TDP_NOFAULTING) != 0)) {
756 /*
757 * Due to both processor errata and lazy TLB invalidation when
758 * access restrictions are removed from virtual pages, memory
759 * accesses that are allowed by the physical mapping layer may
760 * nonetheless cause one spurious page fault per virtual page.
761 * When the thread is executing a "no faulting" section that
762 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
763 * every page fault is treated as a spurious page fault,
764 * unless it accesses the same virtual address as the most
765 * recent page fault within the same "no faulting" section.
766 */
767 if (td->td_md.md_spurflt_addr != eva ||
768 (td->td_pflags & TDP_RESETSPUR) != 0) {
769 /*
770 * Do nothing to the TLB. A stale TLB entry is
771 * flushed automatically by a page fault.
772 */
773 td->td_md.md_spurflt_addr = eva;
774 td->td_pflags &= ~TDP_RESETSPUR;
775 return (0);
776 }
777 } else {
778 /*
779 * If we get a page fault while in a critical section, then
780 * it is most likely a fatal kernel page fault. The kernel
781 * is already going to panic trying to get a sleep lock to
782 * do the VM lookup, so just consider it a fatal trap so the
783 * kernel can print out a useful trap message and even get
784 * to the debugger.
785 *
786 * If we get a page fault while holding a non-sleepable
787 * lock, then it is most likely a fatal kernel page fault.
788 * If WITNESS is enabled, then it's going to whine about
789 * bogus LORs with various VM locks, so just skip to the
790 * fatal trap handling directly.
791 */
792 if (td->td_critnest != 0 ||
793 WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
794 "Kernel page fault") != 0) {
795 trap_fatal(frame, eva);
796 return (-1);
797 }
798 }
799 if (eva >= PMAP_TRM_MIN_ADDRESS) {
800 /*
801 * Don't allow user-mode faults in kernel address space.
802 * An exception: if the faulting address is the invalid
803 * instruction entry in the IDT, then the Intel Pentium
804 * F00F bug workaround was triggered, and we need to
805 * treat it is as an illegal instruction, and not a page
806 * fault.
807 */
808 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
809 if ((eva == (unsigned int)&idt[6]) && has_f00f_bug) {
810 *ucode = ILL_PRVOPC;
811 *signo = SIGILL;
812 return (-2);
813 }
814 #endif
815 if (usermode) {
816 *signo = SIGSEGV;
817 *ucode = SEGV_MAPERR;
818 return (1);
819 }
820 trap_fatal(frame, eva);
821 return (-1);
822 } else {
823 map = usermode ? &p->p_vmspace->vm_map : kernel_map;
824
825 /*
826 * Kernel cannot access a user-space address directly
827 * because user pages are not mapped. Also, page
828 * faults must not be caused during the interrupts.
829 */
830 if (!usermode && td->td_intr_nesting_level != 0) {
831 trap_fatal(frame, eva);
832 return (-1);
833 }
834 }
835
836 /*
837 * If the trap was caused by errant bits in the PTE then panic.
838 */
839 if (frame->tf_err & PGEX_RSV) {
840 trap_fatal(frame, eva);
841 return (-1);
842 }
843
844 /*
845 * PGEX_I is defined only if the execute disable bit capability is
846 * supported and enabled.
847 */
848 if (frame->tf_err & PGEX_W)
849 ftype = VM_PROT_WRITE;
850 else if ((frame->tf_err & PGEX_I) && pg_nx != 0)
851 ftype = VM_PROT_EXECUTE;
852 else
853 ftype = VM_PROT_READ;
854
855 /* Fault in the page. */
856 rv = vm_fault_trap(map, eva, ftype, VM_FAULT_NORMAL, signo, ucode);
857 if (rv == KERN_SUCCESS) {
858 #ifdef HWPMC_HOOKS
859 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
860 PMC_SOFT_CALL_TF( , , page_fault, all, frame);
861 if (ftype == VM_PROT_READ)
862 PMC_SOFT_CALL_TF( , , page_fault, read,
863 frame);
864 else
865 PMC_SOFT_CALL_TF( , , page_fault, write,
866 frame);
867 }
868 #endif
869 return (0);
870 }
871 if (usermode)
872 return (1);
873 if (td->td_intr_nesting_level == 0 &&
874 curpcb->pcb_onfault != NULL) {
875 frame->tf_eip = (int)curpcb->pcb_onfault;
876 return (0);
877 }
878 trap_fatal(frame, eva);
879 return (-1);
880 }
881
882 static void
trap_fatal(struct trapframe * frame,vm_offset_t eva)883 trap_fatal(struct trapframe *frame, vm_offset_t eva)
884 {
885 int code, ss, esp;
886 u_int type;
887 struct soft_segment_descriptor softseg;
888 #ifdef KDB
889 bool handled;
890 #endif
891
892 code = frame->tf_err;
893 type = frame->tf_trapno;
894 sdtossd(&gdt[IDXSEL(frame->tf_cs & 0xffff)].sd, &softseg);
895
896 printf("\n\nFatal trap %d: %s while in %s mode\n", type, trap_msg(type),
897 frame->tf_eflags & PSL_VM ? "vm86" :
898 ISPL(frame->tf_cs) == SEL_UPL ? "user" : "kernel");
899 #ifdef SMP
900 /* two separate prints in case of a trap on an unmapped page */
901 printf("cpuid = %d; ", PCPU_GET(cpuid));
902 printf("apic id = %02x\n", PCPU_GET(apic_id));
903 #endif
904 if (type == T_PAGEFLT) {
905 printf("fault virtual address = 0x%x\n", eva);
906 printf("fault code = %s %s%s, %s\n",
907 code & PGEX_U ? "user" : "supervisor",
908 code & PGEX_W ? "write" : "read",
909 pg_nx != 0 ?
910 (code & PGEX_I ? " instruction" : " data") :
911 "",
912 code & PGEX_RSV ? "reserved bits in PTE" :
913 code & PGEX_P ? "protection violation" : "page not present");
914 } else {
915 printf("error code = %#x\n", code);
916 }
917 printf("instruction pointer = 0x%x:0x%x\n",
918 frame->tf_cs & 0xffff, frame->tf_eip);
919 if (TF_HAS_STACKREGS(frame)) {
920 ss = frame->tf_ss & 0xffff;
921 esp = frame->tf_esp;
922 } else {
923 ss = GSEL(GDATA_SEL, SEL_KPL);
924 esp = (int)&frame->tf_esp;
925 }
926 printf("stack pointer = 0x%x:0x%x\n", ss, esp);
927 printf("frame pointer = 0x%x:0x%x\n", ss, frame->tf_ebp);
928 printf("code segment = base 0x%x, limit 0x%x, type 0x%x\n",
929 softseg.ssd_base, softseg.ssd_limit, softseg.ssd_type);
930 printf(" = DPL %d, pres %d, def32 %d, gran %d\n",
931 softseg.ssd_dpl, softseg.ssd_p, softseg.ssd_def32,
932 softseg.ssd_gran);
933 printf("processor eflags = ");
934 if (frame->tf_eflags & PSL_T)
935 printf("trace trap, ");
936 if (frame->tf_eflags & PSL_I)
937 printf("interrupt enabled, ");
938 if (frame->tf_eflags & PSL_NT)
939 printf("nested task, ");
940 if (frame->tf_eflags & PSL_RF)
941 printf("resume, ");
942 if (frame->tf_eflags & PSL_VM)
943 printf("vm86, ");
944 printf("IOPL = %d\n", (frame->tf_eflags & PSL_IOPL) >> 12);
945 printf("current process = %d (%s)\n",
946 curproc->p_pid, curthread->td_name);
947
948 #ifdef KDB
949 if (debugger_on_trap) {
950 kdb_why = KDB_WHY_TRAP;
951 frame->tf_err = eva; /* smuggle fault address to ddb */
952 handled = kdb_trap(type, 0, frame);
953 frame->tf_err = code; /* restore error code */
954 kdb_why = KDB_WHY_UNSET;
955 if (handled)
956 return;
957 }
958 #endif
959 printf("trap number = %d\n", type);
960 if (trap_msg(type) != NULL)
961 panic("%s", trap_msg(type));
962 else
963 panic("unknown/reserved trap");
964 }
965
966 #ifdef KDTRACE_HOOKS
967 /*
968 * Invoke a userspace DTrace hook. The hook pointer is cleared when no
969 * userspace probes are enabled, so we must synchronize with DTrace to ensure
970 * that a trapping thread is able to call the hook before it is cleared.
971 */
972 static bool
trap_user_dtrace(struct trapframe * frame,int (** hookp)(struct trapframe *))973 trap_user_dtrace(struct trapframe *frame, int (**hookp)(struct trapframe *))
974 {
975 int (*hook)(struct trapframe *);
976
977 hook = atomic_load_ptr(hookp);
978 enable_intr();
979 if (hook != NULL)
980 return ((hook)(frame) == 0);
981 return (false);
982 }
983 #endif
984
985 /*
986 * Double fault handler. Called when a fault occurs while writing
987 * a frame for a trap/exception onto the stack. This usually occurs
988 * when the stack overflows (such is the case with infinite recursion,
989 * for example).
990 *
991 * XXX Note that the current PTD gets replaced by IdlePTD when the
992 * task switch occurs. This means that the stack that was active at
993 * the time of the double fault is not available at <kstack> unless
994 * the machine was idle when the double fault occurred. The downside
995 * of this is that "trace <ebp>" in ddb won't work.
996 */
997 void
dblfault_handler(void)998 dblfault_handler(void)
999 {
1000 struct i386tss *t;
1001
1002 #ifdef KDTRACE_HOOKS
1003 if (dtrace_doubletrap_func != NULL)
1004 (*dtrace_doubletrap_func)();
1005 #endif
1006 printf("\nFatal double fault:\n");
1007 t = PCPU_GET(common_tssp);
1008 printf(
1009 "eip = %#08x esp = %#08x ebp = %#08x eax = %#08x\n"
1010 "edx = %#08x ecx = %#08x edi = %#08x esi = %#08x\n"
1011 "ebx = %#08x\n"
1012 "psl = %#08x cs = %#08x ss = %#08x ds = %#08x\n"
1013 "es = %#08x fs = %#08x gs = %#08x cr3 = %#08x\n",
1014 t->tss_eip, t->tss_esp, t->tss_ebp, t->tss_eax,
1015 t->tss_edx, t->tss_ecx, t->tss_edi, t->tss_esi,
1016 t->tss_ebx,
1017 t->tss_eflags, t->tss_cs, t->tss_ss, t->tss_ds,
1018 t->tss_es, t->tss_fs, t->tss_gs, t->tss_cr3);
1019 #ifdef SMP
1020 printf("cpuid = %d; apic id = %02x\n", PCPU_GET(cpuid),
1021 PCPU_GET(apic_id));
1022 #endif
1023 panic("double fault");
1024 }
1025
1026 int
cpu_fetch_syscall_args(struct thread * td)1027 cpu_fetch_syscall_args(struct thread *td)
1028 {
1029 struct proc *p;
1030 struct trapframe *frame;
1031 struct syscall_args *sa;
1032 caddr_t params;
1033 long tmp;
1034 int error;
1035 #ifdef COMPAT_43
1036 u_int32_t eip;
1037 int cs;
1038 #endif
1039
1040 p = td->td_proc;
1041 frame = td->td_frame;
1042 sa = &td->td_sa;
1043
1044 #ifdef COMPAT_43
1045 if (__predict_false(frame->tf_cs == 7 && frame->tf_eip == 2)) {
1046 /*
1047 * In lcall $7,$0 after int $0x80. Convert the user
1048 * frame to what it would be for a direct int 0x80 instead
1049 * of lcall $7,$0, by popping the lcall return address.
1050 */
1051 error = fueword32((void *)frame->tf_esp, &eip);
1052 if (error == -1)
1053 return (EFAULT);
1054 cs = fuword16((void *)(frame->tf_esp + sizeof(u_int32_t)));
1055 if (cs == -1)
1056 return (EFAULT);
1057
1058 /*
1059 * Unwind in-kernel frame after all stack frame pieces
1060 * were successfully read.
1061 */
1062 frame->tf_eip = eip;
1063 frame->tf_cs = cs;
1064 frame->tf_esp += 2 * sizeof(u_int32_t);
1065 frame->tf_err = 7; /* size of lcall $7,$0 */
1066 }
1067 #endif
1068
1069 sa->code = frame->tf_eax;
1070 sa->original_code = sa->code;
1071 params = (caddr_t)frame->tf_esp + sizeof(uint32_t);
1072
1073 /*
1074 * Need to check if this is a 32 bit or 64 bit syscall.
1075 */
1076 if (sa->code == SYS_syscall) {
1077 /*
1078 * Code is first argument, followed by actual args.
1079 */
1080 error = fueword(params, &tmp);
1081 if (error == -1)
1082 return (EFAULT);
1083 sa->code = tmp;
1084 params += sizeof(uint32_t);
1085 } else if (sa->code == SYS___syscall) {
1086 /*
1087 * Like syscall, but code is a quad, so as to maintain
1088 * quad alignment for the rest of the arguments.
1089 */
1090 error = fueword(params, &tmp);
1091 if (error == -1)
1092 return (EFAULT);
1093 sa->code = tmp;
1094 params += sizeof(quad_t);
1095 }
1096
1097 if (sa->code >= p->p_sysent->sv_size)
1098 sa->callp = &nosys_sysent;
1099 else
1100 sa->callp = &p->p_sysent->sv_table[sa->code];
1101
1102 if (params != NULL && sa->callp->sy_narg != 0)
1103 error = copyin(params, (caddr_t)sa->args,
1104 (u_int)(sa->callp->sy_narg * sizeof(uint32_t)));
1105 else
1106 error = 0;
1107
1108 if (error == 0) {
1109 td->td_retval[0] = 0;
1110 td->td_retval[1] = frame->tf_edx;
1111 }
1112
1113 return (error);
1114 }
1115
1116 #include "../../kern/subr_syscall.c"
1117
1118 /*
1119 * syscall - system call request C handler. A system call is
1120 * essentially treated as a trap by reusing the frame layout.
1121 */
1122 void
syscall(struct trapframe * frame)1123 syscall(struct trapframe *frame)
1124 {
1125 struct thread *td;
1126 register_t orig_tf_eflags;
1127 ksiginfo_t ksi;
1128
1129 #ifdef DIAGNOSTIC
1130 if (!(TRAPF_USERMODE(frame) &&
1131 (curpcb->pcb_flags & PCB_VM86CALL) == 0)) {
1132 panic("syscall");
1133 /* NOT REACHED */
1134 }
1135 #endif
1136 trap_check_kstack();
1137 orig_tf_eflags = frame->tf_eflags;
1138
1139 td = curthread;
1140 td->td_frame = frame;
1141
1142 syscallenter(td);
1143
1144 /*
1145 * Traced syscall.
1146 */
1147 if ((orig_tf_eflags & PSL_T) && !(orig_tf_eflags & PSL_VM)) {
1148 frame->tf_eflags &= ~PSL_T;
1149 ksiginfo_init_trap(&ksi);
1150 ksi.ksi_signo = SIGTRAP;
1151 ksi.ksi_code = TRAP_TRACE;
1152 ksi.ksi_addr = (void *)frame->tf_eip;
1153 trapsignal(td, &ksi);
1154 }
1155
1156 KASSERT(PCB_USER_FPU(td->td_pcb),
1157 ("System call %s returning with kernel FPU ctx leaked",
1158 syscallname(td->td_proc, td->td_sa.code)));
1159 KASSERT(td->td_pcb->pcb_save == get_pcb_user_save_td(td),
1160 ("System call %s returning with mangled pcb_save",
1161 syscallname(td->td_proc, td->td_sa.code)));
1162
1163 syscallret(td);
1164 }
1165