GNU Linux-libre 4.19.295-gnu1
[releases.git] / arch / x86 / include / asm / nospec-branch.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2
3 #ifndef _ASM_X86_NOSPEC_BRANCH_H_
4 #define _ASM_X86_NOSPEC_BRANCH_H_
5
6 #include <linux/static_key.h>
7
8 #include <asm/alternative.h>
9 #include <asm/alternative-asm.h>
10 #include <asm/cpufeatures.h>
11 #include <asm/msr-index.h>
12 #include <asm/percpu.h>
13
14 /*
15  * Fill the CPU return stack buffer.
16  *
17  * Each entry in the RSB, if used for a speculative 'ret', contains an
18  * infinite 'pause; lfence; jmp' loop to capture speculative execution.
19  *
20  * This is required in various cases for retpoline and IBRS-based
21  * mitigations for the Spectre variant 2 vulnerability. Sometimes to
22  * eliminate potentially bogus entries from the RSB, and sometimes
23  * purely to ensure that it doesn't get empty, which on some CPUs would
24  * allow predictions from other (unwanted!) sources to be used.
25  *
26  * We define a CPP macro such that it can be used from both .S files and
27  * inline assembly. It's possible to do a .macro and then include that
28  * from C via asm(".include <asm/nospec-branch.h>") but let's not go there.
29  */
30
31 #define RSB_CLEAR_LOOPS         32      /* To forcibly overwrite all entries */
32 #define RSB_FILL_LOOPS          16      /* To avoid underflow */
33
34 /*
35  * Google experimented with loop-unrolling and this turned out to be
36  * the optimal version — two calls, each with their own speculation
37  * trap should their return address end up getting used, in a loop.
38  */
39 #ifdef CONFIG_X86_64
40 #define __FILL_RETURN_BUFFER(reg, nr, sp)       \
41         mov     $(nr/2), reg;                   \
42 771:                                            \
43         call    772f;                           \
44 773:    /* speculation trap */                  \
45         pause;                                  \
46         lfence;                                 \
47         jmp     773b;                           \
48 772:                                            \
49         call    774f;                           \
50 775:    /* speculation trap */                  \
51         pause;                                  \
52         lfence;                                 \
53         jmp     775b;                           \
54 774:                                            \
55         dec     reg;                            \
56         jnz     771b;                           \
57         add     $(BITS_PER_LONG/8) * nr, sp;    \
58         /* barrier for jnz misprediction */     \
59         lfence;
60 #else
61 /*
62  * i386 doesn't unconditionally have LFENCE, as such it can't
63  * do a loop.
64  */
65 #define __FILL_RETURN_BUFFER(reg, nr, sp)       \
66         .rept nr;                               \
67         call    772f;                           \
68         int3;                                   \
69 772:;                                           \
70         .endr;                                  \
71         add     $(BITS_PER_LONG/8) * nr, sp;
72 #endif
73
74 #define ISSUE_UNBALANCED_RET_GUARD(sp)          \
75         call 992f;                              \
76         int3;                                   \
77 992:                                            \
78         add $(BITS_PER_LONG/8), sp;             \
79         lfence;
80
81 #ifdef __ASSEMBLY__
82
83 /*
84  * This should be used immediately before a retpoline alternative.  It tells
85  * objtool where the retpolines are so that it can make sense of the control
86  * flow by just reading the original instruction(s) and ignoring the
87  * alternatives.
88  */
89 .macro ANNOTATE_NOSPEC_ALTERNATIVE
90         .Lannotate_\@:
91         .pushsection .discard.nospec
92         .long .Lannotate_\@ - .
93         .popsection
94 .endm
95
96 /*
97  * This should be used immediately before an indirect jump/call. It tells
98  * objtool the subsequent indirect jump/call is vouched safe for retpoline
99  * builds.
100  */
101 .macro ANNOTATE_RETPOLINE_SAFE
102         .Lannotate_\@:
103         .pushsection .discard.retpoline_safe
104         _ASM_PTR .Lannotate_\@
105         .popsection
106 .endm
107
108 /*
109  * These are the bare retpoline primitives for indirect jmp and call.
110  * Do not use these directly; they only exist to make the ALTERNATIVE
111  * invocation below less ugly.
112  */
113 .macro RETPOLINE_JMP reg:req
114         call    .Ldo_rop_\@
115 .Lspec_trap_\@:
116         pause
117         lfence
118         jmp     .Lspec_trap_\@
119 .Ldo_rop_\@:
120         mov     \reg, (%_ASM_SP)
121         ret
122 .endm
123
124 /*
125  * This is a wrapper around RETPOLINE_JMP so the called function in reg
126  * returns to the instruction after the macro.
127  */
128 .macro RETPOLINE_CALL reg:req
129         jmp     .Ldo_call_\@
130 .Ldo_retpoline_jmp_\@:
131         RETPOLINE_JMP \reg
132 .Ldo_call_\@:
133         call    .Ldo_retpoline_jmp_\@
134 .endm
135
136 /*
137  * JMP_NOSPEC and CALL_NOSPEC macros can be used instead of a simple
138  * indirect jmp/call which may be susceptible to the Spectre variant 2
139  * attack.
140  */
141 .macro JMP_NOSPEC reg:req
142 #ifdef CONFIG_RETPOLINE
143         ANNOTATE_NOSPEC_ALTERNATIVE
144         ALTERNATIVE_2 __stringify(ANNOTATE_RETPOLINE_SAFE; jmp *\reg),  \
145                 __stringify(RETPOLINE_JMP \reg), X86_FEATURE_RETPOLINE, \
146                 __stringify(lfence; ANNOTATE_RETPOLINE_SAFE; jmp *\reg), X86_FEATURE_RETPOLINE_LFENCE
147 #else
148         jmp     *\reg
149 #endif
150 .endm
151
152 .macro CALL_NOSPEC reg:req
153 #ifdef CONFIG_RETPOLINE
154         ANNOTATE_NOSPEC_ALTERNATIVE
155         ALTERNATIVE_2 __stringify(ANNOTATE_RETPOLINE_SAFE; call *\reg), \
156                 __stringify(RETPOLINE_CALL \reg), X86_FEATURE_RETPOLINE,\
157                 __stringify(lfence; ANNOTATE_RETPOLINE_SAFE; call *\reg), X86_FEATURE_RETPOLINE_LFENCE
158 #else
159         call    *\reg
160 #endif
161 .endm
162
163  /*
164   * A simpler FILL_RETURN_BUFFER macro. Don't make people use the CPP
165   * monstrosity above, manually.
166   */
167 .macro FILL_RETURN_BUFFER reg:req nr:req ftr:req
168         ANNOTATE_NOSPEC_ALTERNATIVE
169         ALTERNATIVE "jmp .Lskip_rsb_\@",                                \
170                 __stringify(__FILL_RETURN_BUFFER(\reg,\nr,%_ASM_SP))    \
171                 \ftr
172 .Lskip_rsb_\@:
173 .endm
174
175 #else /* __ASSEMBLY__ */
176
177 #define ANNOTATE_NOSPEC_ALTERNATIVE                             \
178         "999:\n\t"                                              \
179         ".pushsection .discard.nospec\n\t"                      \
180         ".long 999b - .\n\t"                                    \
181         ".popsection\n\t"
182
183 #define ANNOTATE_RETPOLINE_SAFE                                 \
184         "999:\n\t"                                              \
185         ".pushsection .discard.retpoline_safe\n\t"              \
186         _ASM_PTR " 999b\n\t"                                    \
187         ".popsection\n\t"
188
189 #ifdef CONFIG_RETPOLINE
190 #ifdef CONFIG_X86_64
191
192 /*
193  * Inline asm uses the %V modifier which is only in newer GCC
194  * which is ensured when CONFIG_RETPOLINE is defined.
195  */
196 # define CALL_NOSPEC                                            \
197         ANNOTATE_NOSPEC_ALTERNATIVE                             \
198         ALTERNATIVE_2(                                          \
199         ANNOTATE_RETPOLINE_SAFE                                 \
200         "call *%[thunk_target]\n",                              \
201         "call __x86_indirect_thunk_%V[thunk_target]\n",         \
202         X86_FEATURE_RETPOLINE,                                  \
203         "lfence;\n"                                             \
204         ANNOTATE_RETPOLINE_SAFE                                 \
205         "call *%[thunk_target]\n",                              \
206         X86_FEATURE_RETPOLINE_LFENCE)
207 # define THUNK_TARGET(addr) [thunk_target] "r" (addr)
208
209 #else /* CONFIG_X86_32 */
210 /*
211  * For i386 we use the original ret-equivalent retpoline, because
212  * otherwise we'll run out of registers. We don't care about CET
213  * here, anyway.
214  */
215 # define CALL_NOSPEC                                            \
216         ANNOTATE_NOSPEC_ALTERNATIVE                             \
217         ALTERNATIVE_2(                                          \
218         ANNOTATE_RETPOLINE_SAFE                                 \
219         "call *%[thunk_target]\n",                              \
220         "       jmp    904f;\n"                                 \
221         "       .align 16\n"                                    \
222         "901:   call   903f;\n"                                 \
223         "902:   pause;\n"                                       \
224         "       lfence;\n"                                      \
225         "       jmp    902b;\n"                                 \
226         "       .align 16\n"                                    \
227         "903:   lea    4(%%esp), %%esp;\n"                      \
228         "       pushl  %[thunk_target];\n"                      \
229         "       ret;\n"                                         \
230         "       .align 16\n"                                    \
231         "904:   call   901b;\n",                                \
232         X86_FEATURE_RETPOLINE,                                  \
233         "lfence;\n"                                             \
234         ANNOTATE_RETPOLINE_SAFE                                 \
235         "call *%[thunk_target]\n",                              \
236         X86_FEATURE_RETPOLINE_LFENCE)
237
238 # define THUNK_TARGET(addr) [thunk_target] "rm" (addr)
239 #endif
240 #else /* No retpoline for C / inline asm */
241 # define CALL_NOSPEC "call *%[thunk_target]\n"
242 # define THUNK_TARGET(addr) [thunk_target] "rm" (addr)
243 #endif
244
245 /* The Spectre V2 mitigation variants */
246 enum spectre_v2_mitigation {
247         SPECTRE_V2_NONE,
248         SPECTRE_V2_RETPOLINE,
249         SPECTRE_V2_LFENCE,
250         SPECTRE_V2_EIBRS,
251         SPECTRE_V2_EIBRS_RETPOLINE,
252         SPECTRE_V2_EIBRS_LFENCE,
253         SPECTRE_V2_IBRS,
254 };
255
256 /* The indirect branch speculation control variants */
257 enum spectre_v2_user_mitigation {
258         SPECTRE_V2_USER_NONE,
259         SPECTRE_V2_USER_STRICT,
260         SPECTRE_V2_USER_STRICT_PREFERRED,
261         SPECTRE_V2_USER_PRCTL,
262         SPECTRE_V2_USER_SECCOMP,
263 };
264
265 /* The Speculative Store Bypass disable variants */
266 enum ssb_mitigation {
267         SPEC_STORE_BYPASS_NONE,
268         SPEC_STORE_BYPASS_DISABLE,
269         SPEC_STORE_BYPASS_PRCTL,
270         SPEC_STORE_BYPASS_SECCOMP,
271 };
272
273 extern char __indirect_thunk_start[];
274 extern char __indirect_thunk_end[];
275
276 /*
277  * On VMEXIT we must ensure that no RSB predictions learned in the guest
278  * can be followed in the host, by overwriting the RSB completely. Both
279  * retpoline and IBRS mitigations for Spectre v2 need this; only on future
280  * CPUs with IBRS_ALL *might* it be avoided.
281  */
282 static __always_inline void vmexit_fill_RSB(void)
283 {
284 #ifdef CONFIG_RETPOLINE
285         unsigned long loops;
286
287         asm volatile (ANNOTATE_NOSPEC_ALTERNATIVE
288                       ALTERNATIVE_2("jmp 910f", "", X86_FEATURE_RSB_VMEXIT,
289                                     "jmp 911f", X86_FEATURE_RSB_VMEXIT_LITE)
290                       __stringify(__FILL_RETURN_BUFFER(%0, RSB_CLEAR_LOOPS, %1))
291                       "911:"
292                       __stringify(ISSUE_UNBALANCED_RET_GUARD(%1))
293                       "910:"
294                       : "=r" (loops), ASM_CALL_CONSTRAINT
295                       : : "memory" );
296 #endif
297 }
298
299 static __always_inline
300 void alternative_msr_write(unsigned int msr, u64 val, unsigned int feature)
301 {
302         asm volatile(ALTERNATIVE("", "wrmsr", %c[feature])
303                 : : "c" (msr),
304                     "a" ((u32)val),
305                     "d" ((u32)(val >> 32)),
306                     [feature] "i" (feature)
307                 : "memory");
308 }
309
310 static inline void indirect_branch_prediction_barrier(void)
311 {
312         u64 val = PRED_CMD_IBPB;
313
314         alternative_msr_write(MSR_IA32_PRED_CMD, val, X86_FEATURE_USE_IBPB);
315 }
316
317 /* The Intel SPEC CTRL MSR base value cache */
318 extern u64 x86_spec_ctrl_base;
319 DECLARE_PER_CPU(u64, x86_spec_ctrl_current);
320 extern void update_spec_ctrl_cond(u64 val);
321 extern u64 spec_ctrl_current(void);
322
323 /*
324  * With retpoline, we must use IBRS to restrict branch prediction
325  * before calling into firmware.
326  *
327  * (Implemented as CPP macros due to header hell.)
328  */
329 #define firmware_restrict_branch_speculation_start()                    \
330 do {                                                                    \
331         preempt_disable();                                              \
332         alternative_msr_write(MSR_IA32_SPEC_CTRL,                       \
333                               spec_ctrl_current() | SPEC_CTRL_IBRS,     \
334                               X86_FEATURE_USE_IBRS_FW);                 \
335 } while (0)
336
337 #define firmware_restrict_branch_speculation_end()                      \
338 do {                                                                    \
339         alternative_msr_write(MSR_IA32_SPEC_CTRL,                       \
340                               spec_ctrl_current(),                      \
341                               X86_FEATURE_USE_IBRS_FW);                 \
342         preempt_enable();                                               \
343 } while (0)
344
345 DECLARE_STATIC_KEY_FALSE(switch_to_cond_stibp);
346 DECLARE_STATIC_KEY_FALSE(switch_mm_cond_ibpb);
347 DECLARE_STATIC_KEY_FALSE(switch_mm_always_ibpb);
348
349 DECLARE_STATIC_KEY_FALSE(mds_user_clear);
350 DECLARE_STATIC_KEY_FALSE(mds_idle_clear);
351
352 DECLARE_STATIC_KEY_FALSE(mmio_stale_data_clear);
353
354 #include <asm/segment.h>
355
356 /**
357  * mds_clear_cpu_buffers - Mitigation for MDS and TAA vulnerability
358  *
359  * This uses the otherwise unused and obsolete VERW instruction in
360  * combination with microcode which triggers a CPU buffer flush when the
361  * instruction is executed.
362  */
363 static __always_inline void mds_clear_cpu_buffers(void)
364 {
365         static const u16 ds = __KERNEL_DS;
366
367         /*
368          * Has to be the memory-operand variant because only that
369          * guarantees the CPU buffer flush functionality according to
370          * documentation. The register-operand variant does not.
371          * Works with any segment selector, but a valid writable
372          * data segment is the fastest variant.
373          *
374          * "cc" clobber is required because VERW modifies ZF.
375          */
376         asm volatile("verw %[ds]" : : [ds] "m" (ds) : "cc");
377 }
378
379 /**
380  * mds_user_clear_cpu_buffers - Mitigation for MDS and TAA vulnerability
381  *
382  * Clear CPU buffers if the corresponding static key is enabled
383  */
384 static __always_inline void mds_user_clear_cpu_buffers(void)
385 {
386         if (static_branch_likely(&mds_user_clear))
387                 mds_clear_cpu_buffers();
388 }
389
390 /**
391  * mds_idle_clear_cpu_buffers - Mitigation for MDS vulnerability
392  *
393  * Clear CPU buffers if the corresponding static key is enabled
394  */
395 static inline void mds_idle_clear_cpu_buffers(void)
396 {
397         if (static_branch_likely(&mds_idle_clear))
398                 mds_clear_cpu_buffers();
399 }
400
401 #endif /* __ASSEMBLY__ */
402
403 /*
404  * Below is used in the eBPF JIT compiler and emits the byte sequence
405  * for the following assembly:
406  *
407  * With retpolines configured:
408  *
409  *    callq do_rop
410  *  spec_trap:
411  *    pause
412  *    lfence
413  *    jmp spec_trap
414  *  do_rop:
415  *    mov %rax,(%rsp) for x86_64
416  *    mov %edx,(%esp) for x86_32
417  *    retq
418  *
419  * Without retpolines configured:
420  *
421  *    jmp *%rax for x86_64
422  *    jmp *%edx for x86_32
423  */
424 #ifdef CONFIG_RETPOLINE
425 # ifdef CONFIG_X86_64
426 #  define RETPOLINE_RAX_BPF_JIT_SIZE    17
427 #  define RETPOLINE_RAX_BPF_JIT()                               \
428 do {                                                            \
429         EMIT1_off32(0xE8, 7);    /* callq do_rop */             \
430         /* spec_trap: */                                        \
431         EMIT2(0xF3, 0x90);       /* pause */                    \
432         EMIT3(0x0F, 0xAE, 0xE8); /* lfence */                   \
433         EMIT2(0xEB, 0xF9);       /* jmp spec_trap */            \
434         /* do_rop: */                                           \
435         EMIT4(0x48, 0x89, 0x04, 0x24); /* mov %rax,(%rsp) */    \
436         EMIT1(0xC3);             /* retq */                     \
437 } while (0)
438 # else /* !CONFIG_X86_64 */
439 #  define RETPOLINE_EDX_BPF_JIT()                               \
440 do {                                                            \
441         EMIT1_off32(0xE8, 7);    /* call do_rop */              \
442         /* spec_trap: */                                        \
443         EMIT2(0xF3, 0x90);       /* pause */                    \
444         EMIT3(0x0F, 0xAE, 0xE8); /* lfence */                   \
445         EMIT2(0xEB, 0xF9);       /* jmp spec_trap */            \
446         /* do_rop: */                                           \
447         EMIT3(0x89, 0x14, 0x24); /* mov %edx,(%esp) */          \
448         EMIT1(0xC3);             /* ret */                      \
449 } while (0)
450 # endif
451 #else /* !CONFIG_RETPOLINE */
452 # ifdef CONFIG_X86_64
453 #  define RETPOLINE_RAX_BPF_JIT_SIZE    2
454 #  define RETPOLINE_RAX_BPF_JIT()                               \
455         EMIT2(0xFF, 0xE0);       /* jmp *%rax */
456 # else /* !CONFIG_X86_64 */
457 #  define RETPOLINE_EDX_BPF_JIT()                               \
458         EMIT2(0xFF, 0xE2)        /* jmp *%edx */
459 # endif
460 #endif
461
462 #endif /* _ASM_X86_NOSPEC_BRANCH_H_ */