xref: /openbmc/linux/arch/x86/entry/entry_64.S (revision b24413180f5600bcb3bb70fbed5cf186b60864bd)
1/* SPDX-License-Identifier: GPL-2.0 */
2/*
3 *  linux/arch/x86_64/entry.S
4 *
5 *  Copyright (C) 1991, 1992  Linus Torvalds
6 *  Copyright (C) 2000, 2001, 2002  Andi Kleen SuSE Labs
7 *  Copyright (C) 2000  Pavel Machek <pavel@suse.cz>
8 *
9 * entry.S contains the system-call and fault low-level handling routines.
10 *
11 * Some of this is documented in Documentation/x86/entry_64.txt
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 * - ENTRY/END:		Define functions in the symbol table.
19 * - TRACE_IRQ_*:	Trace hardirq state for lock debugging.
20 * - idtentry:		Define exception entry points.
21 */
22#include <linux/linkage.h>
23#include <asm/segment.h>
24#include <asm/cache.h>
25#include <asm/errno.h>
26#include "calling.h"
27#include <asm/asm-offsets.h>
28#include <asm/msr.h>
29#include <asm/unistd.h>
30#include <asm/thread_info.h>
31#include <asm/hw_irq.h>
32#include <asm/page_types.h>
33#include <asm/irqflags.h>
34#include <asm/paravirt.h>
35#include <asm/percpu.h>
36#include <asm/asm.h>
37#include <asm/smap.h>
38#include <asm/pgtable_types.h>
39#include <asm/export.h>
40#include <asm/frame.h>
41#include <linux/err.h>
42
43.code64
44.section .entry.text, "ax"
45
46#ifdef CONFIG_PARAVIRT
47ENTRY(native_usergs_sysret64)
48	UNWIND_HINT_EMPTY
49	swapgs
50	sysretq
51END(native_usergs_sysret64)
52#endif /* CONFIG_PARAVIRT */
53
54.macro TRACE_IRQS_IRETQ
55#ifdef CONFIG_TRACE_IRQFLAGS
56	bt	$9, EFLAGS(%rsp)		/* interrupts off? */
57	jnc	1f
58	TRACE_IRQS_ON
591:
60#endif
61.endm
62
63/*
64 * When dynamic function tracer is enabled it will add a breakpoint
65 * to all locations that it is about to modify, sync CPUs, update
66 * all the code, sync CPUs, then remove the breakpoints. In this time
67 * if lockdep is enabled, it might jump back into the debug handler
68 * outside the updating of the IST protection. (TRACE_IRQS_ON/OFF).
69 *
70 * We need to change the IDT table before calling TRACE_IRQS_ON/OFF to
71 * make sure the stack pointer does not get reset back to the top
72 * of the debug stack, and instead just reuses the current stack.
73 */
74#if defined(CONFIG_DYNAMIC_FTRACE) && defined(CONFIG_TRACE_IRQFLAGS)
75
76.macro TRACE_IRQS_OFF_DEBUG
77	call	debug_stack_set_zero
78	TRACE_IRQS_OFF
79	call	debug_stack_reset
80.endm
81
82.macro TRACE_IRQS_ON_DEBUG
83	call	debug_stack_set_zero
84	TRACE_IRQS_ON
85	call	debug_stack_reset
86.endm
87
88.macro TRACE_IRQS_IRETQ_DEBUG
89	bt	$9, EFLAGS(%rsp)		/* interrupts off? */
90	jnc	1f
91	TRACE_IRQS_ON_DEBUG
921:
93.endm
94
95#else
96# define TRACE_IRQS_OFF_DEBUG			TRACE_IRQS_OFF
97# define TRACE_IRQS_ON_DEBUG			TRACE_IRQS_ON
98# define TRACE_IRQS_IRETQ_DEBUG			TRACE_IRQS_IRETQ
99#endif
100
101/*
102 * 64-bit SYSCALL instruction entry. Up to 6 arguments in registers.
103 *
104 * This is the only entry point used for 64-bit system calls.  The
105 * hardware interface is reasonably well designed and the register to
106 * argument mapping Linux uses fits well with the registers that are
107 * available when SYSCALL is used.
108 *
109 * SYSCALL instructions can be found inlined in libc implementations as
110 * well as some other programs and libraries.  There are also a handful
111 * of SYSCALL instructions in the vDSO used, for example, as a
112 * clock_gettimeofday fallback.
113 *
114 * 64-bit SYSCALL saves rip to rcx, clears rflags.RF, then saves rflags to r11,
115 * then loads new ss, cs, and rip from previously programmed MSRs.
116 * rflags gets masked by a value from another MSR (so CLD and CLAC
117 * are not needed). SYSCALL does not save anything on the stack
118 * and does not change rsp.
119 *
120 * Registers on entry:
121 * rax  system call number
122 * rcx  return address
123 * r11  saved rflags (note: r11 is callee-clobbered register in C ABI)
124 * rdi  arg0
125 * rsi  arg1
126 * rdx  arg2
127 * r10  arg3 (needs to be moved to rcx to conform to C ABI)
128 * r8   arg4
129 * r9   arg5
130 * (note: r12-r15, rbp, rbx are callee-preserved in C ABI)
131 *
132 * Only called from user space.
133 *
134 * When user can change pt_regs->foo always force IRET. That is because
135 * it deals with uncanonical addresses better. SYSRET has trouble
136 * with them due to bugs in both AMD and Intel CPUs.
137 */
138
139ENTRY(entry_SYSCALL_64)
140	UNWIND_HINT_EMPTY
141	/*
142	 * Interrupts are off on entry.
143	 * We do not frame this tiny irq-off block with TRACE_IRQS_OFF/ON,
144	 * it is too small to ever cause noticeable irq latency.
145	 */
146
147	swapgs
148	movq	%rsp, PER_CPU_VAR(rsp_scratch)
149	movq	PER_CPU_VAR(cpu_current_top_of_stack), %rsp
150
151	TRACE_IRQS_OFF
152
153	/* Construct struct pt_regs on stack */
154	pushq	$__USER_DS			/* pt_regs->ss */
155	pushq	PER_CPU_VAR(rsp_scratch)	/* pt_regs->sp */
156	pushq	%r11				/* pt_regs->flags */
157	pushq	$__USER_CS			/* pt_regs->cs */
158	pushq	%rcx				/* pt_regs->ip */
159GLOBAL(entry_SYSCALL_64_after_hwframe)
160	pushq	%rax				/* pt_regs->orig_ax */
161	pushq	%rdi				/* pt_regs->di */
162	pushq	%rsi				/* pt_regs->si */
163	pushq	%rdx				/* pt_regs->dx */
164	pushq	%rcx				/* pt_regs->cx */
165	pushq	$-ENOSYS			/* pt_regs->ax */
166	pushq	%r8				/* pt_regs->r8 */
167	pushq	%r9				/* pt_regs->r9 */
168	pushq	%r10				/* pt_regs->r10 */
169	pushq	%r11				/* pt_regs->r11 */
170	sub	$(6*8), %rsp			/* pt_regs->bp, bx, r12-15 not saved */
171	UNWIND_HINT_REGS extra=0
172
173	/*
174	 * If we need to do entry work or if we guess we'll need to do
175	 * exit work, go straight to the slow path.
176	 */
177	movq	PER_CPU_VAR(current_task), %r11
178	testl	$_TIF_WORK_SYSCALL_ENTRY|_TIF_ALLWORK_MASK, TASK_TI_flags(%r11)
179	jnz	entry_SYSCALL64_slow_path
180
181entry_SYSCALL_64_fastpath:
182	/*
183	 * Easy case: enable interrupts and issue the syscall.  If the syscall
184	 * needs pt_regs, we'll call a stub that disables interrupts again
185	 * and jumps to the slow path.
186	 */
187	TRACE_IRQS_ON
188	ENABLE_INTERRUPTS(CLBR_NONE)
189#if __SYSCALL_MASK == ~0
190	cmpq	$__NR_syscall_max, %rax
191#else
192	andl	$__SYSCALL_MASK, %eax
193	cmpl	$__NR_syscall_max, %eax
194#endif
195	ja	1f				/* return -ENOSYS (already in pt_regs->ax) */
196	movq	%r10, %rcx
197
198	/*
199	 * This call instruction is handled specially in stub_ptregs_64.
200	 * It might end up jumping to the slow path.  If it jumps, RAX
201	 * and all argument registers are clobbered.
202	 */
203	call	*sys_call_table(, %rax, 8)
204.Lentry_SYSCALL_64_after_fastpath_call:
205
206	movq	%rax, RAX(%rsp)
2071:
208
209	/*
210	 * If we get here, then we know that pt_regs is clean for SYSRET64.
211	 * If we see that no exit work is required (which we are required
212	 * to check with IRQs off), then we can go straight to SYSRET64.
213	 */
214	DISABLE_INTERRUPTS(CLBR_ANY)
215	TRACE_IRQS_OFF
216	movq	PER_CPU_VAR(current_task), %r11
217	testl	$_TIF_ALLWORK_MASK, TASK_TI_flags(%r11)
218	jnz	1f
219
220	LOCKDEP_SYS_EXIT
221	TRACE_IRQS_ON		/* user mode is traced as IRQs on */
222	movq	RIP(%rsp), %rcx
223	movq	EFLAGS(%rsp), %r11
224	RESTORE_C_REGS_EXCEPT_RCX_R11
225	movq	RSP(%rsp), %rsp
226	UNWIND_HINT_EMPTY
227	USERGS_SYSRET64
228
2291:
230	/*
231	 * The fast path looked good when we started, but something changed
232	 * along the way and we need to switch to the slow path.  Calling
233	 * raise(3) will trigger this, for example.  IRQs are off.
234	 */
235	TRACE_IRQS_ON
236	ENABLE_INTERRUPTS(CLBR_ANY)
237	SAVE_EXTRA_REGS
238	movq	%rsp, %rdi
239	call	syscall_return_slowpath	/* returns with IRQs disabled */
240	jmp	return_from_SYSCALL_64
241
242entry_SYSCALL64_slow_path:
243	/* IRQs are off. */
244	SAVE_EXTRA_REGS
245	movq	%rsp, %rdi
246	call	do_syscall_64		/* returns with IRQs disabled */
247
248return_from_SYSCALL_64:
249	RESTORE_EXTRA_REGS
250	TRACE_IRQS_IRETQ		/* we're about to change IF */
251
252	/*
253	 * Try to use SYSRET instead of IRET if we're returning to
254	 * a completely clean 64-bit userspace context.
255	 */
256	movq	RCX(%rsp), %rcx
257	movq	RIP(%rsp), %r11
258	cmpq	%rcx, %r11			/* RCX == RIP */
259	jne	opportunistic_sysret_failed
260
261	/*
262	 * On Intel CPUs, SYSRET with non-canonical RCX/RIP will #GP
263	 * in kernel space.  This essentially lets the user take over
264	 * the kernel, since userspace controls RSP.
265	 *
266	 * If width of "canonical tail" ever becomes variable, this will need
267	 * to be updated to remain correct on both old and new CPUs.
268	 *
269	 * Change top bits to match most significant bit (47th or 56th bit
270	 * depending on paging mode) in the address.
271	 */
272	shl	$(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
273	sar	$(64 - (__VIRTUAL_MASK_SHIFT+1)), %rcx
274
275	/* If this changed %rcx, it was not canonical */
276	cmpq	%rcx, %r11
277	jne	opportunistic_sysret_failed
278
279	cmpq	$__USER_CS, CS(%rsp)		/* CS must match SYSRET */
280	jne	opportunistic_sysret_failed
281
282	movq	R11(%rsp), %r11
283	cmpq	%r11, EFLAGS(%rsp)		/* R11 == RFLAGS */
284	jne	opportunistic_sysret_failed
285
286	/*
287	 * SYSCALL clears RF when it saves RFLAGS in R11 and SYSRET cannot
288	 * restore RF properly. If the slowpath sets it for whatever reason, we
289	 * need to restore it correctly.
290	 *
291	 * SYSRET can restore TF, but unlike IRET, restoring TF results in a
292	 * trap from userspace immediately after SYSRET.  This would cause an
293	 * infinite loop whenever #DB happens with register state that satisfies
294	 * the opportunistic SYSRET conditions.  For example, single-stepping
295	 * this user code:
296	 *
297	 *           movq	$stuck_here, %rcx
298	 *           pushfq
299	 *           popq %r11
300	 *   stuck_here:
301	 *
302	 * would never get past 'stuck_here'.
303	 */
304	testq	$(X86_EFLAGS_RF|X86_EFLAGS_TF), %r11
305	jnz	opportunistic_sysret_failed
306
307	/* nothing to check for RSP */
308
309	cmpq	$__USER_DS, SS(%rsp)		/* SS must match SYSRET */
310	jne	opportunistic_sysret_failed
311
312	/*
313	 * We win! This label is here just for ease of understanding
314	 * perf profiles. Nothing jumps here.
315	 */
316syscall_return_via_sysret:
317	/* rcx and r11 are already restored (see code above) */
318	RESTORE_C_REGS_EXCEPT_RCX_R11
319	movq	RSP(%rsp), %rsp
320	UNWIND_HINT_EMPTY
321	USERGS_SYSRET64
322
323opportunistic_sysret_failed:
324	SWAPGS
325	jmp	restore_c_regs_and_iret
326END(entry_SYSCALL_64)
327
328ENTRY(stub_ptregs_64)
329	/*
330	 * Syscalls marked as needing ptregs land here.
331	 * If we are on the fast path, we need to save the extra regs,
332	 * which we achieve by trying again on the slow path.  If we are on
333	 * the slow path, the extra regs are already saved.
334	 *
335	 * RAX stores a pointer to the C function implementing the syscall.
336	 * IRQs are on.
337	 */
338	cmpq	$.Lentry_SYSCALL_64_after_fastpath_call, (%rsp)
339	jne	1f
340
341	/*
342	 * Called from fast path -- disable IRQs again, pop return address
343	 * and jump to slow path
344	 */
345	DISABLE_INTERRUPTS(CLBR_ANY)
346	TRACE_IRQS_OFF
347	popq	%rax
348	UNWIND_HINT_REGS extra=0
349	jmp	entry_SYSCALL64_slow_path
350
3511:
352	jmp	*%rax				/* Called from C */
353END(stub_ptregs_64)
354
355.macro ptregs_stub func
356ENTRY(ptregs_\func)
357	UNWIND_HINT_FUNC
358	leaq	\func(%rip), %rax
359	jmp	stub_ptregs_64
360END(ptregs_\func)
361.endm
362
363/* Instantiate ptregs_stub for each ptregs-using syscall */
364#define __SYSCALL_64_QUAL_(sym)
365#define __SYSCALL_64_QUAL_ptregs(sym) ptregs_stub sym
366#define __SYSCALL_64(nr, sym, qual) __SYSCALL_64_QUAL_##qual(sym)
367#include <asm/syscalls_64.h>
368
369/*
370 * %rdi: prev task
371 * %rsi: next task
372 */
373ENTRY(__switch_to_asm)
374	UNWIND_HINT_FUNC
375	/*
376	 * Save callee-saved registers
377	 * This must match the order in inactive_task_frame
378	 */
379	pushq	%rbp
380	pushq	%rbx
381	pushq	%r12
382	pushq	%r13
383	pushq	%r14
384	pushq	%r15
385
386	/* switch stack */
387	movq	%rsp, TASK_threadsp(%rdi)
388	movq	TASK_threadsp(%rsi), %rsp
389
390#ifdef CONFIG_CC_STACKPROTECTOR
391	movq	TASK_stack_canary(%rsi), %rbx
392	movq	%rbx, PER_CPU_VAR(irq_stack_union)+stack_canary_offset
393#endif
394
395	/* restore callee-saved registers */
396	popq	%r15
397	popq	%r14
398	popq	%r13
399	popq	%r12
400	popq	%rbx
401	popq	%rbp
402
403	jmp	__switch_to
404END(__switch_to_asm)
405
406/*
407 * A newly forked process directly context switches into this address.
408 *
409 * rax: prev task we switched from
410 * rbx: kernel thread func (NULL for user thread)
411 * r12: kernel thread arg
412 */
413ENTRY(ret_from_fork)
414	UNWIND_HINT_EMPTY
415	movq	%rax, %rdi
416	call	schedule_tail			/* rdi: 'prev' task parameter */
417
418	testq	%rbx, %rbx			/* from kernel_thread? */
419	jnz	1f				/* kernel threads are uncommon */
420
4212:
422	UNWIND_HINT_REGS
423	movq	%rsp, %rdi
424	call	syscall_return_slowpath	/* returns with IRQs disabled */
425	TRACE_IRQS_ON			/* user mode is traced as IRQS on */
426	SWAPGS
427	jmp	restore_regs_and_iret
428
4291:
430	/* kernel thread */
431	movq	%r12, %rdi
432	call	*%rbx
433	/*
434	 * A kernel thread is allowed to return here after successfully
435	 * calling do_execve().  Exit to userspace to complete the execve()
436	 * syscall.
437	 */
438	movq	$0, RAX(%rsp)
439	jmp	2b
440END(ret_from_fork)
441
442/*
443 * Build the entry stubs with some assembler magic.
444 * We pack 1 stub into every 8-byte block.
445 */
446	.align 8
447ENTRY(irq_entries_start)
448    vector=FIRST_EXTERNAL_VECTOR
449    .rept (FIRST_SYSTEM_VECTOR - FIRST_EXTERNAL_VECTOR)
450	UNWIND_HINT_IRET_REGS
451	pushq	$(~vector+0x80)			/* Note: always in signed byte range */
452	jmp	common_interrupt
453	.align	8
454	vector=vector+1
455    .endr
456END(irq_entries_start)
457
458.macro DEBUG_ENTRY_ASSERT_IRQS_OFF
459#ifdef CONFIG_DEBUG_ENTRY
460	pushfq
461	testl $X86_EFLAGS_IF, (%rsp)
462	jz .Lokay_\@
463	ud2
464.Lokay_\@:
465	addq $8, %rsp
466#endif
467.endm
468
469/*
470 * Enters the IRQ stack if we're not already using it.  NMI-safe.  Clobbers
471 * flags and puts old RSP into old_rsp, and leaves all other GPRs alone.
472 * Requires kernel GSBASE.
473 *
474 * The invariant is that, if irq_count != -1, then the IRQ stack is in use.
475 */
476.macro ENTER_IRQ_STACK regs=1 old_rsp
477	DEBUG_ENTRY_ASSERT_IRQS_OFF
478	movq	%rsp, \old_rsp
479
480	.if \regs
481	UNWIND_HINT_REGS base=\old_rsp
482	.endif
483
484	incl	PER_CPU_VAR(irq_count)
485	jnz	.Lirq_stack_push_old_rsp_\@
486
487	/*
488	 * Right now, if we just incremented irq_count to zero, we've
489	 * claimed the IRQ stack but we haven't switched to it yet.
490	 *
491	 * If anything is added that can interrupt us here without using IST,
492	 * it must be *extremely* careful to limit its stack usage.  This
493	 * could include kprobes and a hypothetical future IST-less #DB
494	 * handler.
495	 *
496	 * The OOPS unwinder relies on the word at the top of the IRQ
497	 * stack linking back to the previous RSP for the entire time we're
498	 * on the IRQ stack.  For this to work reliably, we need to write
499	 * it before we actually move ourselves to the IRQ stack.
500	 */
501
502	movq	\old_rsp, PER_CPU_VAR(irq_stack_union + IRQ_STACK_SIZE - 8)
503	movq	PER_CPU_VAR(irq_stack_ptr), %rsp
504
505#ifdef CONFIG_DEBUG_ENTRY
506	/*
507	 * If the first movq above becomes wrong due to IRQ stack layout
508	 * changes, the only way we'll notice is if we try to unwind right
509	 * here.  Assert that we set up the stack right to catch this type
510	 * of bug quickly.
511	 */
512	cmpq	-8(%rsp), \old_rsp
513	je	.Lirq_stack_okay\@
514	ud2
515	.Lirq_stack_okay\@:
516#endif
517
518.Lirq_stack_push_old_rsp_\@:
519	pushq	\old_rsp
520
521	.if \regs
522	UNWIND_HINT_REGS indirect=1
523	.endif
524.endm
525
526/*
527 * Undoes ENTER_IRQ_STACK.
528 */
529.macro LEAVE_IRQ_STACK regs=1
530	DEBUG_ENTRY_ASSERT_IRQS_OFF
531	/* We need to be off the IRQ stack before decrementing irq_count. */
532	popq	%rsp
533
534	.if \regs
535	UNWIND_HINT_REGS
536	.endif
537
538	/*
539	 * As in ENTER_IRQ_STACK, irq_count == 0, we are still claiming
540	 * the irq stack but we're not on it.
541	 */
542
543	decl	PER_CPU_VAR(irq_count)
544.endm
545
546/*
547 * Interrupt entry/exit.
548 *
549 * Interrupt entry points save only callee clobbered registers in fast path.
550 *
551 * Entry runs with interrupts off.
552 */
553
554/* 0(%rsp): ~(interrupt number) */
555	.macro interrupt func
556	cld
557	ALLOC_PT_GPREGS_ON_STACK
558	SAVE_C_REGS
559	SAVE_EXTRA_REGS
560	ENCODE_FRAME_POINTER
561
562	testb	$3, CS(%rsp)
563	jz	1f
564
565	/*
566	 * IRQ from user mode.  Switch to kernel gsbase and inform context
567	 * tracking that we're in kernel mode.
568	 */
569	SWAPGS
570
571	/*
572	 * We need to tell lockdep that IRQs are off.  We can't do this until
573	 * we fix gsbase, and we should do it before enter_from_user_mode
574	 * (which can take locks).  Since TRACE_IRQS_OFF idempotent,
575	 * the simplest way to handle it is to just call it twice if
576	 * we enter from user mode.  There's no reason to optimize this since
577	 * TRACE_IRQS_OFF is a no-op if lockdep is off.
578	 */
579	TRACE_IRQS_OFF
580
581	CALL_enter_from_user_mode
582
5831:
584	ENTER_IRQ_STACK old_rsp=%rdi
585	/* We entered an interrupt context - irqs are off: */
586	TRACE_IRQS_OFF
587
588	call	\func	/* rdi points to pt_regs */
589	.endm
590
591	/*
592	 * The interrupt stubs push (~vector+0x80) onto the stack and
593	 * then jump to common_interrupt.
594	 */
595	.p2align CONFIG_X86_L1_CACHE_SHIFT
596common_interrupt:
597	ASM_CLAC
598	addq	$-0x80, (%rsp)			/* Adjust vector to [-256, -1] range */
599	interrupt do_IRQ
600	/* 0(%rsp): old RSP */
601ret_from_intr:
602	DISABLE_INTERRUPTS(CLBR_ANY)
603	TRACE_IRQS_OFF
604
605	LEAVE_IRQ_STACK
606
607	testb	$3, CS(%rsp)
608	jz	retint_kernel
609
610	/* Interrupt came from user space */
611GLOBAL(retint_user)
612	mov	%rsp,%rdi
613	call	prepare_exit_to_usermode
614	TRACE_IRQS_IRETQ
615	SWAPGS
616	jmp	restore_regs_and_iret
617
618/* Returning to kernel space */
619retint_kernel:
620#ifdef CONFIG_PREEMPT
621	/* Interrupts are off */
622	/* Check if we need preemption */
623	bt	$9, EFLAGS(%rsp)		/* were interrupts off? */
624	jnc	1f
6250:	cmpl	$0, PER_CPU_VAR(__preempt_count)
626	jnz	1f
627	call	preempt_schedule_irq
628	jmp	0b
6291:
630#endif
631	/*
632	 * The iretq could re-enable interrupts:
633	 */
634	TRACE_IRQS_IRETQ
635
636/*
637 * At this label, code paths which return to kernel and to user,
638 * which come from interrupts/exception and from syscalls, merge.
639 */
640GLOBAL(restore_regs_and_iret)
641	RESTORE_EXTRA_REGS
642restore_c_regs_and_iret:
643	RESTORE_C_REGS
644	REMOVE_PT_GPREGS_FROM_STACK 8
645	INTERRUPT_RETURN
646
647ENTRY(native_iret)
648	UNWIND_HINT_IRET_REGS
649	/*
650	 * Are we returning to a stack segment from the LDT?  Note: in
651	 * 64-bit mode SS:RSP on the exception stack is always valid.
652	 */
653#ifdef CONFIG_X86_ESPFIX64
654	testb	$4, (SS-RIP)(%rsp)
655	jnz	native_irq_return_ldt
656#endif
657
658.global native_irq_return_iret
659native_irq_return_iret:
660	/*
661	 * This may fault.  Non-paranoid faults on return to userspace are
662	 * handled by fixup_bad_iret.  These include #SS, #GP, and #NP.
663	 * Double-faults due to espfix64 are handled in do_double_fault.
664	 * Other faults here are fatal.
665	 */
666	iretq
667
668#ifdef CONFIG_X86_ESPFIX64
669native_irq_return_ldt:
670	/*
671	 * We are running with user GSBASE.  All GPRs contain their user
672	 * values.  We have a percpu ESPFIX stack that is eight slots
673	 * long (see ESPFIX_STACK_SIZE).  espfix_waddr points to the bottom
674	 * of the ESPFIX stack.
675	 *
676	 * We clobber RAX and RDI in this code.  We stash RDI on the
677	 * normal stack and RAX on the ESPFIX stack.
678	 *
679	 * The ESPFIX stack layout we set up looks like this:
680	 *
681	 * --- top of ESPFIX stack ---
682	 * SS
683	 * RSP
684	 * RFLAGS
685	 * CS
686	 * RIP  <-- RSP points here when we're done
687	 * RAX  <-- espfix_waddr points here
688	 * --- bottom of ESPFIX stack ---
689	 */
690
691	pushq	%rdi				/* Stash user RDI */
692	SWAPGS
693	movq	PER_CPU_VAR(espfix_waddr), %rdi
694	movq	%rax, (0*8)(%rdi)		/* user RAX */
695	movq	(1*8)(%rsp), %rax		/* user RIP */
696	movq	%rax, (1*8)(%rdi)
697	movq	(2*8)(%rsp), %rax		/* user CS */
698	movq	%rax, (2*8)(%rdi)
699	movq	(3*8)(%rsp), %rax		/* user RFLAGS */
700	movq	%rax, (3*8)(%rdi)
701	movq	(5*8)(%rsp), %rax		/* user SS */
702	movq	%rax, (5*8)(%rdi)
703	movq	(4*8)(%rsp), %rax		/* user RSP */
704	movq	%rax, (4*8)(%rdi)
705	/* Now RAX == RSP. */
706
707	andl	$0xffff0000, %eax		/* RAX = (RSP & 0xffff0000) */
708	popq	%rdi				/* Restore user RDI */
709
710	/*
711	 * espfix_stack[31:16] == 0.  The page tables are set up such that
712	 * (espfix_stack | (X & 0xffff0000)) points to a read-only alias of
713	 * espfix_waddr for any X.  That is, there are 65536 RO aliases of
714	 * the same page.  Set up RSP so that RSP[31:16] contains the
715	 * respective 16 bits of the /userspace/ RSP and RSP nonetheless
716	 * still points to an RO alias of the ESPFIX stack.
717	 */
718	orq	PER_CPU_VAR(espfix_stack), %rax
719	SWAPGS
720	movq	%rax, %rsp
721	UNWIND_HINT_IRET_REGS offset=8
722
723	/*
724	 * At this point, we cannot write to the stack any more, but we can
725	 * still read.
726	 */
727	popq	%rax				/* Restore user RAX */
728
729	/*
730	 * RSP now points to an ordinary IRET frame, except that the page
731	 * is read-only and RSP[31:16] are preloaded with the userspace
732	 * values.  We can now IRET back to userspace.
733	 */
734	jmp	native_irq_return_iret
735#endif
736END(common_interrupt)
737
738/*
739 * APIC interrupts.
740 */
741.macro apicinterrupt3 num sym do_sym
742ENTRY(\sym)
743	UNWIND_HINT_IRET_REGS
744	ASM_CLAC
745	pushq	$~(\num)
746.Lcommon_\sym:
747	interrupt \do_sym
748	jmp	ret_from_intr
749END(\sym)
750.endm
751
752/* Make sure APIC interrupt handlers end up in the irqentry section: */
753#define PUSH_SECTION_IRQENTRY	.pushsection .irqentry.text, "ax"
754#define POP_SECTION_IRQENTRY	.popsection
755
756.macro apicinterrupt num sym do_sym
757PUSH_SECTION_IRQENTRY
758apicinterrupt3 \num \sym \do_sym
759POP_SECTION_IRQENTRY
760.endm
761
762#ifdef CONFIG_SMP
763apicinterrupt3 IRQ_MOVE_CLEANUP_VECTOR		irq_move_cleanup_interrupt	smp_irq_move_cleanup_interrupt
764apicinterrupt3 REBOOT_VECTOR			reboot_interrupt		smp_reboot_interrupt
765#endif
766
767#ifdef CONFIG_X86_UV
768apicinterrupt3 UV_BAU_MESSAGE			uv_bau_message_intr1		uv_bau_message_interrupt
769#endif
770
771apicinterrupt LOCAL_TIMER_VECTOR		apic_timer_interrupt		smp_apic_timer_interrupt
772apicinterrupt X86_PLATFORM_IPI_VECTOR		x86_platform_ipi		smp_x86_platform_ipi
773
774#ifdef CONFIG_HAVE_KVM
775apicinterrupt3 POSTED_INTR_VECTOR		kvm_posted_intr_ipi		smp_kvm_posted_intr_ipi
776apicinterrupt3 POSTED_INTR_WAKEUP_VECTOR	kvm_posted_intr_wakeup_ipi	smp_kvm_posted_intr_wakeup_ipi
777apicinterrupt3 POSTED_INTR_NESTED_VECTOR	kvm_posted_intr_nested_ipi	smp_kvm_posted_intr_nested_ipi
778#endif
779
780#ifdef CONFIG_X86_MCE_THRESHOLD
781apicinterrupt THRESHOLD_APIC_VECTOR		threshold_interrupt		smp_threshold_interrupt
782#endif
783
784#ifdef CONFIG_X86_MCE_AMD
785apicinterrupt DEFERRED_ERROR_VECTOR		deferred_error_interrupt	smp_deferred_error_interrupt
786#endif
787
788#ifdef CONFIG_X86_THERMAL_VECTOR
789apicinterrupt THERMAL_APIC_VECTOR		thermal_interrupt		smp_thermal_interrupt
790#endif
791
792#ifdef CONFIG_SMP
793apicinterrupt CALL_FUNCTION_SINGLE_VECTOR	call_function_single_interrupt	smp_call_function_single_interrupt
794apicinterrupt CALL_FUNCTION_VECTOR		call_function_interrupt		smp_call_function_interrupt
795apicinterrupt RESCHEDULE_VECTOR			reschedule_interrupt		smp_reschedule_interrupt
796#endif
797
798apicinterrupt ERROR_APIC_VECTOR			error_interrupt			smp_error_interrupt
799apicinterrupt SPURIOUS_APIC_VECTOR		spurious_interrupt		smp_spurious_interrupt
800
801#ifdef CONFIG_IRQ_WORK
802apicinterrupt IRQ_WORK_VECTOR			irq_work_interrupt		smp_irq_work_interrupt
803#endif
804
805/*
806 * Exception entry points.
807 */
808#define CPU_TSS_IST(x) PER_CPU_VAR(cpu_tss) + (TSS_ist + ((x) - 1) * 8)
809
810.macro idtentry sym do_sym has_error_code:req paranoid=0 shift_ist=-1
811ENTRY(\sym)
812	UNWIND_HINT_IRET_REGS offset=8
813
814	/* Sanity check */
815	.if \shift_ist != -1 && \paranoid == 0
816	.error "using shift_ist requires paranoid=1"
817	.endif
818
819	ASM_CLAC
820
821	.ifeq \has_error_code
822	pushq	$-1				/* ORIG_RAX: no syscall to restart */
823	.endif
824
825	ALLOC_PT_GPREGS_ON_STACK
826
827	.if \paranoid
828	.if \paranoid == 1
829	testb	$3, CS(%rsp)			/* If coming from userspace, switch stacks */
830	jnz	1f
831	.endif
832	call	paranoid_entry
833	.else
834	call	error_entry
835	.endif
836	UNWIND_HINT_REGS
837	/* returned flag: ebx=0: need swapgs on exit, ebx=1: don't need it */
838
839	.if \paranoid
840	.if \shift_ist != -1
841	TRACE_IRQS_OFF_DEBUG			/* reload IDT in case of recursion */
842	.else
843	TRACE_IRQS_OFF
844	.endif
845	.endif
846
847	movq	%rsp, %rdi			/* pt_regs pointer */
848
849	.if \has_error_code
850	movq	ORIG_RAX(%rsp), %rsi		/* get error code */
851	movq	$-1, ORIG_RAX(%rsp)		/* no syscall to restart */
852	.else
853	xorl	%esi, %esi			/* no error code */
854	.endif
855
856	.if \shift_ist != -1
857	subq	$EXCEPTION_STKSZ, CPU_TSS_IST(\shift_ist)
858	.endif
859
860	call	\do_sym
861
862	.if \shift_ist != -1
863	addq	$EXCEPTION_STKSZ, CPU_TSS_IST(\shift_ist)
864	.endif
865
866	/* these procedures expect "no swapgs" flag in ebx */
867	.if \paranoid
868	jmp	paranoid_exit
869	.else
870	jmp	error_exit
871	.endif
872
873	.if \paranoid == 1
874	/*
875	 * Paranoid entry from userspace.  Switch stacks and treat it
876	 * as a normal entry.  This means that paranoid handlers
877	 * run in real process context if user_mode(regs).
878	 */
8791:
880	call	error_entry
881
882
883	movq	%rsp, %rdi			/* pt_regs pointer */
884	call	sync_regs
885	movq	%rax, %rsp			/* switch stack */
886
887	movq	%rsp, %rdi			/* pt_regs pointer */
888
889	.if \has_error_code
890	movq	ORIG_RAX(%rsp), %rsi		/* get error code */
891	movq	$-1, ORIG_RAX(%rsp)		/* no syscall to restart */
892	.else
893	xorl	%esi, %esi			/* no error code */
894	.endif
895
896	call	\do_sym
897
898	jmp	error_exit			/* %ebx: no swapgs flag */
899	.endif
900END(\sym)
901.endm
902
903idtentry divide_error			do_divide_error			has_error_code=0
904idtentry overflow			do_overflow			has_error_code=0
905idtentry bounds				do_bounds			has_error_code=0
906idtentry invalid_op			do_invalid_op			has_error_code=0
907idtentry device_not_available		do_device_not_available		has_error_code=0
908idtentry double_fault			do_double_fault			has_error_code=1 paranoid=2
909idtentry coprocessor_segment_overrun	do_coprocessor_segment_overrun	has_error_code=0
910idtentry invalid_TSS			do_invalid_TSS			has_error_code=1
911idtentry segment_not_present		do_segment_not_present		has_error_code=1
912idtentry spurious_interrupt_bug		do_spurious_interrupt_bug	has_error_code=0
913idtentry coprocessor_error		do_coprocessor_error		has_error_code=0
914idtentry alignment_check		do_alignment_check		has_error_code=1
915idtentry simd_coprocessor_error		do_simd_coprocessor_error	has_error_code=0
916
917
918	/*
919	 * Reload gs selector with exception handling
920	 * edi:  new selector
921	 */
922ENTRY(native_load_gs_index)
923	FRAME_BEGIN
924	pushfq
925	DISABLE_INTERRUPTS(CLBR_ANY & ~CLBR_RDI)
926	SWAPGS
927.Lgs_change:
928	movl	%edi, %gs
9292:	ALTERNATIVE "", "mfence", X86_BUG_SWAPGS_FENCE
930	SWAPGS
931	popfq
932	FRAME_END
933	ret
934ENDPROC(native_load_gs_index)
935EXPORT_SYMBOL(native_load_gs_index)
936
937	_ASM_EXTABLE(.Lgs_change, bad_gs)
938	.section .fixup, "ax"
939	/* running with kernelgs */
940bad_gs:
941	SWAPGS					/* switch back to user gs */
942.macro ZAP_GS
943	/* This can't be a string because the preprocessor needs to see it. */
944	movl $__USER_DS, %eax
945	movl %eax, %gs
946.endm
947	ALTERNATIVE "", "ZAP_GS", X86_BUG_NULL_SEG
948	xorl	%eax, %eax
949	movl	%eax, %gs
950	jmp	2b
951	.previous
952
953/* Call softirq on interrupt stack. Interrupts are off. */
954ENTRY(do_softirq_own_stack)
955	pushq	%rbp
956	mov	%rsp, %rbp
957	ENTER_IRQ_STACK regs=0 old_rsp=%r11
958	call	__do_softirq
959	LEAVE_IRQ_STACK regs=0
960	leaveq
961	ret
962ENDPROC(do_softirq_own_stack)
963
964#ifdef CONFIG_XEN
965idtentry hypervisor_callback xen_do_hypervisor_callback has_error_code=0
966
967/*
968 * A note on the "critical region" in our callback handler.
969 * We want to avoid stacking callback handlers due to events occurring
970 * during handling of the last event. To do this, we keep events disabled
971 * until we've done all processing. HOWEVER, we must enable events before
972 * popping the stack frame (can't be done atomically) and so it would still
973 * be possible to get enough handler activations to overflow the stack.
974 * Although unlikely, bugs of that kind are hard to track down, so we'd
975 * like to avoid the possibility.
976 * So, on entry to the handler we detect whether we interrupted an
977 * existing activation in its critical region -- if so, we pop the current
978 * activation and restart the handler using the previous one.
979 */
980ENTRY(xen_do_hypervisor_callback)		/* do_hypervisor_callback(struct *pt_regs) */
981
982/*
983 * Since we don't modify %rdi, evtchn_do_upall(struct *pt_regs) will
984 * see the correct pointer to the pt_regs
985 */
986	UNWIND_HINT_FUNC
987	movq	%rdi, %rsp			/* we don't return, adjust the stack frame */
988	UNWIND_HINT_REGS
989
990	ENTER_IRQ_STACK old_rsp=%r10
991	call	xen_evtchn_do_upcall
992	LEAVE_IRQ_STACK
993
994#ifndef CONFIG_PREEMPT
995	call	xen_maybe_preempt_hcall
996#endif
997	jmp	error_exit
998END(xen_do_hypervisor_callback)
999
1000/*
1001 * Hypervisor uses this for application faults while it executes.
1002 * We get here for two reasons:
1003 *  1. Fault while reloading DS, ES, FS or GS
1004 *  2. Fault while executing IRET
1005 * Category 1 we do not need to fix up as Xen has already reloaded all segment
1006 * registers that could be reloaded and zeroed the others.
1007 * Category 2 we fix up by killing the current process. We cannot use the
1008 * normal Linux return path in this case because if we use the IRET hypercall
1009 * to pop the stack frame we end up in an infinite loop of failsafe callbacks.
1010 * We distinguish between categories by comparing each saved segment register
1011 * with its current contents: any discrepancy means we in category 1.
1012 */
1013ENTRY(xen_failsafe_callback)
1014	UNWIND_HINT_EMPTY
1015	movl	%ds, %ecx
1016	cmpw	%cx, 0x10(%rsp)
1017	jne	1f
1018	movl	%es, %ecx
1019	cmpw	%cx, 0x18(%rsp)
1020	jne	1f
1021	movl	%fs, %ecx
1022	cmpw	%cx, 0x20(%rsp)
1023	jne	1f
1024	movl	%gs, %ecx
1025	cmpw	%cx, 0x28(%rsp)
1026	jne	1f
1027	/* All segments match their saved values => Category 2 (Bad IRET). */
1028	movq	(%rsp), %rcx
1029	movq	8(%rsp), %r11
1030	addq	$0x30, %rsp
1031	pushq	$0				/* RIP */
1032	UNWIND_HINT_IRET_REGS offset=8
1033	jmp	general_protection
10341:	/* Segment mismatch => Category 1 (Bad segment). Retry the IRET. */
1035	movq	(%rsp), %rcx
1036	movq	8(%rsp), %r11
1037	addq	$0x30, %rsp
1038	UNWIND_HINT_IRET_REGS
1039	pushq	$-1 /* orig_ax = -1 => not a system call */
1040	ALLOC_PT_GPREGS_ON_STACK
1041	SAVE_C_REGS
1042	SAVE_EXTRA_REGS
1043	ENCODE_FRAME_POINTER
1044	jmp	error_exit
1045END(xen_failsafe_callback)
1046
1047apicinterrupt3 HYPERVISOR_CALLBACK_VECTOR \
1048	xen_hvm_callback_vector xen_evtchn_do_upcall
1049
1050#endif /* CONFIG_XEN */
1051
1052#if IS_ENABLED(CONFIG_HYPERV)
1053apicinterrupt3 HYPERVISOR_CALLBACK_VECTOR \
1054	hyperv_callback_vector hyperv_vector_handler
1055#endif /* CONFIG_HYPERV */
1056
1057idtentry debug			do_debug		has_error_code=0	paranoid=1 shift_ist=DEBUG_STACK
1058idtentry int3			do_int3			has_error_code=0	paranoid=1 shift_ist=DEBUG_STACK
1059idtentry stack_segment		do_stack_segment	has_error_code=1
1060
1061#ifdef CONFIG_XEN
1062idtentry xendebug		do_debug		has_error_code=0
1063idtentry xenint3		do_int3			has_error_code=0
1064#endif
1065
1066idtentry general_protection	do_general_protection	has_error_code=1
1067idtentry page_fault		do_page_fault		has_error_code=1
1068
1069#ifdef CONFIG_KVM_GUEST
1070idtentry async_page_fault	do_async_page_fault	has_error_code=1
1071#endif
1072
1073#ifdef CONFIG_X86_MCE
1074idtentry machine_check					has_error_code=0	paranoid=1 do_sym=*machine_check_vector(%rip)
1075#endif
1076
1077/*
1078 * Save all registers in pt_regs, and switch gs if needed.
1079 * Use slow, but surefire "are we in kernel?" check.
1080 * Return: ebx=0: need swapgs on exit, ebx=1: otherwise
1081 */
1082ENTRY(paranoid_entry)
1083	UNWIND_HINT_FUNC
1084	cld
1085	SAVE_C_REGS 8
1086	SAVE_EXTRA_REGS 8
1087	ENCODE_FRAME_POINTER 8
1088	movl	$1, %ebx
1089	movl	$MSR_GS_BASE, %ecx
1090	rdmsr
1091	testl	%edx, %edx
1092	js	1f				/* negative -> in kernel */
1093	SWAPGS
1094	xorl	%ebx, %ebx
10951:	ret
1096END(paranoid_entry)
1097
1098/*
1099 * "Paranoid" exit path from exception stack.  This is invoked
1100 * only on return from non-NMI IST interrupts that came
1101 * from kernel space.
1102 *
1103 * We may be returning to very strange contexts (e.g. very early
1104 * in syscall entry), so checking for preemption here would
1105 * be complicated.  Fortunately, we there's no good reason
1106 * to try to handle preemption here.
1107 *
1108 * On entry, ebx is "no swapgs" flag (1: don't need swapgs, 0: need it)
1109 */
1110ENTRY(paranoid_exit)
1111	UNWIND_HINT_REGS
1112	DISABLE_INTERRUPTS(CLBR_ANY)
1113	TRACE_IRQS_OFF_DEBUG
1114	testl	%ebx, %ebx			/* swapgs needed? */
1115	jnz	paranoid_exit_no_swapgs
1116	TRACE_IRQS_IRETQ
1117	SWAPGS_UNSAFE_STACK
1118	jmp	paranoid_exit_restore
1119paranoid_exit_no_swapgs:
1120	TRACE_IRQS_IRETQ_DEBUG
1121paranoid_exit_restore:
1122	RESTORE_EXTRA_REGS
1123	RESTORE_C_REGS
1124	REMOVE_PT_GPREGS_FROM_STACK 8
1125	INTERRUPT_RETURN
1126END(paranoid_exit)
1127
1128/*
1129 * Save all registers in pt_regs, and switch gs if needed.
1130 * Return: EBX=0: came from user mode; EBX=1: otherwise
1131 */
1132ENTRY(error_entry)
1133	UNWIND_HINT_FUNC
1134	cld
1135	SAVE_C_REGS 8
1136	SAVE_EXTRA_REGS 8
1137	ENCODE_FRAME_POINTER 8
1138	xorl	%ebx, %ebx
1139	testb	$3, CS+8(%rsp)
1140	jz	.Lerror_kernelspace
1141
1142	/*
1143	 * We entered from user mode or we're pretending to have entered
1144	 * from user mode due to an IRET fault.
1145	 */
1146	SWAPGS
1147
1148.Lerror_entry_from_usermode_after_swapgs:
1149	/*
1150	 * We need to tell lockdep that IRQs are off.  We can't do this until
1151	 * we fix gsbase, and we should do it before enter_from_user_mode
1152	 * (which can take locks).
1153	 */
1154	TRACE_IRQS_OFF
1155	CALL_enter_from_user_mode
1156	ret
1157
1158.Lerror_entry_done:
1159	TRACE_IRQS_OFF
1160	ret
1161
1162	/*
1163	 * There are two places in the kernel that can potentially fault with
1164	 * usergs. Handle them here.  B stepping K8s sometimes report a
1165	 * truncated RIP for IRET exceptions returning to compat mode. Check
1166	 * for these here too.
1167	 */
1168.Lerror_kernelspace:
1169	incl	%ebx
1170	leaq	native_irq_return_iret(%rip), %rcx
1171	cmpq	%rcx, RIP+8(%rsp)
1172	je	.Lerror_bad_iret
1173	movl	%ecx, %eax			/* zero extend */
1174	cmpq	%rax, RIP+8(%rsp)
1175	je	.Lbstep_iret
1176	cmpq	$.Lgs_change, RIP+8(%rsp)
1177	jne	.Lerror_entry_done
1178
1179	/*
1180	 * hack: .Lgs_change can fail with user gsbase.  If this happens, fix up
1181	 * gsbase and proceed.  We'll fix up the exception and land in
1182	 * .Lgs_change's error handler with kernel gsbase.
1183	 */
1184	SWAPGS
1185	jmp .Lerror_entry_done
1186
1187.Lbstep_iret:
1188	/* Fix truncated RIP */
1189	movq	%rcx, RIP+8(%rsp)
1190	/* fall through */
1191
1192.Lerror_bad_iret:
1193	/*
1194	 * We came from an IRET to user mode, so we have user gsbase.
1195	 * Switch to kernel gsbase:
1196	 */
1197	SWAPGS
1198
1199	/*
1200	 * Pretend that the exception came from user mode: set up pt_regs
1201	 * as if we faulted immediately after IRET and clear EBX so that
1202	 * error_exit knows that we will be returning to user mode.
1203	 */
1204	mov	%rsp, %rdi
1205	call	fixup_bad_iret
1206	mov	%rax, %rsp
1207	decl	%ebx
1208	jmp	.Lerror_entry_from_usermode_after_swapgs
1209END(error_entry)
1210
1211
1212/*
1213 * On entry, EBX is a "return to kernel mode" flag:
1214 *   1: already in kernel mode, don't need SWAPGS
1215 *   0: user gsbase is loaded, we need SWAPGS and standard preparation for return to usermode
1216 */
1217ENTRY(error_exit)
1218	UNWIND_HINT_REGS
1219	DISABLE_INTERRUPTS(CLBR_ANY)
1220	TRACE_IRQS_OFF
1221	testl	%ebx, %ebx
1222	jnz	retint_kernel
1223	jmp	retint_user
1224END(error_exit)
1225
1226/* Runs on exception stack */
1227/* XXX: broken on Xen PV */
1228ENTRY(nmi)
1229	UNWIND_HINT_IRET_REGS
1230	/*
1231	 * We allow breakpoints in NMIs. If a breakpoint occurs, then
1232	 * the iretq it performs will take us out of NMI context.
1233	 * This means that we can have nested NMIs where the next
1234	 * NMI is using the top of the stack of the previous NMI. We
1235	 * can't let it execute because the nested NMI will corrupt the
1236	 * stack of the previous NMI. NMI handlers are not re-entrant
1237	 * anyway.
1238	 *
1239	 * To handle this case we do the following:
1240	 *  Check the a special location on the stack that contains
1241	 *  a variable that is set when NMIs are executing.
1242	 *  The interrupted task's stack is also checked to see if it
1243	 *  is an NMI stack.
1244	 *  If the variable is not set and the stack is not the NMI
1245	 *  stack then:
1246	 *    o Set the special variable on the stack
1247	 *    o Copy the interrupt frame into an "outermost" location on the
1248	 *      stack
1249	 *    o Copy the interrupt frame into an "iret" location on the stack
1250	 *    o Continue processing the NMI
1251	 *  If the variable is set or the previous stack is the NMI stack:
1252	 *    o Modify the "iret" location to jump to the repeat_nmi
1253	 *    o return back to the first NMI
1254	 *
1255	 * Now on exit of the first NMI, we first clear the stack variable
1256	 * The NMI stack will tell any nested NMIs at that point that it is
1257	 * nested. Then we pop the stack normally with iret, and if there was
1258	 * a nested NMI that updated the copy interrupt stack frame, a
1259	 * jump will be made to the repeat_nmi code that will handle the second
1260	 * NMI.
1261	 *
1262	 * However, espfix prevents us from directly returning to userspace
1263	 * with a single IRET instruction.  Similarly, IRET to user mode
1264	 * can fault.  We therefore handle NMIs from user space like
1265	 * other IST entries.
1266	 */
1267
1268	ASM_CLAC
1269
1270	/* Use %rdx as our temp variable throughout */
1271	pushq	%rdx
1272
1273	testb	$3, CS-RIP+8(%rsp)
1274	jz	.Lnmi_from_kernel
1275
1276	/*
1277	 * NMI from user mode.  We need to run on the thread stack, but we
1278	 * can't go through the normal entry paths: NMIs are masked, and
1279	 * we don't want to enable interrupts, because then we'll end
1280	 * up in an awkward situation in which IRQs are on but NMIs
1281	 * are off.
1282	 *
1283	 * We also must not push anything to the stack before switching
1284	 * stacks lest we corrupt the "NMI executing" variable.
1285	 */
1286
1287	SWAPGS_UNSAFE_STACK
1288	cld
1289	movq	%rsp, %rdx
1290	movq	PER_CPU_VAR(cpu_current_top_of_stack), %rsp
1291	UNWIND_HINT_IRET_REGS base=%rdx offset=8
1292	pushq	5*8(%rdx)	/* pt_regs->ss */
1293	pushq	4*8(%rdx)	/* pt_regs->rsp */
1294	pushq	3*8(%rdx)	/* pt_regs->flags */
1295	pushq	2*8(%rdx)	/* pt_regs->cs */
1296	pushq	1*8(%rdx)	/* pt_regs->rip */
1297	UNWIND_HINT_IRET_REGS
1298	pushq   $-1		/* pt_regs->orig_ax */
1299	pushq   %rdi		/* pt_regs->di */
1300	pushq   %rsi		/* pt_regs->si */
1301	pushq   (%rdx)		/* pt_regs->dx */
1302	pushq   %rcx		/* pt_regs->cx */
1303	pushq   %rax		/* pt_regs->ax */
1304	pushq   %r8		/* pt_regs->r8 */
1305	pushq   %r9		/* pt_regs->r9 */
1306	pushq   %r10		/* pt_regs->r10 */
1307	pushq   %r11		/* pt_regs->r11 */
1308	pushq	%rbx		/* pt_regs->rbx */
1309	pushq	%rbp		/* pt_regs->rbp */
1310	pushq	%r12		/* pt_regs->r12 */
1311	pushq	%r13		/* pt_regs->r13 */
1312	pushq	%r14		/* pt_regs->r14 */
1313	pushq	%r15		/* pt_regs->r15 */
1314	UNWIND_HINT_REGS
1315	ENCODE_FRAME_POINTER
1316
1317	/*
1318	 * At this point we no longer need to worry about stack damage
1319	 * due to nesting -- we're on the normal thread stack and we're
1320	 * done with the NMI stack.
1321	 */
1322
1323	movq	%rsp, %rdi
1324	movq	$-1, %rsi
1325	call	do_nmi
1326
1327	/*
1328	 * Return back to user mode.  We must *not* do the normal exit
1329	 * work, because we don't want to enable interrupts.
1330	 */
1331	SWAPGS
1332	jmp	restore_regs_and_iret
1333
1334.Lnmi_from_kernel:
1335	/*
1336	 * Here's what our stack frame will look like:
1337	 * +---------------------------------------------------------+
1338	 * | original SS                                             |
1339	 * | original Return RSP                                     |
1340	 * | original RFLAGS                                         |
1341	 * | original CS                                             |
1342	 * | original RIP                                            |
1343	 * +---------------------------------------------------------+
1344	 * | temp storage for rdx                                    |
1345	 * +---------------------------------------------------------+
1346	 * | "NMI executing" variable                                |
1347	 * +---------------------------------------------------------+
1348	 * | iret SS          } Copied from "outermost" frame        |
1349	 * | iret Return RSP  } on each loop iteration; overwritten  |
1350	 * | iret RFLAGS      } by a nested NMI to force another     |
1351	 * | iret CS          } iteration if needed.                 |
1352	 * | iret RIP         }                                      |
1353	 * +---------------------------------------------------------+
1354	 * | outermost SS          } initialized in first_nmi;       |
1355	 * | outermost Return RSP  } will not be changed before      |
1356	 * | outermost RFLAGS      } NMI processing is done.         |
1357	 * | outermost CS          } Copied to "iret" frame on each  |
1358	 * | outermost RIP         } iteration.                      |
1359	 * +---------------------------------------------------------+
1360	 * | pt_regs                                                 |
1361	 * +---------------------------------------------------------+
1362	 *
1363	 * The "original" frame is used by hardware.  Before re-enabling
1364	 * NMIs, we need to be done with it, and we need to leave enough
1365	 * space for the asm code here.
1366	 *
1367	 * We return by executing IRET while RSP points to the "iret" frame.
1368	 * That will either return for real or it will loop back into NMI
1369	 * processing.
1370	 *
1371	 * The "outermost" frame is copied to the "iret" frame on each
1372	 * iteration of the loop, so each iteration starts with the "iret"
1373	 * frame pointing to the final return target.
1374	 */
1375
1376	/*
1377	 * Determine whether we're a nested NMI.
1378	 *
1379	 * If we interrupted kernel code between repeat_nmi and
1380	 * end_repeat_nmi, then we are a nested NMI.  We must not
1381	 * modify the "iret" frame because it's being written by
1382	 * the outer NMI.  That's okay; the outer NMI handler is
1383	 * about to about to call do_nmi anyway, so we can just
1384	 * resume the outer NMI.
1385	 */
1386
1387	movq	$repeat_nmi, %rdx
1388	cmpq	8(%rsp), %rdx
1389	ja	1f
1390	movq	$end_repeat_nmi, %rdx
1391	cmpq	8(%rsp), %rdx
1392	ja	nested_nmi_out
13931:
1394
1395	/*
1396	 * Now check "NMI executing".  If it's set, then we're nested.
1397	 * This will not detect if we interrupted an outer NMI just
1398	 * before IRET.
1399	 */
1400	cmpl	$1, -8(%rsp)
1401	je	nested_nmi
1402
1403	/*
1404	 * Now test if the previous stack was an NMI stack.  This covers
1405	 * the case where we interrupt an outer NMI after it clears
1406	 * "NMI executing" but before IRET.  We need to be careful, though:
1407	 * there is one case in which RSP could point to the NMI stack
1408	 * despite there being no NMI active: naughty userspace controls
1409	 * RSP at the very beginning of the SYSCALL targets.  We can
1410	 * pull a fast one on naughty userspace, though: we program
1411	 * SYSCALL to mask DF, so userspace cannot cause DF to be set
1412	 * if it controls the kernel's RSP.  We set DF before we clear
1413	 * "NMI executing".
1414	 */
1415	lea	6*8(%rsp), %rdx
1416	/* Compare the NMI stack (rdx) with the stack we came from (4*8(%rsp)) */
1417	cmpq	%rdx, 4*8(%rsp)
1418	/* If the stack pointer is above the NMI stack, this is a normal NMI */
1419	ja	first_nmi
1420
1421	subq	$EXCEPTION_STKSZ, %rdx
1422	cmpq	%rdx, 4*8(%rsp)
1423	/* If it is below the NMI stack, it is a normal NMI */
1424	jb	first_nmi
1425
1426	/* Ah, it is within the NMI stack. */
1427
1428	testb	$(X86_EFLAGS_DF >> 8), (3*8 + 1)(%rsp)
1429	jz	first_nmi	/* RSP was user controlled. */
1430
1431	/* This is a nested NMI. */
1432
1433nested_nmi:
1434	/*
1435	 * Modify the "iret" frame to point to repeat_nmi, forcing another
1436	 * iteration of NMI handling.
1437	 */
1438	subq	$8, %rsp
1439	leaq	-10*8(%rsp), %rdx
1440	pushq	$__KERNEL_DS
1441	pushq	%rdx
1442	pushfq
1443	pushq	$__KERNEL_CS
1444	pushq	$repeat_nmi
1445
1446	/* Put stack back */
1447	addq	$(6*8), %rsp
1448
1449nested_nmi_out:
1450	popq	%rdx
1451
1452	/* We are returning to kernel mode, so this cannot result in a fault. */
1453	INTERRUPT_RETURN
1454
1455first_nmi:
1456	/* Restore rdx. */
1457	movq	(%rsp), %rdx
1458
1459	/* Make room for "NMI executing". */
1460	pushq	$0
1461
1462	/* Leave room for the "iret" frame */
1463	subq	$(5*8), %rsp
1464
1465	/* Copy the "original" frame to the "outermost" frame */
1466	.rept 5
1467	pushq	11*8(%rsp)
1468	.endr
1469	UNWIND_HINT_IRET_REGS
1470
1471	/* Everything up to here is safe from nested NMIs */
1472
1473#ifdef CONFIG_DEBUG_ENTRY
1474	/*
1475	 * For ease of testing, unmask NMIs right away.  Disabled by
1476	 * default because IRET is very expensive.
1477	 */
1478	pushq	$0		/* SS */
1479	pushq	%rsp		/* RSP (minus 8 because of the previous push) */
1480	addq	$8, (%rsp)	/* Fix up RSP */
1481	pushfq			/* RFLAGS */
1482	pushq	$__KERNEL_CS	/* CS */
1483	pushq	$1f		/* RIP */
1484	INTERRUPT_RETURN	/* continues at repeat_nmi below */
1485	UNWIND_HINT_IRET_REGS
14861:
1487#endif
1488
1489repeat_nmi:
1490	/*
1491	 * If there was a nested NMI, the first NMI's iret will return
1492	 * here. But NMIs are still enabled and we can take another
1493	 * nested NMI. The nested NMI checks the interrupted RIP to see
1494	 * if it is between repeat_nmi and end_repeat_nmi, and if so
1495	 * it will just return, as we are about to repeat an NMI anyway.
1496	 * This makes it safe to copy to the stack frame that a nested
1497	 * NMI will update.
1498	 *
1499	 * RSP is pointing to "outermost RIP".  gsbase is unknown, but, if
1500	 * we're repeating an NMI, gsbase has the same value that it had on
1501	 * the first iteration.  paranoid_entry will load the kernel
1502	 * gsbase if needed before we call do_nmi.  "NMI executing"
1503	 * is zero.
1504	 */
1505	movq	$1, 10*8(%rsp)		/* Set "NMI executing". */
1506
1507	/*
1508	 * Copy the "outermost" frame to the "iret" frame.  NMIs that nest
1509	 * here must not modify the "iret" frame while we're writing to
1510	 * it or it will end up containing garbage.
1511	 */
1512	addq	$(10*8), %rsp
1513	.rept 5
1514	pushq	-6*8(%rsp)
1515	.endr
1516	subq	$(5*8), %rsp
1517end_repeat_nmi:
1518
1519	/*
1520	 * Everything below this point can be preempted by a nested NMI.
1521	 * If this happens, then the inner NMI will change the "iret"
1522	 * frame to point back to repeat_nmi.
1523	 */
1524	pushq	$-1				/* ORIG_RAX: no syscall to restart */
1525	ALLOC_PT_GPREGS_ON_STACK
1526
1527	/*
1528	 * Use paranoid_entry to handle SWAPGS, but no need to use paranoid_exit
1529	 * as we should not be calling schedule in NMI context.
1530	 * Even with normal interrupts enabled. An NMI should not be
1531	 * setting NEED_RESCHED or anything that normal interrupts and
1532	 * exceptions might do.
1533	 */
1534	call	paranoid_entry
1535	UNWIND_HINT_REGS
1536
1537	/* paranoidentry do_nmi, 0; without TRACE_IRQS_OFF */
1538	movq	%rsp, %rdi
1539	movq	$-1, %rsi
1540	call	do_nmi
1541
1542	testl	%ebx, %ebx			/* swapgs needed? */
1543	jnz	nmi_restore
1544nmi_swapgs:
1545	SWAPGS_UNSAFE_STACK
1546nmi_restore:
1547	RESTORE_EXTRA_REGS
1548	RESTORE_C_REGS
1549
1550	/* Point RSP at the "iret" frame. */
1551	REMOVE_PT_GPREGS_FROM_STACK 6*8
1552
1553	/*
1554	 * Clear "NMI executing".  Set DF first so that we can easily
1555	 * distinguish the remaining code between here and IRET from
1556	 * the SYSCALL entry and exit paths.  On a native kernel, we
1557	 * could just inspect RIP, but, on paravirt kernels,
1558	 * INTERRUPT_RETURN can translate into a jump into a
1559	 * hypercall page.
1560	 */
1561	std
1562	movq	$0, 5*8(%rsp)		/* clear "NMI executing" */
1563
1564	/*
1565	 * INTERRUPT_RETURN reads the "iret" frame and exits the NMI
1566	 * stack in a single instruction.  We are returning to kernel
1567	 * mode, so this cannot result in a fault.
1568	 */
1569	INTERRUPT_RETURN
1570END(nmi)
1571
1572ENTRY(ignore_sysret)
1573	UNWIND_HINT_EMPTY
1574	mov	$-ENOSYS, %eax
1575	sysret
1576END(ignore_sysret)
1577
1578ENTRY(rewind_stack_do_exit)
1579	UNWIND_HINT_FUNC
1580	/* Prevent any naive code from trying to unwind to our caller. */
1581	xorl	%ebp, %ebp
1582
1583	movq	PER_CPU_VAR(cpu_current_top_of_stack), %rax
1584	leaq	-PTREGS_SIZE(%rax), %rsp
1585	UNWIND_HINT_FUNC sp_offset=PTREGS_SIZE
1586
1587	call	do_exit
1588END(rewind_stack_do_exit)
1589