1 /* SPDX-License-Identifier: GPL-2.0 */
3 * linux/arch/x86_64/entry.S
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 * Copyright (C) 2000, 2001, 2002 Andi Kleen SuSE Labs
7 * Copyright (C) 2000 Pavel Machek <pavel@suse.cz>
9 * entry.S contains the system-call and fault low-level handling routines.
11 * Some of this is documented in Documentation/x86/entry_64.rst
13 * A note on terminology:
14 * - iret frame: Architecture defined interrupt frame from SS to RIP
15 * at the top of the kernel process stack.
18 * - SYM_FUNC_START/END:Define functions in the symbol table.
19 * - idtentry: Define exception entry points.
21 #include <linux/linkage.h>
22 #include <asm/segment.h>
23 #include <asm/cache.h>
24 #include <asm/errno.h>
25 #include <asm/asm-offsets.h>
27 #include <asm/unistd.h>
28 #include <asm/thread_info.h>
29 #include <asm/hw_irq.h>
30 #include <asm/page_types.h>
31 #include <asm/irqflags.h>
32 #include <asm/paravirt.h>
33 #include <asm/percpu.h>
36 #include <asm/pgtable_types.h>
37 #include <asm/export.h>
38 #include <asm/frame.h>
39 #include <asm/trapnr.h>
40 #include <asm/nospec-branch.h>
41 #include <asm/fsgsbase.h>
42 #include <linux/err.h>
47 .section .entry.text, "ax"
50 * 64-bit SYSCALL instruction entry. Up to 6 arguments in registers.
52 * This is the only entry point used for 64-bit system calls. The
53 * hardware interface is reasonably well designed and the register to
54 * argument mapping Linux uses fits well with the registers that are
55 * available when SYSCALL is used.
57 * SYSCALL instructions can be found inlined in libc implementations as
58 * well as some other programs and libraries. There are also a handful
59 * of SYSCALL instructions in the vDSO used, for example, as a
60 * clock_gettimeofday fallback.
62 * 64-bit SYSCALL saves rip to rcx, clears rflags.RF, then saves rflags to r11,
63 * then loads new ss, cs, and rip from previously programmed MSRs.
64 * rflags gets masked by a value from another MSR (so CLD and CLAC
65 * are not needed). SYSCALL does not save anything on the stack
66 * and does not change rsp.
69 * rax system call number
71 * r11 saved rflags (note: r11 is callee-clobbered register in C ABI)
75 * r10 arg3 (needs to be moved to rcx to conform to C ABI)
78 * (note: r12-r15, rbp, rbx are callee-preserved in C ABI)
80 * Only called from user space.
82 * When user can change pt_regs->foo always force IRET. That is because
83 * it deals with uncanonical addresses better. SYSRET has trouble
84 * with them due to bugs in both AMD and Intel CPUs.
87 SYM_CODE_START(entry_SYSCALL_64)
92 /* tss.sp2 is scratch space. */
93 movq %rsp, PER_CPU_VAR(cpu_tss_rw + TSS_sp2)
94 SWITCH_TO_KERNEL_CR3 scratch_reg=%rsp
95 movq PER_CPU_VAR(cpu_current_top_of_stack), %rsp
97 SYM_INNER_LABEL(entry_SYSCALL_64_safe_stack, SYM_L_GLOBAL)
100 /* Construct struct pt_regs on stack */
101 pushq $__USER_DS /* pt_regs->ss */
102 pushq PER_CPU_VAR(cpu_tss_rw + TSS_sp2) /* pt_regs->sp */
103 pushq %r11 /* pt_regs->flags */
104 pushq $__USER_CS /* pt_regs->cs */
105 pushq %rcx /* pt_regs->ip */
106 SYM_INNER_LABEL(entry_SYSCALL_64_after_hwframe, SYM_L_GLOBAL)
107 pushq %rax /* pt_regs->orig_ax */
109 PUSH_AND_CLEAR_REGS rax=$-ENOSYS
113 /* Sign extend the lower 32bit as syscall numbers are treated as int */
115 call do_syscall_64 /* returns with IRQs disabled */
118 * Try to use SYSRET instead of IRET if we're returning to
119 * a completely clean 64-bit userspace context. If we're not,
120 * go to the slow exit path.
121 * In the Xen PV case we must use iret anyway.
124 ALTERNATIVE "", "jmp swapgs_restore_regs_and_return_to_usermode", \
130 cmpq %rcx, %r11 /* SYSRET requires RCX == RIP */
131 jne swapgs_restore_regs_and_return_to_usermode
134 * On Intel CPUs, SYSRET with non-canonical RCX/RIP will #GP
135 * in kernel space. This essentially lets the user take over
136 * the kernel, since userspace controls RSP.
138 * If width of "canonical tail" ever becomes variable, this will need
139 * to be updated to remain correct on both old and new CPUs.
141 * Change top bits to match most significant bit (47th or 56th bit
142 * depending on paging mode) in the address.
144 #ifdef CONFIG_X86_5LEVEL
145 ALTERNATIVE "shl $(64 - 48), %rcx; sar $(64 - 48), %rcx", \
146 "shl $(64 - 57), %rcx; sar $(64 - 57), %rcx", X86_FEATURE_LA57
148 shl $(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
149 sar $(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
152 /* If this changed %rcx, it was not canonical */
154 jne swapgs_restore_regs_and_return_to_usermode
156 cmpq $__USER_CS, CS(%rsp) /* CS must match SYSRET */
157 jne swapgs_restore_regs_and_return_to_usermode
160 cmpq %r11, EFLAGS(%rsp) /* R11 == RFLAGS */
161 jne swapgs_restore_regs_and_return_to_usermode
164 * SYSCALL clears RF when it saves RFLAGS in R11 and SYSRET cannot
165 * restore RF properly. If the slowpath sets it for whatever reason, we
166 * need to restore it correctly.
168 * SYSRET can restore TF, but unlike IRET, restoring TF results in a
169 * trap from userspace immediately after SYSRET. This would cause an
170 * infinite loop whenever #DB happens with register state that satisfies
171 * the opportunistic SYSRET conditions. For example, single-stepping
174 * movq $stuck_here, %rcx
179 * would never get past 'stuck_here'.
181 testq $(X86_EFLAGS_RF|X86_EFLAGS_TF), %r11
182 jnz swapgs_restore_regs_and_return_to_usermode
184 /* nothing to check for RSP */
186 cmpq $__USER_DS, SS(%rsp) /* SS must match SYSRET */
187 jne swapgs_restore_regs_and_return_to_usermode
190 * We win! This label is here just for ease of understanding
191 * perf profiles. Nothing jumps here.
193 syscall_return_via_sysret:
197 * Now all regs are restored except RSP and RDI.
198 * Save old stack pointer and switch to trampoline stack.
201 movq PER_CPU_VAR(cpu_tss_rw + TSS_sp0), %rsp
204 pushq RSP-RDI(%rdi) /* RSP */
205 pushq (%rdi) /* RDI */
208 * We are on the trampoline stack. All regs except RDI are live.
209 * We can do future final exit work right here.
211 STACKLEAK_ERASE_NOCLOBBER
213 SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
217 SYM_INNER_LABEL(entry_SYSRETQ_unsafe_stack, SYM_L_GLOBAL)
221 SYM_INNER_LABEL(entry_SYSRETQ_end, SYM_L_GLOBAL)
224 SYM_CODE_END(entry_SYSCALL_64)
230 .pushsection .text, "ax"
231 SYM_FUNC_START(__switch_to_asm)
233 * Save callee-saved registers
234 * This must match the order in inactive_task_frame
244 movq %rsp, TASK_threadsp(%rdi)
245 movq TASK_threadsp(%rsi), %rsp
247 #ifdef CONFIG_STACKPROTECTOR
248 movq TASK_stack_canary(%rsi), %rbx
249 movq %rbx, PER_CPU_VAR(fixed_percpu_data) + stack_canary_offset
252 #ifdef CONFIG_RETPOLINE
254 * When switching from a shallower to a deeper call stack
255 * the RSB may either underflow or use entries populated
256 * with userspace addresses. On CPUs where those concerns
257 * exist, overwrite the RSB with entries which capture
258 * speculative execution to prevent attack.
260 FILL_RETURN_BUFFER %r12, RSB_CLEAR_LOOPS, X86_FEATURE_RSB_CTXSW
263 /* restore callee-saved registers */
272 SYM_FUNC_END(__switch_to_asm)
276 * A newly forked process directly context switches into this address.
278 * rax: prev task we switched from
279 * rbx: kernel thread func (NULL for user thread)
280 * r12: kernel thread arg
282 .pushsection .text, "ax"
283 SYM_CODE_START(ret_from_fork)
285 ANNOTATE_NOENDBR // copy_thread
287 call schedule_tail /* rdi: 'prev' task parameter */
289 testq %rbx, %rbx /* from kernel_thread? */
290 jnz 1f /* kernel threads are uncommon */
295 call syscall_exit_to_user_mode /* returns with IRQs disabled */
296 jmp swapgs_restore_regs_and_return_to_usermode
304 * A kernel thread is allowed to return here after successfully
305 * calling kernel_execve(). Exit to userspace to complete the execve()
310 SYM_CODE_END(ret_from_fork)
313 .macro DEBUG_ENTRY_ASSERT_IRQS_OFF
314 #ifdef CONFIG_DEBUG_ENTRY
317 testl $X86_EFLAGS_IF, %eax
325 /* Save all registers in pt_regs */
326 SYM_CODE_START_LOCAL(push_and_clear_regs)
328 PUSH_AND_CLEAR_REGS save_ret=1
329 ENCODE_FRAME_POINTER 8
331 SYM_CODE_END(push_and_clear_regs)
334 * idtentry_body - Macro to emit code calling the C function
335 * @cfunc: C function to be called
336 * @has_error_code: Hardware pushed error code on stack
338 .macro idtentry_body cfunc has_error_code:req
340 call push_and_clear_regs
344 * Call error_entry() and switch to the task stack if from userspace.
346 * When in XENPV, it is already in the task stack, and it can't fault
347 * for native_iret() nor native_load_gs_index() since XENPV uses its
348 * own pvops for IRET and load_gs_index(). And it doesn't need to
349 * switch the CR3. So it can skip invoking error_entry().
351 ALTERNATIVE "call error_entry; movq %rax, %rsp", \
352 "", X86_FEATURE_XENPV
357 movq %rsp, %rdi /* pt_regs pointer into 1st argument*/
359 .if \has_error_code == 1
360 movq ORIG_RAX(%rsp), %rsi /* get error code into 2nd argument*/
361 movq $-1, ORIG_RAX(%rsp) /* no syscall to restart */
366 /* For some configurations \cfunc ends up being a noreturn. */
373 * idtentry - Macro to generate entry stubs for simple IDT entries
374 * @vector: Vector number
375 * @asmsym: ASM symbol for the entry point
376 * @cfunc: C function to be called
377 * @has_error_code: Hardware pushed error code on stack
379 * The macro emits code to set up the kernel context for straight forward
380 * and simple IDT entries. No IST stack, no paranoid entry checks.
382 .macro idtentry vector asmsym cfunc has_error_code:req
383 SYM_CODE_START(\asmsym)
384 UNWIND_HINT_IRET_REGS offset=\has_error_code*8
389 .if \has_error_code == 0
390 pushq $-1 /* ORIG_RAX: no syscall to restart */
393 .if \vector == X86_TRAP_BP
395 * If coming from kernel space, create a 6-word gap to allow the
396 * int3 handler to emulate a call instruction.
398 testb $3, CS-ORIG_RAX(%rsp)
399 jnz .Lfrom_usermode_no_gap_\@
403 UNWIND_HINT_IRET_REGS offset=8
404 .Lfrom_usermode_no_gap_\@:
407 idtentry_body \cfunc \has_error_code
409 _ASM_NOKPROBE(\asmsym)
410 SYM_CODE_END(\asmsym)
414 * Interrupt entry/exit.
416 + The interrupt stubs push (vector) onto the stack, which is the error_code
417 * position of idtentry exceptions, and jump to one of the two idtentry points
420 * common_interrupt is a hotpath, align it to a cache line
422 .macro idtentry_irq vector cfunc
423 .p2align CONFIG_X86_L1_CACHE_SHIFT
424 idtentry \vector asm_\cfunc \cfunc has_error_code=1
428 * System vectors which invoke their handlers directly and are not
429 * going through the regular common device interrupt handling code.
431 .macro idtentry_sysvec vector cfunc
432 idtentry \vector asm_\cfunc \cfunc has_error_code=0
436 * idtentry_mce_db - Macro to generate entry stubs for #MC and #DB
437 * @vector: Vector number
438 * @asmsym: ASM symbol for the entry point
439 * @cfunc: C function to be called
441 * The macro emits code to set up the kernel context for #MC and #DB
443 * If the entry comes from user space it uses the normal entry path
444 * including the return to user space work and preemption checks on
447 * If hits in kernel mode then it needs to go through the paranoid
448 * entry as the exception can hit any random state. No preemption
449 * check on exit to keep the paranoid path simple.
451 .macro idtentry_mce_db vector asmsym cfunc
452 SYM_CODE_START(\asmsym)
453 UNWIND_HINT_IRET_REGS
458 pushq $-1 /* ORIG_RAX: no syscall to restart */
461 * If the entry is from userspace, switch stacks and treat it as
464 testb $3, CS-ORIG_RAX(%rsp)
465 jnz .Lfrom_usermode_switch_stack_\@
467 /* paranoid_entry returns GS information for paranoid_exit in EBX. */
472 movq %rsp, %rdi /* pt_regs pointer */
478 /* Switch to the regular task stack and use the noist entry point */
479 .Lfrom_usermode_switch_stack_\@:
480 idtentry_body noist_\cfunc, has_error_code=0
482 _ASM_NOKPROBE(\asmsym)
483 SYM_CODE_END(\asmsym)
486 #ifdef CONFIG_AMD_MEM_ENCRYPT
488 * idtentry_vc - Macro to generate entry stub for #VC
489 * @vector: Vector number
490 * @asmsym: ASM symbol for the entry point
491 * @cfunc: C function to be called
493 * The macro emits code to set up the kernel context for #VC. The #VC handler
494 * runs on an IST stack and needs to be able to cause nested #VC exceptions.
496 * To make this work the #VC entry code tries its best to pretend it doesn't use
497 * an IST stack by switching to the task stack if coming from user-space (which
498 * includes early SYSCALL entry path) or back to the stack in the IRET frame if
499 * entered from kernel-mode.
501 * If entered from kernel-mode the return stack is validated first, and if it is
502 * not safe to use (e.g. because it points to the entry stack) the #VC handler
503 * will switch to a fall-back stack (VC2) and call a special handler function.
505 * The macro is only used for one vector, but it is planned to be extended in
506 * the future for the #HV exception.
508 .macro idtentry_vc vector asmsym cfunc
509 SYM_CODE_START(\asmsym)
510 UNWIND_HINT_IRET_REGS
516 * If the entry is from userspace, switch stacks and treat it as
519 testb $3, CS-ORIG_RAX(%rsp)
520 jnz .Lfrom_usermode_switch_stack_\@
523 * paranoid_entry returns SWAPGS flag for paranoid_exit in EBX.
524 * EBX == 0 -> SWAPGS, EBX == 1 -> no SWAPGS
531 * Switch off the IST stack to make it free for nested exceptions. The
532 * vc_switch_off_ist() function will switch back to the interrupted
533 * stack if it is safe to do so. If not it switches to the VC fall-back
536 movq %rsp, %rdi /* pt_regs pointer */
537 call vc_switch_off_ist
538 movq %rax, %rsp /* Switch to new stack */
544 movq ORIG_RAX(%rsp), %rsi /* get error code into 2nd argument*/
545 movq $-1, ORIG_RAX(%rsp) /* no syscall to restart */
547 movq %rsp, %rdi /* pt_regs pointer */
552 * No need to switch back to the IST stack. The current stack is either
553 * identical to the stack in the IRET frame or the VC fall-back stack,
554 * so it is definitely mapped even with PTI enabled.
558 /* Switch to the regular task stack */
559 .Lfrom_usermode_switch_stack_\@:
560 idtentry_body user_\cfunc, has_error_code=1
562 _ASM_NOKPROBE(\asmsym)
563 SYM_CODE_END(\asmsym)
568 * Double fault entry. Straight paranoid. No checks from which context
569 * this comes because for the espfix induced #DF this would do the wrong
572 .macro idtentry_df vector asmsym cfunc
573 SYM_CODE_START(\asmsym)
574 UNWIND_HINT_IRET_REGS offset=8
579 /* paranoid_entry returns GS information for paranoid_exit in EBX. */
583 movq %rsp, %rdi /* pt_regs pointer into first argument */
584 movq ORIG_RAX(%rsp), %rsi /* get error code into 2nd argument*/
585 movq $-1, ORIG_RAX(%rsp) /* no syscall to restart */
588 /* For some configurations \cfunc ends up being a noreturn. */
593 _ASM_NOKPROBE(\asmsym)
594 SYM_CODE_END(\asmsym)
598 * Include the defines which emit the idt entries which are shared
599 * shared between 32 and 64 bit and emit the __irqentry_text_* markers
600 * so the stacktrace boundary checks work.
603 .globl __irqentry_text_start
604 __irqentry_text_start:
606 #include <asm/idtentry.h>
609 .globl __irqentry_text_end
613 SYM_CODE_START_LOCAL(common_interrupt_return)
614 SYM_INNER_LABEL(swapgs_restore_regs_and_return_to_usermode, SYM_L_GLOBAL)
615 #ifdef CONFIG_DEBUG_ENTRY
616 /* Assert that pt_regs indicates user mode. */
623 ALTERNATIVE "", "jmp xenpv_restore_regs_and_return_to_usermode", X86_FEATURE_XENPV
629 * The stack is now user RDI, orig_ax, RIP, CS, EFLAGS, RSP, SS.
630 * Save old stack pointer and switch to trampoline stack.
633 movq PER_CPU_VAR(cpu_tss_rw + TSS_sp0), %rsp
636 /* Copy the IRET frame to the trampoline stack. */
637 pushq 6*8(%rdi) /* SS */
638 pushq 5*8(%rdi) /* RSP */
639 pushq 4*8(%rdi) /* EFLAGS */
640 pushq 3*8(%rdi) /* CS */
641 pushq 2*8(%rdi) /* RIP */
643 /* Push user RDI on the trampoline stack. */
647 * We are on the trampoline stack. All regs except RDI are live.
648 * We can do future final exit work right here.
650 STACKLEAK_ERASE_NOCLOBBER
652 SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
660 SYM_INNER_LABEL(restore_regs_and_return_to_kernel, SYM_L_GLOBAL)
661 #ifdef CONFIG_DEBUG_ENTRY
662 /* Assert that pt_regs indicates kernel mode. */
669 addq $8, %rsp /* skip regs->orig_ax */
671 * ARCH_HAS_MEMBARRIER_SYNC_CORE rely on IRET core serialization
672 * when returning from IPI handler.
675 SYM_INNER_LABEL(early_xen_iret_patch, SYM_L_GLOBAL)
678 .long .Lnative_iret - (. + 4)
682 UNWIND_HINT_IRET_REGS
684 * Are we returning to a stack segment from the LDT? Note: in
685 * 64-bit mode SS:RSP on the exception stack is always valid.
687 #ifdef CONFIG_X86_ESPFIX64
688 testb $4, (SS-RIP)(%rsp)
689 jnz native_irq_return_ldt
692 SYM_INNER_LABEL(native_irq_return_iret, SYM_L_GLOBAL)
693 ANNOTATE_NOENDBR // exc_double_fault
695 * This may fault. Non-paranoid faults on return to userspace are
696 * handled by fixup_bad_iret. These include #SS, #GP, and #NP.
697 * Double-faults due to espfix64 are handled in exc_double_fault.
698 * Other faults here are fatal.
702 #ifdef CONFIG_X86_ESPFIX64
703 native_irq_return_ldt:
705 * We are running with user GSBASE. All GPRs contain their user
706 * values. We have a percpu ESPFIX stack that is eight slots
707 * long (see ESPFIX_STACK_SIZE). espfix_waddr points to the bottom
708 * of the ESPFIX stack.
710 * We clobber RAX and RDI in this code. We stash RDI on the
711 * normal stack and RAX on the ESPFIX stack.
713 * The ESPFIX stack layout we set up looks like this:
715 * --- top of ESPFIX stack ---
720 * RIP <-- RSP points here when we're done
721 * RAX <-- espfix_waddr points here
722 * --- bottom of ESPFIX stack ---
725 pushq %rdi /* Stash user RDI */
726 swapgs /* to kernel GS */
727 SWITCH_TO_KERNEL_CR3 scratch_reg=%rdi /* to kernel CR3 */
729 movq PER_CPU_VAR(espfix_waddr), %rdi
730 movq %rax, (0*8)(%rdi) /* user RAX */
731 movq (1*8)(%rsp), %rax /* user RIP */
732 movq %rax, (1*8)(%rdi)
733 movq (2*8)(%rsp), %rax /* user CS */
734 movq %rax, (2*8)(%rdi)
735 movq (3*8)(%rsp), %rax /* user RFLAGS */
736 movq %rax, (3*8)(%rdi)
737 movq (5*8)(%rsp), %rax /* user SS */
738 movq %rax, (5*8)(%rdi)
739 movq (4*8)(%rsp), %rax /* user RSP */
740 movq %rax, (4*8)(%rdi)
741 /* Now RAX == RSP. */
743 andl $0xffff0000, %eax /* RAX = (RSP & 0xffff0000) */
746 * espfix_stack[31:16] == 0. The page tables are set up such that
747 * (espfix_stack | (X & 0xffff0000)) points to a read-only alias of
748 * espfix_waddr for any X. That is, there are 65536 RO aliases of
749 * the same page. Set up RSP so that RSP[31:16] contains the
750 * respective 16 bits of the /userspace/ RSP and RSP nonetheless
751 * still points to an RO alias of the ESPFIX stack.
753 orq PER_CPU_VAR(espfix_stack), %rax
755 SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
756 swapgs /* to user GS */
757 popq %rdi /* Restore user RDI */
760 UNWIND_HINT_IRET_REGS offset=8
763 * At this point, we cannot write to the stack any more, but we can
766 popq %rax /* Restore user RAX */
769 * RSP now points to an ordinary IRET frame, except that the page
770 * is read-only and RSP[31:16] are preloaded with the userspace
771 * values. We can now IRET back to userspace.
773 jmp native_irq_return_iret
775 SYM_CODE_END(common_interrupt_return)
776 _ASM_NOKPROBE(common_interrupt_return)
779 * Reload gs selector with exception handling
782 * Is in entry.text as it shouldn't be instrumented.
784 SYM_FUNC_START(asm_load_gs_index)
788 ANNOTATE_NOENDBR // error_entry
790 2: ALTERNATIVE "", "mfence", X86_BUG_SWAPGS_FENCE
795 /* running with kernelgs */
797 swapgs /* switch back to user gs */
799 /* This can't be a string because the preprocessor needs to see it. */
800 movl $__USER_DS, %eax
803 ALTERNATIVE "", "ZAP_GS", X86_BUG_NULL_SEG
808 _ASM_EXTABLE(.Lgs_change, .Lbad_gs)
810 SYM_FUNC_END(asm_load_gs_index)
811 EXPORT_SYMBOL(asm_load_gs_index)
815 * A note on the "critical region" in our callback handler.
816 * We want to avoid stacking callback handlers due to events occurring
817 * during handling of the last event. To do this, we keep events disabled
818 * until we've done all processing. HOWEVER, we must enable events before
819 * popping the stack frame (can't be done atomically) and so it would still
820 * be possible to get enough handler activations to overflow the stack.
821 * Although unlikely, bugs of that kind are hard to track down, so we'd
822 * like to avoid the possibility.
823 * So, on entry to the handler we detect whether we interrupted an
824 * existing activation in its critical region -- if so, we pop the current
825 * activation and restart the handler using the previous one.
827 * C calling convention: exc_xen_hypervisor_callback(struct *pt_regs)
829 SYM_CODE_START_LOCAL(exc_xen_hypervisor_callback)
832 * Since we don't modify %rdi, evtchn_do_upall(struct *pt_regs) will
833 * see the correct pointer to the pt_regs
836 movq %rdi, %rsp /* we don't return, adjust the stack frame */
839 call xen_pv_evtchn_do_upcall
842 SYM_CODE_END(exc_xen_hypervisor_callback)
845 * Hypervisor uses this for application faults while it executes.
846 * We get here for two reasons:
847 * 1. Fault while reloading DS, ES, FS or GS
848 * 2. Fault while executing IRET
849 * Category 1 we do not need to fix up as Xen has already reloaded all segment
850 * registers that could be reloaded and zeroed the others.
851 * Category 2 we fix up by killing the current process. We cannot use the
852 * normal Linux return path in this case because if we use the IRET hypercall
853 * to pop the stack frame we end up in an infinite loop of failsafe callbacks.
854 * We distinguish between categories by comparing each saved segment register
855 * with its current contents: any discrepancy means we in category 1.
857 SYM_CODE_START(xen_failsafe_callback)
872 /* All segments match their saved values => Category 2 (Bad IRET). */
877 UNWIND_HINT_IRET_REGS offset=8
878 jmp asm_exc_general_protection
879 1: /* Segment mismatch => Category 1 (Bad segment). Retry the IRET. */
883 UNWIND_HINT_IRET_REGS
884 pushq $-1 /* orig_ax = -1 => not a system call */
888 SYM_CODE_END(xen_failsafe_callback)
889 #endif /* CONFIG_XEN_PV */
892 * Save all registers in pt_regs. Return GSBASE related information
893 * in EBX depending on the availability of the FSGSBASE instructions:
896 * N 0 -> SWAPGS on exit
897 * 1 -> no SWAPGS on exit
899 * Y GSBASE value at entry, must be restored in paranoid_exit
901 SYM_CODE_START_LOCAL(paranoid_entry)
903 PUSH_AND_CLEAR_REGS save_ret=1
904 ENCODE_FRAME_POINTER 8
907 * Always stash CR3 in %r14. This value will be restored,
908 * verbatim, at exit. Needed if paranoid_entry interrupted
909 * another entry that already switched to the user CR3 value
910 * but has not yet returned to userspace.
912 * This is also why CS (stashed in the "iret frame" by the
913 * hardware at entry) can not be used: this may be a return
914 * to kernel code, but with a user CR3 value.
916 * Switching CR3 does not depend on kernel GSBASE so it can
917 * be done before switching to the kernel GSBASE. This is
918 * required for FSGSBASE because the kernel GSBASE has to
919 * be retrieved from a kernel internal table.
921 SAVE_AND_SWITCH_TO_KERNEL_CR3 scratch_reg=%rax save_reg=%r14
924 * Handling GSBASE depends on the availability of FSGSBASE.
926 * Without FSGSBASE the kernel enforces that negative GSBASE
927 * values indicate kernel GSBASE. With FSGSBASE no assumptions
928 * can be made about the GSBASE value when entering from user
931 ALTERNATIVE "jmp .Lparanoid_entry_checkgs", "", X86_FEATURE_FSGSBASE
934 * Read the current GSBASE and store it in %rbx unconditionally,
935 * retrieve and set the current CPUs kernel GSBASE. The stored value
936 * has to be restored in paranoid_exit unconditionally.
938 * The unconditional write to GS base below ensures that no subsequent
939 * loads based on a mispredicted GS base can happen, therefore no LFENCE
942 SAVE_AND_SET_GSBASE scratch_reg=%rax save_reg=%rbx
945 .Lparanoid_entry_checkgs:
946 /* EBX = 1 -> kernel GSBASE active, no restore required */
950 * The kernel-enforced convention is a negative GSBASE indicates
951 * a kernel value. No SWAPGS needed on entry and exit.
953 movl $MSR_GS_BASE, %ecx
956 js .Lparanoid_kernel_gsbase
958 /* EBX = 0 -> SWAPGS required on exit */
961 .Lparanoid_kernel_gsbase:
963 FENCE_SWAPGS_KERNEL_ENTRY
965 SYM_CODE_END(paranoid_entry)
968 * "Paranoid" exit path from exception stack. This is invoked
969 * only on return from non-NMI IST interrupts that came
972 * We may be returning to very strange contexts (e.g. very early
973 * in syscall entry), so checking for preemption here would
974 * be complicated. Fortunately, there's no good reason to try
975 * to handle preemption here.
977 * R/EBX contains the GSBASE related information depending on the
978 * availability of the FSGSBASE instructions:
981 * N 0 -> SWAPGS on exit
982 * 1 -> no SWAPGS on exit
984 * Y User space GSBASE, must be restored unconditionally
986 SYM_CODE_START_LOCAL(paranoid_exit)
989 * The order of operations is important. RESTORE_CR3 requires
992 * NB to anyone to try to optimize this code: this code does
993 * not execute at all for exceptions from user mode. Those
994 * exceptions go through error_exit instead.
996 RESTORE_CR3 scratch_reg=%rax save_reg=%r14
998 /* Handle the three GSBASE cases */
999 ALTERNATIVE "jmp .Lparanoid_exit_checkgs", "", X86_FEATURE_FSGSBASE
1001 /* With FSGSBASE enabled, unconditionally restore GSBASE */
1003 jmp restore_regs_and_return_to_kernel
1005 .Lparanoid_exit_checkgs:
1006 /* On non-FSGSBASE systems, conditionally do SWAPGS */
1008 jnz restore_regs_and_return_to_kernel
1010 /* We are returning to a context with user GSBASE */
1012 jmp restore_regs_and_return_to_kernel
1013 SYM_CODE_END(paranoid_exit)
1016 * Switch GS and CR3 if needed.
1018 SYM_CODE_START_LOCAL(error_entry)
1020 testb $3, CS+8(%rsp)
1021 jz .Lerror_kernelspace
1024 * We entered from user mode or we're pretending to have entered
1025 * from user mode due to an IRET fault.
1028 FENCE_SWAPGS_USER_ENTRY
1029 /* We have user CR3. Change to kernel CR3. */
1030 SWITCH_TO_KERNEL_CR3 scratch_reg=%rax
1032 leaq 8(%rsp), %rdi /* arg0 = pt_regs pointer */
1033 .Lerror_entry_from_usermode_after_swapgs:
1034 /* Put us onto the real thread stack. */
1039 * There are two places in the kernel that can potentially fault with
1040 * usergs. Handle them here. B stepping K8s sometimes report a
1041 * truncated RIP for IRET exceptions returning to compat mode. Check
1042 * for these here too.
1044 .Lerror_kernelspace:
1045 leaq native_irq_return_iret(%rip), %rcx
1046 cmpq %rcx, RIP+8(%rsp)
1048 movl %ecx, %eax /* zero extend */
1049 cmpq %rax, RIP+8(%rsp)
1051 cmpq $.Lgs_change, RIP+8(%rsp)
1052 jne .Lerror_entry_done_lfence
1055 * hack: .Lgs_change can fail with user gsbase. If this happens, fix up
1056 * gsbase and proceed. We'll fix up the exception and land in
1057 * .Lgs_change's error handler with kernel gsbase.
1062 * Issue an LFENCE to prevent GS speculation, regardless of whether it is a
1063 * kernel or user gsbase.
1065 .Lerror_entry_done_lfence:
1066 FENCE_SWAPGS_KERNEL_ENTRY
1067 leaq 8(%rsp), %rax /* return pt_regs pointer */
1071 /* Fix truncated RIP */
1072 movq %rcx, RIP+8(%rsp)
1077 * We came from an IRET to user mode, so we have user
1078 * gsbase and CR3. Switch to kernel gsbase and CR3:
1081 FENCE_SWAPGS_USER_ENTRY
1082 SWITCH_TO_KERNEL_CR3 scratch_reg=%rax
1085 * Pretend that the exception came from user mode: set up pt_regs
1086 * as if we faulted immediately after IRET.
1088 leaq 8(%rsp), %rdi /* arg0 = pt_regs pointer */
1091 jmp .Lerror_entry_from_usermode_after_swapgs
1092 SYM_CODE_END(error_entry)
1094 SYM_CODE_START_LOCAL(error_return)
1096 DEBUG_ENTRY_ASSERT_IRQS_OFF
1098 jz restore_regs_and_return_to_kernel
1099 jmp swapgs_restore_regs_and_return_to_usermode
1100 SYM_CODE_END(error_return)
1103 * Runs on exception stack. Xen PV does not go through this path at all,
1104 * so we can use real assembly here.
1107 * %r14: Used to save/restore the CR3 of the interrupted context
1108 * when PAGE_TABLE_ISOLATION is in use. Do not clobber.
1110 SYM_CODE_START(asm_exc_nmi)
1111 UNWIND_HINT_IRET_REGS
1115 * We allow breakpoints in NMIs. If a breakpoint occurs, then
1116 * the iretq it performs will take us out of NMI context.
1117 * This means that we can have nested NMIs where the next
1118 * NMI is using the top of the stack of the previous NMI. We
1119 * can't let it execute because the nested NMI will corrupt the
1120 * stack of the previous NMI. NMI handlers are not re-entrant
1123 * To handle this case we do the following:
1124 * Check the a special location on the stack that contains
1125 * a variable that is set when NMIs are executing.
1126 * The interrupted task's stack is also checked to see if it
1128 * If the variable is not set and the stack is not the NMI
1130 * o Set the special variable on the stack
1131 * o Copy the interrupt frame into an "outermost" location on the
1133 * o Copy the interrupt frame into an "iret" location on the stack
1134 * o Continue processing the NMI
1135 * If the variable is set or the previous stack is the NMI stack:
1136 * o Modify the "iret" location to jump to the repeat_nmi
1137 * o return back to the first NMI
1139 * Now on exit of the first NMI, we first clear the stack variable
1140 * The NMI stack will tell any nested NMIs at that point that it is
1141 * nested. Then we pop the stack normally with iret, and if there was
1142 * a nested NMI that updated the copy interrupt stack frame, a
1143 * jump will be made to the repeat_nmi code that will handle the second
1146 * However, espfix prevents us from directly returning to userspace
1147 * with a single IRET instruction. Similarly, IRET to user mode
1148 * can fault. We therefore handle NMIs from user space like
1149 * other IST entries.
1155 /* Use %rdx as our temp variable throughout */
1158 testb $3, CS-RIP+8(%rsp)
1159 jz .Lnmi_from_kernel
1162 * NMI from user mode. We need to run on the thread stack, but we
1163 * can't go through the normal entry paths: NMIs are masked, and
1164 * we don't want to enable interrupts, because then we'll end
1165 * up in an awkward situation in which IRQs are on but NMIs
1168 * We also must not push anything to the stack before switching
1169 * stacks lest we corrupt the "NMI executing" variable.
1173 FENCE_SWAPGS_USER_ENTRY
1174 SWITCH_TO_KERNEL_CR3 scratch_reg=%rdx
1176 movq PER_CPU_VAR(cpu_current_top_of_stack), %rsp
1177 UNWIND_HINT_IRET_REGS base=%rdx offset=8
1178 pushq 5*8(%rdx) /* pt_regs->ss */
1179 pushq 4*8(%rdx) /* pt_regs->rsp */
1180 pushq 3*8(%rdx) /* pt_regs->flags */
1181 pushq 2*8(%rdx) /* pt_regs->cs */
1182 pushq 1*8(%rdx) /* pt_regs->rip */
1183 UNWIND_HINT_IRET_REGS
1184 pushq $-1 /* pt_regs->orig_ax */
1185 PUSH_AND_CLEAR_REGS rdx=(%rdx)
1186 ENCODE_FRAME_POINTER
1189 * At this point we no longer need to worry about stack damage
1190 * due to nesting -- we're on the normal thread stack and we're
1191 * done with the NMI stack.
1199 * Return back to user mode. We must *not* do the normal exit
1200 * work, because we don't want to enable interrupts.
1202 jmp swapgs_restore_regs_and_return_to_usermode
1206 * Here's what our stack frame will look like:
1207 * +---------------------------------------------------------+
1209 * | original Return RSP |
1210 * | original RFLAGS |
1213 * +---------------------------------------------------------+
1214 * | temp storage for rdx |
1215 * +---------------------------------------------------------+
1216 * | "NMI executing" variable |
1217 * +---------------------------------------------------------+
1218 * | iret SS } Copied from "outermost" frame |
1219 * | iret Return RSP } on each loop iteration; overwritten |
1220 * | iret RFLAGS } by a nested NMI to force another |
1221 * | iret CS } iteration if needed. |
1223 * +---------------------------------------------------------+
1224 * | outermost SS } initialized in first_nmi; |
1225 * | outermost Return RSP } will not be changed before |
1226 * | outermost RFLAGS } NMI processing is done. |
1227 * | outermost CS } Copied to "iret" frame on each |
1228 * | outermost RIP } iteration. |
1229 * +---------------------------------------------------------+
1231 * +---------------------------------------------------------+
1233 * The "original" frame is used by hardware. Before re-enabling
1234 * NMIs, we need to be done with it, and we need to leave enough
1235 * space for the asm code here.
1237 * We return by executing IRET while RSP points to the "iret" frame.
1238 * That will either return for real or it will loop back into NMI
1241 * The "outermost" frame is copied to the "iret" frame on each
1242 * iteration of the loop, so each iteration starts with the "iret"
1243 * frame pointing to the final return target.
1247 * Determine whether we're a nested NMI.
1249 * If we interrupted kernel code between repeat_nmi and
1250 * end_repeat_nmi, then we are a nested NMI. We must not
1251 * modify the "iret" frame because it's being written by
1252 * the outer NMI. That's okay; the outer NMI handler is
1253 * about to about to call exc_nmi() anyway, so we can just
1254 * resume the outer NMI.
1257 movq $repeat_nmi, %rdx
1260 movq $end_repeat_nmi, %rdx
1266 * Now check "NMI executing". If it's set, then we're nested.
1267 * This will not detect if we interrupted an outer NMI just
1274 * Now test if the previous stack was an NMI stack. This covers
1275 * the case where we interrupt an outer NMI after it clears
1276 * "NMI executing" but before IRET. We need to be careful, though:
1277 * there is one case in which RSP could point to the NMI stack
1278 * despite there being no NMI active: naughty userspace controls
1279 * RSP at the very beginning of the SYSCALL targets. We can
1280 * pull a fast one on naughty userspace, though: we program
1281 * SYSCALL to mask DF, so userspace cannot cause DF to be set
1282 * if it controls the kernel's RSP. We set DF before we clear
1286 /* Compare the NMI stack (rdx) with the stack we came from (4*8(%rsp)) */
1287 cmpq %rdx, 4*8(%rsp)
1288 /* If the stack pointer is above the NMI stack, this is a normal NMI */
1291 subq $EXCEPTION_STKSZ, %rdx
1292 cmpq %rdx, 4*8(%rsp)
1293 /* If it is below the NMI stack, it is a normal NMI */
1296 /* Ah, it is within the NMI stack. */
1298 testb $(X86_EFLAGS_DF >> 8), (3*8 + 1)(%rsp)
1299 jz first_nmi /* RSP was user controlled. */
1301 /* This is a nested NMI. */
1305 * Modify the "iret" frame to point to repeat_nmi, forcing another
1306 * iteration of NMI handling.
1309 leaq -10*8(%rsp), %rdx
1316 /* Put stack back */
1322 /* We are returning to kernel mode, so this cannot result in a fault. */
1329 /* Make room for "NMI executing". */
1332 /* Leave room for the "iret" frame */
1335 /* Copy the "original" frame to the "outermost" frame */
1339 UNWIND_HINT_IRET_REGS
1341 /* Everything up to here is safe from nested NMIs */
1343 #ifdef CONFIG_DEBUG_ENTRY
1345 * For ease of testing, unmask NMIs right away. Disabled by
1346 * default because IRET is very expensive.
1349 pushq %rsp /* RSP (minus 8 because of the previous push) */
1350 addq $8, (%rsp) /* Fix up RSP */
1352 pushq $__KERNEL_CS /* CS */
1354 iretq /* continues at repeat_nmi below */
1355 UNWIND_HINT_IRET_REGS
1360 ANNOTATE_NOENDBR // this code
1362 * If there was a nested NMI, the first NMI's iret will return
1363 * here. But NMIs are still enabled and we can take another
1364 * nested NMI. The nested NMI checks the interrupted RIP to see
1365 * if it is between repeat_nmi and end_repeat_nmi, and if so
1366 * it will just return, as we are about to repeat an NMI anyway.
1367 * This makes it safe to copy to the stack frame that a nested
1370 * RSP is pointing to "outermost RIP". gsbase is unknown, but, if
1371 * we're repeating an NMI, gsbase has the same value that it had on
1372 * the first iteration. paranoid_entry will load the kernel
1373 * gsbase if needed before we call exc_nmi(). "NMI executing"
1376 movq $1, 10*8(%rsp) /* Set "NMI executing". */
1379 * Copy the "outermost" frame to the "iret" frame. NMIs that nest
1380 * here must not modify the "iret" frame while we're writing to
1381 * it or it will end up containing garbage.
1389 ANNOTATE_NOENDBR // this code
1392 * Everything below this point can be preempted by a nested NMI.
1393 * If this happens, then the inner NMI will change the "iret"
1394 * frame to point back to repeat_nmi.
1396 pushq $-1 /* ORIG_RAX: no syscall to restart */
1399 * Use paranoid_entry to handle SWAPGS, but no need to use paranoid_exit
1400 * as we should not be calling schedule in NMI context.
1401 * Even with normal interrupts enabled. An NMI should not be
1402 * setting NEED_RESCHED or anything that normal interrupts and
1403 * exceptions might do.
1412 /* Always restore stashed CR3 value (see paranoid_entry) */
1413 RESTORE_CR3 scratch_reg=%r15 save_reg=%r14
1416 * The above invocation of paranoid_entry stored the GSBASE
1417 * related information in R/EBX depending on the availability
1420 * If FSGSBASE is enabled, restore the saved GSBASE value
1421 * unconditionally, otherwise take the conditional SWAPGS path.
1423 ALTERNATIVE "jmp nmi_no_fsgsbase", "", X86_FEATURE_FSGSBASE
1429 /* EBX == 0 -> invoke SWAPGS */
1440 * Skip orig_ax and the "outermost" frame to point RSP at the "iret"
1441 * at the "iret" frame.
1446 * Clear "NMI executing". Set DF first so that we can easily
1447 * distinguish the remaining code between here and IRET from
1448 * the SYSCALL entry and exit paths.
1450 * We arguably should just inspect RIP instead, but I (Andy) wrote
1451 * this code when I had the misapprehension that Xen PV supported
1452 * NMIs, and Xen PV would break that approach.
1455 movq $0, 5*8(%rsp) /* clear "NMI executing" */
1458 * iretq reads the "iret" frame and exits the NMI stack in a
1459 * single instruction. We are returning to kernel mode, so this
1460 * cannot result in a fault. Similarly, we don't need to worry
1461 * about espfix64 on the way back to kernel mode.
1464 SYM_CODE_END(asm_exc_nmi)
1466 #ifndef CONFIG_IA32_EMULATION
1468 * This handles SYSCALL from 32-bit code. There is no way to program
1469 * MSRs to fully disable 32-bit SYSCALL.
1471 SYM_CODE_START(ignore_sysret)
1476 SYM_CODE_END(ignore_sysret)
1479 .pushsection .text, "ax"
1480 SYM_CODE_START(rewind_stack_and_make_dead)
1482 /* Prevent any naive code from trying to unwind to our caller. */
1485 movq PER_CPU_VAR(cpu_current_top_of_stack), %rax
1486 leaq -PTREGS_SIZE(%rax), %rsp
1490 SYM_CODE_END(rewind_stack_and_make_dead)