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