xref: /openbmc/linux/arch/x86/entry/entry_64.S (revision 2dd6532e)
1/* SPDX-License-Identifier: GPL-2.0 */
2/*
3 *  linux/arch/x86_64/entry.S
4 *
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>
8 *
9 * entry.S contains the system-call and fault low-level handling routines.
10 *
11 * Some of this is documented in Documentation/x86/entry_64.rst
12 *
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.
16 *
17 * Some macro usage:
18 * - SYM_FUNC_START/END:Define functions in the symbol table.
19 * - idtentry:		Define exception entry points.
20 */
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>
26#include <asm/msr.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>
34#include <asm/asm.h>
35#include <asm/smap.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>
43
44#include "calling.h"
45
46.code64
47.section .entry.text, "ax"
48
49/*
50 * 64-bit SYSCALL instruction entry. Up to 6 arguments in registers.
51 *
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.
56 *
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.
61 *
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.
67 *
68 * Registers on entry:
69 * rax  system call number
70 * rcx  return address
71 * r11  saved rflags (note: r11 is callee-clobbered register in C ABI)
72 * rdi  arg0
73 * rsi  arg1
74 * rdx  arg2
75 * r10  arg3 (needs to be moved to rcx to conform to C ABI)
76 * r8   arg4
77 * r9   arg5
78 * (note: r12-r15, rbp, rbx are callee-preserved in C ABI)
79 *
80 * Only called from user space.
81 *
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.
85 */
86
87SYM_CODE_START(entry_SYSCALL_64)
88	UNWIND_HINT_EMPTY
89	ENDBR
90
91	swapgs
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
96
97SYM_INNER_LABEL(entry_SYSCALL_64_safe_stack, SYM_L_GLOBAL)
98	ANNOTATE_NOENDBR
99
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 */
106SYM_INNER_LABEL(entry_SYSCALL_64_after_hwframe, SYM_L_GLOBAL)
107	pushq	%rax					/* pt_regs->orig_ax */
108
109	PUSH_AND_CLEAR_REGS rax=$-ENOSYS
110
111	/* IRQs are off. */
112	movq	%rsp, %rdi
113	/* Sign extend the lower 32bit as syscall numbers are treated as int */
114	movslq	%eax, %rsi
115	call	do_syscall_64		/* returns with IRQs disabled */
116
117	/*
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.
122	 */
123
124	ALTERNATIVE "", "jmp	swapgs_restore_regs_and_return_to_usermode", \
125		X86_FEATURE_XENPV
126
127	movq	RCX(%rsp), %rcx
128	movq	RIP(%rsp), %r11
129
130	cmpq	%rcx, %r11	/* SYSRET requires RCX == RIP */
131	jne	swapgs_restore_regs_and_return_to_usermode
132
133	/*
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.
137	 *
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.
140	 *
141	 * Change top bits to match most significant bit (47th or 56th bit
142	 * depending on paging mode) in the address.
143	 */
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
147#else
148	shl	$(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
149	sar	$(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
150#endif
151
152	/* If this changed %rcx, it was not canonical */
153	cmpq	%rcx, %r11
154	jne	swapgs_restore_regs_and_return_to_usermode
155
156	cmpq	$__USER_CS, CS(%rsp)		/* CS must match SYSRET */
157	jne	swapgs_restore_regs_and_return_to_usermode
158
159	movq	R11(%rsp), %r11
160	cmpq	%r11, EFLAGS(%rsp)		/* R11 == RFLAGS */
161	jne	swapgs_restore_regs_and_return_to_usermode
162
163	/*
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.
167	 *
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
172	 * this user code:
173	 *
174	 *           movq	$stuck_here, %rcx
175	 *           pushfq
176	 *           popq %r11
177	 *   stuck_here:
178	 *
179	 * would never get past 'stuck_here'.
180	 */
181	testq	$(X86_EFLAGS_RF|X86_EFLAGS_TF), %r11
182	jnz	swapgs_restore_regs_and_return_to_usermode
183
184	/* nothing to check for RSP */
185
186	cmpq	$__USER_DS, SS(%rsp)		/* SS must match SYSRET */
187	jne	swapgs_restore_regs_and_return_to_usermode
188
189	/*
190	 * We win! This label is here just for ease of understanding
191	 * perf profiles. Nothing jumps here.
192	 */
193syscall_return_via_sysret:
194	POP_REGS pop_rdi=0
195
196	/*
197	 * Now all regs are restored except RSP and RDI.
198	 * Save old stack pointer and switch to trampoline stack.
199	 */
200	movq	%rsp, %rdi
201	movq	PER_CPU_VAR(cpu_tss_rw + TSS_sp0), %rsp
202	UNWIND_HINT_EMPTY
203
204	pushq	RSP-RDI(%rdi)	/* RSP */
205	pushq	(%rdi)		/* RDI */
206
207	/*
208	 * We are on the trampoline stack.  All regs except RDI are live.
209	 * We can do future final exit work right here.
210	 */
211	STACKLEAK_ERASE_NOCLOBBER
212
213	SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
214
215	popq	%rdi
216	popq	%rsp
217SYM_INNER_LABEL(entry_SYSRETQ_unsafe_stack, SYM_L_GLOBAL)
218	ANNOTATE_NOENDBR
219	swapgs
220	sysretq
221SYM_INNER_LABEL(entry_SYSRETQ_end, SYM_L_GLOBAL)
222	ANNOTATE_NOENDBR
223	int3
224SYM_CODE_END(entry_SYSCALL_64)
225
226/*
227 * %rdi: prev task
228 * %rsi: next task
229 */
230.pushsection .text, "ax"
231SYM_FUNC_START(__switch_to_asm)
232	/*
233	 * Save callee-saved registers
234	 * This must match the order in inactive_task_frame
235	 */
236	pushq	%rbp
237	pushq	%rbx
238	pushq	%r12
239	pushq	%r13
240	pushq	%r14
241	pushq	%r15
242
243	/* switch stack */
244	movq	%rsp, TASK_threadsp(%rdi)
245	movq	TASK_threadsp(%rsi), %rsp
246
247#ifdef CONFIG_STACKPROTECTOR
248	movq	TASK_stack_canary(%rsi), %rbx
249	movq	%rbx, PER_CPU_VAR(fixed_percpu_data) + stack_canary_offset
250#endif
251
252#ifdef CONFIG_RETPOLINE
253	/*
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.
259	 */
260	FILL_RETURN_BUFFER %r12, RSB_CLEAR_LOOPS, X86_FEATURE_RSB_CTXSW
261#endif
262
263	/* restore callee-saved registers */
264	popq	%r15
265	popq	%r14
266	popq	%r13
267	popq	%r12
268	popq	%rbx
269	popq	%rbp
270
271	jmp	__switch_to
272SYM_FUNC_END(__switch_to_asm)
273.popsection
274
275/*
276 * A newly forked process directly context switches into this address.
277 *
278 * rax: prev task we switched from
279 * rbx: kernel thread func (NULL for user thread)
280 * r12: kernel thread arg
281 */
282.pushsection .text, "ax"
283SYM_CODE_START(ret_from_fork)
284	UNWIND_HINT_EMPTY
285	ANNOTATE_NOENDBR // copy_thread
286	movq	%rax, %rdi
287	call	schedule_tail			/* rdi: 'prev' task parameter */
288
289	testq	%rbx, %rbx			/* from kernel_thread? */
290	jnz	1f				/* kernel threads are uncommon */
291
2922:
293	UNWIND_HINT_REGS
294	movq	%rsp, %rdi
295	call	syscall_exit_to_user_mode	/* returns with IRQs disabled */
296	jmp	swapgs_restore_regs_and_return_to_usermode
297
2981:
299	/* kernel thread */
300	UNWIND_HINT_EMPTY
301	movq	%r12, %rdi
302	CALL_NOSPEC rbx
303	/*
304	 * A kernel thread is allowed to return here after successfully
305	 * calling kernel_execve().  Exit to userspace to complete the execve()
306	 * syscall.
307	 */
308	movq	$0, RAX(%rsp)
309	jmp	2b
310SYM_CODE_END(ret_from_fork)
311.popsection
312
313.macro DEBUG_ENTRY_ASSERT_IRQS_OFF
314#ifdef CONFIG_DEBUG_ENTRY
315	pushq %rax
316	SAVE_FLAGS
317	testl $X86_EFLAGS_IF, %eax
318	jz .Lokay_\@
319	ud2
320.Lokay_\@:
321	popq %rax
322#endif
323.endm
324
325/* Save all registers in pt_regs */
326SYM_CODE_START_LOCAL(push_and_clear_regs)
327	UNWIND_HINT_FUNC
328	PUSH_AND_CLEAR_REGS save_ret=1
329	ENCODE_FRAME_POINTER 8
330	RET
331SYM_CODE_END(push_and_clear_regs)
332
333/**
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
337 */
338.macro idtentry_body cfunc has_error_code:req
339
340	call push_and_clear_regs
341	UNWIND_HINT_REGS
342
343	/*
344	 * Call error_entry() and switch to the task stack if from userspace.
345	 *
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().
350	 */
351	ALTERNATIVE "call error_entry; movq %rax, %rsp", \
352		"", X86_FEATURE_XENPV
353
354	ENCODE_FRAME_POINTER
355	UNWIND_HINT_REGS
356
357	movq	%rsp, %rdi			/* pt_regs pointer into 1st argument*/
358
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 */
362	.endif
363
364	call	\cfunc
365
366	/* For some configurations \cfunc ends up being a noreturn. */
367	REACHABLE
368
369	jmp	error_return
370.endm
371
372/**
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
378 *
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.
381 */
382.macro idtentry vector asmsym cfunc has_error_code:req
383SYM_CODE_START(\asmsym)
384	UNWIND_HINT_IRET_REGS offset=\has_error_code*8
385	ENDBR
386	ASM_CLAC
387	cld
388
389	.if \has_error_code == 0
390		pushq	$-1			/* ORIG_RAX: no syscall to restart */
391	.endif
392
393	.if \vector == X86_TRAP_BP
394		/*
395		 * If coming from kernel space, create a 6-word gap to allow the
396		 * int3 handler to emulate a call instruction.
397		 */
398		testb	$3, CS-ORIG_RAX(%rsp)
399		jnz	.Lfrom_usermode_no_gap_\@
400		.rept	6
401		pushq	5*8(%rsp)
402		.endr
403		UNWIND_HINT_IRET_REGS offset=8
404.Lfrom_usermode_no_gap_\@:
405	.endif
406
407	idtentry_body \cfunc \has_error_code
408
409_ASM_NOKPROBE(\asmsym)
410SYM_CODE_END(\asmsym)
411.endm
412
413/*
414 * Interrupt entry/exit.
415 *
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
418 * (common/spurious).
419 *
420 * common_interrupt is a hotpath, align it to a cache line
421 */
422.macro idtentry_irq vector cfunc
423	.p2align CONFIG_X86_L1_CACHE_SHIFT
424	idtentry \vector asm_\cfunc \cfunc has_error_code=1
425.endm
426
427/*
428 * System vectors which invoke their handlers directly and are not
429 * going through the regular common device interrupt handling code.
430 */
431.macro idtentry_sysvec vector cfunc
432	idtentry \vector asm_\cfunc \cfunc has_error_code=0
433.endm
434
435/**
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
440 *
441 * The macro emits code to set up the kernel context for #MC and #DB
442 *
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
445 * exit.
446 *
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.
450 */
451.macro idtentry_mce_db vector asmsym cfunc
452SYM_CODE_START(\asmsym)
453	UNWIND_HINT_IRET_REGS
454	ENDBR
455	ASM_CLAC
456	cld
457
458	pushq	$-1			/* ORIG_RAX: no syscall to restart */
459
460	/*
461	 * If the entry is from userspace, switch stacks and treat it as
462	 * a normal entry.
463	 */
464	testb	$3, CS-ORIG_RAX(%rsp)
465	jnz	.Lfrom_usermode_switch_stack_\@
466
467	/* paranoid_entry returns GS information for paranoid_exit in EBX. */
468	call	paranoid_entry
469
470	UNWIND_HINT_REGS
471
472	movq	%rsp, %rdi		/* pt_regs pointer */
473
474	call	\cfunc
475
476	jmp	paranoid_exit
477
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
481
482_ASM_NOKPROBE(\asmsym)
483SYM_CODE_END(\asmsym)
484.endm
485
486#ifdef CONFIG_AMD_MEM_ENCRYPT
487/**
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
492 *
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.
495 *
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.
500 *
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.
504 *
505 * The macro is only used for one vector, but it is planned to be extended in
506 * the future for the #HV exception.
507 */
508.macro idtentry_vc vector asmsym cfunc
509SYM_CODE_START(\asmsym)
510	UNWIND_HINT_IRET_REGS
511	ENDBR
512	ASM_CLAC
513	cld
514
515	/*
516	 * If the entry is from userspace, switch stacks and treat it as
517	 * a normal entry.
518	 */
519	testb	$3, CS-ORIG_RAX(%rsp)
520	jnz	.Lfrom_usermode_switch_stack_\@
521
522	/*
523	 * paranoid_entry returns SWAPGS flag for paranoid_exit in EBX.
524	 * EBX == 0 -> SWAPGS, EBX == 1 -> no SWAPGS
525	 */
526	call	paranoid_entry
527
528	UNWIND_HINT_REGS
529
530	/*
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
534	 * stack.
535	 */
536	movq	%rsp, %rdi		/* pt_regs pointer */
537	call	vc_switch_off_ist
538	movq	%rax, %rsp		/* Switch to new stack */
539
540	ENCODE_FRAME_POINTER
541	UNWIND_HINT_REGS
542
543	/* Update pt_regs */
544	movq	ORIG_RAX(%rsp), %rsi	/* get error code into 2nd argument*/
545	movq	$-1, ORIG_RAX(%rsp)	/* no syscall to restart */
546
547	movq	%rsp, %rdi		/* pt_regs pointer */
548
549	call	kernel_\cfunc
550
551	/*
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.
555	 */
556	jmp	paranoid_exit
557
558	/* Switch to the regular task stack */
559.Lfrom_usermode_switch_stack_\@:
560	idtentry_body user_\cfunc, has_error_code=1
561
562_ASM_NOKPROBE(\asmsym)
563SYM_CODE_END(\asmsym)
564.endm
565#endif
566
567/*
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
570 * thing.
571 */
572.macro idtentry_df vector asmsym cfunc
573SYM_CODE_START(\asmsym)
574	UNWIND_HINT_IRET_REGS offset=8
575	ENDBR
576	ASM_CLAC
577	cld
578
579	/* paranoid_entry returns GS information for paranoid_exit in EBX. */
580	call	paranoid_entry
581	UNWIND_HINT_REGS
582
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 */
586	call	\cfunc
587
588	/* For some configurations \cfunc ends up being a noreturn. */
589	REACHABLE
590
591	jmp	paranoid_exit
592
593_ASM_NOKPROBE(\asmsym)
594SYM_CODE_END(\asmsym)
595.endm
596
597/*
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.
601 */
602	.align 16
603	.globl __irqentry_text_start
604__irqentry_text_start:
605
606#include <asm/idtentry.h>
607
608	.align 16
609	.globl __irqentry_text_end
610__irqentry_text_end:
611	ANNOTATE_NOENDBR
612
613SYM_CODE_START_LOCAL(common_interrupt_return)
614SYM_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. */
617	testb	$3, CS(%rsp)
618	jnz	1f
619	ud2
6201:
621#endif
622#ifdef CONFIG_XEN_PV
623	ALTERNATIVE "", "jmp xenpv_restore_regs_and_return_to_usermode", X86_FEATURE_XENPV
624#endif
625
626	POP_REGS pop_rdi=0
627
628	/*
629	 * The stack is now user RDI, orig_ax, RIP, CS, EFLAGS, RSP, SS.
630	 * Save old stack pointer and switch to trampoline stack.
631	 */
632	movq	%rsp, %rdi
633	movq	PER_CPU_VAR(cpu_tss_rw + TSS_sp0), %rsp
634	UNWIND_HINT_EMPTY
635
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 */
642
643	/* Push user RDI on the trampoline stack. */
644	pushq	(%rdi)
645
646	/*
647	 * We are on the trampoline stack.  All regs except RDI are live.
648	 * We can do future final exit work right here.
649	 */
650	STACKLEAK_ERASE_NOCLOBBER
651
652	SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
653
654	/* Restore RDI. */
655	popq	%rdi
656	swapgs
657	jmp	.Lnative_iret
658
659
660SYM_INNER_LABEL(restore_regs_and_return_to_kernel, SYM_L_GLOBAL)
661#ifdef CONFIG_DEBUG_ENTRY
662	/* Assert that pt_regs indicates kernel mode. */
663	testb	$3, CS(%rsp)
664	jz	1f
665	ud2
6661:
667#endif
668	POP_REGS
669	addq	$8, %rsp	/* skip regs->orig_ax */
670	/*
671	 * ARCH_HAS_MEMBARRIER_SYNC_CORE rely on IRET core serialization
672	 * when returning from IPI handler.
673	 */
674#ifdef CONFIG_XEN_PV
675SYM_INNER_LABEL(early_xen_iret_patch, SYM_L_GLOBAL)
676	ANNOTATE_NOENDBR
677	.byte 0xe9
678	.long .Lnative_iret - (. + 4)
679#endif
680
681.Lnative_iret:
682	UNWIND_HINT_IRET_REGS
683	/*
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.
686	 */
687#ifdef CONFIG_X86_ESPFIX64
688	testb	$4, (SS-RIP)(%rsp)
689	jnz	native_irq_return_ldt
690#endif
691
692SYM_INNER_LABEL(native_irq_return_iret, SYM_L_GLOBAL)
693	ANNOTATE_NOENDBR // exc_double_fault
694	/*
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.
699	 */
700	iretq
701
702#ifdef CONFIG_X86_ESPFIX64
703native_irq_return_ldt:
704	/*
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.
709	 *
710	 * We clobber RAX and RDI in this code.  We stash RDI on the
711	 * normal stack and RAX on the ESPFIX stack.
712	 *
713	 * The ESPFIX stack layout we set up looks like this:
714	 *
715	 * --- top of ESPFIX stack ---
716	 * SS
717	 * RSP
718	 * RFLAGS
719	 * CS
720	 * RIP  <-- RSP points here when we're done
721	 * RAX  <-- espfix_waddr points here
722	 * --- bottom of ESPFIX stack ---
723	 */
724
725	pushq	%rdi				/* Stash user RDI */
726	swapgs					/* to kernel GS */
727	SWITCH_TO_KERNEL_CR3 scratch_reg=%rdi	/* to kernel CR3 */
728
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. */
742
743	andl	$0xffff0000, %eax		/* RAX = (RSP & 0xffff0000) */
744
745	/*
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.
752	 */
753	orq	PER_CPU_VAR(espfix_stack), %rax
754
755	SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
756	swapgs					/* to user GS */
757	popq	%rdi				/* Restore user RDI */
758
759	movq	%rax, %rsp
760	UNWIND_HINT_IRET_REGS offset=8
761
762	/*
763	 * At this point, we cannot write to the stack any more, but we can
764	 * still read.
765	 */
766	popq	%rax				/* Restore user RAX */
767
768	/*
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.
772	 */
773	jmp	native_irq_return_iret
774#endif
775SYM_CODE_END(common_interrupt_return)
776_ASM_NOKPROBE(common_interrupt_return)
777
778/*
779 * Reload gs selector with exception handling
780 * edi:  new selector
781 *
782 * Is in entry.text as it shouldn't be instrumented.
783 */
784SYM_FUNC_START(asm_load_gs_index)
785	FRAME_BEGIN
786	swapgs
787.Lgs_change:
788	ANNOTATE_NOENDBR // error_entry
789	movl	%edi, %gs
7902:	ALTERNATIVE "", "mfence", X86_BUG_SWAPGS_FENCE
791	swapgs
792	FRAME_END
793	RET
794
795	/* running with kernelgs */
796.Lbad_gs:
797	swapgs					/* switch back to user gs */
798.macro ZAP_GS
799	/* This can't be a string because the preprocessor needs to see it. */
800	movl $__USER_DS, %eax
801	movl %eax, %gs
802.endm
803	ALTERNATIVE "", "ZAP_GS", X86_BUG_NULL_SEG
804	xorl	%eax, %eax
805	movl	%eax, %gs
806	jmp	2b
807
808	_ASM_EXTABLE(.Lgs_change, .Lbad_gs)
809
810SYM_FUNC_END(asm_load_gs_index)
811EXPORT_SYMBOL(asm_load_gs_index)
812
813#ifdef CONFIG_XEN_PV
814/*
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.
826 *
827 * C calling convention: exc_xen_hypervisor_callback(struct *pt_regs)
828 */
829SYM_CODE_START_LOCAL(exc_xen_hypervisor_callback)
830
831/*
832 * Since we don't modify %rdi, evtchn_do_upall(struct *pt_regs) will
833 * see the correct pointer to the pt_regs
834 */
835	UNWIND_HINT_FUNC
836	movq	%rdi, %rsp			/* we don't return, adjust the stack frame */
837	UNWIND_HINT_REGS
838
839	call	xen_pv_evtchn_do_upcall
840
841	jmp	error_return
842SYM_CODE_END(exc_xen_hypervisor_callback)
843
844/*
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.
856 */
857SYM_CODE_START(xen_failsafe_callback)
858	UNWIND_HINT_EMPTY
859	ENDBR
860	movl	%ds, %ecx
861	cmpw	%cx, 0x10(%rsp)
862	jne	1f
863	movl	%es, %ecx
864	cmpw	%cx, 0x18(%rsp)
865	jne	1f
866	movl	%fs, %ecx
867	cmpw	%cx, 0x20(%rsp)
868	jne	1f
869	movl	%gs, %ecx
870	cmpw	%cx, 0x28(%rsp)
871	jne	1f
872	/* All segments match their saved values => Category 2 (Bad IRET). */
873	movq	(%rsp), %rcx
874	movq	8(%rsp), %r11
875	addq	$0x30, %rsp
876	pushq	$0				/* RIP */
877	UNWIND_HINT_IRET_REGS offset=8
878	jmp	asm_exc_general_protection
8791:	/* Segment mismatch => Category 1 (Bad segment). Retry the IRET. */
880	movq	(%rsp), %rcx
881	movq	8(%rsp), %r11
882	addq	$0x30, %rsp
883	UNWIND_HINT_IRET_REGS
884	pushq	$-1 /* orig_ax = -1 => not a system call */
885	PUSH_AND_CLEAR_REGS
886	ENCODE_FRAME_POINTER
887	jmp	error_return
888SYM_CODE_END(xen_failsafe_callback)
889#endif /* CONFIG_XEN_PV */
890
891/*
892 * Save all registers in pt_regs. Return GSBASE related information
893 * in EBX depending on the availability of the FSGSBASE instructions:
894 *
895 * FSGSBASE	R/EBX
896 *     N        0 -> SWAPGS on exit
897 *              1 -> no SWAPGS on exit
898 *
899 *     Y        GSBASE value at entry, must be restored in paranoid_exit
900 */
901SYM_CODE_START_LOCAL(paranoid_entry)
902	UNWIND_HINT_FUNC
903	PUSH_AND_CLEAR_REGS save_ret=1
904	ENCODE_FRAME_POINTER 8
905
906	/*
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.
911	 *
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.
915	 *
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.
920	 */
921	SAVE_AND_SWITCH_TO_KERNEL_CR3 scratch_reg=%rax save_reg=%r14
922
923	/*
924	 * Handling GSBASE depends on the availability of FSGSBASE.
925	 *
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
929	 * space.
930	 */
931	ALTERNATIVE "jmp .Lparanoid_entry_checkgs", "", X86_FEATURE_FSGSBASE
932
933	/*
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.
937	 *
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
940	 * is needed here.
941	 */
942	SAVE_AND_SET_GSBASE scratch_reg=%rax save_reg=%rbx
943	RET
944
945.Lparanoid_entry_checkgs:
946	/* EBX = 1 -> kernel GSBASE active, no restore required */
947	movl	$1, %ebx
948
949	/*
950	 * The kernel-enforced convention is a negative GSBASE indicates
951	 * a kernel value. No SWAPGS needed on entry and exit.
952	 */
953	movl	$MSR_GS_BASE, %ecx
954	rdmsr
955	testl	%edx, %edx
956	js	.Lparanoid_kernel_gsbase
957
958	/* EBX = 0 -> SWAPGS required on exit */
959	xorl	%ebx, %ebx
960	swapgs
961.Lparanoid_kernel_gsbase:
962
963	FENCE_SWAPGS_KERNEL_ENTRY
964	RET
965SYM_CODE_END(paranoid_entry)
966
967/*
968 * "Paranoid" exit path from exception stack.  This is invoked
969 * only on return from non-NMI IST interrupts that came
970 * from kernel space.
971 *
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.
976 *
977 * R/EBX contains the GSBASE related information depending on the
978 * availability of the FSGSBASE instructions:
979 *
980 * FSGSBASE	R/EBX
981 *     N        0 -> SWAPGS on exit
982 *              1 -> no SWAPGS on exit
983 *
984 *     Y        User space GSBASE, must be restored unconditionally
985 */
986SYM_CODE_START_LOCAL(paranoid_exit)
987	UNWIND_HINT_REGS
988	/*
989	 * The order of operations is important. RESTORE_CR3 requires
990	 * kernel GSBASE.
991	 *
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.
995	 */
996	RESTORE_CR3	scratch_reg=%rax save_reg=%r14
997
998	/* Handle the three GSBASE cases */
999	ALTERNATIVE "jmp .Lparanoid_exit_checkgs", "", X86_FEATURE_FSGSBASE
1000
1001	/* With FSGSBASE enabled, unconditionally restore GSBASE */
1002	wrgsbase	%rbx
1003	jmp		restore_regs_and_return_to_kernel
1004
1005.Lparanoid_exit_checkgs:
1006	/* On non-FSGSBASE systems, conditionally do SWAPGS */
1007	testl		%ebx, %ebx
1008	jnz		restore_regs_and_return_to_kernel
1009
1010	/* We are returning to a context with user GSBASE */
1011	swapgs
1012	jmp		restore_regs_and_return_to_kernel
1013SYM_CODE_END(paranoid_exit)
1014
1015/*
1016 * Switch GS and CR3 if needed.
1017 */
1018SYM_CODE_START_LOCAL(error_entry)
1019	UNWIND_HINT_FUNC
1020	testb	$3, CS+8(%rsp)
1021	jz	.Lerror_kernelspace
1022
1023	/*
1024	 * We entered from user mode or we're pretending to have entered
1025	 * from user mode due to an IRET fault.
1026	 */
1027	swapgs
1028	FENCE_SWAPGS_USER_ENTRY
1029	/* We have user CR3.  Change to kernel CR3. */
1030	SWITCH_TO_KERNEL_CR3 scratch_reg=%rax
1031
1032	leaq	8(%rsp), %rdi			/* arg0 = pt_regs pointer */
1033.Lerror_entry_from_usermode_after_swapgs:
1034	/* Put us onto the real thread stack. */
1035	call	sync_regs
1036	RET
1037
1038	/*
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.
1043	 */
1044.Lerror_kernelspace:
1045	leaq	native_irq_return_iret(%rip), %rcx
1046	cmpq	%rcx, RIP+8(%rsp)
1047	je	.Lerror_bad_iret
1048	movl	%ecx, %eax			/* zero extend */
1049	cmpq	%rax, RIP+8(%rsp)
1050	je	.Lbstep_iret
1051	cmpq	$.Lgs_change, RIP+8(%rsp)
1052	jne	.Lerror_entry_done_lfence
1053
1054	/*
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.
1058	 */
1059	swapgs
1060
1061	/*
1062	 * Issue an LFENCE to prevent GS speculation, regardless of whether it is a
1063	 * kernel or user gsbase.
1064	 */
1065.Lerror_entry_done_lfence:
1066	FENCE_SWAPGS_KERNEL_ENTRY
1067	leaq	8(%rsp), %rax			/* return pt_regs pointer */
1068	RET
1069
1070.Lbstep_iret:
1071	/* Fix truncated RIP */
1072	movq	%rcx, RIP+8(%rsp)
1073	/* fall through */
1074
1075.Lerror_bad_iret:
1076	/*
1077	 * We came from an IRET to user mode, so we have user
1078	 * gsbase and CR3.  Switch to kernel gsbase and CR3:
1079	 */
1080	swapgs
1081	FENCE_SWAPGS_USER_ENTRY
1082	SWITCH_TO_KERNEL_CR3 scratch_reg=%rax
1083
1084	/*
1085	 * Pretend that the exception came from user mode: set up pt_regs
1086	 * as if we faulted immediately after IRET.
1087	 */
1088	leaq	8(%rsp), %rdi			/* arg0 = pt_regs pointer */
1089	call	fixup_bad_iret
1090	mov	%rax, %rdi
1091	jmp	.Lerror_entry_from_usermode_after_swapgs
1092SYM_CODE_END(error_entry)
1093
1094SYM_CODE_START_LOCAL(error_return)
1095	UNWIND_HINT_REGS
1096	DEBUG_ENTRY_ASSERT_IRQS_OFF
1097	testb	$3, CS(%rsp)
1098	jz	restore_regs_and_return_to_kernel
1099	jmp	swapgs_restore_regs_and_return_to_usermode
1100SYM_CODE_END(error_return)
1101
1102/*
1103 * Runs on exception stack.  Xen PV does not go through this path at all,
1104 * so we can use real assembly here.
1105 *
1106 * Registers:
1107 *	%r14: Used to save/restore the CR3 of the interrupted context
1108 *	      when PAGE_TABLE_ISOLATION is in use.  Do not clobber.
1109 */
1110SYM_CODE_START(asm_exc_nmi)
1111	UNWIND_HINT_IRET_REGS
1112	ENDBR
1113
1114	/*
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
1121	 * anyway.
1122	 *
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
1127	 *  is an NMI stack.
1128	 *  If the variable is not set and the stack is not the NMI
1129	 *  stack then:
1130	 *    o Set the special variable on the stack
1131	 *    o Copy the interrupt frame into an "outermost" location on the
1132	 *      stack
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
1138	 *
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
1144	 * NMI.
1145	 *
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.
1150	 */
1151
1152	ASM_CLAC
1153	cld
1154
1155	/* Use %rdx as our temp variable throughout */
1156	pushq	%rdx
1157
1158	testb	$3, CS-RIP+8(%rsp)
1159	jz	.Lnmi_from_kernel
1160
1161	/*
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
1166	 * are off.
1167	 *
1168	 * We also must not push anything to the stack before switching
1169	 * stacks lest we corrupt the "NMI executing" variable.
1170	 */
1171
1172	swapgs
1173	FENCE_SWAPGS_USER_ENTRY
1174	SWITCH_TO_KERNEL_CR3 scratch_reg=%rdx
1175	movq	%rsp, %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
1187
1188	/*
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.
1192	 */
1193
1194	movq	%rsp, %rdi
1195	movq	$-1, %rsi
1196	call	exc_nmi
1197
1198	/*
1199	 * Return back to user mode.  We must *not* do the normal exit
1200	 * work, because we don't want to enable interrupts.
1201	 */
1202	jmp	swapgs_restore_regs_and_return_to_usermode
1203
1204.Lnmi_from_kernel:
1205	/*
1206	 * Here's what our stack frame will look like:
1207	 * +---------------------------------------------------------+
1208	 * | original SS                                             |
1209	 * | original Return RSP                                     |
1210	 * | original RFLAGS                                         |
1211	 * | original CS                                             |
1212	 * | original RIP                                            |
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.                 |
1222	 * | iret RIP         }                                      |
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	 * +---------------------------------------------------------+
1230	 * | pt_regs                                                 |
1231	 * +---------------------------------------------------------+
1232	 *
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.
1236	 *
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
1239	 * processing.
1240	 *
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.
1244	 */
1245
1246	/*
1247	 * Determine whether we're a nested NMI.
1248	 *
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.
1255	 */
1256
1257	movq	$repeat_nmi, %rdx
1258	cmpq	8(%rsp), %rdx
1259	ja	1f
1260	movq	$end_repeat_nmi, %rdx
1261	cmpq	8(%rsp), %rdx
1262	ja	nested_nmi_out
12631:
1264
1265	/*
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
1268	 * before IRET.
1269	 */
1270	cmpl	$1, -8(%rsp)
1271	je	nested_nmi
1272
1273	/*
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
1283	 * "NMI executing".
1284	 */
1285	lea	6*8(%rsp), %rdx
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 */
1289	ja	first_nmi
1290
1291	subq	$EXCEPTION_STKSZ, %rdx
1292	cmpq	%rdx, 4*8(%rsp)
1293	/* If it is below the NMI stack, it is a normal NMI */
1294	jb	first_nmi
1295
1296	/* Ah, it is within the NMI stack. */
1297
1298	testb	$(X86_EFLAGS_DF >> 8), (3*8 + 1)(%rsp)
1299	jz	first_nmi	/* RSP was user controlled. */
1300
1301	/* This is a nested NMI. */
1302
1303nested_nmi:
1304	/*
1305	 * Modify the "iret" frame to point to repeat_nmi, forcing another
1306	 * iteration of NMI handling.
1307	 */
1308	subq	$8, %rsp
1309	leaq	-10*8(%rsp), %rdx
1310	pushq	$__KERNEL_DS
1311	pushq	%rdx
1312	pushfq
1313	pushq	$__KERNEL_CS
1314	pushq	$repeat_nmi
1315
1316	/* Put stack back */
1317	addq	$(6*8), %rsp
1318
1319nested_nmi_out:
1320	popq	%rdx
1321
1322	/* We are returning to kernel mode, so this cannot result in a fault. */
1323	iretq
1324
1325first_nmi:
1326	/* Restore rdx. */
1327	movq	(%rsp), %rdx
1328
1329	/* Make room for "NMI executing". */
1330	pushq	$0
1331
1332	/* Leave room for the "iret" frame */
1333	subq	$(5*8), %rsp
1334
1335	/* Copy the "original" frame to the "outermost" frame */
1336	.rept 5
1337	pushq	11*8(%rsp)
1338	.endr
1339	UNWIND_HINT_IRET_REGS
1340
1341	/* Everything up to here is safe from nested NMIs */
1342
1343#ifdef CONFIG_DEBUG_ENTRY
1344	/*
1345	 * For ease of testing, unmask NMIs right away.  Disabled by
1346	 * default because IRET is very expensive.
1347	 */
1348	pushq	$0		/* SS */
1349	pushq	%rsp		/* RSP (minus 8 because of the previous push) */
1350	addq	$8, (%rsp)	/* Fix up RSP */
1351	pushfq			/* RFLAGS */
1352	pushq	$__KERNEL_CS	/* CS */
1353	pushq	$1f		/* RIP */
1354	iretq			/* continues at repeat_nmi below */
1355	UNWIND_HINT_IRET_REGS
13561:
1357#endif
1358
1359repeat_nmi:
1360	ANNOTATE_NOENDBR // this code
1361	/*
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
1368	 * NMI will update.
1369	 *
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"
1374	 * is zero.
1375	 */
1376	movq	$1, 10*8(%rsp)		/* Set "NMI executing". */
1377
1378	/*
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.
1382	 */
1383	addq	$(10*8), %rsp
1384	.rept 5
1385	pushq	-6*8(%rsp)
1386	.endr
1387	subq	$(5*8), %rsp
1388end_repeat_nmi:
1389	ANNOTATE_NOENDBR // this code
1390
1391	/*
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.
1395	 */
1396	pushq	$-1				/* ORIG_RAX: no syscall to restart */
1397
1398	/*
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.
1404	 */
1405	call	paranoid_entry
1406	UNWIND_HINT_REGS
1407
1408	movq	%rsp, %rdi
1409	movq	$-1, %rsi
1410	call	exc_nmi
1411
1412	/* Always restore stashed CR3 value (see paranoid_entry) */
1413	RESTORE_CR3 scratch_reg=%r15 save_reg=%r14
1414
1415	/*
1416	 * The above invocation of paranoid_entry stored the GSBASE
1417	 * related information in R/EBX depending on the availability
1418	 * of FSGSBASE.
1419	 *
1420	 * If FSGSBASE is enabled, restore the saved GSBASE value
1421	 * unconditionally, otherwise take the conditional SWAPGS path.
1422	 */
1423	ALTERNATIVE "jmp nmi_no_fsgsbase", "", X86_FEATURE_FSGSBASE
1424
1425	wrgsbase	%rbx
1426	jmp	nmi_restore
1427
1428nmi_no_fsgsbase:
1429	/* EBX == 0 -> invoke SWAPGS */
1430	testl	%ebx, %ebx
1431	jnz	nmi_restore
1432
1433nmi_swapgs:
1434	swapgs
1435
1436nmi_restore:
1437	POP_REGS
1438
1439	/*
1440	 * Skip orig_ax and the "outermost" frame to point RSP at the "iret"
1441	 * at the "iret" frame.
1442	 */
1443	addq	$6*8, %rsp
1444
1445	/*
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.
1449	 *
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.
1453	 */
1454	std
1455	movq	$0, 5*8(%rsp)		/* clear "NMI executing" */
1456
1457	/*
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.
1462	 */
1463	iretq
1464SYM_CODE_END(asm_exc_nmi)
1465
1466#ifndef CONFIG_IA32_EMULATION
1467/*
1468 * This handles SYSCALL from 32-bit code.  There is no way to program
1469 * MSRs to fully disable 32-bit SYSCALL.
1470 */
1471SYM_CODE_START(ignore_sysret)
1472	UNWIND_HINT_EMPTY
1473	ENDBR
1474	mov	$-ENOSYS, %eax
1475	sysretl
1476SYM_CODE_END(ignore_sysret)
1477#endif
1478
1479.pushsection .text, "ax"
1480SYM_CODE_START(rewind_stack_and_make_dead)
1481	UNWIND_HINT_FUNC
1482	/* Prevent any naive code from trying to unwind to our caller. */
1483	xorl	%ebp, %ebp
1484
1485	movq	PER_CPU_VAR(cpu_current_top_of_stack), %rax
1486	leaq	-PTREGS_SIZE(%rax), %rsp
1487	UNWIND_HINT_REGS
1488
1489	call	make_task_dead
1490SYM_CODE_END(rewind_stack_and_make_dead)
1491.popsection
1492