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