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#include <linux/objtool.h>
8#include <linux/linkage.h>
9
10#include <asm/alternative.h>
11#include <asm/cpufeatures.h>
12#include <asm/msr-index.h>
13#include <asm/unwind_hints.h>
14#include <asm/percpu.h>
15#include <asm/current.h>
16
17/*
18 * Call depth tracking for Intel SKL CPUs to address the RSB underflow
19 * issue in software.
20 *
21 * The tracking does not use a counter. It uses uses arithmetic shift
22 * right on call entry and logical shift left on return.
23 *
24 * The depth tracking variable is initialized to 0x8000.... when the call
25 * depth is zero. The arithmetic shift right sign extends the MSB and
26 * saturates after the 12th call. The shift count is 5 for both directions
27 * so the tracking covers 12 nested calls.
28 *
29 *  Call
30 *  0: 0x8000000000000000	0x0000000000000000
31 *  1: 0xfc00000000000000	0xf000000000000000
32 * ...
33 * 11: 0xfffffffffffffff8	0xfffffffffffffc00
34 * 12: 0xffffffffffffffff	0xffffffffffffffe0
35 *
36 * After a return buffer fill the depth is credited 12 calls before the
37 * next stuffing has to take place.
38 *
39 * There is a inaccuracy for situations like this:
40 *
41 *  10 calls
42 *   5 returns
43 *   3 calls
44 *   4 returns
45 *   3 calls
46 *   ....
47 *
48 * The shift count might cause this to be off by one in either direction,
49 * but there is still a cushion vs. the RSB depth. The algorithm does not
50 * claim to be perfect and it can be speculated around by the CPU, but it
51 * is considered that it obfuscates the problem enough to make exploitation
52 * extremly difficult.
53 */
54#define RET_DEPTH_SHIFT			5
55#define RSB_RET_STUFF_LOOPS		16
56#define RET_DEPTH_INIT			0x8000000000000000ULL
57#define RET_DEPTH_INIT_FROM_CALL	0xfc00000000000000ULL
58#define RET_DEPTH_CREDIT		0xffffffffffffffffULL
59
60#ifdef CONFIG_CALL_THUNKS_DEBUG
61# define CALL_THUNKS_DEBUG_INC_CALLS				\
62	incq	%gs:__x86_call_count;
63# define CALL_THUNKS_DEBUG_INC_RETS				\
64	incq	%gs:__x86_ret_count;
65# define CALL_THUNKS_DEBUG_INC_STUFFS				\
66	incq	%gs:__x86_stuffs_count;
67# define CALL_THUNKS_DEBUG_INC_CTXSW				\
68	incq	%gs:__x86_ctxsw_count;
69#else
70# define CALL_THUNKS_DEBUG_INC_CALLS
71# define CALL_THUNKS_DEBUG_INC_RETS
72# define CALL_THUNKS_DEBUG_INC_STUFFS
73# define CALL_THUNKS_DEBUG_INC_CTXSW
74#endif
75
76#if defined(CONFIG_CALL_DEPTH_TRACKING) && !defined(COMPILE_OFFSETS)
77
78#include <asm/asm-offsets.h>
79
80#define CREDIT_CALL_DEPTH					\
81	movq	$-1, PER_CPU_VAR(pcpu_hot + X86_call_depth);
82
83#define ASM_CREDIT_CALL_DEPTH					\
84	movq	$-1, PER_CPU_VAR(pcpu_hot + X86_call_depth);
85
86#define RESET_CALL_DEPTH					\
87	xor	%eax, %eax;					\
88	bts	$63, %rax;					\
89	movq	%rax, PER_CPU_VAR(pcpu_hot + X86_call_depth);
90
91#define RESET_CALL_DEPTH_FROM_CALL				\
92	movb	$0xfc, %al;					\
93	shl	$56, %rax;					\
94	movq	%rax, PER_CPU_VAR(pcpu_hot + X86_call_depth);	\
95	CALL_THUNKS_DEBUG_INC_CALLS
96
97#define INCREMENT_CALL_DEPTH					\
98	sarq	$5, %gs:pcpu_hot + X86_call_depth;		\
99	CALL_THUNKS_DEBUG_INC_CALLS
100
101#define ASM_INCREMENT_CALL_DEPTH				\
102	sarq	$5, PER_CPU_VAR(pcpu_hot + X86_call_depth);	\
103	CALL_THUNKS_DEBUG_INC_CALLS
104
105#else
106#define CREDIT_CALL_DEPTH
107#define ASM_CREDIT_CALL_DEPTH
108#define RESET_CALL_DEPTH
109#define INCREMENT_CALL_DEPTH
110#define ASM_INCREMENT_CALL_DEPTH
111#define RESET_CALL_DEPTH_FROM_CALL
112#endif
113
114/*
115 * Fill the CPU return stack buffer.
116 *
117 * Each entry in the RSB, if used for a speculative 'ret', contains an
118 * infinite 'pause; lfence; jmp' loop to capture speculative execution.
119 *
120 * This is required in various cases for retpoline and IBRS-based
121 * mitigations for the Spectre variant 2 vulnerability. Sometimes to
122 * eliminate potentially bogus entries from the RSB, and sometimes
123 * purely to ensure that it doesn't get empty, which on some CPUs would
124 * allow predictions from other (unwanted!) sources to be used.
125 *
126 * We define a CPP macro such that it can be used from both .S files and
127 * inline assembly. It's possible to do a .macro and then include that
128 * from C via asm(".include <asm/nospec-branch.h>") but let's not go there.
129 */
130
131#define RETPOLINE_THUNK_SIZE	32
132#define RSB_CLEAR_LOOPS		32	/* To forcibly overwrite all entries */
133
134/*
135 * Common helper for __FILL_RETURN_BUFFER and __FILL_ONE_RETURN.
136 */
137#define __FILL_RETURN_SLOT			\
138	ANNOTATE_INTRA_FUNCTION_CALL;		\
139	call	772f;				\
140	int3;					\
141772:
142
143/*
144 * Stuff the entire RSB.
145 *
146 * Google experimented with loop-unrolling and this turned out to be
147 * the optimal version - two calls, each with their own speculation
148 * trap should their return address end up getting used, in a loop.
149 */
150#ifdef CONFIG_X86_64
151#define __FILL_RETURN_BUFFER(reg, nr)			\
152	mov	$(nr/2), reg;				\
153771:							\
154	__FILL_RETURN_SLOT				\
155	__FILL_RETURN_SLOT				\
156	add	$(BITS_PER_LONG/8) * 2, %_ASM_SP;	\
157	dec	reg;					\
158	jnz	771b;					\
159	/* barrier for jnz misprediction */		\
160	lfence;						\
161	ASM_CREDIT_CALL_DEPTH				\
162	CALL_THUNKS_DEBUG_INC_CTXSW
163#else
164/*
165 * i386 doesn't unconditionally have LFENCE, as such it can't
166 * do a loop.
167 */
168#define __FILL_RETURN_BUFFER(reg, nr)			\
169	.rept nr;					\
170	__FILL_RETURN_SLOT;				\
171	.endr;						\
172	add	$(BITS_PER_LONG/8) * nr, %_ASM_SP;
173#endif
174
175/*
176 * Stuff a single RSB slot.
177 *
178 * To mitigate Post-Barrier RSB speculation, one CALL instruction must be
179 * forced to retire before letting a RET instruction execute.
180 *
181 * On PBRSB-vulnerable CPUs, it is not safe for a RET to be executed
182 * before this point.
183 */
184#define __FILL_ONE_RETURN				\
185	__FILL_RETURN_SLOT				\
186	add	$(BITS_PER_LONG/8), %_ASM_SP;		\
187	lfence;
188
189#ifdef __ASSEMBLY__
190
191/*
192 * This should be used immediately before an indirect jump/call. It tells
193 * objtool the subsequent indirect jump/call is vouched safe for retpoline
194 * builds.
195 */
196.macro ANNOTATE_RETPOLINE_SAFE
197.Lhere_\@:
198	.pushsection .discard.retpoline_safe
199	.long .Lhere_\@
200	.popsection
201.endm
202
203/*
204 * (ab)use RETPOLINE_SAFE on RET to annotate away 'bare' RET instructions
205 * vs RETBleed validation.
206 */
207#define ANNOTATE_UNRET_SAFE ANNOTATE_RETPOLINE_SAFE
208
209/*
210 * Abuse ANNOTATE_RETPOLINE_SAFE on a NOP to indicate UNRET_END, should
211 * eventually turn into it's own annotation.
212 */
213.macro VALIDATE_UNRET_END
214#if defined(CONFIG_NOINSTR_VALIDATION) && \
215	(defined(CONFIG_CPU_UNRET_ENTRY) || defined(CONFIG_CPU_SRSO))
216	ANNOTATE_RETPOLINE_SAFE
217	nop
218#endif
219.endm
220
221/*
222 * Equivalent to -mindirect-branch-cs-prefix; emit the 5 byte jmp/call
223 * to the retpoline thunk with a CS prefix when the register requires
224 * a RAX prefix byte to encode. Also see apply_retpolines().
225 */
226.macro __CS_PREFIX reg:req
227	.irp rs,r8,r9,r10,r11,r12,r13,r14,r15
228	.ifc \reg,\rs
229	.byte 0x2e
230	.endif
231	.endr
232.endm
233
234/*
235 * JMP_NOSPEC and CALL_NOSPEC macros can be used instead of a simple
236 * indirect jmp/call which may be susceptible to the Spectre variant 2
237 * attack.
238 *
239 * NOTE: these do not take kCFI into account and are thus not comparable to C
240 * indirect calls, take care when using. The target of these should be an ENDBR
241 * instruction irrespective of kCFI.
242 */
243.macro JMP_NOSPEC reg:req
244#ifdef CONFIG_RETPOLINE
245	__CS_PREFIX \reg
246	jmp	__x86_indirect_thunk_\reg
247#else
248	jmp	*%\reg
249	int3
250#endif
251.endm
252
253.macro CALL_NOSPEC reg:req
254#ifdef CONFIG_RETPOLINE
255	__CS_PREFIX \reg
256	call	__x86_indirect_thunk_\reg
257#else
258	call	*%\reg
259#endif
260.endm
261
262 /*
263  * A simpler FILL_RETURN_BUFFER macro. Don't make people use the CPP
264  * monstrosity above, manually.
265  */
266.macro FILL_RETURN_BUFFER reg:req nr:req ftr:req ftr2=ALT_NOT(X86_FEATURE_ALWAYS)
267	ALTERNATIVE_2 "jmp .Lskip_rsb_\@", \
268		__stringify(__FILL_RETURN_BUFFER(\reg,\nr)), \ftr, \
269		__stringify(nop;nop;__FILL_ONE_RETURN), \ftr2
270
271.Lskip_rsb_\@:
272.endm
273
274#if defined(CONFIG_CPU_UNRET_ENTRY) || defined(CONFIG_CPU_SRSO)
275#define CALL_UNTRAIN_RET	"call entry_untrain_ret"
276#else
277#define CALL_UNTRAIN_RET	""
278#endif
279
280/*
281 * Mitigate RETBleed for AMD/Hygon Zen uarch. Requires KERNEL CR3 because the
282 * return thunk isn't mapped into the userspace tables (then again, AMD
283 * typically has NO_MELTDOWN).
284 *
285 * While retbleed_untrain_ret() doesn't clobber anything but requires stack,
286 * entry_ibpb() will clobber AX, CX, DX.
287 *
288 * As such, this must be placed after every *SWITCH_TO_KERNEL_CR3 at a point
289 * where we have a stack but before any RET instruction.
290 */
291.macro UNTRAIN_RET
292#if defined(CONFIG_CPU_UNRET_ENTRY) || defined(CONFIG_CPU_IBPB_ENTRY) || \
293	defined(CONFIG_CALL_DEPTH_TRACKING) || defined(CONFIG_CPU_SRSO)
294	VALIDATE_UNRET_END
295	ALTERNATIVE_3 "",						\
296		      CALL_UNTRAIN_RET, X86_FEATURE_UNRET,		\
297		      "call entry_ibpb", X86_FEATURE_ENTRY_IBPB,	\
298		      __stringify(RESET_CALL_DEPTH), X86_FEATURE_CALL_DEPTH
299#endif
300.endm
301
302.macro UNTRAIN_RET_VM
303#if defined(CONFIG_CPU_UNRET_ENTRY) || defined(CONFIG_CPU_IBPB_ENTRY) || \
304	defined(CONFIG_CALL_DEPTH_TRACKING) || defined(CONFIG_CPU_SRSO)
305	VALIDATE_UNRET_END
306	ALTERNATIVE_3 "",						\
307		      CALL_UNTRAIN_RET, X86_FEATURE_UNRET,		\
308		      "call entry_ibpb", X86_FEATURE_IBPB_ON_VMEXIT,	\
309		      __stringify(RESET_CALL_DEPTH), X86_FEATURE_CALL_DEPTH
310#endif
311.endm
312
313.macro UNTRAIN_RET_FROM_CALL
314#if defined(CONFIG_CPU_UNRET_ENTRY) || defined(CONFIG_CPU_IBPB_ENTRY) || \
315	defined(CONFIG_CALL_DEPTH_TRACKING) || defined(CONFIG_CPU_SRSO)
316	VALIDATE_UNRET_END
317	ALTERNATIVE_3 "",						\
318		      CALL_UNTRAIN_RET, X86_FEATURE_UNRET,		\
319		      "call entry_ibpb", X86_FEATURE_ENTRY_IBPB,	\
320		      __stringify(RESET_CALL_DEPTH_FROM_CALL), X86_FEATURE_CALL_DEPTH
321#endif
322.endm
323
324
325.macro CALL_DEPTH_ACCOUNT
326#ifdef CONFIG_CALL_DEPTH_TRACKING
327	ALTERNATIVE "",							\
328		    __stringify(ASM_INCREMENT_CALL_DEPTH), X86_FEATURE_CALL_DEPTH
329#endif
330.endm
331
332/*
333 * Macro to execute VERW instruction that mitigate transient data sampling
334 * attacks such as MDS. On affected systems a microcode update overloaded VERW
335 * instruction to also clear the CPU buffers. VERW clobbers CFLAGS.ZF.
336 *
337 * Note: Only the memory operand variant of VERW clears the CPU buffers.
338 */
339.macro CLEAR_CPU_BUFFERS
340	ALTERNATIVE "", __stringify(verw _ASM_RIP(mds_verw_sel)), X86_FEATURE_CLEAR_CPU_BUF
341.endm
342
343#else /* __ASSEMBLY__ */
344
345#define ANNOTATE_RETPOLINE_SAFE					\
346	"999:\n\t"						\
347	".pushsection .discard.retpoline_safe\n\t"		\
348	".long 999b\n\t"					\
349	".popsection\n\t"
350
351typedef u8 retpoline_thunk_t[RETPOLINE_THUNK_SIZE];
352extern retpoline_thunk_t __x86_indirect_thunk_array[];
353extern retpoline_thunk_t __x86_indirect_call_thunk_array[];
354extern retpoline_thunk_t __x86_indirect_jump_thunk_array[];
355
356#ifdef CONFIG_RETHUNK
357extern void __x86_return_thunk(void);
358#else
359static inline void __x86_return_thunk(void) {}
360#endif
361
362extern void retbleed_return_thunk(void);
363extern void srso_return_thunk(void);
364extern void srso_alias_return_thunk(void);
365
366extern void retbleed_untrain_ret(void);
367extern void srso_untrain_ret(void);
368extern void srso_alias_untrain_ret(void);
369
370extern void entry_untrain_ret(void);
371extern void entry_ibpb(void);
372
373extern void (*x86_return_thunk)(void);
374
375#ifdef CONFIG_CALL_DEPTH_TRACKING
376extern void __x86_return_skl(void);
377
378static inline void x86_set_skl_return_thunk(void)
379{
380	x86_return_thunk = &__x86_return_skl;
381}
382
383#define CALL_DEPTH_ACCOUNT					\
384	ALTERNATIVE("",						\
385		    __stringify(INCREMENT_CALL_DEPTH),		\
386		    X86_FEATURE_CALL_DEPTH)
387
388#ifdef CONFIG_CALL_THUNKS_DEBUG
389DECLARE_PER_CPU(u64, __x86_call_count);
390DECLARE_PER_CPU(u64, __x86_ret_count);
391DECLARE_PER_CPU(u64, __x86_stuffs_count);
392DECLARE_PER_CPU(u64, __x86_ctxsw_count);
393#endif
394#else
395static inline void x86_set_skl_return_thunk(void) {}
396
397#define CALL_DEPTH_ACCOUNT ""
398
399#endif
400
401#ifdef CONFIG_RETPOLINE
402
403#define GEN(reg) \
404	extern retpoline_thunk_t __x86_indirect_thunk_ ## reg;
405#include <asm/GEN-for-each-reg.h>
406#undef GEN
407
408#define GEN(reg)						\
409	extern retpoline_thunk_t __x86_indirect_call_thunk_ ## reg;
410#include <asm/GEN-for-each-reg.h>
411#undef GEN
412
413#define GEN(reg)						\
414	extern retpoline_thunk_t __x86_indirect_jump_thunk_ ## reg;
415#include <asm/GEN-for-each-reg.h>
416#undef GEN
417
418#ifdef CONFIG_X86_64
419
420/*
421 * Inline asm uses the %V modifier which is only in newer GCC
422 * which is ensured when CONFIG_RETPOLINE is defined.
423 */
424# define CALL_NOSPEC						\
425	ALTERNATIVE_2(						\
426	ANNOTATE_RETPOLINE_SAFE					\
427	"call *%[thunk_target]\n",				\
428	"call __x86_indirect_thunk_%V[thunk_target]\n",		\
429	X86_FEATURE_RETPOLINE,					\
430	"lfence;\n"						\
431	ANNOTATE_RETPOLINE_SAFE					\
432	"call *%[thunk_target]\n",				\
433	X86_FEATURE_RETPOLINE_LFENCE)
434
435# define THUNK_TARGET(addr) [thunk_target] "r" (addr)
436
437#else /* CONFIG_X86_32 */
438/*
439 * For i386 we use the original ret-equivalent retpoline, because
440 * otherwise we'll run out of registers. We don't care about CET
441 * here, anyway.
442 */
443# define CALL_NOSPEC						\
444	ALTERNATIVE_2(						\
445	ANNOTATE_RETPOLINE_SAFE					\
446	"call *%[thunk_target]\n",				\
447	"       jmp    904f;\n"					\
448	"       .align 16\n"					\
449	"901:	call   903f;\n"					\
450	"902:	pause;\n"					\
451	"    	lfence;\n"					\
452	"       jmp    902b;\n"					\
453	"       .align 16\n"					\
454	"903:	lea    4(%%esp), %%esp;\n"			\
455	"       pushl  %[thunk_target];\n"			\
456	"       ret;\n"						\
457	"       .align 16\n"					\
458	"904:	call   901b;\n",				\
459	X86_FEATURE_RETPOLINE,					\
460	"lfence;\n"						\
461	ANNOTATE_RETPOLINE_SAFE					\
462	"call *%[thunk_target]\n",				\
463	X86_FEATURE_RETPOLINE_LFENCE)
464
465# define THUNK_TARGET(addr) [thunk_target] "rm" (addr)
466#endif
467#else /* No retpoline for C / inline asm */
468# define CALL_NOSPEC "call *%[thunk_target]\n"
469# define THUNK_TARGET(addr) [thunk_target] "rm" (addr)
470#endif
471
472/* The Spectre V2 mitigation variants */
473enum spectre_v2_mitigation {
474	SPECTRE_V2_NONE,
475	SPECTRE_V2_RETPOLINE,
476	SPECTRE_V2_LFENCE,
477	SPECTRE_V2_EIBRS,
478	SPECTRE_V2_EIBRS_RETPOLINE,
479	SPECTRE_V2_EIBRS_LFENCE,
480	SPECTRE_V2_IBRS,
481};
482
483/* The indirect branch speculation control variants */
484enum spectre_v2_user_mitigation {
485	SPECTRE_V2_USER_NONE,
486	SPECTRE_V2_USER_STRICT,
487	SPECTRE_V2_USER_STRICT_PREFERRED,
488	SPECTRE_V2_USER_PRCTL,
489	SPECTRE_V2_USER_SECCOMP,
490};
491
492/* The Speculative Store Bypass disable variants */
493enum ssb_mitigation {
494	SPEC_STORE_BYPASS_NONE,
495	SPEC_STORE_BYPASS_DISABLE,
496	SPEC_STORE_BYPASS_PRCTL,
497	SPEC_STORE_BYPASS_SECCOMP,
498};
499
500static __always_inline
501void alternative_msr_write(unsigned int msr, u64 val, unsigned int feature)
502{
503	asm volatile(ALTERNATIVE("", "wrmsr", %c[feature])
504		: : "c" (msr),
505		    "a" ((u32)val),
506		    "d" ((u32)(val >> 32)),
507		    [feature] "i" (feature)
508		: "memory");
509}
510
511extern u64 x86_pred_cmd;
512
513static inline void indirect_branch_prediction_barrier(void)
514{
515	alternative_msr_write(MSR_IA32_PRED_CMD, x86_pred_cmd, X86_FEATURE_USE_IBPB);
516}
517
518/* The Intel SPEC CTRL MSR base value cache */
519extern u64 x86_spec_ctrl_base;
520DECLARE_PER_CPU(u64, x86_spec_ctrl_current);
521extern void update_spec_ctrl_cond(u64 val);
522extern u64 spec_ctrl_current(void);
523
524/*
525 * With retpoline, we must use IBRS to restrict branch prediction
526 * before calling into firmware.
527 *
528 * (Implemented as CPP macros due to header hell.)
529 */
530#define firmware_restrict_branch_speculation_start()			\
531do {									\
532	preempt_disable();						\
533	alternative_msr_write(MSR_IA32_SPEC_CTRL,			\
534			      spec_ctrl_current() | SPEC_CTRL_IBRS,	\
535			      X86_FEATURE_USE_IBRS_FW);			\
536	alternative_msr_write(MSR_IA32_PRED_CMD, PRED_CMD_IBPB,		\
537			      X86_FEATURE_USE_IBPB_FW);			\
538} while (0)
539
540#define firmware_restrict_branch_speculation_end()			\
541do {									\
542	alternative_msr_write(MSR_IA32_SPEC_CTRL,			\
543			      spec_ctrl_current(),			\
544			      X86_FEATURE_USE_IBRS_FW);			\
545	preempt_enable();						\
546} while (0)
547
548DECLARE_STATIC_KEY_FALSE(switch_to_cond_stibp);
549DECLARE_STATIC_KEY_FALSE(switch_mm_cond_ibpb);
550DECLARE_STATIC_KEY_FALSE(switch_mm_always_ibpb);
551
552DECLARE_STATIC_KEY_FALSE(mds_idle_clear);
553
554DECLARE_STATIC_KEY_FALSE(switch_mm_cond_l1d_flush);
555
556DECLARE_STATIC_KEY_FALSE(mmio_stale_data_clear);
557
558extern u16 mds_verw_sel;
559
560#include <asm/segment.h>
561
562/**
563 * mds_clear_cpu_buffers - Mitigation for MDS and TAA vulnerability
564 *
565 * This uses the otherwise unused and obsolete VERW instruction in
566 * combination with microcode which triggers a CPU buffer flush when the
567 * instruction is executed.
568 */
569static __always_inline void mds_clear_cpu_buffers(void)
570{
571	static const u16 ds = __KERNEL_DS;
572
573	/*
574	 * Has to be the memory-operand variant because only that
575	 * guarantees the CPU buffer flush functionality according to
576	 * documentation. The register-operand variant does not.
577	 * Works with any segment selector, but a valid writable
578	 * data segment is the fastest variant.
579	 *
580	 * "cc" clobber is required because VERW modifies ZF.
581	 */
582	asm volatile("verw %[ds]" : : [ds] "m" (ds) : "cc");
583}
584
585/**
586 * mds_idle_clear_cpu_buffers - Mitigation for MDS vulnerability
587 *
588 * Clear CPU buffers if the corresponding static key is enabled
589 */
590static __always_inline void mds_idle_clear_cpu_buffers(void)
591{
592	if (static_branch_likely(&mds_idle_clear))
593		mds_clear_cpu_buffers();
594}
595
596#endif /* __ASSEMBLY__ */
597
598#endif /* _ASM_X86_NOSPEC_BRANCH_H_ */
599