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