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