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