xref: /openbmc/linux/arch/x86/entry/entry_64.S (revision d15cb3da)
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
99	/* Construct struct pt_regs on stack */
100	pushq	$__USER_DS				/* pt_regs->ss */
101	pushq	PER_CPU_VAR(cpu_tss_rw + TSS_sp2)	/* pt_regs->sp */
102	pushq	%r11					/* pt_regs->flags */
103	pushq	$__USER_CS				/* pt_regs->cs */
104	pushq	%rcx					/* pt_regs->ip */
105SYM_INNER_LABEL(entry_SYSCALL_64_after_hwframe, SYM_L_GLOBAL)
106	pushq	%rax					/* pt_regs->orig_ax */
107
108	PUSH_AND_CLEAR_REGS rax=$-ENOSYS
109
110	/* IRQs are off. */
111	movq	%rsp, %rdi
112	/* Sign extend the lower 32bit as syscall numbers are treated as int */
113	movslq	%eax, %rsi
114	call	do_syscall_64		/* returns with IRQs disabled */
115
116	/*
117	 * Try to use SYSRET instead of IRET if we're returning to
118	 * a completely clean 64-bit userspace context.  If we're not,
119	 * go to the slow exit path.
120	 * In the Xen PV case we must use iret anyway.
121	 */
122
123	ALTERNATIVE "", "jmp	swapgs_restore_regs_and_return_to_usermode", \
124		X86_FEATURE_XENPV
125
126	movq	RCX(%rsp), %rcx
127	movq	RIP(%rsp), %r11
128
129	cmpq	%rcx, %r11	/* SYSRET requires RCX == RIP */
130	jne	swapgs_restore_regs_and_return_to_usermode
131
132	/*
133	 * On Intel CPUs, SYSRET with non-canonical RCX/RIP will #GP
134	 * in kernel space.  This essentially lets the user take over
135	 * the kernel, since userspace controls RSP.
136	 *
137	 * If width of "canonical tail" ever becomes variable, this will need
138	 * to be updated to remain correct on both old and new CPUs.
139	 *
140	 * Change top bits to match most significant bit (47th or 56th bit
141	 * depending on paging mode) in the address.
142	 */
143#ifdef CONFIG_X86_5LEVEL
144	ALTERNATIVE "shl $(64 - 48), %rcx; sar $(64 - 48), %rcx", \
145		"shl $(64 - 57), %rcx; sar $(64 - 57), %rcx", X86_FEATURE_LA57
146#else
147	shl	$(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
148	sar	$(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
149#endif
150
151	/* If this changed %rcx, it was not canonical */
152	cmpq	%rcx, %r11
153	jne	swapgs_restore_regs_and_return_to_usermode
154
155	cmpq	$__USER_CS, CS(%rsp)		/* CS must match SYSRET */
156	jne	swapgs_restore_regs_and_return_to_usermode
157
158	movq	R11(%rsp), %r11
159	cmpq	%r11, EFLAGS(%rsp)		/* R11 == RFLAGS */
160	jne	swapgs_restore_regs_and_return_to_usermode
161
162	/*
163	 * SYSCALL clears RF when it saves RFLAGS in R11 and SYSRET cannot
164	 * restore RF properly. If the slowpath sets it for whatever reason, we
165	 * need to restore it correctly.
166	 *
167	 * SYSRET can restore TF, but unlike IRET, restoring TF results in a
168	 * trap from userspace immediately after SYSRET.  This would cause an
169	 * infinite loop whenever #DB happens with register state that satisfies
170	 * the opportunistic SYSRET conditions.  For example, single-stepping
171	 * this user code:
172	 *
173	 *           movq	$stuck_here, %rcx
174	 *           pushfq
175	 *           popq %r11
176	 *   stuck_here:
177	 *
178	 * would never get past 'stuck_here'.
179	 */
180	testq	$(X86_EFLAGS_RF|X86_EFLAGS_TF), %r11
181	jnz	swapgs_restore_regs_and_return_to_usermode
182
183	/* nothing to check for RSP */
184
185	cmpq	$__USER_DS, SS(%rsp)		/* SS must match SYSRET */
186	jne	swapgs_restore_regs_and_return_to_usermode
187
188	/*
189	 * We win! This label is here just for ease of understanding
190	 * perf profiles. Nothing jumps here.
191	 */
192syscall_return_via_sysret:
193	/* rcx and r11 are already restored (see code above) */
194	POP_REGS pop_rdi=0 skip_r11rcx=1
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
217	swapgs
218	sysretq
219SYM_CODE_END(entry_SYSCALL_64)
220
221/*
222 * %rdi: prev task
223 * %rsi: next task
224 */
225.pushsection .text, "ax"
226SYM_FUNC_START(__switch_to_asm)
227	/*
228	 * Save callee-saved registers
229	 * This must match the order in inactive_task_frame
230	 */
231	pushq	%rbp
232	pushq	%rbx
233	pushq	%r12
234	pushq	%r13
235	pushq	%r14
236	pushq	%r15
237
238	/* switch stack */
239	movq	%rsp, TASK_threadsp(%rdi)
240	movq	TASK_threadsp(%rsi), %rsp
241
242#ifdef CONFIG_STACKPROTECTOR
243	movq	TASK_stack_canary(%rsi), %rbx
244	movq	%rbx, PER_CPU_VAR(fixed_percpu_data) + stack_canary_offset
245#endif
246
247#ifdef CONFIG_RETPOLINE
248	/*
249	 * When switching from a shallower to a deeper call stack
250	 * the RSB may either underflow or use entries populated
251	 * with userspace addresses. On CPUs where those concerns
252	 * exist, overwrite the RSB with entries which capture
253	 * speculative execution to prevent attack.
254	 */
255	FILL_RETURN_BUFFER %r12, RSB_CLEAR_LOOPS, X86_FEATURE_RSB_CTXSW
256#endif
257
258	/* restore callee-saved registers */
259	popq	%r15
260	popq	%r14
261	popq	%r13
262	popq	%r12
263	popq	%rbx
264	popq	%rbp
265
266	jmp	__switch_to
267SYM_FUNC_END(__switch_to_asm)
268.popsection
269
270/*
271 * A newly forked process directly context switches into this address.
272 *
273 * rax: prev task we switched from
274 * rbx: kernel thread func (NULL for user thread)
275 * r12: kernel thread arg
276 */
277.pushsection .text, "ax"
278SYM_CODE_START(ret_from_fork)
279	UNWIND_HINT_EMPTY
280	movq	%rax, %rdi
281	call	schedule_tail			/* rdi: 'prev' task parameter */
282
283	testq	%rbx, %rbx			/* from kernel_thread? */
284	jnz	1f				/* kernel threads are uncommon */
285
2862:
287	UNWIND_HINT_REGS
288	movq	%rsp, %rdi
289	call	syscall_exit_to_user_mode	/* returns with IRQs disabled */
290	jmp	swapgs_restore_regs_and_return_to_usermode
291
2921:
293	/* kernel thread */
294	UNWIND_HINT_EMPTY
295	movq	%r12, %rdi
296	CALL_NOSPEC rbx
297	/*
298	 * A kernel thread is allowed to return here after successfully
299	 * calling kernel_execve().  Exit to userspace to complete the execve()
300	 * syscall.
301	 */
302	movq	$0, RAX(%rsp)
303	jmp	2b
304SYM_CODE_END(ret_from_fork)
305.popsection
306
307.macro DEBUG_ENTRY_ASSERT_IRQS_OFF
308#ifdef CONFIG_DEBUG_ENTRY
309	pushq %rax
310	SAVE_FLAGS
311	testl $X86_EFLAGS_IF, %eax
312	jz .Lokay_\@
313	ud2
314.Lokay_\@:
315	popq %rax
316#endif
317.endm
318
319/**
320 * idtentry_body - Macro to emit code calling the C function
321 * @cfunc:		C function to be called
322 * @has_error_code:	Hardware pushed error code on stack
323 */
324.macro idtentry_body cfunc has_error_code:req
325
326	call	error_entry
327	UNWIND_HINT_REGS
328
329	movq	%rsp, %rdi			/* pt_regs pointer into 1st argument*/
330
331	.if \has_error_code == 1
332		movq	ORIG_RAX(%rsp), %rsi	/* get error code into 2nd argument*/
333		movq	$-1, ORIG_RAX(%rsp)	/* no syscall to restart */
334	.endif
335
336	call	\cfunc
337
338	jmp	error_return
339.endm
340
341/**
342 * idtentry - Macro to generate entry stubs for simple IDT entries
343 * @vector:		Vector number
344 * @asmsym:		ASM symbol for the entry point
345 * @cfunc:		C function to be called
346 * @has_error_code:	Hardware pushed error code on stack
347 *
348 * The macro emits code to set up the kernel context for straight forward
349 * and simple IDT entries. No IST stack, no paranoid entry checks.
350 */
351.macro idtentry vector asmsym cfunc has_error_code:req
352SYM_CODE_START(\asmsym)
353	UNWIND_HINT_IRET_REGS offset=\has_error_code*8
354	ENDBR
355	ASM_CLAC
356
357	.if \has_error_code == 0
358		pushq	$-1			/* ORIG_RAX: no syscall to restart */
359	.endif
360
361	.if \vector == X86_TRAP_BP
362		/*
363		 * If coming from kernel space, create a 6-word gap to allow the
364		 * int3 handler to emulate a call instruction.
365		 */
366		testb	$3, CS-ORIG_RAX(%rsp)
367		jnz	.Lfrom_usermode_no_gap_\@
368		.rept	6
369		pushq	5*8(%rsp)
370		.endr
371		UNWIND_HINT_IRET_REGS offset=8
372.Lfrom_usermode_no_gap_\@:
373	.endif
374
375	idtentry_body \cfunc \has_error_code
376
377_ASM_NOKPROBE(\asmsym)
378SYM_CODE_END(\asmsym)
379.endm
380
381/*
382 * Interrupt entry/exit.
383 *
384 + The interrupt stubs push (vector) onto the stack, which is the error_code
385 * position of idtentry exceptions, and jump to one of the two idtentry points
386 * (common/spurious).
387 *
388 * common_interrupt is a hotpath, align it to a cache line
389 */
390.macro idtentry_irq vector cfunc
391	.p2align CONFIG_X86_L1_CACHE_SHIFT
392	idtentry \vector asm_\cfunc \cfunc has_error_code=1
393.endm
394
395/*
396 * System vectors which invoke their handlers directly and are not
397 * going through the regular common device interrupt handling code.
398 */
399.macro idtentry_sysvec vector cfunc
400	idtentry \vector asm_\cfunc \cfunc has_error_code=0
401.endm
402
403/**
404 * idtentry_mce_db - Macro to generate entry stubs for #MC and #DB
405 * @vector:		Vector number
406 * @asmsym:		ASM symbol for the entry point
407 * @cfunc:		C function to be called
408 *
409 * The macro emits code to set up the kernel context for #MC and #DB
410 *
411 * If the entry comes from user space it uses the normal entry path
412 * including the return to user space work and preemption checks on
413 * exit.
414 *
415 * If hits in kernel mode then it needs to go through the paranoid
416 * entry as the exception can hit any random state. No preemption
417 * check on exit to keep the paranoid path simple.
418 */
419.macro idtentry_mce_db vector asmsym cfunc
420SYM_CODE_START(\asmsym)
421	UNWIND_HINT_IRET_REGS
422	ENDBR
423	ASM_CLAC
424
425	pushq	$-1			/* ORIG_RAX: no syscall to restart */
426
427	/*
428	 * If the entry is from userspace, switch stacks and treat it as
429	 * a normal entry.
430	 */
431	testb	$3, CS-ORIG_RAX(%rsp)
432	jnz	.Lfrom_usermode_switch_stack_\@
433
434	/* paranoid_entry returns GS information for paranoid_exit in EBX. */
435	call	paranoid_entry
436
437	UNWIND_HINT_REGS
438
439	movq	%rsp, %rdi		/* pt_regs pointer */
440
441	call	\cfunc
442
443	jmp	paranoid_exit
444
445	/* Switch to the regular task stack and use the noist entry point */
446.Lfrom_usermode_switch_stack_\@:
447	idtentry_body noist_\cfunc, has_error_code=0
448
449_ASM_NOKPROBE(\asmsym)
450SYM_CODE_END(\asmsym)
451.endm
452
453#ifdef CONFIG_AMD_MEM_ENCRYPT
454/**
455 * idtentry_vc - Macro to generate entry stub for #VC
456 * @vector:		Vector number
457 * @asmsym:		ASM symbol for the entry point
458 * @cfunc:		C function to be called
459 *
460 * The macro emits code to set up the kernel context for #VC. The #VC handler
461 * runs on an IST stack and needs to be able to cause nested #VC exceptions.
462 *
463 * To make this work the #VC entry code tries its best to pretend it doesn't use
464 * an IST stack by switching to the task stack if coming from user-space (which
465 * includes early SYSCALL entry path) or back to the stack in the IRET frame if
466 * entered from kernel-mode.
467 *
468 * If entered from kernel-mode the return stack is validated first, and if it is
469 * not safe to use (e.g. because it points to the entry stack) the #VC handler
470 * will switch to a fall-back stack (VC2) and call a special handler function.
471 *
472 * The macro is only used for one vector, but it is planned to be extended in
473 * the future for the #HV exception.
474 */
475.macro idtentry_vc vector asmsym cfunc
476SYM_CODE_START(\asmsym)
477	UNWIND_HINT_IRET_REGS
478	ENDBR
479	ASM_CLAC
480
481	/*
482	 * If the entry is from userspace, switch stacks and treat it as
483	 * a normal entry.
484	 */
485	testb	$3, CS-ORIG_RAX(%rsp)
486	jnz	.Lfrom_usermode_switch_stack_\@
487
488	/*
489	 * paranoid_entry returns SWAPGS flag for paranoid_exit in EBX.
490	 * EBX == 0 -> SWAPGS, EBX == 1 -> no SWAPGS
491	 */
492	call	paranoid_entry
493
494	UNWIND_HINT_REGS
495
496	/*
497	 * Switch off the IST stack to make it free for nested exceptions. The
498	 * vc_switch_off_ist() function will switch back to the interrupted
499	 * stack if it is safe to do so. If not it switches to the VC fall-back
500	 * stack.
501	 */
502	movq	%rsp, %rdi		/* pt_regs pointer */
503	call	vc_switch_off_ist
504	movq	%rax, %rsp		/* Switch to new stack */
505
506	UNWIND_HINT_REGS
507
508	/* Update pt_regs */
509	movq	ORIG_RAX(%rsp), %rsi	/* get error code into 2nd argument*/
510	movq	$-1, ORIG_RAX(%rsp)	/* no syscall to restart */
511
512	movq	%rsp, %rdi		/* pt_regs pointer */
513
514	call	kernel_\cfunc
515
516	/*
517	 * No need to switch back to the IST stack. The current stack is either
518	 * identical to the stack in the IRET frame or the VC fall-back stack,
519	 * so it is definitely mapped even with PTI enabled.
520	 */
521	jmp	paranoid_exit
522
523	/* Switch to the regular task stack */
524.Lfrom_usermode_switch_stack_\@:
525	idtentry_body user_\cfunc, has_error_code=1
526
527_ASM_NOKPROBE(\asmsym)
528SYM_CODE_END(\asmsym)
529.endm
530#endif
531
532/*
533 * Double fault entry. Straight paranoid. No checks from which context
534 * this comes because for the espfix induced #DF this would do the wrong
535 * thing.
536 */
537.macro idtentry_df vector asmsym cfunc
538SYM_CODE_START(\asmsym)
539	UNWIND_HINT_IRET_REGS offset=8
540	ENDBR
541	ASM_CLAC
542
543	/* paranoid_entry returns GS information for paranoid_exit in EBX. */
544	call	paranoid_entry
545	UNWIND_HINT_REGS
546
547	movq	%rsp, %rdi		/* pt_regs pointer into first argument */
548	movq	ORIG_RAX(%rsp), %rsi	/* get error code into 2nd argument*/
549	movq	$-1, ORIG_RAX(%rsp)	/* no syscall to restart */
550	call	\cfunc
551
552	jmp	paranoid_exit
553
554_ASM_NOKPROBE(\asmsym)
555SYM_CODE_END(\asmsym)
556.endm
557
558/*
559 * Include the defines which emit the idt entries which are shared
560 * shared between 32 and 64 bit and emit the __irqentry_text_* markers
561 * so the stacktrace boundary checks work.
562 */
563	.align 16
564	.globl __irqentry_text_start
565__irqentry_text_start:
566
567#include <asm/idtentry.h>
568
569	.align 16
570	.globl __irqentry_text_end
571__irqentry_text_end:
572
573SYM_CODE_START_LOCAL(common_interrupt_return)
574SYM_INNER_LABEL(swapgs_restore_regs_and_return_to_usermode, SYM_L_GLOBAL)
575#ifdef CONFIG_DEBUG_ENTRY
576	/* Assert that pt_regs indicates user mode. */
577	testb	$3, CS(%rsp)
578	jnz	1f
579	ud2
5801:
581#endif
582#ifdef CONFIG_XEN_PV
583	ALTERNATIVE "", "jmp xenpv_restore_regs_and_return_to_usermode", X86_FEATURE_XENPV
584#endif
585
586	POP_REGS pop_rdi=0
587
588	/*
589	 * The stack is now user RDI, orig_ax, RIP, CS, EFLAGS, RSP, SS.
590	 * Save old stack pointer and switch to trampoline stack.
591	 */
592	movq	%rsp, %rdi
593	movq	PER_CPU_VAR(cpu_tss_rw + TSS_sp0), %rsp
594	UNWIND_HINT_EMPTY
595
596	/* Copy the IRET frame to the trampoline stack. */
597	pushq	6*8(%rdi)	/* SS */
598	pushq	5*8(%rdi)	/* RSP */
599	pushq	4*8(%rdi)	/* EFLAGS */
600	pushq	3*8(%rdi)	/* CS */
601	pushq	2*8(%rdi)	/* RIP */
602
603	/* Push user RDI on the trampoline stack. */
604	pushq	(%rdi)
605
606	/*
607	 * We are on the trampoline stack.  All regs except RDI are live.
608	 * We can do future final exit work right here.
609	 */
610	STACKLEAK_ERASE_NOCLOBBER
611
612	SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
613
614	/* Restore RDI. */
615	popq	%rdi
616	swapgs
617	jmp	.Lnative_iret
618
619
620SYM_INNER_LABEL(restore_regs_and_return_to_kernel, SYM_L_GLOBAL)
621#ifdef CONFIG_DEBUG_ENTRY
622	/* Assert that pt_regs indicates kernel mode. */
623	testb	$3, CS(%rsp)
624	jz	1f
625	ud2
6261:
627#endif
628	POP_REGS
629	addq	$8, %rsp	/* skip regs->orig_ax */
630	/*
631	 * ARCH_HAS_MEMBARRIER_SYNC_CORE rely on IRET core serialization
632	 * when returning from IPI handler.
633	 */
634#ifdef CONFIG_XEN_PV
635SYM_INNER_LABEL(early_xen_iret_patch, SYM_L_GLOBAL)
636	ANNOTATE_NOENDBR
637	.byte 0xe9
638	.long .Lnative_iret - (. + 4)
639#endif
640
641.Lnative_iret:
642	UNWIND_HINT_IRET_REGS
643	/*
644	 * Are we returning to a stack segment from the LDT?  Note: in
645	 * 64-bit mode SS:RSP on the exception stack is always valid.
646	 */
647#ifdef CONFIG_X86_ESPFIX64
648	testb	$4, (SS-RIP)(%rsp)
649	jnz	native_irq_return_ldt
650#endif
651
652SYM_INNER_LABEL(native_irq_return_iret, SYM_L_GLOBAL)
653	/*
654	 * This may fault.  Non-paranoid faults on return to userspace are
655	 * handled by fixup_bad_iret.  These include #SS, #GP, and #NP.
656	 * Double-faults due to espfix64 are handled in exc_double_fault.
657	 * Other faults here are fatal.
658	 */
659	iretq
660
661#ifdef CONFIG_X86_ESPFIX64
662native_irq_return_ldt:
663	/*
664	 * We are running with user GSBASE.  All GPRs contain their user
665	 * values.  We have a percpu ESPFIX stack that is eight slots
666	 * long (see ESPFIX_STACK_SIZE).  espfix_waddr points to the bottom
667	 * of the ESPFIX stack.
668	 *
669	 * We clobber RAX and RDI in this code.  We stash RDI on the
670	 * normal stack and RAX on the ESPFIX stack.
671	 *
672	 * The ESPFIX stack layout we set up looks like this:
673	 *
674	 * --- top of ESPFIX stack ---
675	 * SS
676	 * RSP
677	 * RFLAGS
678	 * CS
679	 * RIP  <-- RSP points here when we're done
680	 * RAX  <-- espfix_waddr points here
681	 * --- bottom of ESPFIX stack ---
682	 */
683
684	pushq	%rdi				/* Stash user RDI */
685	swapgs					/* to kernel GS */
686	SWITCH_TO_KERNEL_CR3 scratch_reg=%rdi	/* to kernel CR3 */
687
688	movq	PER_CPU_VAR(espfix_waddr), %rdi
689	movq	%rax, (0*8)(%rdi)		/* user RAX */
690	movq	(1*8)(%rsp), %rax		/* user RIP */
691	movq	%rax, (1*8)(%rdi)
692	movq	(2*8)(%rsp), %rax		/* user CS */
693	movq	%rax, (2*8)(%rdi)
694	movq	(3*8)(%rsp), %rax		/* user RFLAGS */
695	movq	%rax, (3*8)(%rdi)
696	movq	(5*8)(%rsp), %rax		/* user SS */
697	movq	%rax, (5*8)(%rdi)
698	movq	(4*8)(%rsp), %rax		/* user RSP */
699	movq	%rax, (4*8)(%rdi)
700	/* Now RAX == RSP. */
701
702	andl	$0xffff0000, %eax		/* RAX = (RSP & 0xffff0000) */
703
704	/*
705	 * espfix_stack[31:16] == 0.  The page tables are set up such that
706	 * (espfix_stack | (X & 0xffff0000)) points to a read-only alias of
707	 * espfix_waddr for any X.  That is, there are 65536 RO aliases of
708	 * the same page.  Set up RSP so that RSP[31:16] contains the
709	 * respective 16 bits of the /userspace/ RSP and RSP nonetheless
710	 * still points to an RO alias of the ESPFIX stack.
711	 */
712	orq	PER_CPU_VAR(espfix_stack), %rax
713
714	SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
715	swapgs					/* to user GS */
716	popq	%rdi				/* Restore user RDI */
717
718	movq	%rax, %rsp
719	UNWIND_HINT_IRET_REGS offset=8
720
721	/*
722	 * At this point, we cannot write to the stack any more, but we can
723	 * still read.
724	 */
725	popq	%rax				/* Restore user RAX */
726
727	/*
728	 * RSP now points to an ordinary IRET frame, except that the page
729	 * is read-only and RSP[31:16] are preloaded with the userspace
730	 * values.  We can now IRET back to userspace.
731	 */
732	jmp	native_irq_return_iret
733#endif
734SYM_CODE_END(common_interrupt_return)
735_ASM_NOKPROBE(common_interrupt_return)
736
737/*
738 * Reload gs selector with exception handling
739 * edi:  new selector
740 *
741 * Is in entry.text as it shouldn't be instrumented.
742 */
743SYM_FUNC_START(asm_load_gs_index)
744	FRAME_BEGIN
745	swapgs
746.Lgs_change:
747	movl	%edi, %gs
7482:	ALTERNATIVE "", "mfence", X86_BUG_SWAPGS_FENCE
749	swapgs
750	FRAME_END
751	RET
752
753	/* running with kernelgs */
754.Lbad_gs:
755	swapgs					/* switch back to user gs */
756.macro ZAP_GS
757	/* This can't be a string because the preprocessor needs to see it. */
758	movl $__USER_DS, %eax
759	movl %eax, %gs
760.endm
761	ALTERNATIVE "", "ZAP_GS", X86_BUG_NULL_SEG
762	xorl	%eax, %eax
763	movl	%eax, %gs
764	jmp	2b
765
766	_ASM_EXTABLE(.Lgs_change, .Lbad_gs)
767
768SYM_FUNC_END(asm_load_gs_index)
769EXPORT_SYMBOL(asm_load_gs_index)
770
771#ifdef CONFIG_XEN_PV
772/*
773 * A note on the "critical region" in our callback handler.
774 * We want to avoid stacking callback handlers due to events occurring
775 * during handling of the last event. To do this, we keep events disabled
776 * until we've done all processing. HOWEVER, we must enable events before
777 * popping the stack frame (can't be done atomically) and so it would still
778 * be possible to get enough handler activations to overflow the stack.
779 * Although unlikely, bugs of that kind are hard to track down, so we'd
780 * like to avoid the possibility.
781 * So, on entry to the handler we detect whether we interrupted an
782 * existing activation in its critical region -- if so, we pop the current
783 * activation and restart the handler using the previous one.
784 *
785 * C calling convention: exc_xen_hypervisor_callback(struct *pt_regs)
786 */
787SYM_CODE_START_LOCAL(exc_xen_hypervisor_callback)
788
789/*
790 * Since we don't modify %rdi, evtchn_do_upall(struct *pt_regs) will
791 * see the correct pointer to the pt_regs
792 */
793	UNWIND_HINT_FUNC
794	movq	%rdi, %rsp			/* we don't return, adjust the stack frame */
795	UNWIND_HINT_REGS
796
797	call	xen_pv_evtchn_do_upcall
798
799	jmp	error_return
800SYM_CODE_END(exc_xen_hypervisor_callback)
801
802/*
803 * Hypervisor uses this for application faults while it executes.
804 * We get here for two reasons:
805 *  1. Fault while reloading DS, ES, FS or GS
806 *  2. Fault while executing IRET
807 * Category 1 we do not need to fix up as Xen has already reloaded all segment
808 * registers that could be reloaded and zeroed the others.
809 * Category 2 we fix up by killing the current process. We cannot use the
810 * normal Linux return path in this case because if we use the IRET hypercall
811 * to pop the stack frame we end up in an infinite loop of failsafe callbacks.
812 * We distinguish between categories by comparing each saved segment register
813 * with its current contents: any discrepancy means we in category 1.
814 */
815SYM_CODE_START(xen_failsafe_callback)
816	UNWIND_HINT_EMPTY
817	ENDBR
818	movl	%ds, %ecx
819	cmpw	%cx, 0x10(%rsp)
820	jne	1f
821	movl	%es, %ecx
822	cmpw	%cx, 0x18(%rsp)
823	jne	1f
824	movl	%fs, %ecx
825	cmpw	%cx, 0x20(%rsp)
826	jne	1f
827	movl	%gs, %ecx
828	cmpw	%cx, 0x28(%rsp)
829	jne	1f
830	/* All segments match their saved values => Category 2 (Bad IRET). */
831	movq	(%rsp), %rcx
832	movq	8(%rsp), %r11
833	addq	$0x30, %rsp
834	pushq	$0				/* RIP */
835	UNWIND_HINT_IRET_REGS offset=8
836	jmp	asm_exc_general_protection
8371:	/* Segment mismatch => Category 1 (Bad segment). Retry the IRET. */
838	movq	(%rsp), %rcx
839	movq	8(%rsp), %r11
840	addq	$0x30, %rsp
841	UNWIND_HINT_IRET_REGS
842	pushq	$-1 /* orig_ax = -1 => not a system call */
843	PUSH_AND_CLEAR_REGS
844	ENCODE_FRAME_POINTER
845	jmp	error_return
846SYM_CODE_END(xen_failsafe_callback)
847#endif /* CONFIG_XEN_PV */
848
849/*
850 * Save all registers in pt_regs. Return GSBASE related information
851 * in EBX depending on the availability of the FSGSBASE instructions:
852 *
853 * FSGSBASE	R/EBX
854 *     N        0 -> SWAPGS on exit
855 *              1 -> no SWAPGS on exit
856 *
857 *     Y        GSBASE value at entry, must be restored in paranoid_exit
858 */
859SYM_CODE_START_LOCAL(paranoid_entry)
860	UNWIND_HINT_FUNC
861	cld
862	PUSH_AND_CLEAR_REGS save_ret=1
863	ENCODE_FRAME_POINTER 8
864
865	/*
866	 * Always stash CR3 in %r14.  This value will be restored,
867	 * verbatim, at exit.  Needed if paranoid_entry interrupted
868	 * another entry that already switched to the user CR3 value
869	 * but has not yet returned to userspace.
870	 *
871	 * This is also why CS (stashed in the "iret frame" by the
872	 * hardware at entry) can not be used: this may be a return
873	 * to kernel code, but with a user CR3 value.
874	 *
875	 * Switching CR3 does not depend on kernel GSBASE so it can
876	 * be done before switching to the kernel GSBASE. This is
877	 * required for FSGSBASE because the kernel GSBASE has to
878	 * be retrieved from a kernel internal table.
879	 */
880	SAVE_AND_SWITCH_TO_KERNEL_CR3 scratch_reg=%rax save_reg=%r14
881
882	/*
883	 * Handling GSBASE depends on the availability of FSGSBASE.
884	 *
885	 * Without FSGSBASE the kernel enforces that negative GSBASE
886	 * values indicate kernel GSBASE. With FSGSBASE no assumptions
887	 * can be made about the GSBASE value when entering from user
888	 * space.
889	 */
890	ALTERNATIVE "jmp .Lparanoid_entry_checkgs", "", X86_FEATURE_FSGSBASE
891
892	/*
893	 * Read the current GSBASE and store it in %rbx unconditionally,
894	 * retrieve and set the current CPUs kernel GSBASE. The stored value
895	 * has to be restored in paranoid_exit unconditionally.
896	 *
897	 * The unconditional write to GS base below ensures that no subsequent
898	 * loads based on a mispredicted GS base can happen, therefore no LFENCE
899	 * is needed here.
900	 */
901	SAVE_AND_SET_GSBASE scratch_reg=%rax save_reg=%rbx
902	RET
903
904.Lparanoid_entry_checkgs:
905	/* EBX = 1 -> kernel GSBASE active, no restore required */
906	movl	$1, %ebx
907
908	/*
909	 * The kernel-enforced convention is a negative GSBASE indicates
910	 * a kernel value. No SWAPGS needed on entry and exit.
911	 */
912	movl	$MSR_GS_BASE, %ecx
913	rdmsr
914	testl	%edx, %edx
915	js	.Lparanoid_kernel_gsbase
916
917	/* EBX = 0 -> SWAPGS required on exit */
918	xorl	%ebx, %ebx
919	swapgs
920.Lparanoid_kernel_gsbase:
921
922	FENCE_SWAPGS_KERNEL_ENTRY
923	RET
924SYM_CODE_END(paranoid_entry)
925
926/*
927 * "Paranoid" exit path from exception stack.  This is invoked
928 * only on return from non-NMI IST interrupts that came
929 * from kernel space.
930 *
931 * We may be returning to very strange contexts (e.g. very early
932 * in syscall entry), so checking for preemption here would
933 * be complicated.  Fortunately, there's no good reason to try
934 * to handle preemption here.
935 *
936 * R/EBX contains the GSBASE related information depending on the
937 * availability of the FSGSBASE instructions:
938 *
939 * FSGSBASE	R/EBX
940 *     N        0 -> SWAPGS on exit
941 *              1 -> no SWAPGS on exit
942 *
943 *     Y        User space GSBASE, must be restored unconditionally
944 */
945SYM_CODE_START_LOCAL(paranoid_exit)
946	UNWIND_HINT_REGS
947	/*
948	 * The order of operations is important. RESTORE_CR3 requires
949	 * kernel GSBASE.
950	 *
951	 * NB to anyone to try to optimize this code: this code does
952	 * not execute at all for exceptions from user mode. Those
953	 * exceptions go through error_exit instead.
954	 */
955	RESTORE_CR3	scratch_reg=%rax save_reg=%r14
956
957	/* Handle the three GSBASE cases */
958	ALTERNATIVE "jmp .Lparanoid_exit_checkgs", "", X86_FEATURE_FSGSBASE
959
960	/* With FSGSBASE enabled, unconditionally restore GSBASE */
961	wrgsbase	%rbx
962	jmp		restore_regs_and_return_to_kernel
963
964.Lparanoid_exit_checkgs:
965	/* On non-FSGSBASE systems, conditionally do SWAPGS */
966	testl		%ebx, %ebx
967	jnz		restore_regs_and_return_to_kernel
968
969	/* We are returning to a context with user GSBASE */
970	swapgs
971	jmp		restore_regs_and_return_to_kernel
972SYM_CODE_END(paranoid_exit)
973
974/*
975 * Save all registers in pt_regs, and switch GS if needed.
976 */
977SYM_CODE_START_LOCAL(error_entry)
978	UNWIND_HINT_FUNC
979	cld
980	PUSH_AND_CLEAR_REGS save_ret=1
981	ENCODE_FRAME_POINTER 8
982	testb	$3, CS+8(%rsp)
983	jz	.Lerror_kernelspace
984
985	/*
986	 * We entered from user mode or we're pretending to have entered
987	 * from user mode due to an IRET fault.
988	 */
989	SWAPGS
990	FENCE_SWAPGS_USER_ENTRY
991	/* We have user CR3.  Change to kernel CR3. */
992	SWITCH_TO_KERNEL_CR3 scratch_reg=%rax
993
994.Lerror_entry_from_usermode_after_swapgs:
995	/* Put us onto the real thread stack. */
996	popq	%r12				/* save return addr in %12 */
997	movq	%rsp, %rdi			/* arg0 = pt_regs pointer */
998	call	sync_regs
999	movq	%rax, %rsp			/* switch stack */
1000	ENCODE_FRAME_POINTER
1001	pushq	%r12
1002	RET
1003
1004	/*
1005	 * There are two places in the kernel that can potentially fault with
1006	 * usergs. Handle them here.  B stepping K8s sometimes report a
1007	 * truncated RIP for IRET exceptions returning to compat mode. Check
1008	 * for these here too.
1009	 */
1010.Lerror_kernelspace:
1011	leaq	native_irq_return_iret(%rip), %rcx
1012	cmpq	%rcx, RIP+8(%rsp)
1013	je	.Lerror_bad_iret
1014	movl	%ecx, %eax			/* zero extend */
1015	cmpq	%rax, RIP+8(%rsp)
1016	je	.Lbstep_iret
1017	cmpq	$.Lgs_change, RIP+8(%rsp)
1018	jne	.Lerror_entry_done_lfence
1019
1020	/*
1021	 * hack: .Lgs_change can fail with user gsbase.  If this happens, fix up
1022	 * gsbase and proceed.  We'll fix up the exception and land in
1023	 * .Lgs_change's error handler with kernel gsbase.
1024	 */
1025	SWAPGS
1026
1027	/*
1028	 * Issue an LFENCE to prevent GS speculation, regardless of whether it is a
1029	 * kernel or user gsbase.
1030	 */
1031.Lerror_entry_done_lfence:
1032	FENCE_SWAPGS_KERNEL_ENTRY
1033	RET
1034
1035.Lbstep_iret:
1036	/* Fix truncated RIP */
1037	movq	%rcx, RIP+8(%rsp)
1038	/* fall through */
1039
1040.Lerror_bad_iret:
1041	/*
1042	 * We came from an IRET to user mode, so we have user
1043	 * gsbase and CR3.  Switch to kernel gsbase and CR3:
1044	 */
1045	SWAPGS
1046	FENCE_SWAPGS_USER_ENTRY
1047	SWITCH_TO_KERNEL_CR3 scratch_reg=%rax
1048
1049	/*
1050	 * Pretend that the exception came from user mode: set up pt_regs
1051	 * as if we faulted immediately after IRET.
1052	 */
1053	mov	%rsp, %rdi
1054	call	fixup_bad_iret
1055	mov	%rax, %rsp
1056	jmp	.Lerror_entry_from_usermode_after_swapgs
1057SYM_CODE_END(error_entry)
1058
1059SYM_CODE_START_LOCAL(error_return)
1060	UNWIND_HINT_REGS
1061	DEBUG_ENTRY_ASSERT_IRQS_OFF
1062	testb	$3, CS(%rsp)
1063	jz	restore_regs_and_return_to_kernel
1064	jmp	swapgs_restore_regs_and_return_to_usermode
1065SYM_CODE_END(error_return)
1066
1067/*
1068 * Runs on exception stack.  Xen PV does not go through this path at all,
1069 * so we can use real assembly here.
1070 *
1071 * Registers:
1072 *	%r14: Used to save/restore the CR3 of the interrupted context
1073 *	      when PAGE_TABLE_ISOLATION is in use.  Do not clobber.
1074 */
1075SYM_CODE_START(asm_exc_nmi)
1076	UNWIND_HINT_IRET_REGS
1077	ENDBR
1078
1079	/*
1080	 * We allow breakpoints in NMIs. If a breakpoint occurs, then
1081	 * the iretq it performs will take us out of NMI context.
1082	 * This means that we can have nested NMIs where the next
1083	 * NMI is using the top of the stack of the previous NMI. We
1084	 * can't let it execute because the nested NMI will corrupt the
1085	 * stack of the previous NMI. NMI handlers are not re-entrant
1086	 * anyway.
1087	 *
1088	 * To handle this case we do the following:
1089	 *  Check the a special location on the stack that contains
1090	 *  a variable that is set when NMIs are executing.
1091	 *  The interrupted task's stack is also checked to see if it
1092	 *  is an NMI stack.
1093	 *  If the variable is not set and the stack is not the NMI
1094	 *  stack then:
1095	 *    o Set the special variable on the stack
1096	 *    o Copy the interrupt frame into an "outermost" location on the
1097	 *      stack
1098	 *    o Copy the interrupt frame into an "iret" location on the stack
1099	 *    o Continue processing the NMI
1100	 *  If the variable is set or the previous stack is the NMI stack:
1101	 *    o Modify the "iret" location to jump to the repeat_nmi
1102	 *    o return back to the first NMI
1103	 *
1104	 * Now on exit of the first NMI, we first clear the stack variable
1105	 * The NMI stack will tell any nested NMIs at that point that it is
1106	 * nested. Then we pop the stack normally with iret, and if there was
1107	 * a nested NMI that updated the copy interrupt stack frame, a
1108	 * jump will be made to the repeat_nmi code that will handle the second
1109	 * NMI.
1110	 *
1111	 * However, espfix prevents us from directly returning to userspace
1112	 * with a single IRET instruction.  Similarly, IRET to user mode
1113	 * can fault.  We therefore handle NMIs from user space like
1114	 * other IST entries.
1115	 */
1116
1117	ASM_CLAC
1118
1119	/* Use %rdx as our temp variable throughout */
1120	pushq	%rdx
1121
1122	testb	$3, CS-RIP+8(%rsp)
1123	jz	.Lnmi_from_kernel
1124
1125	/*
1126	 * NMI from user mode.  We need to run on the thread stack, but we
1127	 * can't go through the normal entry paths: NMIs are masked, and
1128	 * we don't want to enable interrupts, because then we'll end
1129	 * up in an awkward situation in which IRQs are on but NMIs
1130	 * are off.
1131	 *
1132	 * We also must not push anything to the stack before switching
1133	 * stacks lest we corrupt the "NMI executing" variable.
1134	 */
1135
1136	swapgs
1137	cld
1138	FENCE_SWAPGS_USER_ENTRY
1139	SWITCH_TO_KERNEL_CR3 scratch_reg=%rdx
1140	movq	%rsp, %rdx
1141	movq	PER_CPU_VAR(cpu_current_top_of_stack), %rsp
1142	UNWIND_HINT_IRET_REGS base=%rdx offset=8
1143	pushq	5*8(%rdx)	/* pt_regs->ss */
1144	pushq	4*8(%rdx)	/* pt_regs->rsp */
1145	pushq	3*8(%rdx)	/* pt_regs->flags */
1146	pushq	2*8(%rdx)	/* pt_regs->cs */
1147	pushq	1*8(%rdx)	/* pt_regs->rip */
1148	UNWIND_HINT_IRET_REGS
1149	pushq   $-1		/* pt_regs->orig_ax */
1150	PUSH_AND_CLEAR_REGS rdx=(%rdx)
1151	ENCODE_FRAME_POINTER
1152
1153	/*
1154	 * At this point we no longer need to worry about stack damage
1155	 * due to nesting -- we're on the normal thread stack and we're
1156	 * done with the NMI stack.
1157	 */
1158
1159	movq	%rsp, %rdi
1160	movq	$-1, %rsi
1161	call	exc_nmi
1162
1163	/*
1164	 * Return back to user mode.  We must *not* do the normal exit
1165	 * work, because we don't want to enable interrupts.
1166	 */
1167	jmp	swapgs_restore_regs_and_return_to_usermode
1168
1169.Lnmi_from_kernel:
1170	/*
1171	 * Here's what our stack frame will look like:
1172	 * +---------------------------------------------------------+
1173	 * | original SS                                             |
1174	 * | original Return RSP                                     |
1175	 * | original RFLAGS                                         |
1176	 * | original CS                                             |
1177	 * | original RIP                                            |
1178	 * +---------------------------------------------------------+
1179	 * | temp storage for rdx                                    |
1180	 * +---------------------------------------------------------+
1181	 * | "NMI executing" variable                                |
1182	 * +---------------------------------------------------------+
1183	 * | iret SS          } Copied from "outermost" frame        |
1184	 * | iret Return RSP  } on each loop iteration; overwritten  |
1185	 * | iret RFLAGS      } by a nested NMI to force another     |
1186	 * | iret CS          } iteration if needed.                 |
1187	 * | iret RIP         }                                      |
1188	 * +---------------------------------------------------------+
1189	 * | outermost SS          } initialized in first_nmi;       |
1190	 * | outermost Return RSP  } will not be changed before      |
1191	 * | outermost RFLAGS      } NMI processing is done.         |
1192	 * | outermost CS          } Copied to "iret" frame on each  |
1193	 * | outermost RIP         } iteration.                      |
1194	 * +---------------------------------------------------------+
1195	 * | pt_regs                                                 |
1196	 * +---------------------------------------------------------+
1197	 *
1198	 * The "original" frame is used by hardware.  Before re-enabling
1199	 * NMIs, we need to be done with it, and we need to leave enough
1200	 * space for the asm code here.
1201	 *
1202	 * We return by executing IRET while RSP points to the "iret" frame.
1203	 * That will either return for real or it will loop back into NMI
1204	 * processing.
1205	 *
1206	 * The "outermost" frame is copied to the "iret" frame on each
1207	 * iteration of the loop, so each iteration starts with the "iret"
1208	 * frame pointing to the final return target.
1209	 */
1210
1211	/*
1212	 * Determine whether we're a nested NMI.
1213	 *
1214	 * If we interrupted kernel code between repeat_nmi and
1215	 * end_repeat_nmi, then we are a nested NMI.  We must not
1216	 * modify the "iret" frame because it's being written by
1217	 * the outer NMI.  That's okay; the outer NMI handler is
1218	 * about to about to call exc_nmi() anyway, so we can just
1219	 * resume the outer NMI.
1220	 */
1221
1222	movq	$repeat_nmi, %rdx
1223	cmpq	8(%rsp), %rdx
1224	ja	1f
1225	movq	$end_repeat_nmi, %rdx
1226	cmpq	8(%rsp), %rdx
1227	ja	nested_nmi_out
12281:
1229
1230	/*
1231	 * Now check "NMI executing".  If it's set, then we're nested.
1232	 * This will not detect if we interrupted an outer NMI just
1233	 * before IRET.
1234	 */
1235	cmpl	$1, -8(%rsp)
1236	je	nested_nmi
1237
1238	/*
1239	 * Now test if the previous stack was an NMI stack.  This covers
1240	 * the case where we interrupt an outer NMI after it clears
1241	 * "NMI executing" but before IRET.  We need to be careful, though:
1242	 * there is one case in which RSP could point to the NMI stack
1243	 * despite there being no NMI active: naughty userspace controls
1244	 * RSP at the very beginning of the SYSCALL targets.  We can
1245	 * pull a fast one on naughty userspace, though: we program
1246	 * SYSCALL to mask DF, so userspace cannot cause DF to be set
1247	 * if it controls the kernel's RSP.  We set DF before we clear
1248	 * "NMI executing".
1249	 */
1250	lea	6*8(%rsp), %rdx
1251	/* Compare the NMI stack (rdx) with the stack we came from (4*8(%rsp)) */
1252	cmpq	%rdx, 4*8(%rsp)
1253	/* If the stack pointer is above the NMI stack, this is a normal NMI */
1254	ja	first_nmi
1255
1256	subq	$EXCEPTION_STKSZ, %rdx
1257	cmpq	%rdx, 4*8(%rsp)
1258	/* If it is below the NMI stack, it is a normal NMI */
1259	jb	first_nmi
1260
1261	/* Ah, it is within the NMI stack. */
1262
1263	testb	$(X86_EFLAGS_DF >> 8), (3*8 + 1)(%rsp)
1264	jz	first_nmi	/* RSP was user controlled. */
1265
1266	/* This is a nested NMI. */
1267
1268nested_nmi:
1269	/*
1270	 * Modify the "iret" frame to point to repeat_nmi, forcing another
1271	 * iteration of NMI handling.
1272	 */
1273	subq	$8, %rsp
1274	leaq	-10*8(%rsp), %rdx
1275	pushq	$__KERNEL_DS
1276	pushq	%rdx
1277	pushfq
1278	pushq	$__KERNEL_CS
1279	pushq	$repeat_nmi
1280
1281	/* Put stack back */
1282	addq	$(6*8), %rsp
1283
1284nested_nmi_out:
1285	popq	%rdx
1286
1287	/* We are returning to kernel mode, so this cannot result in a fault. */
1288	iretq
1289
1290first_nmi:
1291	/* Restore rdx. */
1292	movq	(%rsp), %rdx
1293
1294	/* Make room for "NMI executing". */
1295	pushq	$0
1296
1297	/* Leave room for the "iret" frame */
1298	subq	$(5*8), %rsp
1299
1300	/* Copy the "original" frame to the "outermost" frame */
1301	.rept 5
1302	pushq	11*8(%rsp)
1303	.endr
1304	UNWIND_HINT_IRET_REGS
1305
1306	/* Everything up to here is safe from nested NMIs */
1307
1308#ifdef CONFIG_DEBUG_ENTRY
1309	/*
1310	 * For ease of testing, unmask NMIs right away.  Disabled by
1311	 * default because IRET is very expensive.
1312	 */
1313	pushq	$0		/* SS */
1314	pushq	%rsp		/* RSP (minus 8 because of the previous push) */
1315	addq	$8, (%rsp)	/* Fix up RSP */
1316	pushfq			/* RFLAGS */
1317	pushq	$__KERNEL_CS	/* CS */
1318	pushq	$1f		/* RIP */
1319	iretq			/* continues at repeat_nmi below */
1320	UNWIND_HINT_IRET_REGS
13211:
1322#endif
1323
1324repeat_nmi:
1325	/*
1326	 * If there was a nested NMI, the first NMI's iret will return
1327	 * here. But NMIs are still enabled and we can take another
1328	 * nested NMI. The nested NMI checks the interrupted RIP to see
1329	 * if it is between repeat_nmi and end_repeat_nmi, and if so
1330	 * it will just return, as we are about to repeat an NMI anyway.
1331	 * This makes it safe to copy to the stack frame that a nested
1332	 * NMI will update.
1333	 *
1334	 * RSP is pointing to "outermost RIP".  gsbase is unknown, but, if
1335	 * we're repeating an NMI, gsbase has the same value that it had on
1336	 * the first iteration.  paranoid_entry will load the kernel
1337	 * gsbase if needed before we call exc_nmi().  "NMI executing"
1338	 * is zero.
1339	 */
1340	movq	$1, 10*8(%rsp)		/* Set "NMI executing". */
1341
1342	/*
1343	 * Copy the "outermost" frame to the "iret" frame.  NMIs that nest
1344	 * here must not modify the "iret" frame while we're writing to
1345	 * it or it will end up containing garbage.
1346	 */
1347	addq	$(10*8), %rsp
1348	.rept 5
1349	pushq	-6*8(%rsp)
1350	.endr
1351	subq	$(5*8), %rsp
1352end_repeat_nmi:
1353
1354	/*
1355	 * Everything below this point can be preempted by a nested NMI.
1356	 * If this happens, then the inner NMI will change the "iret"
1357	 * frame to point back to repeat_nmi.
1358	 */
1359	pushq	$-1				/* ORIG_RAX: no syscall to restart */
1360
1361	/*
1362	 * Use paranoid_entry to handle SWAPGS, but no need to use paranoid_exit
1363	 * as we should not be calling schedule in NMI context.
1364	 * Even with normal interrupts enabled. An NMI should not be
1365	 * setting NEED_RESCHED or anything that normal interrupts and
1366	 * exceptions might do.
1367	 */
1368	call	paranoid_entry
1369	UNWIND_HINT_REGS
1370
1371	movq	%rsp, %rdi
1372	movq	$-1, %rsi
1373	call	exc_nmi
1374
1375	/* Always restore stashed CR3 value (see paranoid_entry) */
1376	RESTORE_CR3 scratch_reg=%r15 save_reg=%r14
1377
1378	/*
1379	 * The above invocation of paranoid_entry stored the GSBASE
1380	 * related information in R/EBX depending on the availability
1381	 * of FSGSBASE.
1382	 *
1383	 * If FSGSBASE is enabled, restore the saved GSBASE value
1384	 * unconditionally, otherwise take the conditional SWAPGS path.
1385	 */
1386	ALTERNATIVE "jmp nmi_no_fsgsbase", "", X86_FEATURE_FSGSBASE
1387
1388	wrgsbase	%rbx
1389	jmp	nmi_restore
1390
1391nmi_no_fsgsbase:
1392	/* EBX == 0 -> invoke SWAPGS */
1393	testl	%ebx, %ebx
1394	jnz	nmi_restore
1395
1396nmi_swapgs:
1397	swapgs
1398
1399nmi_restore:
1400	POP_REGS
1401
1402	/*
1403	 * Skip orig_ax and the "outermost" frame to point RSP at the "iret"
1404	 * at the "iret" frame.
1405	 */
1406	addq	$6*8, %rsp
1407
1408	/*
1409	 * Clear "NMI executing".  Set DF first so that we can easily
1410	 * distinguish the remaining code between here and IRET from
1411	 * the SYSCALL entry and exit paths.
1412	 *
1413	 * We arguably should just inspect RIP instead, but I (Andy) wrote
1414	 * this code when I had the misapprehension that Xen PV supported
1415	 * NMIs, and Xen PV would break that approach.
1416	 */
1417	std
1418	movq	$0, 5*8(%rsp)		/* clear "NMI executing" */
1419
1420	/*
1421	 * iretq reads the "iret" frame and exits the NMI stack in a
1422	 * single instruction.  We are returning to kernel mode, so this
1423	 * cannot result in a fault.  Similarly, we don't need to worry
1424	 * about espfix64 on the way back to kernel mode.
1425	 */
1426	iretq
1427SYM_CODE_END(asm_exc_nmi)
1428
1429#ifndef CONFIG_IA32_EMULATION
1430/*
1431 * This handles SYSCALL from 32-bit code.  There is no way to program
1432 * MSRs to fully disable 32-bit SYSCALL.
1433 */
1434SYM_CODE_START(ignore_sysret)
1435	UNWIND_HINT_EMPTY
1436	ENDBR
1437	mov	$-ENOSYS, %eax
1438	sysretl
1439SYM_CODE_END(ignore_sysret)
1440#endif
1441
1442.pushsection .text, "ax"
1443SYM_CODE_START(rewind_stack_and_make_dead)
1444	UNWIND_HINT_FUNC
1445	/* Prevent any naive code from trying to unwind to our caller. */
1446	xorl	%ebp, %ebp
1447
1448	movq	PER_CPU_VAR(cpu_current_top_of_stack), %rax
1449	leaq	-PTREGS_SIZE(%rax), %rsp
1450	UNWIND_HINT_REGS
1451
1452	call	make_task_dead
1453SYM_CODE_END(rewind_stack_and_make_dead)
1454.popsection
1455