Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  *  Copyright (C) 1991, 1992  Linus Torvalds
0003  *  Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs
0004  *
0005  *  Pentium III FXSR, SSE support
0006  *  Gareth Hughes <gareth@valinux.com>, May 2000
0007  */
0008 
0009 /*
0010  * Handle hardware traps and faults.
0011  */
0012 
0013 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0014 
0015 #include <linux/context_tracking.h>
0016 #include <linux/interrupt.h>
0017 #include <linux/kallsyms.h>
0018 #include <linux/spinlock.h>
0019 #include <linux/kprobes.h>
0020 #include <linux/uaccess.h>
0021 #include <linux/kdebug.h>
0022 #include <linux/kgdb.h>
0023 #include <linux/kernel.h>
0024 #include <linux/export.h>
0025 #include <linux/ptrace.h>
0026 #include <linux/uprobes.h>
0027 #include <linux/string.h>
0028 #include <linux/delay.h>
0029 #include <linux/errno.h>
0030 #include <linux/kexec.h>
0031 #include <linux/sched.h>
0032 #include <linux/sched/task_stack.h>
0033 #include <linux/timer.h>
0034 #include <linux/init.h>
0035 #include <linux/bug.h>
0036 #include <linux/nmi.h>
0037 #include <linux/mm.h>
0038 #include <linux/smp.h>
0039 #include <linux/io.h>
0040 #include <linux/hardirq.h>
0041 #include <linux/atomic.h>
0042 #include <linux/ioasid.h>
0043 
0044 #include <asm/stacktrace.h>
0045 #include <asm/processor.h>
0046 #include <asm/debugreg.h>
0047 #include <asm/realmode.h>
0048 #include <asm/text-patching.h>
0049 #include <asm/ftrace.h>
0050 #include <asm/traps.h>
0051 #include <asm/desc.h>
0052 #include <asm/fpu/api.h>
0053 #include <asm/cpu.h>
0054 #include <asm/cpu_entry_area.h>
0055 #include <asm/mce.h>
0056 #include <asm/fixmap.h>
0057 #include <asm/mach_traps.h>
0058 #include <asm/alternative.h>
0059 #include <asm/fpu/xstate.h>
0060 #include <asm/vm86.h>
0061 #include <asm/umip.h>
0062 #include <asm/insn.h>
0063 #include <asm/insn-eval.h>
0064 #include <asm/vdso.h>
0065 #include <asm/tdx.h>
0066 
0067 #ifdef CONFIG_X86_64
0068 #include <asm/x86_init.h>
0069 #include <asm/proto.h>
0070 #else
0071 #include <asm/processor-flags.h>
0072 #include <asm/setup.h>
0073 #include <asm/proto.h>
0074 #endif
0075 
0076 DECLARE_BITMAP(system_vectors, NR_VECTORS);
0077 
0078 static inline void cond_local_irq_enable(struct pt_regs *regs)
0079 {
0080     if (regs->flags & X86_EFLAGS_IF)
0081         local_irq_enable();
0082 }
0083 
0084 static inline void cond_local_irq_disable(struct pt_regs *regs)
0085 {
0086     if (regs->flags & X86_EFLAGS_IF)
0087         local_irq_disable();
0088 }
0089 
0090 __always_inline int is_valid_bugaddr(unsigned long addr)
0091 {
0092     if (addr < TASK_SIZE_MAX)
0093         return 0;
0094 
0095     /*
0096      * We got #UD, if the text isn't readable we'd have gotten
0097      * a different exception.
0098      */
0099     return *(unsigned short *)addr == INSN_UD2;
0100 }
0101 
0102 static nokprobe_inline int
0103 do_trap_no_signal(struct task_struct *tsk, int trapnr, const char *str,
0104           struct pt_regs *regs, long error_code)
0105 {
0106     if (v8086_mode(regs)) {
0107         /*
0108          * Traps 0, 1, 3, 4, and 5 should be forwarded to vm86.
0109          * On nmi (interrupt 2), do_trap should not be called.
0110          */
0111         if (trapnr < X86_TRAP_UD) {
0112             if (!handle_vm86_trap((struct kernel_vm86_regs *) regs,
0113                         error_code, trapnr))
0114                 return 0;
0115         }
0116     } else if (!user_mode(regs)) {
0117         if (fixup_exception(regs, trapnr, error_code, 0))
0118             return 0;
0119 
0120         tsk->thread.error_code = error_code;
0121         tsk->thread.trap_nr = trapnr;
0122         die(str, regs, error_code);
0123     } else {
0124         if (fixup_vdso_exception(regs, trapnr, error_code, 0))
0125             return 0;
0126     }
0127 
0128     /*
0129      * We want error_code and trap_nr set for userspace faults and
0130      * kernelspace faults which result in die(), but not
0131      * kernelspace faults which are fixed up.  die() gives the
0132      * process no chance to handle the signal and notice the
0133      * kernel fault information, so that won't result in polluting
0134      * the information about previously queued, but not yet
0135      * delivered, faults.  See also exc_general_protection below.
0136      */
0137     tsk->thread.error_code = error_code;
0138     tsk->thread.trap_nr = trapnr;
0139 
0140     return -1;
0141 }
0142 
0143 static void show_signal(struct task_struct *tsk, int signr,
0144             const char *type, const char *desc,
0145             struct pt_regs *regs, long error_code)
0146 {
0147     if (show_unhandled_signals && unhandled_signal(tsk, signr) &&
0148         printk_ratelimit()) {
0149         pr_info("%s[%d] %s%s ip:%lx sp:%lx error:%lx",
0150             tsk->comm, task_pid_nr(tsk), type, desc,
0151             regs->ip, regs->sp, error_code);
0152         print_vma_addr(KERN_CONT " in ", regs->ip);
0153         pr_cont("\n");
0154     }
0155 }
0156 
0157 static void
0158 do_trap(int trapnr, int signr, char *str, struct pt_regs *regs,
0159     long error_code, int sicode, void __user *addr)
0160 {
0161     struct task_struct *tsk = current;
0162 
0163     if (!do_trap_no_signal(tsk, trapnr, str, regs, error_code))
0164         return;
0165 
0166     show_signal(tsk, signr, "trap ", str, regs, error_code);
0167 
0168     if (!sicode)
0169         force_sig(signr);
0170     else
0171         force_sig_fault(signr, sicode, addr);
0172 }
0173 NOKPROBE_SYMBOL(do_trap);
0174 
0175 static void do_error_trap(struct pt_regs *regs, long error_code, char *str,
0176     unsigned long trapnr, int signr, int sicode, void __user *addr)
0177 {
0178     RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
0179 
0180     if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, signr) !=
0181             NOTIFY_STOP) {
0182         cond_local_irq_enable(regs);
0183         do_trap(trapnr, signr, str, regs, error_code, sicode, addr);
0184         cond_local_irq_disable(regs);
0185     }
0186 }
0187 
0188 /*
0189  * Posix requires to provide the address of the faulting instruction for
0190  * SIGILL (#UD) and SIGFPE (#DE) in the si_addr member of siginfo_t.
0191  *
0192  * This address is usually regs->ip, but when an uprobe moved the code out
0193  * of line then regs->ip points to the XOL code which would confuse
0194  * anything which analyzes the fault address vs. the unmodified binary. If
0195  * a trap happened in XOL code then uprobe maps regs->ip back to the
0196  * original instruction address.
0197  */
0198 static __always_inline void __user *error_get_trap_addr(struct pt_regs *regs)
0199 {
0200     return (void __user *)uprobe_get_trap_addr(regs);
0201 }
0202 
0203 DEFINE_IDTENTRY(exc_divide_error)
0204 {
0205     do_error_trap(regs, 0, "divide error", X86_TRAP_DE, SIGFPE,
0206               FPE_INTDIV, error_get_trap_addr(regs));
0207 }
0208 
0209 DEFINE_IDTENTRY(exc_overflow)
0210 {
0211     do_error_trap(regs, 0, "overflow", X86_TRAP_OF, SIGSEGV, 0, NULL);
0212 }
0213 
0214 #ifdef CONFIG_X86_KERNEL_IBT
0215 
0216 static __ro_after_init bool ibt_fatal = true;
0217 
0218 extern void ibt_selftest_ip(void); /* code label defined in asm below */
0219 
0220 enum cp_error_code {
0221     CP_EC        = (1 << 15) - 1,
0222 
0223     CP_RET       = 1,
0224     CP_IRET      = 2,
0225     CP_ENDBR     = 3,
0226     CP_RSTRORSSP = 4,
0227     CP_SETSSBSY  = 5,
0228 
0229     CP_ENCL      = 1 << 15,
0230 };
0231 
0232 DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)
0233 {
0234     if (!cpu_feature_enabled(X86_FEATURE_IBT)) {
0235         pr_err("Unexpected #CP\n");
0236         BUG();
0237     }
0238 
0239     if (WARN_ON_ONCE(user_mode(regs) || (error_code & CP_EC) != CP_ENDBR))
0240         return;
0241 
0242     if (unlikely(regs->ip == (unsigned long)&ibt_selftest_ip)) {
0243         regs->ax = 0;
0244         return;
0245     }
0246 
0247     pr_err("Missing ENDBR: %pS\n", (void *)instruction_pointer(regs));
0248     if (!ibt_fatal) {
0249         printk(KERN_DEFAULT CUT_HERE);
0250         __warn(__FILE__, __LINE__, (void *)regs->ip, TAINT_WARN, regs, NULL);
0251         return;
0252     }
0253     BUG();
0254 }
0255 
0256 /* Must be noinline to ensure uniqueness of ibt_selftest_ip. */
0257 noinline bool ibt_selftest(void)
0258 {
0259     unsigned long ret;
0260 
0261     asm ("  lea ibt_selftest_ip(%%rip), %%rax\n\t"
0262          ANNOTATE_RETPOLINE_SAFE
0263          "  jmp *%%rax\n\t"
0264          "ibt_selftest_ip:\n\t"
0265          UNWIND_HINT_FUNC
0266          ANNOTATE_NOENDBR
0267          "  nop\n\t"
0268 
0269          : "=a" (ret) : : "memory");
0270 
0271     return !ret;
0272 }
0273 
0274 static int __init ibt_setup(char *str)
0275 {
0276     if (!strcmp(str, "off"))
0277         setup_clear_cpu_cap(X86_FEATURE_IBT);
0278 
0279     if (!strcmp(str, "warn"))
0280         ibt_fatal = false;
0281 
0282     return 1;
0283 }
0284 
0285 __setup("ibt=", ibt_setup);
0286 
0287 #endif /* CONFIG_X86_KERNEL_IBT */
0288 
0289 #ifdef CONFIG_X86_F00F_BUG
0290 void handle_invalid_op(struct pt_regs *regs)
0291 #else
0292 static inline void handle_invalid_op(struct pt_regs *regs)
0293 #endif
0294 {
0295     do_error_trap(regs, 0, "invalid opcode", X86_TRAP_UD, SIGILL,
0296               ILL_ILLOPN, error_get_trap_addr(regs));
0297 }
0298 
0299 static noinstr bool handle_bug(struct pt_regs *regs)
0300 {
0301     bool handled = false;
0302 
0303     if (!is_valid_bugaddr(regs->ip))
0304         return handled;
0305 
0306     /*
0307      * All lies, just get the WARN/BUG out.
0308      */
0309     instrumentation_begin();
0310     /*
0311      * Since we're emulating a CALL with exceptions, restore the interrupt
0312      * state to what it was at the exception site.
0313      */
0314     if (regs->flags & X86_EFLAGS_IF)
0315         raw_local_irq_enable();
0316     if (report_bug(regs->ip, regs) == BUG_TRAP_TYPE_WARN) {
0317         regs->ip += LEN_UD2;
0318         handled = true;
0319     }
0320     if (regs->flags & X86_EFLAGS_IF)
0321         raw_local_irq_disable();
0322     instrumentation_end();
0323 
0324     return handled;
0325 }
0326 
0327 DEFINE_IDTENTRY_RAW(exc_invalid_op)
0328 {
0329     irqentry_state_t state;
0330 
0331     /*
0332      * We use UD2 as a short encoding for 'CALL __WARN', as such
0333      * handle it before exception entry to avoid recursive WARN
0334      * in case exception entry is the one triggering WARNs.
0335      */
0336     if (!user_mode(regs) && handle_bug(regs))
0337         return;
0338 
0339     state = irqentry_enter(regs);
0340     instrumentation_begin();
0341     handle_invalid_op(regs);
0342     instrumentation_end();
0343     irqentry_exit(regs, state);
0344 }
0345 
0346 DEFINE_IDTENTRY(exc_coproc_segment_overrun)
0347 {
0348     do_error_trap(regs, 0, "coprocessor segment overrun",
0349               X86_TRAP_OLD_MF, SIGFPE, 0, NULL);
0350 }
0351 
0352 DEFINE_IDTENTRY_ERRORCODE(exc_invalid_tss)
0353 {
0354     do_error_trap(regs, error_code, "invalid TSS", X86_TRAP_TS, SIGSEGV,
0355               0, NULL);
0356 }
0357 
0358 DEFINE_IDTENTRY_ERRORCODE(exc_segment_not_present)
0359 {
0360     do_error_trap(regs, error_code, "segment not present", X86_TRAP_NP,
0361               SIGBUS, 0, NULL);
0362 }
0363 
0364 DEFINE_IDTENTRY_ERRORCODE(exc_stack_segment)
0365 {
0366     do_error_trap(regs, error_code, "stack segment", X86_TRAP_SS, SIGBUS,
0367               0, NULL);
0368 }
0369 
0370 DEFINE_IDTENTRY_ERRORCODE(exc_alignment_check)
0371 {
0372     char *str = "alignment check";
0373 
0374     if (notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_AC, SIGBUS) == NOTIFY_STOP)
0375         return;
0376 
0377     if (!user_mode(regs))
0378         die("Split lock detected\n", regs, error_code);
0379 
0380     local_irq_enable();
0381 
0382     if (handle_user_split_lock(regs, error_code))
0383         goto out;
0384 
0385     do_trap(X86_TRAP_AC, SIGBUS, "alignment check", regs,
0386         error_code, BUS_ADRALN, NULL);
0387 
0388 out:
0389     local_irq_disable();
0390 }
0391 
0392 #ifdef CONFIG_VMAP_STACK
0393 __visible void __noreturn handle_stack_overflow(struct pt_regs *regs,
0394                         unsigned long fault_address,
0395                         struct stack_info *info)
0396 {
0397     const char *name = stack_type_name(info->type);
0398 
0399     printk(KERN_EMERG "BUG: %s stack guard page was hit at %p (stack is %p..%p)\n",
0400            name, (void *)fault_address, info->begin, info->end);
0401 
0402     die("stack guard page", regs, 0);
0403 
0404     /* Be absolutely certain we don't return. */
0405     panic("%s stack guard hit", name);
0406 }
0407 #endif
0408 
0409 /*
0410  * Runs on an IST stack for x86_64 and on a special task stack for x86_32.
0411  *
0412  * On x86_64, this is more or less a normal kernel entry.  Notwithstanding the
0413  * SDM's warnings about double faults being unrecoverable, returning works as
0414  * expected.  Presumably what the SDM actually means is that the CPU may get
0415  * the register state wrong on entry, so returning could be a bad idea.
0416  *
0417  * Various CPU engineers have promised that double faults due to an IRET fault
0418  * while the stack is read-only are, in fact, recoverable.
0419  *
0420  * On x86_32, this is entered through a task gate, and regs are synthesized
0421  * from the TSS.  Returning is, in principle, okay, but changes to regs will
0422  * be lost.  If, for some reason, we need to return to a context with modified
0423  * regs, the shim code could be adjusted to synchronize the registers.
0424  *
0425  * The 32bit #DF shim provides CR2 already as an argument. On 64bit it needs
0426  * to be read before doing anything else.
0427  */
0428 DEFINE_IDTENTRY_DF(exc_double_fault)
0429 {
0430     static const char str[] = "double fault";
0431     struct task_struct *tsk = current;
0432 
0433 #ifdef CONFIG_VMAP_STACK
0434     unsigned long address = read_cr2();
0435     struct stack_info info;
0436 #endif
0437 
0438 #ifdef CONFIG_X86_ESPFIX64
0439     extern unsigned char native_irq_return_iret[];
0440 
0441     /*
0442      * If IRET takes a non-IST fault on the espfix64 stack, then we
0443      * end up promoting it to a doublefault.  In that case, take
0444      * advantage of the fact that we're not using the normal (TSS.sp0)
0445      * stack right now.  We can write a fake #GP(0) frame at TSS.sp0
0446      * and then modify our own IRET frame so that, when we return,
0447      * we land directly at the #GP(0) vector with the stack already
0448      * set up according to its expectations.
0449      *
0450      * The net result is that our #GP handler will think that we
0451      * entered from usermode with the bad user context.
0452      *
0453      * No need for nmi_enter() here because we don't use RCU.
0454      */
0455     if (((long)regs->sp >> P4D_SHIFT) == ESPFIX_PGD_ENTRY &&
0456         regs->cs == __KERNEL_CS &&
0457         regs->ip == (unsigned long)native_irq_return_iret)
0458     {
0459         struct pt_regs *gpregs = (struct pt_regs *)this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
0460         unsigned long *p = (unsigned long *)regs->sp;
0461 
0462         /*
0463          * regs->sp points to the failing IRET frame on the
0464          * ESPFIX64 stack.  Copy it to the entry stack.  This fills
0465          * in gpregs->ss through gpregs->ip.
0466          *
0467          */
0468         gpregs->ip  = p[0];
0469         gpregs->cs  = p[1];
0470         gpregs->flags   = p[2];
0471         gpregs->sp  = p[3];
0472         gpregs->ss  = p[4];
0473         gpregs->orig_ax = 0;  /* Missing (lost) #GP error code */
0474 
0475         /*
0476          * Adjust our frame so that we return straight to the #GP
0477          * vector with the expected RSP value.  This is safe because
0478          * we won't enable interrupts or schedule before we invoke
0479          * general_protection, so nothing will clobber the stack
0480          * frame we just set up.
0481          *
0482          * We will enter general_protection with kernel GSBASE,
0483          * which is what the stub expects, given that the faulting
0484          * RIP will be the IRET instruction.
0485          */
0486         regs->ip = (unsigned long)asm_exc_general_protection;
0487         regs->sp = (unsigned long)&gpregs->orig_ax;
0488 
0489         return;
0490     }
0491 #endif
0492 
0493     irqentry_nmi_enter(regs);
0494     instrumentation_begin();
0495     notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_DF, SIGSEGV);
0496 
0497     tsk->thread.error_code = error_code;
0498     tsk->thread.trap_nr = X86_TRAP_DF;
0499 
0500 #ifdef CONFIG_VMAP_STACK
0501     /*
0502      * If we overflow the stack into a guard page, the CPU will fail
0503      * to deliver #PF and will send #DF instead.  Similarly, if we
0504      * take any non-IST exception while too close to the bottom of
0505      * the stack, the processor will get a page fault while
0506      * delivering the exception and will generate a double fault.
0507      *
0508      * According to the SDM (footnote in 6.15 under "Interrupt 14 -
0509      * Page-Fault Exception (#PF):
0510      *
0511      *   Processors update CR2 whenever a page fault is detected. If a
0512      *   second page fault occurs while an earlier page fault is being
0513      *   delivered, the faulting linear address of the second fault will
0514      *   overwrite the contents of CR2 (replacing the previous
0515      *   address). These updates to CR2 occur even if the page fault
0516      *   results in a double fault or occurs during the delivery of a
0517      *   double fault.
0518      *
0519      * The logic below has a small possibility of incorrectly diagnosing
0520      * some errors as stack overflows.  For example, if the IDT or GDT
0521      * gets corrupted such that #GP delivery fails due to a bad descriptor
0522      * causing #GP and we hit this condition while CR2 coincidentally
0523      * points to the stack guard page, we'll think we overflowed the
0524      * stack.  Given that we're going to panic one way or another
0525      * if this happens, this isn't necessarily worth fixing.
0526      *
0527      * If necessary, we could improve the test by only diagnosing
0528      * a stack overflow if the saved RSP points within 47 bytes of
0529      * the bottom of the stack: if RSP == tsk_stack + 48 and we
0530      * take an exception, the stack is already aligned and there
0531      * will be enough room SS, RSP, RFLAGS, CS, RIP, and a
0532      * possible error code, so a stack overflow would *not* double
0533      * fault.  With any less space left, exception delivery could
0534      * fail, and, as a practical matter, we've overflowed the
0535      * stack even if the actual trigger for the double fault was
0536      * something else.
0537      */
0538     if (get_stack_guard_info((void *)address, &info))
0539         handle_stack_overflow(regs, address, &info);
0540 #endif
0541 
0542     pr_emerg("PANIC: double fault, error_code: 0x%lx\n", error_code);
0543     die("double fault", regs, error_code);
0544     panic("Machine halted.");
0545     instrumentation_end();
0546 }
0547 
0548 DEFINE_IDTENTRY(exc_bounds)
0549 {
0550     if (notify_die(DIE_TRAP, "bounds", regs, 0,
0551             X86_TRAP_BR, SIGSEGV) == NOTIFY_STOP)
0552         return;
0553     cond_local_irq_enable(regs);
0554 
0555     if (!user_mode(regs))
0556         die("bounds", regs, 0);
0557 
0558     do_trap(X86_TRAP_BR, SIGSEGV, "bounds", regs, 0, 0, NULL);
0559 
0560     cond_local_irq_disable(regs);
0561 }
0562 
0563 enum kernel_gp_hint {
0564     GP_NO_HINT,
0565     GP_NON_CANONICAL,
0566     GP_CANONICAL
0567 };
0568 
0569 /*
0570  * When an uncaught #GP occurs, try to determine the memory address accessed by
0571  * the instruction and return that address to the caller. Also, try to figure
0572  * out whether any part of the access to that address was non-canonical.
0573  */
0574 static enum kernel_gp_hint get_kernel_gp_address(struct pt_regs *regs,
0575                          unsigned long *addr)
0576 {
0577     u8 insn_buf[MAX_INSN_SIZE];
0578     struct insn insn;
0579     int ret;
0580 
0581     if (copy_from_kernel_nofault(insn_buf, (void *)regs->ip,
0582             MAX_INSN_SIZE))
0583         return GP_NO_HINT;
0584 
0585     ret = insn_decode_kernel(&insn, insn_buf);
0586     if (ret < 0)
0587         return GP_NO_HINT;
0588 
0589     *addr = (unsigned long)insn_get_addr_ref(&insn, regs);
0590     if (*addr == -1UL)
0591         return GP_NO_HINT;
0592 
0593 #ifdef CONFIG_X86_64
0594     /*
0595      * Check that:
0596      *  - the operand is not in the kernel half
0597      *  - the last byte of the operand is not in the user canonical half
0598      */
0599     if (*addr < ~__VIRTUAL_MASK &&
0600         *addr + insn.opnd_bytes - 1 > __VIRTUAL_MASK)
0601         return GP_NON_CANONICAL;
0602 #endif
0603 
0604     return GP_CANONICAL;
0605 }
0606 
0607 #define GPFSTR "general protection fault"
0608 
0609 static bool fixup_iopl_exception(struct pt_regs *regs)
0610 {
0611     struct thread_struct *t = &current->thread;
0612     unsigned char byte;
0613     unsigned long ip;
0614 
0615     if (!IS_ENABLED(CONFIG_X86_IOPL_IOPERM) || t->iopl_emul != 3)
0616         return false;
0617 
0618     if (insn_get_effective_ip(regs, &ip))
0619         return false;
0620 
0621     if (get_user(byte, (const char __user *)ip))
0622         return false;
0623 
0624     if (byte != 0xfa && byte != 0xfb)
0625         return false;
0626 
0627     if (!t->iopl_warn && printk_ratelimit()) {
0628         pr_err("%s[%d] attempts to use CLI/STI, pretending it's a NOP, ip:%lx",
0629                current->comm, task_pid_nr(current), ip);
0630         print_vma_addr(KERN_CONT " in ", ip);
0631         pr_cont("\n");
0632         t->iopl_warn = 1;
0633     }
0634 
0635     regs->ip += 1;
0636     return true;
0637 }
0638 
0639 /*
0640  * The unprivileged ENQCMD instruction generates #GPs if the
0641  * IA32_PASID MSR has not been populated.  If possible, populate
0642  * the MSR from a PASID previously allocated to the mm.
0643  */
0644 static bool try_fixup_enqcmd_gp(void)
0645 {
0646 #ifdef CONFIG_IOMMU_SVA
0647     u32 pasid;
0648 
0649     /*
0650      * MSR_IA32_PASID is managed using XSAVE.  Directly
0651      * writing to the MSR is only possible when fpregs
0652      * are valid and the fpstate is not.  This is
0653      * guaranteed when handling a userspace exception
0654      * in *before* interrupts are re-enabled.
0655      */
0656     lockdep_assert_irqs_disabled();
0657 
0658     /*
0659      * Hardware without ENQCMD will not generate
0660      * #GPs that can be fixed up here.
0661      */
0662     if (!cpu_feature_enabled(X86_FEATURE_ENQCMD))
0663         return false;
0664 
0665     pasid = current->mm->pasid;
0666 
0667     /*
0668      * If the mm has not been allocated a
0669      * PASID, the #GP can not be fixed up.
0670      */
0671     if (!pasid_valid(pasid))
0672         return false;
0673 
0674     /*
0675      * Did this thread already have its PASID activated?
0676      * If so, the #GP must be from something else.
0677      */
0678     if (current->pasid_activated)
0679         return false;
0680 
0681     wrmsrl(MSR_IA32_PASID, pasid | MSR_IA32_PASID_VALID);
0682     current->pasid_activated = 1;
0683 
0684     return true;
0685 #else
0686     return false;
0687 #endif
0688 }
0689 
0690 static bool gp_try_fixup_and_notify(struct pt_regs *regs, int trapnr,
0691                     unsigned long error_code, const char *str)
0692 {
0693     if (fixup_exception(regs, trapnr, error_code, 0))
0694         return true;
0695 
0696     current->thread.error_code = error_code;
0697     current->thread.trap_nr = trapnr;
0698 
0699     /*
0700      * To be potentially processing a kprobe fault and to trust the result
0701      * from kprobe_running(), we have to be non-preemptible.
0702      */
0703     if (!preemptible() && kprobe_running() &&
0704         kprobe_fault_handler(regs, trapnr))
0705         return true;
0706 
0707     return notify_die(DIE_GPF, str, regs, error_code, trapnr, SIGSEGV) == NOTIFY_STOP;
0708 }
0709 
0710 static void gp_user_force_sig_segv(struct pt_regs *regs, int trapnr,
0711                    unsigned long error_code, const char *str)
0712 {
0713     current->thread.error_code = error_code;
0714     current->thread.trap_nr = trapnr;
0715     show_signal(current, SIGSEGV, "", str, regs, error_code);
0716     force_sig(SIGSEGV);
0717 }
0718 
0719 DEFINE_IDTENTRY_ERRORCODE(exc_general_protection)
0720 {
0721     char desc[sizeof(GPFSTR) + 50 + 2*sizeof(unsigned long) + 1] = GPFSTR;
0722     enum kernel_gp_hint hint = GP_NO_HINT;
0723     unsigned long gp_addr;
0724 
0725     if (user_mode(regs) && try_fixup_enqcmd_gp())
0726         return;
0727 
0728     cond_local_irq_enable(regs);
0729 
0730     if (static_cpu_has(X86_FEATURE_UMIP)) {
0731         if (user_mode(regs) && fixup_umip_exception(regs))
0732             goto exit;
0733     }
0734 
0735     if (v8086_mode(regs)) {
0736         local_irq_enable();
0737         handle_vm86_fault((struct kernel_vm86_regs *) regs, error_code);
0738         local_irq_disable();
0739         return;
0740     }
0741 
0742     if (user_mode(regs)) {
0743         if (fixup_iopl_exception(regs))
0744             goto exit;
0745 
0746         if (fixup_vdso_exception(regs, X86_TRAP_GP, error_code, 0))
0747             goto exit;
0748 
0749         gp_user_force_sig_segv(regs, X86_TRAP_GP, error_code, desc);
0750         goto exit;
0751     }
0752 
0753     if (gp_try_fixup_and_notify(regs, X86_TRAP_GP, error_code, desc))
0754         goto exit;
0755 
0756     if (error_code)
0757         snprintf(desc, sizeof(desc), "segment-related " GPFSTR);
0758     else
0759         hint = get_kernel_gp_address(regs, &gp_addr);
0760 
0761     if (hint != GP_NO_HINT)
0762         snprintf(desc, sizeof(desc), GPFSTR ", %s 0x%lx",
0763              (hint == GP_NON_CANONICAL) ? "probably for non-canonical address"
0764                             : "maybe for address",
0765              gp_addr);
0766 
0767     /*
0768      * KASAN is interested only in the non-canonical case, clear it
0769      * otherwise.
0770      */
0771     if (hint != GP_NON_CANONICAL)
0772         gp_addr = 0;
0773 
0774     die_addr(desc, regs, error_code, gp_addr);
0775 
0776 exit:
0777     cond_local_irq_disable(regs);
0778 }
0779 
0780 static bool do_int3(struct pt_regs *regs)
0781 {
0782     int res;
0783 
0784 #ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
0785     if (kgdb_ll_trap(DIE_INT3, "int3", regs, 0, X86_TRAP_BP,
0786              SIGTRAP) == NOTIFY_STOP)
0787         return true;
0788 #endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
0789 
0790 #ifdef CONFIG_KPROBES
0791     if (kprobe_int3_handler(regs))
0792         return true;
0793 #endif
0794     res = notify_die(DIE_INT3, "int3", regs, 0, X86_TRAP_BP, SIGTRAP);
0795 
0796     return res == NOTIFY_STOP;
0797 }
0798 NOKPROBE_SYMBOL(do_int3);
0799 
0800 static void do_int3_user(struct pt_regs *regs)
0801 {
0802     if (do_int3(regs))
0803         return;
0804 
0805     cond_local_irq_enable(regs);
0806     do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, 0, 0, NULL);
0807     cond_local_irq_disable(regs);
0808 }
0809 
0810 DEFINE_IDTENTRY_RAW(exc_int3)
0811 {
0812     /*
0813      * poke_int3_handler() is completely self contained code; it does (and
0814      * must) *NOT* call out to anything, lest it hits upon yet another
0815      * INT3.
0816      */
0817     if (poke_int3_handler(regs))
0818         return;
0819 
0820     /*
0821      * irqentry_enter_from_user_mode() uses static_branch_{,un}likely()
0822      * and therefore can trigger INT3, hence poke_int3_handler() must
0823      * be done before. If the entry came from kernel mode, then use
0824      * nmi_enter() because the INT3 could have been hit in any context
0825      * including NMI.
0826      */
0827     if (user_mode(regs)) {
0828         irqentry_enter_from_user_mode(regs);
0829         instrumentation_begin();
0830         do_int3_user(regs);
0831         instrumentation_end();
0832         irqentry_exit_to_user_mode(regs);
0833     } else {
0834         irqentry_state_t irq_state = irqentry_nmi_enter(regs);
0835 
0836         instrumentation_begin();
0837         if (!do_int3(regs))
0838             die("int3", regs, 0);
0839         instrumentation_end();
0840         irqentry_nmi_exit(regs, irq_state);
0841     }
0842 }
0843 
0844 #ifdef CONFIG_X86_64
0845 /*
0846  * Help handler running on a per-cpu (IST or entry trampoline) stack
0847  * to switch to the normal thread stack if the interrupted code was in
0848  * user mode. The actual stack switch is done in entry_64.S
0849  */
0850 asmlinkage __visible noinstr struct pt_regs *sync_regs(struct pt_regs *eregs)
0851 {
0852     struct pt_regs *regs = (struct pt_regs *)this_cpu_read(cpu_current_top_of_stack) - 1;
0853     if (regs != eregs)
0854         *regs = *eregs;
0855     return regs;
0856 }
0857 
0858 #ifdef CONFIG_AMD_MEM_ENCRYPT
0859 asmlinkage __visible noinstr struct pt_regs *vc_switch_off_ist(struct pt_regs *regs)
0860 {
0861     unsigned long sp, *stack;
0862     struct stack_info info;
0863     struct pt_regs *regs_ret;
0864 
0865     /*
0866      * In the SYSCALL entry path the RSP value comes from user-space - don't
0867      * trust it and switch to the current kernel stack
0868      */
0869     if (ip_within_syscall_gap(regs)) {
0870         sp = this_cpu_read(cpu_current_top_of_stack);
0871         goto sync;
0872     }
0873 
0874     /*
0875      * From here on the RSP value is trusted. Now check whether entry
0876      * happened from a safe stack. Not safe are the entry or unknown stacks,
0877      * use the fall-back stack instead in this case.
0878      */
0879     sp    = regs->sp;
0880     stack = (unsigned long *)sp;
0881 
0882     if (!get_stack_info_noinstr(stack, current, &info) || info.type == STACK_TYPE_ENTRY ||
0883         info.type > STACK_TYPE_EXCEPTION_LAST)
0884         sp = __this_cpu_ist_top_va(VC2);
0885 
0886 sync:
0887     /*
0888      * Found a safe stack - switch to it as if the entry didn't happen via
0889      * IST stack. The code below only copies pt_regs, the real switch happens
0890      * in assembly code.
0891      */
0892     sp = ALIGN_DOWN(sp, 8) - sizeof(*regs_ret);
0893 
0894     regs_ret = (struct pt_regs *)sp;
0895     *regs_ret = *regs;
0896 
0897     return regs_ret;
0898 }
0899 #endif
0900 
0901 asmlinkage __visible noinstr struct pt_regs *fixup_bad_iret(struct pt_regs *bad_regs)
0902 {
0903     struct pt_regs tmp, *new_stack;
0904 
0905     /*
0906      * This is called from entry_64.S early in handling a fault
0907      * caused by a bad iret to user mode.  To handle the fault
0908      * correctly, we want to move our stack frame to where it would
0909      * be had we entered directly on the entry stack (rather than
0910      * just below the IRET frame) and we want to pretend that the
0911      * exception came from the IRET target.
0912      */
0913     new_stack = (struct pt_regs *)__this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
0914 
0915     /* Copy the IRET target to the temporary storage. */
0916     __memcpy(&tmp.ip, (void *)bad_regs->sp, 5*8);
0917 
0918     /* Copy the remainder of the stack from the current stack. */
0919     __memcpy(&tmp, bad_regs, offsetof(struct pt_regs, ip));
0920 
0921     /* Update the entry stack */
0922     __memcpy(new_stack, &tmp, sizeof(tmp));
0923 
0924     BUG_ON(!user_mode(new_stack));
0925     return new_stack;
0926 }
0927 #endif
0928 
0929 static bool is_sysenter_singlestep(struct pt_regs *regs)
0930 {
0931     /*
0932      * We don't try for precision here.  If we're anywhere in the region of
0933      * code that can be single-stepped in the SYSENTER entry path, then
0934      * assume that this is a useless single-step trap due to SYSENTER
0935      * being invoked with TF set.  (We don't know in advance exactly
0936      * which instructions will be hit because BTF could plausibly
0937      * be set.)
0938      */
0939 #ifdef CONFIG_X86_32
0940     return (regs->ip - (unsigned long)__begin_SYSENTER_singlestep_region) <
0941         (unsigned long)__end_SYSENTER_singlestep_region -
0942         (unsigned long)__begin_SYSENTER_singlestep_region;
0943 #elif defined(CONFIG_IA32_EMULATION)
0944     return (regs->ip - (unsigned long)entry_SYSENTER_compat) <
0945         (unsigned long)__end_entry_SYSENTER_compat -
0946         (unsigned long)entry_SYSENTER_compat;
0947 #else
0948     return false;
0949 #endif
0950 }
0951 
0952 static __always_inline unsigned long debug_read_clear_dr6(void)
0953 {
0954     unsigned long dr6;
0955 
0956     /*
0957      * The Intel SDM says:
0958      *
0959      *   Certain debug exceptions may clear bits 0-3. The remaining
0960      *   contents of the DR6 register are never cleared by the
0961      *   processor. To avoid confusion in identifying debug
0962      *   exceptions, debug handlers should clear the register before
0963      *   returning to the interrupted task.
0964      *
0965      * Keep it simple: clear DR6 immediately.
0966      */
0967     get_debugreg(dr6, 6);
0968     set_debugreg(DR6_RESERVED, 6);
0969     dr6 ^= DR6_RESERVED; /* Flip to positive polarity */
0970 
0971     return dr6;
0972 }
0973 
0974 /*
0975  * Our handling of the processor debug registers is non-trivial.
0976  * We do not clear them on entry and exit from the kernel. Therefore
0977  * it is possible to get a watchpoint trap here from inside the kernel.
0978  * However, the code in ./ptrace.c has ensured that the user can
0979  * only set watchpoints on userspace addresses. Therefore the in-kernel
0980  * watchpoint trap can only occur in code which is reading/writing
0981  * from user space. Such code must not hold kernel locks (since it
0982  * can equally take a page fault), therefore it is safe to call
0983  * force_sig_info even though that claims and releases locks.
0984  *
0985  * Code in ./signal.c ensures that the debug control register
0986  * is restored before we deliver any signal, and therefore that
0987  * user code runs with the correct debug control register even though
0988  * we clear it here.
0989  *
0990  * Being careful here means that we don't have to be as careful in a
0991  * lot of more complicated places (task switching can be a bit lazy
0992  * about restoring all the debug state, and ptrace doesn't have to
0993  * find every occurrence of the TF bit that could be saved away even
0994  * by user code)
0995  *
0996  * May run on IST stack.
0997  */
0998 
0999 static bool notify_debug(struct pt_regs *regs, unsigned long *dr6)
1000 {
1001     /*
1002      * Notifiers will clear bits in @dr6 to indicate the event has been
1003      * consumed - hw_breakpoint_handler(), single_stop_cont().
1004      *
1005      * Notifiers will set bits in @virtual_dr6 to indicate the desire
1006      * for signals - ptrace_triggered(), kgdb_hw_overflow_handler().
1007      */
1008     if (notify_die(DIE_DEBUG, "debug", regs, (long)dr6, 0, SIGTRAP) == NOTIFY_STOP)
1009         return true;
1010 
1011     return false;
1012 }
1013 
1014 static __always_inline void exc_debug_kernel(struct pt_regs *regs,
1015                          unsigned long dr6)
1016 {
1017     /*
1018      * Disable breakpoints during exception handling; recursive exceptions
1019      * are exceedingly 'fun'.
1020      *
1021      * Since this function is NOKPROBE, and that also applies to
1022      * HW_BREAKPOINT_X, we can't hit a breakpoint before this (XXX except a
1023      * HW_BREAKPOINT_W on our stack)
1024      *
1025      * Entry text is excluded for HW_BP_X and cpu_entry_area, which
1026      * includes the entry stack is excluded for everything.
1027      */
1028     unsigned long dr7 = local_db_save();
1029     irqentry_state_t irq_state = irqentry_nmi_enter(regs);
1030     instrumentation_begin();
1031 
1032     /*
1033      * If something gets miswired and we end up here for a user mode
1034      * #DB, we will malfunction.
1035      */
1036     WARN_ON_ONCE(user_mode(regs));
1037 
1038     if (test_thread_flag(TIF_BLOCKSTEP)) {
1039         /*
1040          * The SDM says "The processor clears the BTF flag when it
1041          * generates a debug exception." but PTRACE_BLOCKSTEP requested
1042          * it for userspace, but we just took a kernel #DB, so re-set
1043          * BTF.
1044          */
1045         unsigned long debugctl;
1046 
1047         rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
1048         debugctl |= DEBUGCTLMSR_BTF;
1049         wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
1050     }
1051 
1052     /*
1053      * Catch SYSENTER with TF set and clear DR_STEP. If this hit a
1054      * watchpoint at the same time then that will still be handled.
1055      */
1056     if ((dr6 & DR_STEP) && is_sysenter_singlestep(regs))
1057         dr6 &= ~DR_STEP;
1058 
1059     /*
1060      * The kernel doesn't use INT1
1061      */
1062     if (!dr6)
1063         goto out;
1064 
1065     if (notify_debug(regs, &dr6))
1066         goto out;
1067 
1068     /*
1069      * The kernel doesn't use TF single-step outside of:
1070      *
1071      *  - Kprobes, consumed through kprobe_debug_handler()
1072      *  - KGDB, consumed through notify_debug()
1073      *
1074      * So if we get here with DR_STEP set, something is wonky.
1075      *
1076      * A known way to trigger this is through QEMU's GDB stub,
1077      * which leaks #DB into the guest and causes IST recursion.
1078      */
1079     if (WARN_ON_ONCE(dr6 & DR_STEP))
1080         regs->flags &= ~X86_EFLAGS_TF;
1081 out:
1082     instrumentation_end();
1083     irqentry_nmi_exit(regs, irq_state);
1084 
1085     local_db_restore(dr7);
1086 }
1087 
1088 static __always_inline void exc_debug_user(struct pt_regs *regs,
1089                        unsigned long dr6)
1090 {
1091     bool icebp;
1092 
1093     /*
1094      * If something gets miswired and we end up here for a kernel mode
1095      * #DB, we will malfunction.
1096      */
1097     WARN_ON_ONCE(!user_mode(regs));
1098 
1099     /*
1100      * NB: We can't easily clear DR7 here because
1101      * irqentry_exit_to_usermode() can invoke ptrace, schedule, access
1102      * user memory, etc.  This means that a recursive #DB is possible.  If
1103      * this happens, that #DB will hit exc_debug_kernel() and clear DR7.
1104      * Since we're not on the IST stack right now, everything will be
1105      * fine.
1106      */
1107 
1108     irqentry_enter_from_user_mode(regs);
1109     instrumentation_begin();
1110 
1111     /*
1112      * Start the virtual/ptrace DR6 value with just the DR_STEP mask
1113      * of the real DR6. ptrace_triggered() will set the DR_TRAPn bits.
1114      *
1115      * Userspace expects DR_STEP to be visible in ptrace_get_debugreg(6)
1116      * even if it is not the result of PTRACE_SINGLESTEP.
1117      */
1118     current->thread.virtual_dr6 = (dr6 & DR_STEP);
1119 
1120     /*
1121      * The SDM says "The processor clears the BTF flag when it
1122      * generates a debug exception."  Clear TIF_BLOCKSTEP to keep
1123      * TIF_BLOCKSTEP in sync with the hardware BTF flag.
1124      */
1125     clear_thread_flag(TIF_BLOCKSTEP);
1126 
1127     /*
1128      * If dr6 has no reason to give us about the origin of this trap,
1129      * then it's very likely the result of an icebp/int01 trap.
1130      * User wants a sigtrap for that.
1131      */
1132     icebp = !dr6;
1133 
1134     if (notify_debug(regs, &dr6))
1135         goto out;
1136 
1137     /* It's safe to allow irq's after DR6 has been saved */
1138     local_irq_enable();
1139 
1140     if (v8086_mode(regs)) {
1141         handle_vm86_trap((struct kernel_vm86_regs *)regs, 0, X86_TRAP_DB);
1142         goto out_irq;
1143     }
1144 
1145     /* #DB for bus lock can only be triggered from userspace. */
1146     if (dr6 & DR_BUS_LOCK)
1147         handle_bus_lock(regs);
1148 
1149     /* Add the virtual_dr6 bits for signals. */
1150     dr6 |= current->thread.virtual_dr6;
1151     if (dr6 & (DR_STEP | DR_TRAP_BITS) || icebp)
1152         send_sigtrap(regs, 0, get_si_code(dr6));
1153 
1154 out_irq:
1155     local_irq_disable();
1156 out:
1157     instrumentation_end();
1158     irqentry_exit_to_user_mode(regs);
1159 }
1160 
1161 #ifdef CONFIG_X86_64
1162 /* IST stack entry */
1163 DEFINE_IDTENTRY_DEBUG(exc_debug)
1164 {
1165     exc_debug_kernel(regs, debug_read_clear_dr6());
1166 }
1167 
1168 /* User entry, runs on regular task stack */
1169 DEFINE_IDTENTRY_DEBUG_USER(exc_debug)
1170 {
1171     exc_debug_user(regs, debug_read_clear_dr6());
1172 }
1173 #else
1174 /* 32 bit does not have separate entry points. */
1175 DEFINE_IDTENTRY_RAW(exc_debug)
1176 {
1177     unsigned long dr6 = debug_read_clear_dr6();
1178 
1179     if (user_mode(regs))
1180         exc_debug_user(regs, dr6);
1181     else
1182         exc_debug_kernel(regs, dr6);
1183 }
1184 #endif
1185 
1186 /*
1187  * Note that we play around with the 'TS' bit in an attempt to get
1188  * the correct behaviour even in the presence of the asynchronous
1189  * IRQ13 behaviour
1190  */
1191 static void math_error(struct pt_regs *regs, int trapnr)
1192 {
1193     struct task_struct *task = current;
1194     struct fpu *fpu = &task->thread.fpu;
1195     int si_code;
1196     char *str = (trapnr == X86_TRAP_MF) ? "fpu exception" :
1197                         "simd exception";
1198 
1199     cond_local_irq_enable(regs);
1200 
1201     if (!user_mode(regs)) {
1202         if (fixup_exception(regs, trapnr, 0, 0))
1203             goto exit;
1204 
1205         task->thread.error_code = 0;
1206         task->thread.trap_nr = trapnr;
1207 
1208         if (notify_die(DIE_TRAP, str, regs, 0, trapnr,
1209                    SIGFPE) != NOTIFY_STOP)
1210             die(str, regs, 0);
1211         goto exit;
1212     }
1213 
1214     /*
1215      * Synchronize the FPU register state to the memory register state
1216      * if necessary. This allows the exception handler to inspect it.
1217      */
1218     fpu_sync_fpstate(fpu);
1219 
1220     task->thread.trap_nr    = trapnr;
1221     task->thread.error_code = 0;
1222 
1223     si_code = fpu__exception_code(fpu, trapnr);
1224     /* Retry when we get spurious exceptions: */
1225     if (!si_code)
1226         goto exit;
1227 
1228     if (fixup_vdso_exception(regs, trapnr, 0, 0))
1229         goto exit;
1230 
1231     force_sig_fault(SIGFPE, si_code,
1232             (void __user *)uprobe_get_trap_addr(regs));
1233 exit:
1234     cond_local_irq_disable(regs);
1235 }
1236 
1237 DEFINE_IDTENTRY(exc_coprocessor_error)
1238 {
1239     math_error(regs, X86_TRAP_MF);
1240 }
1241 
1242 DEFINE_IDTENTRY(exc_simd_coprocessor_error)
1243 {
1244     if (IS_ENABLED(CONFIG_X86_INVD_BUG)) {
1245         /* AMD 486 bug: INVD in CPL 0 raises #XF instead of #GP */
1246         if (!static_cpu_has(X86_FEATURE_XMM)) {
1247             __exc_general_protection(regs, 0);
1248             return;
1249         }
1250     }
1251     math_error(regs, X86_TRAP_XF);
1252 }
1253 
1254 DEFINE_IDTENTRY(exc_spurious_interrupt_bug)
1255 {
1256     /*
1257      * This addresses a Pentium Pro Erratum:
1258      *
1259      * PROBLEM: If the APIC subsystem is configured in mixed mode with
1260      * Virtual Wire mode implemented through the local APIC, an
1261      * interrupt vector of 0Fh (Intel reserved encoding) may be
1262      * generated by the local APIC (Int 15).  This vector may be
1263      * generated upon receipt of a spurious interrupt (an interrupt
1264      * which is removed before the system receives the INTA sequence)
1265      * instead of the programmed 8259 spurious interrupt vector.
1266      *
1267      * IMPLICATION: The spurious interrupt vector programmed in the
1268      * 8259 is normally handled by an operating system's spurious
1269      * interrupt handler. However, a vector of 0Fh is unknown to some
1270      * operating systems, which would crash if this erratum occurred.
1271      *
1272      * In theory this could be limited to 32bit, but the handler is not
1273      * hurting and who knows which other CPUs suffer from this.
1274      */
1275 }
1276 
1277 static bool handle_xfd_event(struct pt_regs *regs)
1278 {
1279     u64 xfd_err;
1280     int err;
1281 
1282     if (!IS_ENABLED(CONFIG_X86_64) || !cpu_feature_enabled(X86_FEATURE_XFD))
1283         return false;
1284 
1285     rdmsrl(MSR_IA32_XFD_ERR, xfd_err);
1286     if (!xfd_err)
1287         return false;
1288 
1289     wrmsrl(MSR_IA32_XFD_ERR, 0);
1290 
1291     /* Die if that happens in kernel space */
1292     if (WARN_ON(!user_mode(regs)))
1293         return false;
1294 
1295     local_irq_enable();
1296 
1297     err = xfd_enable_feature(xfd_err);
1298 
1299     switch (err) {
1300     case -EPERM:
1301         force_sig_fault(SIGILL, ILL_ILLOPC, error_get_trap_addr(regs));
1302         break;
1303     case -EFAULT:
1304         force_sig(SIGSEGV);
1305         break;
1306     }
1307 
1308     local_irq_disable();
1309     return true;
1310 }
1311 
1312 DEFINE_IDTENTRY(exc_device_not_available)
1313 {
1314     unsigned long cr0 = read_cr0();
1315 
1316     if (handle_xfd_event(regs))
1317         return;
1318 
1319 #ifdef CONFIG_MATH_EMULATION
1320     if (!boot_cpu_has(X86_FEATURE_FPU) && (cr0 & X86_CR0_EM)) {
1321         struct math_emu_info info = { };
1322 
1323         cond_local_irq_enable(regs);
1324 
1325         info.regs = regs;
1326         math_emulate(&info);
1327 
1328         cond_local_irq_disable(regs);
1329         return;
1330     }
1331 #endif
1332 
1333     /* This should not happen. */
1334     if (WARN(cr0 & X86_CR0_TS, "CR0.TS was set")) {
1335         /* Try to fix it up and carry on. */
1336         write_cr0(cr0 & ~X86_CR0_TS);
1337     } else {
1338         /*
1339          * Something terrible happened, and we're better off trying
1340          * to kill the task than getting stuck in a never-ending
1341          * loop of #NM faults.
1342          */
1343         die("unexpected #NM exception", regs, 0);
1344     }
1345 }
1346 
1347 #ifdef CONFIG_INTEL_TDX_GUEST
1348 
1349 #define VE_FAULT_STR "VE fault"
1350 
1351 static void ve_raise_fault(struct pt_regs *regs, long error_code)
1352 {
1353     if (user_mode(regs)) {
1354         gp_user_force_sig_segv(regs, X86_TRAP_VE, error_code, VE_FAULT_STR);
1355         return;
1356     }
1357 
1358     if (gp_try_fixup_and_notify(regs, X86_TRAP_VE, error_code, VE_FAULT_STR))
1359         return;
1360 
1361     die_addr(VE_FAULT_STR, regs, error_code, 0);
1362 }
1363 
1364 /*
1365  * Virtualization Exceptions (#VE) are delivered to TDX guests due to
1366  * specific guest actions which may happen in either user space or the
1367  * kernel:
1368  *
1369  *  * Specific instructions (WBINVD, for example)
1370  *  * Specific MSR accesses
1371  *  * Specific CPUID leaf accesses
1372  *  * Access to specific guest physical addresses
1373  *
1374  * In the settings that Linux will run in, virtualization exceptions are
1375  * never generated on accesses to normal, TD-private memory that has been
1376  * accepted (by BIOS or with tdx_enc_status_changed()).
1377  *
1378  * Syscall entry code has a critical window where the kernel stack is not
1379  * yet set up. Any exception in this window leads to hard to debug issues
1380  * and can be exploited for privilege escalation. Exceptions in the NMI
1381  * entry code also cause issues. Returning from the exception handler with
1382  * IRET will re-enable NMIs and nested NMI will corrupt the NMI stack.
1383  *
1384  * For these reasons, the kernel avoids #VEs during the syscall gap and
1385  * the NMI entry code. Entry code paths do not access TD-shared memory,
1386  * MMIO regions, use #VE triggering MSRs, instructions, or CPUID leaves
1387  * that might generate #VE. VMM can remove memory from TD at any point,
1388  * but access to unaccepted (or missing) private memory leads to VM
1389  * termination, not to #VE.
1390  *
1391  * Similarly to page faults and breakpoints, #VEs are allowed in NMI
1392  * handlers once the kernel is ready to deal with nested NMIs.
1393  *
1394  * During #VE delivery, all interrupts, including NMIs, are blocked until
1395  * TDGETVEINFO is called. It prevents #VE nesting until the kernel reads
1396  * the VE info.
1397  *
1398  * If a guest kernel action which would normally cause a #VE occurs in
1399  * the interrupt-disabled region before TDGETVEINFO, a #DF (fault
1400  * exception) is delivered to the guest which will result in an oops.
1401  *
1402  * The entry code has been audited carefully for following these expectations.
1403  * Changes in the entry code have to be audited for correctness vs. this
1404  * aspect. Similarly to #PF, #VE in these places will expose kernel to
1405  * privilege escalation or may lead to random crashes.
1406  */
1407 DEFINE_IDTENTRY(exc_virtualization_exception)
1408 {
1409     struct ve_info ve;
1410 
1411     /*
1412      * NMIs/Machine-checks/Interrupts will be in a disabled state
1413      * till TDGETVEINFO TDCALL is executed. This ensures that VE
1414      * info cannot be overwritten by a nested #VE.
1415      */
1416     tdx_get_ve_info(&ve);
1417 
1418     cond_local_irq_enable(regs);
1419 
1420     /*
1421      * If tdx_handle_virt_exception() could not process
1422      * it successfully, treat it as #GP(0) and handle it.
1423      */
1424     if (!tdx_handle_virt_exception(regs, &ve))
1425         ve_raise_fault(regs, 0);
1426 
1427     cond_local_irq_disable(regs);
1428 }
1429 
1430 #endif
1431 
1432 #ifdef CONFIG_X86_32
1433 DEFINE_IDTENTRY_SW(iret_error)
1434 {
1435     local_irq_enable();
1436     if (notify_die(DIE_TRAP, "iret exception", regs, 0,
1437             X86_TRAP_IRET, SIGILL) != NOTIFY_STOP) {
1438         do_trap(X86_TRAP_IRET, SIGILL, "iret exception", regs, 0,
1439             ILL_BADSTK, (void __user *)NULL);
1440     }
1441     local_irq_disable();
1442 }
1443 #endif
1444 
1445 void __init trap_init(void)
1446 {
1447     /* Init cpu_entry_area before IST entries are set up */
1448     setup_cpu_entry_areas();
1449 
1450     /* Init GHCB memory pages when running as an SEV-ES guest */
1451     sev_es_init_vc_handling();
1452 
1453     /* Initialize TSS before setting up traps so ISTs work */
1454     cpu_init_exception_handling();
1455     /* Setup traps as cpu_init() might #GP */
1456     idt_setup_traps();
1457     cpu_init();
1458 }