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