Mention branches and keyring.
[releases.git] / x86 / kernel / cpu / bugs.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Copyright (C) 1994  Linus Torvalds
4  *
5  *  Cyrix stuff, June 1998 by:
6  *      - Rafael R. Reilova (moved everything from head.S),
7  *        <rreilova@ececs.uc.edu>
8  *      - Channing Corn (tests & fixes),
9  *      - Andrew D. Balsa (code cleanup).
10  */
11 #include <linux/init.h>
12 #include <linux/cpu.h>
13 #include <linux/module.h>
14 #include <linux/nospec.h>
15 #include <linux/prctl.h>
16 #include <linux/sched/smt.h>
17 #include <linux/pgtable.h>
18 #include <linux/bpf.h>
19
20 #include <asm/spec-ctrl.h>
21 #include <asm/cmdline.h>
22 #include <asm/bugs.h>
23 #include <asm/processor.h>
24 #include <asm/processor-flags.h>
25 #include <asm/fpu/api.h>
26 #include <asm/msr.h>
27 #include <asm/vmx.h>
28 #include <asm/paravirt.h>
29 #include <asm/intel-family.h>
30 #include <asm/e820/api.h>
31 #include <asm/hypervisor.h>
32 #include <asm/tlbflush.h>
33
34 #include "cpu.h"
35
36 static void __init spectre_v1_select_mitigation(void);
37 static void __init spectre_v2_select_mitigation(void);
38 static void __init retbleed_select_mitigation(void);
39 static void __init spectre_v2_user_select_mitigation(void);
40 static void __init ssb_select_mitigation(void);
41 static void __init l1tf_select_mitigation(void);
42 static void __init mds_select_mitigation(void);
43 static void __init md_clear_update_mitigation(void);
44 static void __init md_clear_select_mitigation(void);
45 static void __init taa_select_mitigation(void);
46 static void __init mmio_select_mitigation(void);
47 static void __init srbds_select_mitigation(void);
48 static void __init l1d_flush_select_mitigation(void);
49 static void __init gds_select_mitigation(void);
50 static void __init srso_select_mitigation(void);
51
52 /* The base value of the SPEC_CTRL MSR without task-specific bits set */
53 u64 x86_spec_ctrl_base;
54 EXPORT_SYMBOL_GPL(x86_spec_ctrl_base);
55
56 /* The current value of the SPEC_CTRL MSR with task-specific bits set */
57 DEFINE_PER_CPU(u64, x86_spec_ctrl_current);
58 EXPORT_SYMBOL_GPL(x86_spec_ctrl_current);
59
60 u64 x86_pred_cmd __ro_after_init = PRED_CMD_IBPB;
61 EXPORT_SYMBOL_GPL(x86_pred_cmd);
62
63 static u64 __ro_after_init x86_arch_cap_msr;
64
65 static DEFINE_MUTEX(spec_ctrl_mutex);
66
67 void (*x86_return_thunk)(void) __ro_after_init = &__x86_return_thunk;
68
69 /* Update SPEC_CTRL MSR and its cached copy unconditionally */
70 static void update_spec_ctrl(u64 val)
71 {
72         this_cpu_write(x86_spec_ctrl_current, val);
73         wrmsrl(MSR_IA32_SPEC_CTRL, val);
74 }
75
76 /*
77  * Keep track of the SPEC_CTRL MSR value for the current task, which may differ
78  * from x86_spec_ctrl_base due to STIBP/SSB in __speculation_ctrl_update().
79  */
80 void update_spec_ctrl_cond(u64 val)
81 {
82         if (this_cpu_read(x86_spec_ctrl_current) == val)
83                 return;
84
85         this_cpu_write(x86_spec_ctrl_current, val);
86
87         /*
88          * When KERNEL_IBRS this MSR is written on return-to-user, unless
89          * forced the update can be delayed until that time.
90          */
91         if (!cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS))
92                 wrmsrl(MSR_IA32_SPEC_CTRL, val);
93 }
94
95 u64 spec_ctrl_current(void)
96 {
97         return this_cpu_read(x86_spec_ctrl_current);
98 }
99 EXPORT_SYMBOL_GPL(spec_ctrl_current);
100
101 /*
102  * AMD specific MSR info for Speculative Store Bypass control.
103  * x86_amd_ls_cfg_ssbd_mask is initialized in identify_boot_cpu().
104  */
105 u64 __ro_after_init x86_amd_ls_cfg_base;
106 u64 __ro_after_init x86_amd_ls_cfg_ssbd_mask;
107
108 /* Control conditional STIBP in switch_to() */
109 DEFINE_STATIC_KEY_FALSE(switch_to_cond_stibp);
110 /* Control conditional IBPB in switch_mm() */
111 DEFINE_STATIC_KEY_FALSE(switch_mm_cond_ibpb);
112 /* Control unconditional IBPB in switch_mm() */
113 DEFINE_STATIC_KEY_FALSE(switch_mm_always_ibpb);
114
115 /* Control MDS CPU buffer clear before idling (halt, mwait) */
116 DEFINE_STATIC_KEY_FALSE(mds_idle_clear);
117 EXPORT_SYMBOL_GPL(mds_idle_clear);
118
119 /*
120  * Controls whether l1d flush based mitigations are enabled,
121  * based on hw features and admin setting via boot parameter
122  * defaults to false
123  */
124 DEFINE_STATIC_KEY_FALSE(switch_mm_cond_l1d_flush);
125
126 /* Controls CPU Fill buffer clear before KVM guest MMIO accesses */
127 DEFINE_STATIC_KEY_FALSE(mmio_stale_data_clear);
128 EXPORT_SYMBOL_GPL(mmio_stale_data_clear);
129
130 void __init cpu_select_mitigations(void)
131 {
132         /*
133          * Read the SPEC_CTRL MSR to account for reserved bits which may
134          * have unknown values. AMD64_LS_CFG MSR is cached in the early AMD
135          * init code as it is not enumerated and depends on the family.
136          */
137         if (cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL)) {
138                 rdmsrl(MSR_IA32_SPEC_CTRL, x86_spec_ctrl_base);
139
140                 /*
141                  * Previously running kernel (kexec), may have some controls
142                  * turned ON. Clear them and let the mitigations setup below
143                  * rediscover them based on configuration.
144                  */
145                 x86_spec_ctrl_base &= ~SPEC_CTRL_MITIGATIONS_MASK;
146         }
147
148         x86_arch_cap_msr = x86_read_arch_cap_msr();
149
150         /* Select the proper CPU mitigations before patching alternatives: */
151         spectre_v1_select_mitigation();
152         spectre_v2_select_mitigation();
153         /*
154          * retbleed_select_mitigation() relies on the state set by
155          * spectre_v2_select_mitigation(); specifically it wants to know about
156          * spectre_v2=ibrs.
157          */
158         retbleed_select_mitigation();
159         /*
160          * spectre_v2_user_select_mitigation() relies on the state set by
161          * retbleed_select_mitigation(); specifically the STIBP selection is
162          * forced for UNRET or IBPB.
163          */
164         spectre_v2_user_select_mitigation();
165         ssb_select_mitigation();
166         l1tf_select_mitigation();
167         md_clear_select_mitigation();
168         srbds_select_mitigation();
169         l1d_flush_select_mitigation();
170
171         /*
172          * srso_select_mitigation() depends and must run after
173          * retbleed_select_mitigation().
174          */
175         srso_select_mitigation();
176         gds_select_mitigation();
177 }
178
179 /*
180  * NOTE: This function is *only* called for SVM, since Intel uses
181  * MSR_IA32_SPEC_CTRL for SSBD.
182  */
183 void
184 x86_virt_spec_ctrl(u64 guest_virt_spec_ctrl, bool setguest)
185 {
186         u64 guestval, hostval;
187         struct thread_info *ti = current_thread_info();
188
189         /*
190          * If SSBD is not handled in MSR_SPEC_CTRL on AMD, update
191          * MSR_AMD64_L2_CFG or MSR_VIRT_SPEC_CTRL if supported.
192          */
193         if (!static_cpu_has(X86_FEATURE_LS_CFG_SSBD) &&
194             !static_cpu_has(X86_FEATURE_VIRT_SSBD))
195                 return;
196
197         /*
198          * If the host has SSBD mitigation enabled, force it in the host's
199          * virtual MSR value. If its not permanently enabled, evaluate
200          * current's TIF_SSBD thread flag.
201          */
202         if (static_cpu_has(X86_FEATURE_SPEC_STORE_BYPASS_DISABLE))
203                 hostval = SPEC_CTRL_SSBD;
204         else
205                 hostval = ssbd_tif_to_spec_ctrl(ti->flags);
206
207         /* Sanitize the guest value */
208         guestval = guest_virt_spec_ctrl & SPEC_CTRL_SSBD;
209
210         if (hostval != guestval) {
211                 unsigned long tif;
212
213                 tif = setguest ? ssbd_spec_ctrl_to_tif(guestval) :
214                                  ssbd_spec_ctrl_to_tif(hostval);
215
216                 speculation_ctrl_update(tif);
217         }
218 }
219 EXPORT_SYMBOL_GPL(x86_virt_spec_ctrl);
220
221 static void x86_amd_ssb_disable(void)
222 {
223         u64 msrval = x86_amd_ls_cfg_base | x86_amd_ls_cfg_ssbd_mask;
224
225         if (boot_cpu_has(X86_FEATURE_VIRT_SSBD))
226                 wrmsrl(MSR_AMD64_VIRT_SPEC_CTRL, SPEC_CTRL_SSBD);
227         else if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD))
228                 wrmsrl(MSR_AMD64_LS_CFG, msrval);
229 }
230
231 #undef pr_fmt
232 #define pr_fmt(fmt)     "MDS: " fmt
233
234 /* Default mitigation for MDS-affected CPUs */
235 static enum mds_mitigations mds_mitigation __ro_after_init = MDS_MITIGATION_FULL;
236 static bool mds_nosmt __ro_after_init = false;
237
238 static const char * const mds_strings[] = {
239         [MDS_MITIGATION_OFF]    = "Vulnerable",
240         [MDS_MITIGATION_FULL]   = "Mitigation: Clear CPU buffers",
241         [MDS_MITIGATION_VMWERV] = "Vulnerable: Clear CPU buffers attempted, no microcode",
242 };
243
244 static void __init mds_select_mitigation(void)
245 {
246         if (!boot_cpu_has_bug(X86_BUG_MDS) || cpu_mitigations_off()) {
247                 mds_mitigation = MDS_MITIGATION_OFF;
248                 return;
249         }
250
251         if (mds_mitigation == MDS_MITIGATION_FULL) {
252                 if (!boot_cpu_has(X86_FEATURE_MD_CLEAR))
253                         mds_mitigation = MDS_MITIGATION_VMWERV;
254
255                 setup_force_cpu_cap(X86_FEATURE_CLEAR_CPU_BUF);
256
257                 if (!boot_cpu_has(X86_BUG_MSBDS_ONLY) &&
258                     (mds_nosmt || cpu_mitigations_auto_nosmt()))
259                         cpu_smt_disable(false);
260         }
261 }
262
263 static int __init mds_cmdline(char *str)
264 {
265         if (!boot_cpu_has_bug(X86_BUG_MDS))
266                 return 0;
267
268         if (!str)
269                 return -EINVAL;
270
271         if (!strcmp(str, "off"))
272                 mds_mitigation = MDS_MITIGATION_OFF;
273         else if (!strcmp(str, "full"))
274                 mds_mitigation = MDS_MITIGATION_FULL;
275         else if (!strcmp(str, "full,nosmt")) {
276                 mds_mitigation = MDS_MITIGATION_FULL;
277                 mds_nosmt = true;
278         }
279
280         return 0;
281 }
282 early_param("mds", mds_cmdline);
283
284 #undef pr_fmt
285 #define pr_fmt(fmt)     "TAA: " fmt
286
287 enum taa_mitigations {
288         TAA_MITIGATION_OFF,
289         TAA_MITIGATION_UCODE_NEEDED,
290         TAA_MITIGATION_VERW,
291         TAA_MITIGATION_TSX_DISABLED,
292 };
293
294 /* Default mitigation for TAA-affected CPUs */
295 static enum taa_mitigations taa_mitigation __ro_after_init = TAA_MITIGATION_VERW;
296 static bool taa_nosmt __ro_after_init;
297
298 static const char * const taa_strings[] = {
299         [TAA_MITIGATION_OFF]            = "Vulnerable",
300         [TAA_MITIGATION_UCODE_NEEDED]   = "Vulnerable: Clear CPU buffers attempted, no microcode",
301         [TAA_MITIGATION_VERW]           = "Mitigation: Clear CPU buffers",
302         [TAA_MITIGATION_TSX_DISABLED]   = "Mitigation: TSX disabled",
303 };
304
305 static void __init taa_select_mitigation(void)
306 {
307         if (!boot_cpu_has_bug(X86_BUG_TAA)) {
308                 taa_mitigation = TAA_MITIGATION_OFF;
309                 return;
310         }
311
312         /* TSX previously disabled by tsx=off */
313         if (!boot_cpu_has(X86_FEATURE_RTM)) {
314                 taa_mitigation = TAA_MITIGATION_TSX_DISABLED;
315                 return;
316         }
317
318         if (cpu_mitigations_off()) {
319                 taa_mitigation = TAA_MITIGATION_OFF;
320                 return;
321         }
322
323         /*
324          * TAA mitigation via VERW is turned off if both
325          * tsx_async_abort=off and mds=off are specified.
326          */
327         if (taa_mitigation == TAA_MITIGATION_OFF &&
328             mds_mitigation == MDS_MITIGATION_OFF)
329                 return;
330
331         if (boot_cpu_has(X86_FEATURE_MD_CLEAR))
332                 taa_mitigation = TAA_MITIGATION_VERW;
333         else
334                 taa_mitigation = TAA_MITIGATION_UCODE_NEEDED;
335
336         /*
337          * VERW doesn't clear the CPU buffers when MD_CLEAR=1 and MDS_NO=1.
338          * A microcode update fixes this behavior to clear CPU buffers. It also
339          * adds support for MSR_IA32_TSX_CTRL which is enumerated by the
340          * ARCH_CAP_TSX_CTRL_MSR bit.
341          *
342          * On MDS_NO=1 CPUs if ARCH_CAP_TSX_CTRL_MSR is not set, microcode
343          * update is required.
344          */
345         if ( (x86_arch_cap_msr & ARCH_CAP_MDS_NO) &&
346             !(x86_arch_cap_msr & ARCH_CAP_TSX_CTRL_MSR))
347                 taa_mitigation = TAA_MITIGATION_UCODE_NEEDED;
348
349         /*
350          * TSX is enabled, select alternate mitigation for TAA which is
351          * the same as MDS. Enable MDS static branch to clear CPU buffers.
352          *
353          * For guests that can't determine whether the correct microcode is
354          * present on host, enable the mitigation for UCODE_NEEDED as well.
355          */
356         setup_force_cpu_cap(X86_FEATURE_CLEAR_CPU_BUF);
357
358         if (taa_nosmt || cpu_mitigations_auto_nosmt())
359                 cpu_smt_disable(false);
360 }
361
362 static int __init tsx_async_abort_parse_cmdline(char *str)
363 {
364         if (!boot_cpu_has_bug(X86_BUG_TAA))
365                 return 0;
366
367         if (!str)
368                 return -EINVAL;
369
370         if (!strcmp(str, "off")) {
371                 taa_mitigation = TAA_MITIGATION_OFF;
372         } else if (!strcmp(str, "full")) {
373                 taa_mitigation = TAA_MITIGATION_VERW;
374         } else if (!strcmp(str, "full,nosmt")) {
375                 taa_mitigation = TAA_MITIGATION_VERW;
376                 taa_nosmt = true;
377         }
378
379         return 0;
380 }
381 early_param("tsx_async_abort", tsx_async_abort_parse_cmdline);
382
383 #undef pr_fmt
384 #define pr_fmt(fmt)     "MMIO Stale Data: " fmt
385
386 enum mmio_mitigations {
387         MMIO_MITIGATION_OFF,
388         MMIO_MITIGATION_UCODE_NEEDED,
389         MMIO_MITIGATION_VERW,
390 };
391
392 /* Default mitigation for Processor MMIO Stale Data vulnerabilities */
393 static enum mmio_mitigations mmio_mitigation __ro_after_init = MMIO_MITIGATION_VERW;
394 static bool mmio_nosmt __ro_after_init = false;
395
396 static const char * const mmio_strings[] = {
397         [MMIO_MITIGATION_OFF]           = "Vulnerable",
398         [MMIO_MITIGATION_UCODE_NEEDED]  = "Vulnerable: Clear CPU buffers attempted, no microcode",
399         [MMIO_MITIGATION_VERW]          = "Mitigation: Clear CPU buffers",
400 };
401
402 static void __init mmio_select_mitigation(void)
403 {
404         if (!boot_cpu_has_bug(X86_BUG_MMIO_STALE_DATA) ||
405              boot_cpu_has_bug(X86_BUG_MMIO_UNKNOWN) ||
406              cpu_mitigations_off()) {
407                 mmio_mitigation = MMIO_MITIGATION_OFF;
408                 return;
409         }
410
411         if (mmio_mitigation == MMIO_MITIGATION_OFF)
412                 return;
413
414         /*
415          * Enable CPU buffer clear mitigation for host and VMM, if also affected
416          * by MDS or TAA. Otherwise, enable mitigation for VMM only.
417          */
418         if (boot_cpu_has_bug(X86_BUG_MDS) || (boot_cpu_has_bug(X86_BUG_TAA) &&
419                                               boot_cpu_has(X86_FEATURE_RTM)))
420                 setup_force_cpu_cap(X86_FEATURE_CLEAR_CPU_BUF);
421
422         /*
423          * X86_FEATURE_CLEAR_CPU_BUF could be enabled by other VERW based
424          * mitigations, disable KVM-only mitigation in that case.
425          */
426         if (boot_cpu_has(X86_FEATURE_CLEAR_CPU_BUF))
427                 static_branch_disable(&mmio_stale_data_clear);
428         else
429                 static_branch_enable(&mmio_stale_data_clear);
430
431         /*
432          * If Processor-MMIO-Stale-Data bug is present and Fill Buffer data can
433          * be propagated to uncore buffers, clearing the Fill buffers on idle
434          * is required irrespective of SMT state.
435          */
436         if (!(x86_arch_cap_msr & ARCH_CAP_FBSDP_NO))
437                 static_branch_enable(&mds_idle_clear);
438
439         /*
440          * Check if the system has the right microcode.
441          *
442          * CPU Fill buffer clear mitigation is enumerated by either an explicit
443          * FB_CLEAR or by the presence of both MD_CLEAR and L1D_FLUSH on MDS
444          * affected systems.
445          */
446         if ((x86_arch_cap_msr & ARCH_CAP_FB_CLEAR) ||
447             (boot_cpu_has(X86_FEATURE_MD_CLEAR) &&
448              boot_cpu_has(X86_FEATURE_FLUSH_L1D) &&
449              !(x86_arch_cap_msr & ARCH_CAP_MDS_NO)))
450                 mmio_mitigation = MMIO_MITIGATION_VERW;
451         else
452                 mmio_mitigation = MMIO_MITIGATION_UCODE_NEEDED;
453
454         if (mmio_nosmt || cpu_mitigations_auto_nosmt())
455                 cpu_smt_disable(false);
456 }
457
458 static int __init mmio_stale_data_parse_cmdline(char *str)
459 {
460         if (!boot_cpu_has_bug(X86_BUG_MMIO_STALE_DATA))
461                 return 0;
462
463         if (!str)
464                 return -EINVAL;
465
466         if (!strcmp(str, "off")) {
467                 mmio_mitigation = MMIO_MITIGATION_OFF;
468         } else if (!strcmp(str, "full")) {
469                 mmio_mitigation = MMIO_MITIGATION_VERW;
470         } else if (!strcmp(str, "full,nosmt")) {
471                 mmio_mitigation = MMIO_MITIGATION_VERW;
472                 mmio_nosmt = true;
473         }
474
475         return 0;
476 }
477 early_param("mmio_stale_data", mmio_stale_data_parse_cmdline);
478
479 #undef pr_fmt
480 #define pr_fmt(fmt)     "Register File Data Sampling: " fmt
481
482 enum rfds_mitigations {
483         RFDS_MITIGATION_OFF,
484         RFDS_MITIGATION_VERW,
485         RFDS_MITIGATION_UCODE_NEEDED,
486 };
487
488 /* Default mitigation for Register File Data Sampling */
489 static enum rfds_mitigations rfds_mitigation __ro_after_init =
490         IS_ENABLED(CONFIG_MITIGATION_RFDS) ? RFDS_MITIGATION_VERW : RFDS_MITIGATION_OFF;
491
492 static const char * const rfds_strings[] = {
493         [RFDS_MITIGATION_OFF]                   = "Vulnerable",
494         [RFDS_MITIGATION_VERW]                  = "Mitigation: Clear Register File",
495         [RFDS_MITIGATION_UCODE_NEEDED]          = "Vulnerable: No microcode",
496 };
497
498 static void __init rfds_select_mitigation(void)
499 {
500         if (!boot_cpu_has_bug(X86_BUG_RFDS) || cpu_mitigations_off()) {
501                 rfds_mitigation = RFDS_MITIGATION_OFF;
502                 return;
503         }
504         if (rfds_mitigation == RFDS_MITIGATION_OFF)
505                 return;
506
507         if (x86_arch_cap_msr & ARCH_CAP_RFDS_CLEAR)
508                 setup_force_cpu_cap(X86_FEATURE_CLEAR_CPU_BUF);
509         else
510                 rfds_mitigation = RFDS_MITIGATION_UCODE_NEEDED;
511 }
512
513 static __init int rfds_parse_cmdline(char *str)
514 {
515         if (!str)
516                 return -EINVAL;
517
518         if (!boot_cpu_has_bug(X86_BUG_RFDS))
519                 return 0;
520
521         if (!strcmp(str, "off"))
522                 rfds_mitigation = RFDS_MITIGATION_OFF;
523         else if (!strcmp(str, "on"))
524                 rfds_mitigation = RFDS_MITIGATION_VERW;
525
526         return 0;
527 }
528 early_param("reg_file_data_sampling", rfds_parse_cmdline);
529
530 #undef pr_fmt
531 #define pr_fmt(fmt)     "" fmt
532
533 static void __init md_clear_update_mitigation(void)
534 {
535         if (cpu_mitigations_off())
536                 return;
537
538         if (!boot_cpu_has(X86_FEATURE_CLEAR_CPU_BUF))
539                 goto out;
540
541         /*
542          * X86_FEATURE_CLEAR_CPU_BUF is now enabled. Update MDS, TAA and MMIO
543          * Stale Data mitigation, if necessary.
544          */
545         if (mds_mitigation == MDS_MITIGATION_OFF &&
546             boot_cpu_has_bug(X86_BUG_MDS)) {
547                 mds_mitigation = MDS_MITIGATION_FULL;
548                 mds_select_mitigation();
549         }
550         if (taa_mitigation == TAA_MITIGATION_OFF &&
551             boot_cpu_has_bug(X86_BUG_TAA)) {
552                 taa_mitigation = TAA_MITIGATION_VERW;
553                 taa_select_mitigation();
554         }
555         /*
556          * MMIO_MITIGATION_OFF is not checked here so that mmio_stale_data_clear
557          * gets updated correctly as per X86_FEATURE_CLEAR_CPU_BUF state.
558          */
559         if (boot_cpu_has_bug(X86_BUG_MMIO_STALE_DATA)) {
560                 mmio_mitigation = MMIO_MITIGATION_VERW;
561                 mmio_select_mitigation();
562         }
563         if (rfds_mitigation == RFDS_MITIGATION_OFF &&
564             boot_cpu_has_bug(X86_BUG_RFDS)) {
565                 rfds_mitigation = RFDS_MITIGATION_VERW;
566                 rfds_select_mitigation();
567         }
568 out:
569         if (boot_cpu_has_bug(X86_BUG_MDS))
570                 pr_info("MDS: %s\n", mds_strings[mds_mitigation]);
571         if (boot_cpu_has_bug(X86_BUG_TAA))
572                 pr_info("TAA: %s\n", taa_strings[taa_mitigation]);
573         if (boot_cpu_has_bug(X86_BUG_MMIO_STALE_DATA))
574                 pr_info("MMIO Stale Data: %s\n", mmio_strings[mmio_mitigation]);
575         else if (boot_cpu_has_bug(X86_BUG_MMIO_UNKNOWN))
576                 pr_info("MMIO Stale Data: Unknown: No mitigations\n");
577         if (boot_cpu_has_bug(X86_BUG_RFDS))
578                 pr_info("Register File Data Sampling: %s\n", rfds_strings[rfds_mitigation]);
579 }
580
581 static void __init md_clear_select_mitigation(void)
582 {
583         mds_select_mitigation();
584         taa_select_mitigation();
585         mmio_select_mitigation();
586         rfds_select_mitigation();
587
588         /*
589          * As these mitigations are inter-related and rely on VERW instruction
590          * to clear the microarchitural buffers, update and print their status
591          * after mitigation selection is done for each of these vulnerabilities.
592          */
593         md_clear_update_mitigation();
594 }
595
596 #undef pr_fmt
597 #define pr_fmt(fmt)     "SRBDS: " fmt
598
599 enum srbds_mitigations {
600         SRBDS_MITIGATION_OFF,
601         SRBDS_MITIGATION_UCODE_NEEDED,
602         SRBDS_MITIGATION_FULL,
603         SRBDS_MITIGATION_TSX_OFF,
604         SRBDS_MITIGATION_HYPERVISOR,
605 };
606
607 static enum srbds_mitigations srbds_mitigation __ro_after_init = SRBDS_MITIGATION_FULL;
608
609 static const char * const srbds_strings[] = {
610         [SRBDS_MITIGATION_OFF]          = "Vulnerable",
611         [SRBDS_MITIGATION_UCODE_NEEDED] = "Vulnerable: No microcode",
612         [SRBDS_MITIGATION_FULL]         = "Mitigation: Microcode",
613         [SRBDS_MITIGATION_TSX_OFF]      = "Mitigation: TSX disabled",
614         [SRBDS_MITIGATION_HYPERVISOR]   = "Unknown: Dependent on hypervisor status",
615 };
616
617 static bool srbds_off;
618
619 void update_srbds_msr(void)
620 {
621         u64 mcu_ctrl;
622
623         if (!boot_cpu_has_bug(X86_BUG_SRBDS))
624                 return;
625
626         if (boot_cpu_has(X86_FEATURE_HYPERVISOR))
627                 return;
628
629         if (srbds_mitigation == SRBDS_MITIGATION_UCODE_NEEDED)
630                 return;
631
632         /*
633          * A MDS_NO CPU for which SRBDS mitigation is not needed due to TSX
634          * being disabled and it hasn't received the SRBDS MSR microcode.
635          */
636         if (!boot_cpu_has(X86_FEATURE_SRBDS_CTRL))
637                 return;
638
639         rdmsrl(MSR_IA32_MCU_OPT_CTRL, mcu_ctrl);
640
641         switch (srbds_mitigation) {
642         case SRBDS_MITIGATION_OFF:
643         case SRBDS_MITIGATION_TSX_OFF:
644                 mcu_ctrl |= RNGDS_MITG_DIS;
645                 break;
646         case SRBDS_MITIGATION_FULL:
647                 mcu_ctrl &= ~RNGDS_MITG_DIS;
648                 break;
649         default:
650                 break;
651         }
652
653         wrmsrl(MSR_IA32_MCU_OPT_CTRL, mcu_ctrl);
654 }
655
656 static void __init srbds_select_mitigation(void)
657 {
658         if (!boot_cpu_has_bug(X86_BUG_SRBDS))
659                 return;
660
661         /*
662          * Check to see if this is one of the MDS_NO systems supporting TSX that
663          * are only exposed to SRBDS when TSX is enabled or when CPU is affected
664          * by Processor MMIO Stale Data vulnerability.
665          */
666         if ((x86_arch_cap_msr & ARCH_CAP_MDS_NO) && !boot_cpu_has(X86_FEATURE_RTM) &&
667             !boot_cpu_has_bug(X86_BUG_MMIO_STALE_DATA))
668                 srbds_mitigation = SRBDS_MITIGATION_TSX_OFF;
669         else if (boot_cpu_has(X86_FEATURE_HYPERVISOR))
670                 srbds_mitigation = SRBDS_MITIGATION_HYPERVISOR;
671         else if (!boot_cpu_has(X86_FEATURE_SRBDS_CTRL))
672                 srbds_mitigation = SRBDS_MITIGATION_UCODE_NEEDED;
673         else if (cpu_mitigations_off() || srbds_off)
674                 srbds_mitigation = SRBDS_MITIGATION_OFF;
675
676         update_srbds_msr();
677         pr_info("%s\n", srbds_strings[srbds_mitigation]);
678 }
679
680 static int __init srbds_parse_cmdline(char *str)
681 {
682         if (!str)
683                 return -EINVAL;
684
685         if (!boot_cpu_has_bug(X86_BUG_SRBDS))
686                 return 0;
687
688         srbds_off = !strcmp(str, "off");
689         return 0;
690 }
691 early_param("srbds", srbds_parse_cmdline);
692
693 #undef pr_fmt
694 #define pr_fmt(fmt)     "L1D Flush : " fmt
695
696 enum l1d_flush_mitigations {
697         L1D_FLUSH_OFF = 0,
698         L1D_FLUSH_ON,
699 };
700
701 static enum l1d_flush_mitigations l1d_flush_mitigation __initdata = L1D_FLUSH_OFF;
702
703 static void __init l1d_flush_select_mitigation(void)
704 {
705         if (!l1d_flush_mitigation || !boot_cpu_has(X86_FEATURE_FLUSH_L1D))
706                 return;
707
708         static_branch_enable(&switch_mm_cond_l1d_flush);
709         pr_info("Conditional flush on switch_mm() enabled\n");
710 }
711
712 static int __init l1d_flush_parse_cmdline(char *str)
713 {
714         if (!strcmp(str, "on"))
715                 l1d_flush_mitigation = L1D_FLUSH_ON;
716
717         return 0;
718 }
719 early_param("l1d_flush", l1d_flush_parse_cmdline);
720
721 #undef pr_fmt
722 #define pr_fmt(fmt)     "GDS: " fmt
723
724 enum gds_mitigations {
725         GDS_MITIGATION_OFF,
726         GDS_MITIGATION_UCODE_NEEDED,
727         GDS_MITIGATION_FORCE,
728         GDS_MITIGATION_FULL,
729         GDS_MITIGATION_FULL_LOCKED,
730         GDS_MITIGATION_HYPERVISOR,
731 };
732
733 #if IS_ENABLED(CONFIG_GDS_FORCE_MITIGATION)
734 static enum gds_mitigations gds_mitigation __ro_after_init = GDS_MITIGATION_FORCE;
735 #else
736 static enum gds_mitigations gds_mitigation __ro_after_init = GDS_MITIGATION_FULL;
737 #endif
738
739 static const char * const gds_strings[] = {
740         [GDS_MITIGATION_OFF]            = "Vulnerable",
741         [GDS_MITIGATION_UCODE_NEEDED]   = "Vulnerable: No microcode",
742         [GDS_MITIGATION_FORCE]          = "Mitigation: AVX disabled, no microcode",
743         [GDS_MITIGATION_FULL]           = "Mitigation: Microcode",
744         [GDS_MITIGATION_FULL_LOCKED]    = "Mitigation: Microcode (locked)",
745         [GDS_MITIGATION_HYPERVISOR]     = "Unknown: Dependent on hypervisor status",
746 };
747
748 bool gds_ucode_mitigated(void)
749 {
750         return (gds_mitigation == GDS_MITIGATION_FULL ||
751                 gds_mitigation == GDS_MITIGATION_FULL_LOCKED);
752 }
753 EXPORT_SYMBOL_GPL(gds_ucode_mitigated);
754
755 void update_gds_msr(void)
756 {
757         u64 mcu_ctrl_after;
758         u64 mcu_ctrl;
759
760         switch (gds_mitigation) {
761         case GDS_MITIGATION_OFF:
762                 rdmsrl(MSR_IA32_MCU_OPT_CTRL, mcu_ctrl);
763                 mcu_ctrl |= GDS_MITG_DIS;
764                 break;
765         case GDS_MITIGATION_FULL_LOCKED:
766                 /*
767                  * The LOCKED state comes from the boot CPU. APs might not have
768                  * the same state. Make sure the mitigation is enabled on all
769                  * CPUs.
770                  */
771         case GDS_MITIGATION_FULL:
772                 rdmsrl(MSR_IA32_MCU_OPT_CTRL, mcu_ctrl);
773                 mcu_ctrl &= ~GDS_MITG_DIS;
774                 break;
775         case GDS_MITIGATION_FORCE:
776         case GDS_MITIGATION_UCODE_NEEDED:
777         case GDS_MITIGATION_HYPERVISOR:
778                 return;
779         };
780
781         wrmsrl(MSR_IA32_MCU_OPT_CTRL, mcu_ctrl);
782
783         /*
784          * Check to make sure that the WRMSR value was not ignored. Writes to
785          * GDS_MITG_DIS will be ignored if this processor is locked but the boot
786          * processor was not.
787          */
788         rdmsrl(MSR_IA32_MCU_OPT_CTRL, mcu_ctrl_after);
789         WARN_ON_ONCE(mcu_ctrl != mcu_ctrl_after);
790 }
791
792 static void __init gds_select_mitigation(void)
793 {
794         u64 mcu_ctrl;
795
796         if (!boot_cpu_has_bug(X86_BUG_GDS))
797                 return;
798
799         if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) {
800                 gds_mitigation = GDS_MITIGATION_HYPERVISOR;
801                 goto out;
802         }
803
804         if (cpu_mitigations_off())
805                 gds_mitigation = GDS_MITIGATION_OFF;
806         /* Will verify below that mitigation _can_ be disabled */
807
808         /* No microcode */
809         if (!(x86_arch_cap_msr & ARCH_CAP_GDS_CTRL)) {
810                 if (gds_mitigation == GDS_MITIGATION_FORCE) {
811                         /*
812                          * This only needs to be done on the boot CPU so do it
813                          * here rather than in update_gds_msr()
814                          */
815                         setup_clear_cpu_cap(X86_FEATURE_AVX);
816                         pr_warn("Microcode update needed! Disabling AVX as mitigation.\n");
817                 } else {
818                         gds_mitigation = GDS_MITIGATION_UCODE_NEEDED;
819                 }
820                 goto out;
821         }
822
823         /* Microcode has mitigation, use it */
824         if (gds_mitigation == GDS_MITIGATION_FORCE)
825                 gds_mitigation = GDS_MITIGATION_FULL;
826
827         rdmsrl(MSR_IA32_MCU_OPT_CTRL, mcu_ctrl);
828         if (mcu_ctrl & GDS_MITG_LOCKED) {
829                 if (gds_mitigation == GDS_MITIGATION_OFF)
830                         pr_warn("Mitigation locked. Disable failed.\n");
831
832                 /*
833                  * The mitigation is selected from the boot CPU. All other CPUs
834                  * _should_ have the same state. If the boot CPU isn't locked
835                  * but others are then update_gds_msr() will WARN() of the state
836                  * mismatch. If the boot CPU is locked update_gds_msr() will
837                  * ensure the other CPUs have the mitigation enabled.
838                  */
839                 gds_mitigation = GDS_MITIGATION_FULL_LOCKED;
840         }
841
842         update_gds_msr();
843 out:
844         pr_info("%s\n", gds_strings[gds_mitigation]);
845 }
846
847 static int __init gds_parse_cmdline(char *str)
848 {
849         if (!str)
850                 return -EINVAL;
851
852         if (!boot_cpu_has_bug(X86_BUG_GDS))
853                 return 0;
854
855         if (!strcmp(str, "off"))
856                 gds_mitigation = GDS_MITIGATION_OFF;
857         else if (!strcmp(str, "force"))
858                 gds_mitigation = GDS_MITIGATION_FORCE;
859
860         return 0;
861 }
862 early_param("gather_data_sampling", gds_parse_cmdline);
863
864 #undef pr_fmt
865 #define pr_fmt(fmt)     "Spectre V1 : " fmt
866
867 enum spectre_v1_mitigation {
868         SPECTRE_V1_MITIGATION_NONE,
869         SPECTRE_V1_MITIGATION_AUTO,
870 };
871
872 static enum spectre_v1_mitigation spectre_v1_mitigation __ro_after_init =
873         SPECTRE_V1_MITIGATION_AUTO;
874
875 static const char * const spectre_v1_strings[] = {
876         [SPECTRE_V1_MITIGATION_NONE] = "Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers",
877         [SPECTRE_V1_MITIGATION_AUTO] = "Mitigation: usercopy/swapgs barriers and __user pointer sanitization",
878 };
879
880 /*
881  * Does SMAP provide full mitigation against speculative kernel access to
882  * userspace?
883  */
884 static bool smap_works_speculatively(void)
885 {
886         if (!boot_cpu_has(X86_FEATURE_SMAP))
887                 return false;
888
889         /*
890          * On CPUs which are vulnerable to Meltdown, SMAP does not
891          * prevent speculative access to user data in the L1 cache.
892          * Consider SMAP to be non-functional as a mitigation on these
893          * CPUs.
894          */
895         if (boot_cpu_has(X86_BUG_CPU_MELTDOWN))
896                 return false;
897
898         return true;
899 }
900
901 static void __init spectre_v1_select_mitigation(void)
902 {
903         if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V1) || cpu_mitigations_off()) {
904                 spectre_v1_mitigation = SPECTRE_V1_MITIGATION_NONE;
905                 return;
906         }
907
908         if (spectre_v1_mitigation == SPECTRE_V1_MITIGATION_AUTO) {
909                 /*
910                  * With Spectre v1, a user can speculatively control either
911                  * path of a conditional swapgs with a user-controlled GS
912                  * value.  The mitigation is to add lfences to both code paths.
913                  *
914                  * If FSGSBASE is enabled, the user can put a kernel address in
915                  * GS, in which case SMAP provides no protection.
916                  *
917                  * If FSGSBASE is disabled, the user can only put a user space
918                  * address in GS.  That makes an attack harder, but still
919                  * possible if there's no SMAP protection.
920                  */
921                 if (boot_cpu_has(X86_FEATURE_FSGSBASE) ||
922                     !smap_works_speculatively()) {
923                         /*
924                          * Mitigation can be provided from SWAPGS itself or
925                          * PTI as the CR3 write in the Meltdown mitigation
926                          * is serializing.
927                          *
928                          * If neither is there, mitigate with an LFENCE to
929                          * stop speculation through swapgs.
930                          */
931                         if (boot_cpu_has_bug(X86_BUG_SWAPGS) &&
932                             !boot_cpu_has(X86_FEATURE_PTI))
933                                 setup_force_cpu_cap(X86_FEATURE_FENCE_SWAPGS_USER);
934
935                         /*
936                          * Enable lfences in the kernel entry (non-swapgs)
937                          * paths, to prevent user entry from speculatively
938                          * skipping swapgs.
939                          */
940                         setup_force_cpu_cap(X86_FEATURE_FENCE_SWAPGS_KERNEL);
941                 }
942         }
943
944         pr_info("%s\n", spectre_v1_strings[spectre_v1_mitigation]);
945 }
946
947 static int __init nospectre_v1_cmdline(char *str)
948 {
949         spectre_v1_mitigation = SPECTRE_V1_MITIGATION_NONE;
950         return 0;
951 }
952 early_param("nospectre_v1", nospectre_v1_cmdline);
953
954 static enum spectre_v2_mitigation spectre_v2_enabled __ro_after_init =
955         SPECTRE_V2_NONE;
956
957 #undef pr_fmt
958 #define pr_fmt(fmt)     "RETBleed: " fmt
959
960 enum retbleed_mitigation {
961         RETBLEED_MITIGATION_NONE,
962         RETBLEED_MITIGATION_UNRET,
963         RETBLEED_MITIGATION_IBPB,
964         RETBLEED_MITIGATION_IBRS,
965         RETBLEED_MITIGATION_EIBRS,
966 };
967
968 enum retbleed_mitigation_cmd {
969         RETBLEED_CMD_OFF,
970         RETBLEED_CMD_AUTO,
971         RETBLEED_CMD_UNRET,
972         RETBLEED_CMD_IBPB,
973 };
974
975 static const char * const retbleed_strings[] = {
976         [RETBLEED_MITIGATION_NONE]      = "Vulnerable",
977         [RETBLEED_MITIGATION_UNRET]     = "Mitigation: untrained return thunk",
978         [RETBLEED_MITIGATION_IBPB]      = "Mitigation: IBPB",
979         [RETBLEED_MITIGATION_IBRS]      = "Mitigation: IBRS",
980         [RETBLEED_MITIGATION_EIBRS]     = "Mitigation: Enhanced IBRS",
981 };
982
983 static enum retbleed_mitigation retbleed_mitigation __ro_after_init =
984         RETBLEED_MITIGATION_NONE;
985 static enum retbleed_mitigation_cmd retbleed_cmd __ro_after_init =
986         RETBLEED_CMD_AUTO;
987
988 static int __ro_after_init retbleed_nosmt = false;
989
990 static int __init retbleed_parse_cmdline(char *str)
991 {
992         if (!str)
993                 return -EINVAL;
994
995         while (str) {
996                 char *next = strchr(str, ',');
997                 if (next) {
998                         *next = 0;
999                         next++;
1000                 }
1001
1002                 if (!strcmp(str, "off")) {
1003                         retbleed_cmd = RETBLEED_CMD_OFF;
1004                 } else if (!strcmp(str, "auto")) {
1005                         retbleed_cmd = RETBLEED_CMD_AUTO;
1006                 } else if (!strcmp(str, "unret")) {
1007                         retbleed_cmd = RETBLEED_CMD_UNRET;
1008                 } else if (!strcmp(str, "ibpb")) {
1009                         retbleed_cmd = RETBLEED_CMD_IBPB;
1010                 } else if (!strcmp(str, "nosmt")) {
1011                         retbleed_nosmt = true;
1012                 } else {
1013                         pr_err("Ignoring unknown retbleed option (%s).", str);
1014                 }
1015
1016                 str = next;
1017         }
1018
1019         return 0;
1020 }
1021 early_param("retbleed", retbleed_parse_cmdline);
1022
1023 #define RETBLEED_UNTRAIN_MSG "WARNING: BTB untrained return thunk mitigation is only effective on AMD/Hygon!\n"
1024 #define RETBLEED_INTEL_MSG "WARNING: Spectre v2 mitigation leaves CPU vulnerable to RETBleed attacks, data leaks possible!\n"
1025
1026 static void __init retbleed_select_mitigation(void)
1027 {
1028         bool mitigate_smt = false;
1029
1030         if (!boot_cpu_has_bug(X86_BUG_RETBLEED) || cpu_mitigations_off())
1031                 return;
1032
1033         switch (retbleed_cmd) {
1034         case RETBLEED_CMD_OFF:
1035                 return;
1036
1037         case RETBLEED_CMD_UNRET:
1038                 if (IS_ENABLED(CONFIG_CPU_UNRET_ENTRY)) {
1039                         retbleed_mitigation = RETBLEED_MITIGATION_UNRET;
1040                 } else {
1041                         pr_err("WARNING: kernel not compiled with CPU_UNRET_ENTRY.\n");
1042                         goto do_cmd_auto;
1043                 }
1044                 break;
1045
1046         case RETBLEED_CMD_IBPB:
1047                 if (!boot_cpu_has(X86_FEATURE_IBPB)) {
1048                         pr_err("WARNING: CPU does not support IBPB.\n");
1049                         goto do_cmd_auto;
1050                 } else if (IS_ENABLED(CONFIG_CPU_IBPB_ENTRY)) {
1051                         retbleed_mitigation = RETBLEED_MITIGATION_IBPB;
1052                 } else {
1053                         pr_err("WARNING: kernel not compiled with CPU_IBPB_ENTRY.\n");
1054                         goto do_cmd_auto;
1055                 }
1056                 break;
1057
1058 do_cmd_auto:
1059         case RETBLEED_CMD_AUTO:
1060         default:
1061                 if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
1062                     boot_cpu_data.x86_vendor == X86_VENDOR_HYGON) {
1063                         if (IS_ENABLED(CONFIG_CPU_UNRET_ENTRY))
1064                                 retbleed_mitigation = RETBLEED_MITIGATION_UNRET;
1065                         else if (IS_ENABLED(CONFIG_CPU_IBPB_ENTRY) && boot_cpu_has(X86_FEATURE_IBPB))
1066                                 retbleed_mitigation = RETBLEED_MITIGATION_IBPB;
1067                 }
1068
1069                 /*
1070                  * The Intel mitigation (IBRS or eIBRS) was already selected in
1071                  * spectre_v2_select_mitigation().  'retbleed_mitigation' will
1072                  * be set accordingly below.
1073                  */
1074
1075                 break;
1076         }
1077
1078         switch (retbleed_mitigation) {
1079         case RETBLEED_MITIGATION_UNRET:
1080                 setup_force_cpu_cap(X86_FEATURE_RETHUNK);
1081                 setup_force_cpu_cap(X86_FEATURE_UNRET);
1082
1083                 if (IS_ENABLED(CONFIG_RETHUNK))
1084                         x86_return_thunk = retbleed_return_thunk;
1085
1086                 if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD &&
1087                     boot_cpu_data.x86_vendor != X86_VENDOR_HYGON)
1088                         pr_err(RETBLEED_UNTRAIN_MSG);
1089
1090                 mitigate_smt = true;
1091                 break;
1092
1093         case RETBLEED_MITIGATION_IBPB:
1094                 setup_force_cpu_cap(X86_FEATURE_ENTRY_IBPB);
1095                 mitigate_smt = true;
1096                 break;
1097
1098         default:
1099                 break;
1100         }
1101
1102         if (mitigate_smt && !boot_cpu_has(X86_FEATURE_STIBP) &&
1103             (retbleed_nosmt || cpu_mitigations_auto_nosmt()))
1104                 cpu_smt_disable(false);
1105
1106         /*
1107          * Let IBRS trump all on Intel without affecting the effects of the
1108          * retbleed= cmdline option.
1109          */
1110         if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) {
1111                 switch (spectre_v2_enabled) {
1112                 case SPECTRE_V2_IBRS:
1113                         retbleed_mitigation = RETBLEED_MITIGATION_IBRS;
1114                         break;
1115                 case SPECTRE_V2_EIBRS:
1116                 case SPECTRE_V2_EIBRS_RETPOLINE:
1117                 case SPECTRE_V2_EIBRS_LFENCE:
1118                         retbleed_mitigation = RETBLEED_MITIGATION_EIBRS;
1119                         break;
1120                 default:
1121                         pr_err(RETBLEED_INTEL_MSG);
1122                 }
1123         }
1124
1125         pr_info("%s\n", retbleed_strings[retbleed_mitigation]);
1126 }
1127
1128 #undef pr_fmt
1129 #define pr_fmt(fmt)     "Spectre V2 : " fmt
1130
1131 static enum spectre_v2_user_mitigation spectre_v2_user_stibp __ro_after_init =
1132         SPECTRE_V2_USER_NONE;
1133 static enum spectre_v2_user_mitigation spectre_v2_user_ibpb __ro_after_init =
1134         SPECTRE_V2_USER_NONE;
1135
1136 #ifdef CONFIG_RETPOLINE
1137 static bool spectre_v2_bad_module;
1138
1139 bool retpoline_module_ok(bool has_retpoline)
1140 {
1141         if (spectre_v2_enabled == SPECTRE_V2_NONE || has_retpoline)
1142                 return true;
1143
1144         pr_err("System may be vulnerable to spectre v2\n");
1145         spectre_v2_bad_module = true;
1146         return false;
1147 }
1148
1149 static inline const char *spectre_v2_module_string(void)
1150 {
1151         return spectre_v2_bad_module ? " - vulnerable module loaded" : "";
1152 }
1153 #else
1154 static inline const char *spectre_v2_module_string(void) { return ""; }
1155 #endif
1156
1157 #define SPECTRE_V2_LFENCE_MSG "WARNING: LFENCE mitigation is not recommended for this CPU, data leaks possible!\n"
1158 #define SPECTRE_V2_EIBRS_EBPF_MSG "WARNING: Unprivileged eBPF is enabled with eIBRS on, data leaks possible via Spectre v2 BHB attacks!\n"
1159 #define SPECTRE_V2_EIBRS_LFENCE_EBPF_SMT_MSG "WARNING: Unprivileged eBPF is enabled with eIBRS+LFENCE mitigation and SMT, data leaks possible via Spectre v2 BHB attacks!\n"
1160 #define SPECTRE_V2_IBRS_PERF_MSG "WARNING: IBRS mitigation selected on Enhanced IBRS CPU, this may cause unnecessary performance loss\n"
1161
1162 #ifdef CONFIG_BPF_SYSCALL
1163 void unpriv_ebpf_notify(int new_state)
1164 {
1165         if (new_state)
1166                 return;
1167
1168         /* Unprivileged eBPF is enabled */
1169
1170         switch (spectre_v2_enabled) {
1171         case SPECTRE_V2_EIBRS:
1172                 pr_err(SPECTRE_V2_EIBRS_EBPF_MSG);
1173                 break;
1174         case SPECTRE_V2_EIBRS_LFENCE:
1175                 if (sched_smt_active())
1176                         pr_err(SPECTRE_V2_EIBRS_LFENCE_EBPF_SMT_MSG);
1177                 break;
1178         default:
1179                 break;
1180         }
1181 }
1182 #endif
1183
1184 static inline bool match_option(const char *arg, int arglen, const char *opt)
1185 {
1186         int len = strlen(opt);
1187
1188         return len == arglen && !strncmp(arg, opt, len);
1189 }
1190
1191 /* The kernel command line selection for spectre v2 */
1192 enum spectre_v2_mitigation_cmd {
1193         SPECTRE_V2_CMD_NONE,
1194         SPECTRE_V2_CMD_AUTO,
1195         SPECTRE_V2_CMD_FORCE,
1196         SPECTRE_V2_CMD_RETPOLINE,
1197         SPECTRE_V2_CMD_RETPOLINE_GENERIC,
1198         SPECTRE_V2_CMD_RETPOLINE_LFENCE,
1199         SPECTRE_V2_CMD_EIBRS,
1200         SPECTRE_V2_CMD_EIBRS_RETPOLINE,
1201         SPECTRE_V2_CMD_EIBRS_LFENCE,
1202         SPECTRE_V2_CMD_IBRS,
1203 };
1204
1205 enum spectre_v2_user_cmd {
1206         SPECTRE_V2_USER_CMD_NONE,
1207         SPECTRE_V2_USER_CMD_AUTO,
1208         SPECTRE_V2_USER_CMD_FORCE,
1209         SPECTRE_V2_USER_CMD_PRCTL,
1210         SPECTRE_V2_USER_CMD_PRCTL_IBPB,
1211         SPECTRE_V2_USER_CMD_SECCOMP,
1212         SPECTRE_V2_USER_CMD_SECCOMP_IBPB,
1213 };
1214
1215 static const char * const spectre_v2_user_strings[] = {
1216         [SPECTRE_V2_USER_NONE]                  = "User space: Vulnerable",
1217         [SPECTRE_V2_USER_STRICT]                = "User space: Mitigation: STIBP protection",
1218         [SPECTRE_V2_USER_STRICT_PREFERRED]      = "User space: Mitigation: STIBP always-on protection",
1219         [SPECTRE_V2_USER_PRCTL]                 = "User space: Mitigation: STIBP via prctl",
1220         [SPECTRE_V2_USER_SECCOMP]               = "User space: Mitigation: STIBP via seccomp and prctl",
1221 };
1222
1223 static const struct {
1224         const char                      *option;
1225         enum spectre_v2_user_cmd        cmd;
1226         bool                            secure;
1227 } v2_user_options[] __initconst = {
1228         { "auto",               SPECTRE_V2_USER_CMD_AUTO,               false },
1229         { "off",                SPECTRE_V2_USER_CMD_NONE,               false },
1230         { "on",                 SPECTRE_V2_USER_CMD_FORCE,              true  },
1231         { "prctl",              SPECTRE_V2_USER_CMD_PRCTL,              false },
1232         { "prctl,ibpb",         SPECTRE_V2_USER_CMD_PRCTL_IBPB,         false },
1233         { "seccomp",            SPECTRE_V2_USER_CMD_SECCOMP,            false },
1234         { "seccomp,ibpb",       SPECTRE_V2_USER_CMD_SECCOMP_IBPB,       false },
1235 };
1236
1237 static void __init spec_v2_user_print_cond(const char *reason, bool secure)
1238 {
1239         if (boot_cpu_has_bug(X86_BUG_SPECTRE_V2) != secure)
1240                 pr_info("spectre_v2_user=%s forced on command line.\n", reason);
1241 }
1242
1243 static __ro_after_init enum spectre_v2_mitigation_cmd spectre_v2_cmd;
1244
1245 static enum spectre_v2_user_cmd __init
1246 spectre_v2_parse_user_cmdline(void)
1247 {
1248         char arg[20];
1249         int ret, i;
1250
1251         switch (spectre_v2_cmd) {
1252         case SPECTRE_V2_CMD_NONE:
1253                 return SPECTRE_V2_USER_CMD_NONE;
1254         case SPECTRE_V2_CMD_FORCE:
1255                 return SPECTRE_V2_USER_CMD_FORCE;
1256         default:
1257                 break;
1258         }
1259
1260         ret = cmdline_find_option(boot_command_line, "spectre_v2_user",
1261                                   arg, sizeof(arg));
1262         if (ret < 0)
1263                 return SPECTRE_V2_USER_CMD_AUTO;
1264
1265         for (i = 0; i < ARRAY_SIZE(v2_user_options); i++) {
1266                 if (match_option(arg, ret, v2_user_options[i].option)) {
1267                         spec_v2_user_print_cond(v2_user_options[i].option,
1268                                                 v2_user_options[i].secure);
1269                         return v2_user_options[i].cmd;
1270                 }
1271         }
1272
1273         pr_err("Unknown user space protection option (%s). Switching to AUTO select\n", arg);
1274         return SPECTRE_V2_USER_CMD_AUTO;
1275 }
1276
1277 static inline bool spectre_v2_in_eibrs_mode(enum spectre_v2_mitigation mode)
1278 {
1279         return mode == SPECTRE_V2_EIBRS ||
1280                mode == SPECTRE_V2_EIBRS_RETPOLINE ||
1281                mode == SPECTRE_V2_EIBRS_LFENCE;
1282 }
1283
1284 static inline bool spectre_v2_in_ibrs_mode(enum spectre_v2_mitigation mode)
1285 {
1286         return spectre_v2_in_eibrs_mode(mode) || mode == SPECTRE_V2_IBRS;
1287 }
1288
1289 static void __init
1290 spectre_v2_user_select_mitigation(void)
1291 {
1292         enum spectre_v2_user_mitigation mode = SPECTRE_V2_USER_NONE;
1293         bool smt_possible = IS_ENABLED(CONFIG_SMP);
1294         enum spectre_v2_user_cmd cmd;
1295
1296         if (!boot_cpu_has(X86_FEATURE_IBPB) && !boot_cpu_has(X86_FEATURE_STIBP))
1297                 return;
1298
1299         if (cpu_smt_control == CPU_SMT_FORCE_DISABLED ||
1300             cpu_smt_control == CPU_SMT_NOT_SUPPORTED)
1301                 smt_possible = false;
1302
1303         cmd = spectre_v2_parse_user_cmdline();
1304         switch (cmd) {
1305         case SPECTRE_V2_USER_CMD_NONE:
1306                 goto set_mode;
1307         case SPECTRE_V2_USER_CMD_FORCE:
1308                 mode = SPECTRE_V2_USER_STRICT;
1309                 break;
1310         case SPECTRE_V2_USER_CMD_AUTO:
1311         case SPECTRE_V2_USER_CMD_PRCTL:
1312         case SPECTRE_V2_USER_CMD_PRCTL_IBPB:
1313                 mode = SPECTRE_V2_USER_PRCTL;
1314                 break;
1315         case SPECTRE_V2_USER_CMD_SECCOMP:
1316         case SPECTRE_V2_USER_CMD_SECCOMP_IBPB:
1317                 if (IS_ENABLED(CONFIG_SECCOMP))
1318                         mode = SPECTRE_V2_USER_SECCOMP;
1319                 else
1320                         mode = SPECTRE_V2_USER_PRCTL;
1321                 break;
1322         }
1323
1324         /* Initialize Indirect Branch Prediction Barrier */
1325         if (boot_cpu_has(X86_FEATURE_IBPB)) {
1326                 setup_force_cpu_cap(X86_FEATURE_USE_IBPB);
1327
1328                 spectre_v2_user_ibpb = mode;
1329                 switch (cmd) {
1330                 case SPECTRE_V2_USER_CMD_FORCE:
1331                 case SPECTRE_V2_USER_CMD_PRCTL_IBPB:
1332                 case SPECTRE_V2_USER_CMD_SECCOMP_IBPB:
1333                         static_branch_enable(&switch_mm_always_ibpb);
1334                         spectre_v2_user_ibpb = SPECTRE_V2_USER_STRICT;
1335                         break;
1336                 case SPECTRE_V2_USER_CMD_PRCTL:
1337                 case SPECTRE_V2_USER_CMD_AUTO:
1338                 case SPECTRE_V2_USER_CMD_SECCOMP:
1339                         static_branch_enable(&switch_mm_cond_ibpb);
1340                         break;
1341                 default:
1342                         break;
1343                 }
1344
1345                 pr_info("mitigation: Enabling %s Indirect Branch Prediction Barrier\n",
1346                         static_key_enabled(&switch_mm_always_ibpb) ?
1347                         "always-on" : "conditional");
1348         }
1349
1350         /*
1351          * If no STIBP, Intel enhanced IBRS is enabled, or SMT impossible, STIBP
1352          * is not required.
1353          *
1354          * Intel's Enhanced IBRS also protects against cross-thread branch target
1355          * injection in user-mode as the IBRS bit remains always set which
1356          * implicitly enables cross-thread protections.  However, in legacy IBRS
1357          * mode, the IBRS bit is set only on kernel entry and cleared on return
1358          * to userspace.  AMD Automatic IBRS also does not protect userspace.
1359          * These modes therefore disable the implicit cross-thread protection,
1360          * so allow for STIBP to be selected in those cases.
1361          */
1362         if (!boot_cpu_has(X86_FEATURE_STIBP) ||
1363             !smt_possible ||
1364             (spectre_v2_in_eibrs_mode(spectre_v2_enabled) &&
1365              !boot_cpu_has(X86_FEATURE_AUTOIBRS)))
1366                 return;
1367
1368         /*
1369          * At this point, an STIBP mode other than "off" has been set.
1370          * If STIBP support is not being forced, check if STIBP always-on
1371          * is preferred.
1372          */
1373         if (mode != SPECTRE_V2_USER_STRICT &&
1374             boot_cpu_has(X86_FEATURE_AMD_STIBP_ALWAYS_ON))
1375                 mode = SPECTRE_V2_USER_STRICT_PREFERRED;
1376
1377         if (retbleed_mitigation == RETBLEED_MITIGATION_UNRET ||
1378             retbleed_mitigation == RETBLEED_MITIGATION_IBPB) {
1379                 if (mode != SPECTRE_V2_USER_STRICT &&
1380                     mode != SPECTRE_V2_USER_STRICT_PREFERRED)
1381                         pr_info("Selecting STIBP always-on mode to complement retbleed mitigation\n");
1382                 mode = SPECTRE_V2_USER_STRICT_PREFERRED;
1383         }
1384
1385         spectre_v2_user_stibp = mode;
1386
1387 set_mode:
1388         pr_info("%s\n", spectre_v2_user_strings[mode]);
1389 }
1390
1391 static const char * const spectre_v2_strings[] = {
1392         [SPECTRE_V2_NONE]                       = "Vulnerable",
1393         [SPECTRE_V2_RETPOLINE]                  = "Mitigation: Retpolines",
1394         [SPECTRE_V2_LFENCE]                     = "Mitigation: LFENCE",
1395         [SPECTRE_V2_EIBRS]                      = "Mitigation: Enhanced / Automatic IBRS",
1396         [SPECTRE_V2_EIBRS_LFENCE]               = "Mitigation: Enhanced / Automatic IBRS + LFENCE",
1397         [SPECTRE_V2_EIBRS_RETPOLINE]            = "Mitigation: Enhanced / Automatic IBRS + Retpolines",
1398         [SPECTRE_V2_IBRS]                       = "Mitigation: IBRS",
1399 };
1400
1401 static const struct {
1402         const char *option;
1403         enum spectre_v2_mitigation_cmd cmd;
1404         bool secure;
1405 } mitigation_options[] __initconst = {
1406         { "off",                SPECTRE_V2_CMD_NONE,              false },
1407         { "on",                 SPECTRE_V2_CMD_FORCE,             true  },
1408         { "retpoline",          SPECTRE_V2_CMD_RETPOLINE,         false },
1409         { "retpoline,amd",      SPECTRE_V2_CMD_RETPOLINE_LFENCE,  false },
1410         { "retpoline,lfence",   SPECTRE_V2_CMD_RETPOLINE_LFENCE,  false },
1411         { "retpoline,generic",  SPECTRE_V2_CMD_RETPOLINE_GENERIC, false },
1412         { "eibrs",              SPECTRE_V2_CMD_EIBRS,             false },
1413         { "eibrs,lfence",       SPECTRE_V2_CMD_EIBRS_LFENCE,      false },
1414         { "eibrs,retpoline",    SPECTRE_V2_CMD_EIBRS_RETPOLINE,   false },
1415         { "auto",               SPECTRE_V2_CMD_AUTO,              false },
1416         { "ibrs",               SPECTRE_V2_CMD_IBRS,              false },
1417 };
1418
1419 static void __init spec_v2_print_cond(const char *reason, bool secure)
1420 {
1421         if (boot_cpu_has_bug(X86_BUG_SPECTRE_V2) != secure)
1422                 pr_info("%s selected on command line.\n", reason);
1423 }
1424
1425 static enum spectre_v2_mitigation_cmd __init spectre_v2_parse_cmdline(void)
1426 {
1427         enum spectre_v2_mitigation_cmd cmd = SPECTRE_V2_CMD_AUTO;
1428         char arg[20];
1429         int ret, i;
1430
1431         if (cmdline_find_option_bool(boot_command_line, "nospectre_v2") ||
1432             cpu_mitigations_off())
1433                 return SPECTRE_V2_CMD_NONE;
1434
1435         ret = cmdline_find_option(boot_command_line, "spectre_v2", arg, sizeof(arg));
1436         if (ret < 0)
1437                 return SPECTRE_V2_CMD_AUTO;
1438
1439         for (i = 0; i < ARRAY_SIZE(mitigation_options); i++) {
1440                 if (!match_option(arg, ret, mitigation_options[i].option))
1441                         continue;
1442                 cmd = mitigation_options[i].cmd;
1443                 break;
1444         }
1445
1446         if (i >= ARRAY_SIZE(mitigation_options)) {
1447                 pr_err("unknown option (%s). Switching to AUTO select\n", arg);
1448                 return SPECTRE_V2_CMD_AUTO;
1449         }
1450
1451         if ((cmd == SPECTRE_V2_CMD_RETPOLINE ||
1452              cmd == SPECTRE_V2_CMD_RETPOLINE_LFENCE ||
1453              cmd == SPECTRE_V2_CMD_RETPOLINE_GENERIC ||
1454              cmd == SPECTRE_V2_CMD_EIBRS_LFENCE ||
1455              cmd == SPECTRE_V2_CMD_EIBRS_RETPOLINE) &&
1456             !IS_ENABLED(CONFIG_RETPOLINE)) {
1457                 pr_err("%s selected but not compiled in. Switching to AUTO select\n",
1458                        mitigation_options[i].option);
1459                 return SPECTRE_V2_CMD_AUTO;
1460         }
1461
1462         if ((cmd == SPECTRE_V2_CMD_EIBRS ||
1463              cmd == SPECTRE_V2_CMD_EIBRS_LFENCE ||
1464              cmd == SPECTRE_V2_CMD_EIBRS_RETPOLINE) &&
1465             !boot_cpu_has(X86_FEATURE_IBRS_ENHANCED)) {
1466                 pr_err("%s selected but CPU doesn't have Enhanced or Automatic IBRS. Switching to AUTO select\n",
1467                        mitigation_options[i].option);
1468                 return SPECTRE_V2_CMD_AUTO;
1469         }
1470
1471         if ((cmd == SPECTRE_V2_CMD_RETPOLINE_LFENCE ||
1472              cmd == SPECTRE_V2_CMD_EIBRS_LFENCE) &&
1473             !boot_cpu_has(X86_FEATURE_LFENCE_RDTSC)) {
1474                 pr_err("%s selected, but CPU doesn't have a serializing LFENCE. Switching to AUTO select\n",
1475                        mitigation_options[i].option);
1476                 return SPECTRE_V2_CMD_AUTO;
1477         }
1478
1479         if (cmd == SPECTRE_V2_CMD_IBRS && !IS_ENABLED(CONFIG_CPU_IBRS_ENTRY)) {
1480                 pr_err("%s selected but not compiled in. Switching to AUTO select\n",
1481                        mitigation_options[i].option);
1482                 return SPECTRE_V2_CMD_AUTO;
1483         }
1484
1485         if (cmd == SPECTRE_V2_CMD_IBRS && boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
1486                 pr_err("%s selected but not Intel CPU. Switching to AUTO select\n",
1487                        mitigation_options[i].option);
1488                 return SPECTRE_V2_CMD_AUTO;
1489         }
1490
1491         if (cmd == SPECTRE_V2_CMD_IBRS && !boot_cpu_has(X86_FEATURE_IBRS)) {
1492                 pr_err("%s selected but CPU doesn't have IBRS. Switching to AUTO select\n",
1493                        mitigation_options[i].option);
1494                 return SPECTRE_V2_CMD_AUTO;
1495         }
1496
1497         if (cmd == SPECTRE_V2_CMD_IBRS && boot_cpu_has(X86_FEATURE_XENPV)) {
1498                 pr_err("%s selected but running as XenPV guest. Switching to AUTO select\n",
1499                        mitigation_options[i].option);
1500                 return SPECTRE_V2_CMD_AUTO;
1501         }
1502
1503         spec_v2_print_cond(mitigation_options[i].option,
1504                            mitigation_options[i].secure);
1505         return cmd;
1506 }
1507
1508 static enum spectre_v2_mitigation __init spectre_v2_select_retpoline(void)
1509 {
1510         if (!IS_ENABLED(CONFIG_RETPOLINE)) {
1511                 pr_err("Kernel not compiled with retpoline; no mitigation available!");
1512                 return SPECTRE_V2_NONE;
1513         }
1514
1515         return SPECTRE_V2_RETPOLINE;
1516 }
1517
1518 static bool __ro_after_init rrsba_disabled;
1519
1520 /* Disable in-kernel use of non-RSB RET predictors */
1521 static void __init spec_ctrl_disable_kernel_rrsba(void)
1522 {
1523         if (rrsba_disabled)
1524                 return;
1525
1526         if (!(x86_arch_cap_msr & ARCH_CAP_RRSBA)) {
1527                 rrsba_disabled = true;
1528                 return;
1529         }
1530
1531         if (!boot_cpu_has(X86_FEATURE_RRSBA_CTRL))
1532                 return;
1533
1534         x86_spec_ctrl_base |= SPEC_CTRL_RRSBA_DIS_S;
1535         update_spec_ctrl(x86_spec_ctrl_base);
1536         rrsba_disabled = true;
1537 }
1538
1539 static void __init spectre_v2_determine_rsb_fill_type_at_vmexit(enum spectre_v2_mitigation mode)
1540 {
1541         /*
1542          * Similar to context switches, there are two types of RSB attacks
1543          * after VM exit:
1544          *
1545          * 1) RSB underflow
1546          *
1547          * 2) Poisoned RSB entry
1548          *
1549          * When retpoline is enabled, both are mitigated by filling/clearing
1550          * the RSB.
1551          *
1552          * When IBRS is enabled, while #1 would be mitigated by the IBRS branch
1553          * prediction isolation protections, RSB still needs to be cleared
1554          * because of #2.  Note that SMEP provides no protection here, unlike
1555          * user-space-poisoned RSB entries.
1556          *
1557          * eIBRS should protect against RSB poisoning, but if the EIBRS_PBRSB
1558          * bug is present then a LITE version of RSB protection is required,
1559          * just a single call needs to retire before a RET is executed.
1560          */
1561         switch (mode) {
1562         case SPECTRE_V2_NONE:
1563                 return;
1564
1565         case SPECTRE_V2_EIBRS_LFENCE:
1566         case SPECTRE_V2_EIBRS:
1567                 if (boot_cpu_has_bug(X86_BUG_EIBRS_PBRSB)) {
1568                         setup_force_cpu_cap(X86_FEATURE_RSB_VMEXIT_LITE);
1569                         pr_info("Spectre v2 / PBRSB-eIBRS: Retire a single CALL on VMEXIT\n");
1570                 }
1571                 return;
1572
1573         case SPECTRE_V2_EIBRS_RETPOLINE:
1574         case SPECTRE_V2_RETPOLINE:
1575         case SPECTRE_V2_LFENCE:
1576         case SPECTRE_V2_IBRS:
1577                 setup_force_cpu_cap(X86_FEATURE_RSB_VMEXIT);
1578                 pr_info("Spectre v2 / SpectreRSB : Filling RSB on VMEXIT\n");
1579                 return;
1580         }
1581
1582         pr_warn_once("Unknown Spectre v2 mode, disabling RSB mitigation at VM exit");
1583         dump_stack();
1584 }
1585
1586 /*
1587  * Set BHI_DIS_S to prevent indirect branches in kernel to be influenced by
1588  * branch history in userspace. Not needed if BHI_NO is set.
1589  */
1590 static bool __init spec_ctrl_bhi_dis(void)
1591 {
1592         if (!boot_cpu_has(X86_FEATURE_BHI_CTRL))
1593                 return false;
1594
1595         x86_spec_ctrl_base |= SPEC_CTRL_BHI_DIS_S;
1596         update_spec_ctrl(x86_spec_ctrl_base);
1597         setup_force_cpu_cap(X86_FEATURE_CLEAR_BHB_HW);
1598
1599         return true;
1600 }
1601
1602 enum bhi_mitigations {
1603         BHI_MITIGATION_OFF,
1604         BHI_MITIGATION_ON,
1605 };
1606
1607 static enum bhi_mitigations bhi_mitigation __ro_after_init =
1608         IS_ENABLED(CONFIG_MITIGATION_SPECTRE_BHI) ? BHI_MITIGATION_ON : BHI_MITIGATION_OFF;
1609
1610 static int __init spectre_bhi_parse_cmdline(char *str)
1611 {
1612         if (!str)
1613                 return -EINVAL;
1614
1615         if (!strcmp(str, "off"))
1616                 bhi_mitigation = BHI_MITIGATION_OFF;
1617         else if (!strcmp(str, "on"))
1618                 bhi_mitigation = BHI_MITIGATION_ON;
1619         else
1620                 pr_err("Ignoring unknown spectre_bhi option (%s)", str);
1621
1622         return 0;
1623 }
1624 early_param("spectre_bhi", spectre_bhi_parse_cmdline);
1625
1626 static void __init bhi_select_mitigation(void)
1627 {
1628         if (bhi_mitigation == BHI_MITIGATION_OFF)
1629                 return;
1630
1631         /* Retpoline mitigates against BHI unless the CPU has RRSBA behavior */
1632         if (boot_cpu_has(X86_FEATURE_RETPOLINE) &&
1633             !boot_cpu_has(X86_FEATURE_RETPOLINE_LFENCE)) {
1634                 spec_ctrl_disable_kernel_rrsba();
1635                 if (rrsba_disabled)
1636                         return;
1637         }
1638
1639         if (spec_ctrl_bhi_dis())
1640                 return;
1641
1642         if (!IS_ENABLED(CONFIG_X86_64))
1643                 return;
1644
1645         /* Mitigate KVM by default */
1646         setup_force_cpu_cap(X86_FEATURE_CLEAR_BHB_LOOP_ON_VMEXIT);
1647         pr_info("Spectre BHI mitigation: SW BHB clearing on vm exit\n");
1648
1649         /* Mitigate syscalls when the mitigation is forced =on */
1650         setup_force_cpu_cap(X86_FEATURE_CLEAR_BHB_LOOP);
1651         pr_info("Spectre BHI mitigation: SW BHB clearing on syscall\n");
1652 }
1653
1654 static void __init spectre_v2_select_mitigation(void)
1655 {
1656         enum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline();
1657         enum spectre_v2_mitigation mode = SPECTRE_V2_NONE;
1658
1659         /*
1660          * If the CPU is not affected and the command line mode is NONE or AUTO
1661          * then nothing to do.
1662          */
1663         if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2) &&
1664             (cmd == SPECTRE_V2_CMD_NONE || cmd == SPECTRE_V2_CMD_AUTO))
1665                 return;
1666
1667         switch (cmd) {
1668         case SPECTRE_V2_CMD_NONE:
1669                 return;
1670
1671         case SPECTRE_V2_CMD_FORCE:
1672         case SPECTRE_V2_CMD_AUTO:
1673                 if (boot_cpu_has(X86_FEATURE_IBRS_ENHANCED)) {
1674                         mode = SPECTRE_V2_EIBRS;
1675                         break;
1676                 }
1677
1678                 if (IS_ENABLED(CONFIG_CPU_IBRS_ENTRY) &&
1679                     boot_cpu_has_bug(X86_BUG_RETBLEED) &&
1680                     retbleed_cmd != RETBLEED_CMD_OFF &&
1681                     boot_cpu_has(X86_FEATURE_IBRS) &&
1682                     boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) {
1683                         mode = SPECTRE_V2_IBRS;
1684                         break;
1685                 }
1686
1687                 mode = spectre_v2_select_retpoline();
1688                 break;
1689
1690         case SPECTRE_V2_CMD_RETPOLINE_LFENCE:
1691                 pr_err(SPECTRE_V2_LFENCE_MSG);
1692                 mode = SPECTRE_V2_LFENCE;
1693                 break;
1694
1695         case SPECTRE_V2_CMD_RETPOLINE_GENERIC:
1696                 mode = SPECTRE_V2_RETPOLINE;
1697                 break;
1698
1699         case SPECTRE_V2_CMD_RETPOLINE:
1700                 mode = spectre_v2_select_retpoline();
1701                 break;
1702
1703         case SPECTRE_V2_CMD_IBRS:
1704                 mode = SPECTRE_V2_IBRS;
1705                 break;
1706
1707         case SPECTRE_V2_CMD_EIBRS:
1708                 mode = SPECTRE_V2_EIBRS;
1709                 break;
1710
1711         case SPECTRE_V2_CMD_EIBRS_LFENCE:
1712                 mode = SPECTRE_V2_EIBRS_LFENCE;
1713                 break;
1714
1715         case SPECTRE_V2_CMD_EIBRS_RETPOLINE:
1716                 mode = SPECTRE_V2_EIBRS_RETPOLINE;
1717                 break;
1718         }
1719
1720         if (mode == SPECTRE_V2_EIBRS && unprivileged_ebpf_enabled())
1721                 pr_err(SPECTRE_V2_EIBRS_EBPF_MSG);
1722
1723         if (spectre_v2_in_ibrs_mode(mode)) {
1724                 if (boot_cpu_has(X86_FEATURE_AUTOIBRS)) {
1725                         msr_set_bit(MSR_EFER, _EFER_AUTOIBRS);
1726                 } else {
1727                         x86_spec_ctrl_base |= SPEC_CTRL_IBRS;
1728                         update_spec_ctrl(x86_spec_ctrl_base);
1729                 }
1730         }
1731
1732         switch (mode) {
1733         case SPECTRE_V2_NONE:
1734         case SPECTRE_V2_EIBRS:
1735                 break;
1736
1737         case SPECTRE_V2_IBRS:
1738                 setup_force_cpu_cap(X86_FEATURE_KERNEL_IBRS);
1739                 if (boot_cpu_has(X86_FEATURE_IBRS_ENHANCED))
1740                         pr_warn(SPECTRE_V2_IBRS_PERF_MSG);
1741                 break;
1742
1743         case SPECTRE_V2_LFENCE:
1744         case SPECTRE_V2_EIBRS_LFENCE:
1745                 setup_force_cpu_cap(X86_FEATURE_RETPOLINE_LFENCE);
1746                 fallthrough;
1747
1748         case SPECTRE_V2_RETPOLINE:
1749         case SPECTRE_V2_EIBRS_RETPOLINE:
1750                 setup_force_cpu_cap(X86_FEATURE_RETPOLINE);
1751                 break;
1752         }
1753
1754         /*
1755          * Disable alternate RSB predictions in kernel when indirect CALLs and
1756          * JMPs gets protection against BHI and Intramode-BTI, but RET
1757          * prediction from a non-RSB predictor is still a risk.
1758          */
1759         if (mode == SPECTRE_V2_EIBRS_LFENCE ||
1760             mode == SPECTRE_V2_EIBRS_RETPOLINE ||
1761             mode == SPECTRE_V2_RETPOLINE)
1762                 spec_ctrl_disable_kernel_rrsba();
1763
1764         if (boot_cpu_has(X86_BUG_BHI))
1765                 bhi_select_mitigation();
1766
1767         spectre_v2_enabled = mode;
1768         pr_info("%s\n", spectre_v2_strings[mode]);
1769
1770         /*
1771          * If Spectre v2 protection has been enabled, fill the RSB during a
1772          * context switch.  In general there are two types of RSB attacks
1773          * across context switches, for which the CALLs/RETs may be unbalanced.
1774          *
1775          * 1) RSB underflow
1776          *
1777          *    Some Intel parts have "bottomless RSB".  When the RSB is empty,
1778          *    speculated return targets may come from the branch predictor,
1779          *    which could have a user-poisoned BTB or BHB entry.
1780          *
1781          *    AMD has it even worse: *all* returns are speculated from the BTB,
1782          *    regardless of the state of the RSB.
1783          *
1784          *    When IBRS or eIBRS is enabled, the "user -> kernel" attack
1785          *    scenario is mitigated by the IBRS branch prediction isolation
1786          *    properties, so the RSB buffer filling wouldn't be necessary to
1787          *    protect against this type of attack.
1788          *
1789          *    The "user -> user" attack scenario is mitigated by RSB filling.
1790          *
1791          * 2) Poisoned RSB entry
1792          *
1793          *    If the 'next' in-kernel return stack is shorter than 'prev',
1794          *    'next' could be tricked into speculating with a user-poisoned RSB
1795          *    entry.
1796          *
1797          *    The "user -> kernel" attack scenario is mitigated by SMEP and
1798          *    eIBRS.
1799          *
1800          *    The "user -> user" scenario, also known as SpectreBHB, requires
1801          *    RSB clearing.
1802          *
1803          * So to mitigate all cases, unconditionally fill RSB on context
1804          * switches.
1805          *
1806          * FIXME: Is this pointless for retbleed-affected AMD?
1807          */
1808         setup_force_cpu_cap(X86_FEATURE_RSB_CTXSW);
1809         pr_info("Spectre v2 / SpectreRSB mitigation: Filling RSB on context switch\n");
1810
1811         spectre_v2_determine_rsb_fill_type_at_vmexit(mode);
1812
1813         /*
1814          * Retpoline protects the kernel, but doesn't protect firmware.  IBRS
1815          * and Enhanced IBRS protect firmware too, so enable IBRS around
1816          * firmware calls only when IBRS / Enhanced / Automatic IBRS aren't
1817          * otherwise enabled.
1818          *
1819          * Use "mode" to check Enhanced IBRS instead of boot_cpu_has(), because
1820          * the user might select retpoline on the kernel command line and if
1821          * the CPU supports Enhanced IBRS, kernel might un-intentionally not
1822          * enable IBRS around firmware calls.
1823          */
1824         if (boot_cpu_has_bug(X86_BUG_RETBLEED) &&
1825             boot_cpu_has(X86_FEATURE_IBPB) &&
1826             (boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
1827              boot_cpu_data.x86_vendor == X86_VENDOR_HYGON)) {
1828
1829                 if (retbleed_cmd != RETBLEED_CMD_IBPB) {
1830                         setup_force_cpu_cap(X86_FEATURE_USE_IBPB_FW);
1831                         pr_info("Enabling Speculation Barrier for firmware calls\n");
1832                 }
1833
1834         } else if (boot_cpu_has(X86_FEATURE_IBRS) && !spectre_v2_in_ibrs_mode(mode)) {
1835                 setup_force_cpu_cap(X86_FEATURE_USE_IBRS_FW);
1836                 pr_info("Enabling Restricted Speculation for firmware calls\n");
1837         }
1838
1839         /* Set up IBPB and STIBP depending on the general spectre V2 command */
1840         spectre_v2_cmd = cmd;
1841 }
1842
1843 static void update_stibp_msr(void * __unused)
1844 {
1845         u64 val = spec_ctrl_current() | (x86_spec_ctrl_base & SPEC_CTRL_STIBP);
1846         update_spec_ctrl(val);
1847 }
1848
1849 /* Update x86_spec_ctrl_base in case SMT state changed. */
1850 static void update_stibp_strict(void)
1851 {
1852         u64 mask = x86_spec_ctrl_base & ~SPEC_CTRL_STIBP;
1853
1854         if (sched_smt_active())
1855                 mask |= SPEC_CTRL_STIBP;
1856
1857         if (mask == x86_spec_ctrl_base)
1858                 return;
1859
1860         pr_info("Update user space SMT mitigation: STIBP %s\n",
1861                 mask & SPEC_CTRL_STIBP ? "always-on" : "off");
1862         x86_spec_ctrl_base = mask;
1863         on_each_cpu(update_stibp_msr, NULL, 1);
1864 }
1865
1866 /* Update the static key controlling the evaluation of TIF_SPEC_IB */
1867 static void update_indir_branch_cond(void)
1868 {
1869         if (sched_smt_active())
1870                 static_branch_enable(&switch_to_cond_stibp);
1871         else
1872                 static_branch_disable(&switch_to_cond_stibp);
1873 }
1874
1875 #undef pr_fmt
1876 #define pr_fmt(fmt) fmt
1877
1878 /* Update the static key controlling the MDS CPU buffer clear in idle */
1879 static void update_mds_branch_idle(void)
1880 {
1881         /*
1882          * Enable the idle clearing if SMT is active on CPUs which are
1883          * affected only by MSBDS and not any other MDS variant.
1884          *
1885          * The other variants cannot be mitigated when SMT is enabled, so
1886          * clearing the buffers on idle just to prevent the Store Buffer
1887          * repartitioning leak would be a window dressing exercise.
1888          */
1889         if (!boot_cpu_has_bug(X86_BUG_MSBDS_ONLY))
1890                 return;
1891
1892         if (sched_smt_active()) {
1893                 static_branch_enable(&mds_idle_clear);
1894         } else if (mmio_mitigation == MMIO_MITIGATION_OFF ||
1895                    (x86_arch_cap_msr & ARCH_CAP_FBSDP_NO)) {
1896                 static_branch_disable(&mds_idle_clear);
1897         }
1898 }
1899
1900 #define MDS_MSG_SMT "MDS CPU bug present and SMT on, data leak possible. See https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/mds.html for more details.\n"
1901 #define TAA_MSG_SMT "TAA CPU bug present and SMT on, data leak possible. See https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/tsx_async_abort.html for more details.\n"
1902 #define MMIO_MSG_SMT "MMIO Stale Data CPU bug present and SMT on, data leak possible. See https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/processor_mmio_stale_data.html for more details.\n"
1903
1904 void cpu_bugs_smt_update(void)
1905 {
1906         mutex_lock(&spec_ctrl_mutex);
1907
1908         if (sched_smt_active() && unprivileged_ebpf_enabled() &&
1909             spectre_v2_enabled == SPECTRE_V2_EIBRS_LFENCE)
1910                 pr_warn_once(SPECTRE_V2_EIBRS_LFENCE_EBPF_SMT_MSG);
1911
1912         switch (spectre_v2_user_stibp) {
1913         case SPECTRE_V2_USER_NONE:
1914                 break;
1915         case SPECTRE_V2_USER_STRICT:
1916         case SPECTRE_V2_USER_STRICT_PREFERRED:
1917                 update_stibp_strict();
1918                 break;
1919         case SPECTRE_V2_USER_PRCTL:
1920         case SPECTRE_V2_USER_SECCOMP:
1921                 update_indir_branch_cond();
1922                 break;
1923         }
1924
1925         switch (mds_mitigation) {
1926         case MDS_MITIGATION_FULL:
1927         case MDS_MITIGATION_VMWERV:
1928                 if (sched_smt_active() && !boot_cpu_has(X86_BUG_MSBDS_ONLY))
1929                         pr_warn_once(MDS_MSG_SMT);
1930                 update_mds_branch_idle();
1931                 break;
1932         case MDS_MITIGATION_OFF:
1933                 break;
1934         }
1935
1936         switch (taa_mitigation) {
1937         case TAA_MITIGATION_VERW:
1938         case TAA_MITIGATION_UCODE_NEEDED:
1939                 if (sched_smt_active())
1940                         pr_warn_once(TAA_MSG_SMT);
1941                 break;
1942         case TAA_MITIGATION_TSX_DISABLED:
1943         case TAA_MITIGATION_OFF:
1944                 break;
1945         }
1946
1947         switch (mmio_mitigation) {
1948         case MMIO_MITIGATION_VERW:
1949         case MMIO_MITIGATION_UCODE_NEEDED:
1950                 if (sched_smt_active())
1951                         pr_warn_once(MMIO_MSG_SMT);
1952                 break;
1953         case MMIO_MITIGATION_OFF:
1954                 break;
1955         }
1956
1957         mutex_unlock(&spec_ctrl_mutex);
1958 }
1959
1960 #undef pr_fmt
1961 #define pr_fmt(fmt)     "Speculative Store Bypass: " fmt
1962
1963 static enum ssb_mitigation ssb_mode __ro_after_init = SPEC_STORE_BYPASS_NONE;
1964
1965 /* The kernel command line selection */
1966 enum ssb_mitigation_cmd {
1967         SPEC_STORE_BYPASS_CMD_NONE,
1968         SPEC_STORE_BYPASS_CMD_AUTO,
1969         SPEC_STORE_BYPASS_CMD_ON,
1970         SPEC_STORE_BYPASS_CMD_PRCTL,
1971         SPEC_STORE_BYPASS_CMD_SECCOMP,
1972 };
1973
1974 static const char * const ssb_strings[] = {
1975         [SPEC_STORE_BYPASS_NONE]        = "Vulnerable",
1976         [SPEC_STORE_BYPASS_DISABLE]     = "Mitigation: Speculative Store Bypass disabled",
1977         [SPEC_STORE_BYPASS_PRCTL]       = "Mitigation: Speculative Store Bypass disabled via prctl",
1978         [SPEC_STORE_BYPASS_SECCOMP]     = "Mitigation: Speculative Store Bypass disabled via prctl and seccomp",
1979 };
1980
1981 static const struct {
1982         const char *option;
1983         enum ssb_mitigation_cmd cmd;
1984 } ssb_mitigation_options[]  __initconst = {
1985         { "auto",       SPEC_STORE_BYPASS_CMD_AUTO },    /* Platform decides */
1986         { "on",         SPEC_STORE_BYPASS_CMD_ON },      /* Disable Speculative Store Bypass */
1987         { "off",        SPEC_STORE_BYPASS_CMD_NONE },    /* Don't touch Speculative Store Bypass */
1988         { "prctl",      SPEC_STORE_BYPASS_CMD_PRCTL },   /* Disable Speculative Store Bypass via prctl */
1989         { "seccomp",    SPEC_STORE_BYPASS_CMD_SECCOMP }, /* Disable Speculative Store Bypass via prctl and seccomp */
1990 };
1991
1992 static enum ssb_mitigation_cmd __init ssb_parse_cmdline(void)
1993 {
1994         enum ssb_mitigation_cmd cmd = SPEC_STORE_BYPASS_CMD_AUTO;
1995         char arg[20];
1996         int ret, i;
1997
1998         if (cmdline_find_option_bool(boot_command_line, "nospec_store_bypass_disable") ||
1999             cpu_mitigations_off()) {
2000                 return SPEC_STORE_BYPASS_CMD_NONE;
2001         } else {
2002                 ret = cmdline_find_option(boot_command_line, "spec_store_bypass_disable",
2003                                           arg, sizeof(arg));
2004                 if (ret < 0)
2005                         return SPEC_STORE_BYPASS_CMD_AUTO;
2006
2007                 for (i = 0; i < ARRAY_SIZE(ssb_mitigation_options); i++) {
2008                         if (!match_option(arg, ret, ssb_mitigation_options[i].option))
2009                                 continue;
2010
2011                         cmd = ssb_mitigation_options[i].cmd;
2012                         break;
2013                 }
2014
2015                 if (i >= ARRAY_SIZE(ssb_mitigation_options)) {
2016                         pr_err("unknown option (%s). Switching to AUTO select\n", arg);
2017                         return SPEC_STORE_BYPASS_CMD_AUTO;
2018                 }
2019         }
2020
2021         return cmd;
2022 }
2023
2024 static enum ssb_mitigation __init __ssb_select_mitigation(void)
2025 {
2026         enum ssb_mitigation mode = SPEC_STORE_BYPASS_NONE;
2027         enum ssb_mitigation_cmd cmd;
2028
2029         if (!boot_cpu_has(X86_FEATURE_SSBD))
2030                 return mode;
2031
2032         cmd = ssb_parse_cmdline();
2033         if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS) &&
2034             (cmd == SPEC_STORE_BYPASS_CMD_NONE ||
2035              cmd == SPEC_STORE_BYPASS_CMD_AUTO))
2036                 return mode;
2037
2038         switch (cmd) {
2039         case SPEC_STORE_BYPASS_CMD_SECCOMP:
2040                 /*
2041                  * Choose prctl+seccomp as the default mode if seccomp is
2042                  * enabled.
2043                  */
2044                 if (IS_ENABLED(CONFIG_SECCOMP))
2045                         mode = SPEC_STORE_BYPASS_SECCOMP;
2046                 else
2047                         mode = SPEC_STORE_BYPASS_PRCTL;
2048                 break;
2049         case SPEC_STORE_BYPASS_CMD_ON:
2050                 mode = SPEC_STORE_BYPASS_DISABLE;
2051                 break;
2052         case SPEC_STORE_BYPASS_CMD_AUTO:
2053         case SPEC_STORE_BYPASS_CMD_PRCTL:
2054                 mode = SPEC_STORE_BYPASS_PRCTL;
2055                 break;
2056         case SPEC_STORE_BYPASS_CMD_NONE:
2057                 break;
2058         }
2059
2060         /*
2061          * We have three CPU feature flags that are in play here:
2062          *  - X86_BUG_SPEC_STORE_BYPASS - CPU is susceptible.
2063          *  - X86_FEATURE_SSBD - CPU is able to turn off speculative store bypass
2064          *  - X86_FEATURE_SPEC_STORE_BYPASS_DISABLE - engage the mitigation
2065          */
2066         if (mode == SPEC_STORE_BYPASS_DISABLE) {
2067                 setup_force_cpu_cap(X86_FEATURE_SPEC_STORE_BYPASS_DISABLE);
2068                 /*
2069                  * Intel uses the SPEC CTRL MSR Bit(2) for this, while AMD may
2070                  * use a completely different MSR and bit dependent on family.
2071                  */
2072                 if (!static_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) &&
2073                     !static_cpu_has(X86_FEATURE_AMD_SSBD)) {
2074                         x86_amd_ssb_disable();
2075                 } else {
2076                         x86_spec_ctrl_base |= SPEC_CTRL_SSBD;
2077                         update_spec_ctrl(x86_spec_ctrl_base);
2078                 }
2079         }
2080
2081         return mode;
2082 }
2083
2084 static void ssb_select_mitigation(void)
2085 {
2086         ssb_mode = __ssb_select_mitigation();
2087
2088         if (boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
2089                 pr_info("%s\n", ssb_strings[ssb_mode]);
2090 }
2091
2092 #undef pr_fmt
2093 #define pr_fmt(fmt)     "Speculation prctl: " fmt
2094
2095 static void task_update_spec_tif(struct task_struct *tsk)
2096 {
2097         /* Force the update of the real TIF bits */
2098         set_tsk_thread_flag(tsk, TIF_SPEC_FORCE_UPDATE);
2099
2100         /*
2101          * Immediately update the speculation control MSRs for the current
2102          * task, but for a non-current task delay setting the CPU
2103          * mitigation until it is scheduled next.
2104          *
2105          * This can only happen for SECCOMP mitigation. For PRCTL it's
2106          * always the current task.
2107          */
2108         if (tsk == current)
2109                 speculation_ctrl_update_current();
2110 }
2111
2112 static int l1d_flush_prctl_set(struct task_struct *task, unsigned long ctrl)
2113 {
2114
2115         if (!static_branch_unlikely(&switch_mm_cond_l1d_flush))
2116                 return -EPERM;
2117
2118         switch (ctrl) {
2119         case PR_SPEC_ENABLE:
2120                 set_ti_thread_flag(&task->thread_info, TIF_SPEC_L1D_FLUSH);
2121                 return 0;
2122         case PR_SPEC_DISABLE:
2123                 clear_ti_thread_flag(&task->thread_info, TIF_SPEC_L1D_FLUSH);
2124                 return 0;
2125         default:
2126                 return -ERANGE;
2127         }
2128 }
2129
2130 static int ssb_prctl_set(struct task_struct *task, unsigned long ctrl)
2131 {
2132         if (ssb_mode != SPEC_STORE_BYPASS_PRCTL &&
2133             ssb_mode != SPEC_STORE_BYPASS_SECCOMP)
2134                 return -ENXIO;
2135
2136         switch (ctrl) {
2137         case PR_SPEC_ENABLE:
2138                 /* If speculation is force disabled, enable is not allowed */
2139                 if (task_spec_ssb_force_disable(task))
2140                         return -EPERM;
2141                 task_clear_spec_ssb_disable(task);
2142                 task_clear_spec_ssb_noexec(task);
2143                 task_update_spec_tif(task);
2144                 break;
2145         case PR_SPEC_DISABLE:
2146                 task_set_spec_ssb_disable(task);
2147                 task_clear_spec_ssb_noexec(task);
2148                 task_update_spec_tif(task);
2149                 break;
2150         case PR_SPEC_FORCE_DISABLE:
2151                 task_set_spec_ssb_disable(task);
2152                 task_set_spec_ssb_force_disable(task);
2153                 task_clear_spec_ssb_noexec(task);
2154                 task_update_spec_tif(task);
2155                 break;
2156         case PR_SPEC_DISABLE_NOEXEC:
2157                 if (task_spec_ssb_force_disable(task))
2158                         return -EPERM;
2159                 task_set_spec_ssb_disable(task);
2160                 task_set_spec_ssb_noexec(task);
2161                 task_update_spec_tif(task);
2162                 break;
2163         default:
2164                 return -ERANGE;
2165         }
2166         return 0;
2167 }
2168
2169 static bool is_spec_ib_user_controlled(void)
2170 {
2171         return spectre_v2_user_ibpb == SPECTRE_V2_USER_PRCTL ||
2172                 spectre_v2_user_ibpb == SPECTRE_V2_USER_SECCOMP ||
2173                 spectre_v2_user_stibp == SPECTRE_V2_USER_PRCTL ||
2174                 spectre_v2_user_stibp == SPECTRE_V2_USER_SECCOMP;
2175 }
2176
2177 static int ib_prctl_set(struct task_struct *task, unsigned long ctrl)
2178 {
2179         switch (ctrl) {
2180         case PR_SPEC_ENABLE:
2181                 if (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE &&
2182                     spectre_v2_user_stibp == SPECTRE_V2_USER_NONE)
2183                         return 0;
2184
2185                 /*
2186                  * With strict mode for both IBPB and STIBP, the instruction
2187                  * code paths avoid checking this task flag and instead,
2188                  * unconditionally run the instruction. However, STIBP and IBPB
2189                  * are independent and either can be set to conditionally
2190                  * enabled regardless of the mode of the other.
2191                  *
2192                  * If either is set to conditional, allow the task flag to be
2193                  * updated, unless it was force-disabled by a previous prctl
2194                  * call. Currently, this is possible on an AMD CPU which has the
2195                  * feature X86_FEATURE_AMD_STIBP_ALWAYS_ON. In this case, if the
2196                  * kernel is booted with 'spectre_v2_user=seccomp', then
2197                  * spectre_v2_user_ibpb == SPECTRE_V2_USER_SECCOMP and
2198                  * spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED.
2199                  */
2200                 if (!is_spec_ib_user_controlled() ||
2201                     task_spec_ib_force_disable(task))
2202                         return -EPERM;
2203
2204                 task_clear_spec_ib_disable(task);
2205                 task_update_spec_tif(task);
2206                 break;
2207         case PR_SPEC_DISABLE:
2208         case PR_SPEC_FORCE_DISABLE:
2209                 /*
2210                  * Indirect branch speculation is always allowed when
2211                  * mitigation is force disabled.
2212                  */
2213                 if (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE &&
2214                     spectre_v2_user_stibp == SPECTRE_V2_USER_NONE)
2215                         return -EPERM;
2216
2217                 if (!is_spec_ib_user_controlled())
2218                         return 0;
2219
2220                 task_set_spec_ib_disable(task);
2221                 if (ctrl == PR_SPEC_FORCE_DISABLE)
2222                         task_set_spec_ib_force_disable(task);
2223                 task_update_spec_tif(task);
2224                 if (task == current)
2225                         indirect_branch_prediction_barrier();
2226                 break;
2227         default:
2228                 return -ERANGE;
2229         }
2230         return 0;
2231 }
2232
2233 int arch_prctl_spec_ctrl_set(struct task_struct *task, unsigned long which,
2234                              unsigned long ctrl)
2235 {
2236         switch (which) {
2237         case PR_SPEC_STORE_BYPASS:
2238                 return ssb_prctl_set(task, ctrl);
2239         case PR_SPEC_INDIRECT_BRANCH:
2240                 return ib_prctl_set(task, ctrl);
2241         case PR_SPEC_L1D_FLUSH:
2242                 return l1d_flush_prctl_set(task, ctrl);
2243         default:
2244                 return -ENODEV;
2245         }
2246 }
2247
2248 #ifdef CONFIG_SECCOMP
2249 void arch_seccomp_spec_mitigate(struct task_struct *task)
2250 {
2251         if (ssb_mode == SPEC_STORE_BYPASS_SECCOMP)
2252                 ssb_prctl_set(task, PR_SPEC_FORCE_DISABLE);
2253         if (spectre_v2_user_ibpb == SPECTRE_V2_USER_SECCOMP ||
2254             spectre_v2_user_stibp == SPECTRE_V2_USER_SECCOMP)
2255                 ib_prctl_set(task, PR_SPEC_FORCE_DISABLE);
2256 }
2257 #endif
2258
2259 static int l1d_flush_prctl_get(struct task_struct *task)
2260 {
2261         if (!static_branch_unlikely(&switch_mm_cond_l1d_flush))
2262                 return PR_SPEC_FORCE_DISABLE;
2263
2264         if (test_ti_thread_flag(&task->thread_info, TIF_SPEC_L1D_FLUSH))
2265                 return PR_SPEC_PRCTL | PR_SPEC_ENABLE;
2266         else
2267                 return PR_SPEC_PRCTL | PR_SPEC_DISABLE;
2268 }
2269
2270 static int ssb_prctl_get(struct task_struct *task)
2271 {
2272         switch (ssb_mode) {
2273         case SPEC_STORE_BYPASS_DISABLE:
2274                 return PR_SPEC_DISABLE;
2275         case SPEC_STORE_BYPASS_SECCOMP:
2276         case SPEC_STORE_BYPASS_PRCTL:
2277                 if (task_spec_ssb_force_disable(task))
2278                         return PR_SPEC_PRCTL | PR_SPEC_FORCE_DISABLE;
2279                 if (task_spec_ssb_noexec(task))
2280                         return PR_SPEC_PRCTL | PR_SPEC_DISABLE_NOEXEC;
2281                 if (task_spec_ssb_disable(task))
2282                         return PR_SPEC_PRCTL | PR_SPEC_DISABLE;
2283                 return PR_SPEC_PRCTL | PR_SPEC_ENABLE;
2284         default:
2285                 if (boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
2286                         return PR_SPEC_ENABLE;
2287                 return PR_SPEC_NOT_AFFECTED;
2288         }
2289 }
2290
2291 static int ib_prctl_get(struct task_struct *task)
2292 {
2293         if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2))
2294                 return PR_SPEC_NOT_AFFECTED;
2295
2296         if (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE &&
2297             spectre_v2_user_stibp == SPECTRE_V2_USER_NONE)
2298                 return PR_SPEC_ENABLE;
2299         else if (is_spec_ib_user_controlled()) {
2300                 if (task_spec_ib_force_disable(task))
2301                         return PR_SPEC_PRCTL | PR_SPEC_FORCE_DISABLE;
2302                 if (task_spec_ib_disable(task))
2303                         return PR_SPEC_PRCTL | PR_SPEC_DISABLE;
2304                 return PR_SPEC_PRCTL | PR_SPEC_ENABLE;
2305         } else if (spectre_v2_user_ibpb == SPECTRE_V2_USER_STRICT ||
2306             spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT ||
2307             spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED)
2308                 return PR_SPEC_DISABLE;
2309         else
2310                 return PR_SPEC_NOT_AFFECTED;
2311 }
2312
2313 int arch_prctl_spec_ctrl_get(struct task_struct *task, unsigned long which)
2314 {
2315         switch (which) {
2316         case PR_SPEC_STORE_BYPASS:
2317                 return ssb_prctl_get(task);
2318         case PR_SPEC_INDIRECT_BRANCH:
2319                 return ib_prctl_get(task);
2320         case PR_SPEC_L1D_FLUSH:
2321                 return l1d_flush_prctl_get(task);
2322         default:
2323                 return -ENODEV;
2324         }
2325 }
2326
2327 void x86_spec_ctrl_setup_ap(void)
2328 {
2329         if (boot_cpu_has(X86_FEATURE_MSR_SPEC_CTRL))
2330                 update_spec_ctrl(x86_spec_ctrl_base);
2331
2332         if (ssb_mode == SPEC_STORE_BYPASS_DISABLE)
2333                 x86_amd_ssb_disable();
2334 }
2335
2336 bool itlb_multihit_kvm_mitigation;
2337 EXPORT_SYMBOL_GPL(itlb_multihit_kvm_mitigation);
2338
2339 #undef pr_fmt
2340 #define pr_fmt(fmt)     "L1TF: " fmt
2341
2342 /* Default mitigation for L1TF-affected CPUs */
2343 enum l1tf_mitigations l1tf_mitigation __ro_after_init = L1TF_MITIGATION_FLUSH;
2344 #if IS_ENABLED(CONFIG_KVM_INTEL)
2345 EXPORT_SYMBOL_GPL(l1tf_mitigation);
2346 #endif
2347 enum vmx_l1d_flush_state l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
2348 EXPORT_SYMBOL_GPL(l1tf_vmx_mitigation);
2349
2350 /*
2351  * These CPUs all support 44bits physical address space internally in the
2352  * cache but CPUID can report a smaller number of physical address bits.
2353  *
2354  * The L1TF mitigation uses the top most address bit for the inversion of
2355  * non present PTEs. When the installed memory reaches into the top most
2356  * address bit due to memory holes, which has been observed on machines
2357  * which report 36bits physical address bits and have 32G RAM installed,
2358  * then the mitigation range check in l1tf_select_mitigation() triggers.
2359  * This is a false positive because the mitigation is still possible due to
2360  * the fact that the cache uses 44bit internally. Use the cache bits
2361  * instead of the reported physical bits and adjust them on the affected
2362  * machines to 44bit if the reported bits are less than 44.
2363  */
2364 static void override_cache_bits(struct cpuinfo_x86 *c)
2365 {
2366         if (c->x86 != 6)
2367                 return;
2368
2369         switch (c->x86_model) {
2370         case INTEL_FAM6_NEHALEM:
2371         case INTEL_FAM6_WESTMERE:
2372         case INTEL_FAM6_SANDYBRIDGE:
2373         case INTEL_FAM6_IVYBRIDGE:
2374         case INTEL_FAM6_HASWELL:
2375         case INTEL_FAM6_HASWELL_L:
2376         case INTEL_FAM6_HASWELL_G:
2377         case INTEL_FAM6_BROADWELL:
2378         case INTEL_FAM6_BROADWELL_G:
2379         case INTEL_FAM6_SKYLAKE_L:
2380         case INTEL_FAM6_SKYLAKE:
2381         case INTEL_FAM6_KABYLAKE_L:
2382         case INTEL_FAM6_KABYLAKE:
2383                 if (c->x86_cache_bits < 44)
2384                         c->x86_cache_bits = 44;
2385                 break;
2386         }
2387 }
2388
2389 static void __init l1tf_select_mitigation(void)
2390 {
2391         u64 half_pa;
2392
2393         if (!boot_cpu_has_bug(X86_BUG_L1TF))
2394                 return;
2395
2396         if (cpu_mitigations_off())
2397                 l1tf_mitigation = L1TF_MITIGATION_OFF;
2398         else if (cpu_mitigations_auto_nosmt())
2399                 l1tf_mitigation = L1TF_MITIGATION_FLUSH_NOSMT;
2400
2401         override_cache_bits(&boot_cpu_data);
2402
2403         switch (l1tf_mitigation) {
2404         case L1TF_MITIGATION_OFF:
2405         case L1TF_MITIGATION_FLUSH_NOWARN:
2406         case L1TF_MITIGATION_FLUSH:
2407                 break;
2408         case L1TF_MITIGATION_FLUSH_NOSMT:
2409         case L1TF_MITIGATION_FULL:
2410                 cpu_smt_disable(false);
2411                 break;
2412         case L1TF_MITIGATION_FULL_FORCE:
2413                 cpu_smt_disable(true);
2414                 break;
2415         }
2416
2417 #if CONFIG_PGTABLE_LEVELS == 2
2418         pr_warn("Kernel not compiled for PAE. No mitigation for L1TF\n");
2419         return;
2420 #endif
2421
2422         half_pa = (u64)l1tf_pfn_limit() << PAGE_SHIFT;
2423         if (l1tf_mitigation != L1TF_MITIGATION_OFF &&
2424                         e820__mapped_any(half_pa, ULLONG_MAX - half_pa, E820_TYPE_RAM)) {
2425                 pr_warn("System has more than MAX_PA/2 memory. L1TF mitigation not effective.\n");
2426                 pr_info("You may make it effective by booting the kernel with mem=%llu parameter.\n",
2427                                 half_pa);
2428                 pr_info("However, doing so will make a part of your RAM unusable.\n");
2429                 pr_info("Reading https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html might help you decide.\n");
2430                 return;
2431         }
2432
2433         setup_force_cpu_cap(X86_FEATURE_L1TF_PTEINV);
2434 }
2435
2436 static int __init l1tf_cmdline(char *str)
2437 {
2438         if (!boot_cpu_has_bug(X86_BUG_L1TF))
2439                 return 0;
2440
2441         if (!str)
2442                 return -EINVAL;
2443
2444         if (!strcmp(str, "off"))
2445                 l1tf_mitigation = L1TF_MITIGATION_OFF;
2446         else if (!strcmp(str, "flush,nowarn"))
2447                 l1tf_mitigation = L1TF_MITIGATION_FLUSH_NOWARN;
2448         else if (!strcmp(str, "flush"))
2449                 l1tf_mitigation = L1TF_MITIGATION_FLUSH;
2450         else if (!strcmp(str, "flush,nosmt"))
2451                 l1tf_mitigation = L1TF_MITIGATION_FLUSH_NOSMT;
2452         else if (!strcmp(str, "full"))
2453                 l1tf_mitigation = L1TF_MITIGATION_FULL;
2454         else if (!strcmp(str, "full,force"))
2455                 l1tf_mitigation = L1TF_MITIGATION_FULL_FORCE;
2456
2457         return 0;
2458 }
2459 early_param("l1tf", l1tf_cmdline);
2460
2461 #undef pr_fmt
2462 #define pr_fmt(fmt)     "Speculative Return Stack Overflow: " fmt
2463
2464 enum srso_mitigation {
2465         SRSO_MITIGATION_NONE,
2466         SRSO_MITIGATION_MICROCODE,
2467         SRSO_MITIGATION_SAFE_RET,
2468         SRSO_MITIGATION_IBPB,
2469         SRSO_MITIGATION_IBPB_ON_VMEXIT,
2470 };
2471
2472 enum srso_mitigation_cmd {
2473         SRSO_CMD_OFF,
2474         SRSO_CMD_MICROCODE,
2475         SRSO_CMD_SAFE_RET,
2476         SRSO_CMD_IBPB,
2477         SRSO_CMD_IBPB_ON_VMEXIT,
2478 };
2479
2480 static const char * const srso_strings[] = {
2481         [SRSO_MITIGATION_NONE]           = "Vulnerable",
2482         [SRSO_MITIGATION_MICROCODE]      = "Mitigation: microcode",
2483         [SRSO_MITIGATION_SAFE_RET]       = "Mitigation: safe RET",
2484         [SRSO_MITIGATION_IBPB]           = "Mitigation: IBPB",
2485         [SRSO_MITIGATION_IBPB_ON_VMEXIT] = "Mitigation: IBPB on VMEXIT only"
2486 };
2487
2488 static enum srso_mitigation srso_mitigation __ro_after_init = SRSO_MITIGATION_NONE;
2489 static enum srso_mitigation_cmd srso_cmd __ro_after_init = SRSO_CMD_SAFE_RET;
2490
2491 static int __init srso_parse_cmdline(char *str)
2492 {
2493         if (!str)
2494                 return -EINVAL;
2495
2496         if (!strcmp(str, "off"))
2497                 srso_cmd = SRSO_CMD_OFF;
2498         else if (!strcmp(str, "microcode"))
2499                 srso_cmd = SRSO_CMD_MICROCODE;
2500         else if (!strcmp(str, "safe-ret"))
2501                 srso_cmd = SRSO_CMD_SAFE_RET;
2502         else if (!strcmp(str, "ibpb"))
2503                 srso_cmd = SRSO_CMD_IBPB;
2504         else if (!strcmp(str, "ibpb-vmexit"))
2505                 srso_cmd = SRSO_CMD_IBPB_ON_VMEXIT;
2506         else
2507                 pr_err("Ignoring unknown SRSO option (%s).", str);
2508
2509         return 0;
2510 }
2511 early_param("spec_rstack_overflow", srso_parse_cmdline);
2512
2513 #define SRSO_NOTICE "WARNING: See https://kernel.org/doc/html/latest/admin-guide/hw-vuln/srso.html for mitigation options."
2514
2515 static void __init srso_select_mitigation(void)
2516 {
2517         bool has_microcode;
2518
2519         if (!boot_cpu_has_bug(X86_BUG_SRSO) || cpu_mitigations_off())
2520                 goto pred_cmd;
2521
2522         /*
2523          * The first check is for the kernel running as a guest in order
2524          * for guests to verify whether IBPB is a viable mitigation.
2525          */
2526         has_microcode = boot_cpu_has(X86_FEATURE_IBPB_BRTYPE) || cpu_has_ibpb_brtype_microcode();
2527         if (!has_microcode) {
2528                 pr_warn("IBPB-extending microcode not applied!\n");
2529                 pr_warn(SRSO_NOTICE);
2530         } else {
2531                 /*
2532                  * Enable the synthetic (even if in a real CPUID leaf)
2533                  * flags for guests.
2534                  */
2535                 setup_force_cpu_cap(X86_FEATURE_IBPB_BRTYPE);
2536
2537                 /*
2538                  * Zen1/2 with SMT off aren't vulnerable after the right
2539                  * IBPB microcode has been applied.
2540                  */
2541                 if (boot_cpu_data.x86 < 0x19 && !cpu_smt_possible()) {
2542                         setup_force_cpu_cap(X86_FEATURE_SRSO_NO);
2543                         return;
2544                 }
2545         }
2546
2547         if (retbleed_mitigation == RETBLEED_MITIGATION_IBPB) {
2548                 if (has_microcode) {
2549                         pr_err("Retbleed IBPB mitigation enabled, using same for SRSO\n");
2550                         srso_mitigation = SRSO_MITIGATION_IBPB;
2551                         goto pred_cmd;
2552                 }
2553         }
2554
2555         switch (srso_cmd) {
2556         case SRSO_CMD_OFF:
2557                 goto pred_cmd;
2558
2559         case SRSO_CMD_MICROCODE:
2560                 if (has_microcode) {
2561                         srso_mitigation = SRSO_MITIGATION_MICROCODE;
2562                         pr_warn(SRSO_NOTICE);
2563                 }
2564                 break;
2565
2566         case SRSO_CMD_SAFE_RET:
2567                 if (IS_ENABLED(CONFIG_CPU_SRSO)) {
2568                         /*
2569                          * Enable the return thunk for generated code
2570                          * like ftrace, static_call, etc.
2571                          */
2572                         setup_force_cpu_cap(X86_FEATURE_RETHUNK);
2573                         setup_force_cpu_cap(X86_FEATURE_UNRET);
2574
2575                         if (boot_cpu_data.x86 == 0x19) {
2576                                 setup_force_cpu_cap(X86_FEATURE_SRSO_ALIAS);
2577                                 x86_return_thunk = srso_alias_return_thunk;
2578                         } else {
2579                                 setup_force_cpu_cap(X86_FEATURE_SRSO);
2580                                 x86_return_thunk = srso_return_thunk;
2581                         }
2582                         srso_mitigation = SRSO_MITIGATION_SAFE_RET;
2583                 } else {
2584                         pr_err("WARNING: kernel not compiled with CPU_SRSO.\n");
2585                         goto pred_cmd;
2586                 }
2587                 break;
2588
2589         case SRSO_CMD_IBPB:
2590                 if (IS_ENABLED(CONFIG_CPU_IBPB_ENTRY)) {
2591                         if (has_microcode) {
2592                                 setup_force_cpu_cap(X86_FEATURE_ENTRY_IBPB);
2593                                 srso_mitigation = SRSO_MITIGATION_IBPB;
2594                         }
2595                 } else {
2596                         pr_err("WARNING: kernel not compiled with CPU_IBPB_ENTRY.\n");
2597                         goto pred_cmd;
2598                 }
2599                 break;
2600
2601         case SRSO_CMD_IBPB_ON_VMEXIT:
2602                 if (IS_ENABLED(CONFIG_CPU_SRSO)) {
2603                         if (!boot_cpu_has(X86_FEATURE_ENTRY_IBPB) && has_microcode) {
2604                                 setup_force_cpu_cap(X86_FEATURE_IBPB_ON_VMEXIT);
2605                                 srso_mitigation = SRSO_MITIGATION_IBPB_ON_VMEXIT;
2606                         }
2607                 } else {
2608                         pr_err("WARNING: kernel not compiled with CPU_SRSO.\n");
2609                         goto pred_cmd;
2610                 }
2611                 break;
2612
2613         default:
2614                 break;
2615         }
2616
2617         pr_info("%s%s\n", srso_strings[srso_mitigation], (has_microcode ? "" : ", no microcode"));
2618
2619 pred_cmd:
2620         if ((!boot_cpu_has_bug(X86_BUG_SRSO) || srso_cmd == SRSO_CMD_OFF) &&
2621              boot_cpu_has(X86_FEATURE_SBPB))
2622                 x86_pred_cmd = PRED_CMD_SBPB;
2623 }
2624
2625 #undef pr_fmt
2626 #define pr_fmt(fmt) fmt
2627
2628 #ifdef CONFIG_SYSFS
2629
2630 #define L1TF_DEFAULT_MSG "Mitigation: PTE Inversion"
2631
2632 #if IS_ENABLED(CONFIG_KVM_INTEL)
2633 static const char * const l1tf_vmx_states[] = {
2634         [VMENTER_L1D_FLUSH_AUTO]                = "auto",
2635         [VMENTER_L1D_FLUSH_NEVER]               = "vulnerable",
2636         [VMENTER_L1D_FLUSH_COND]                = "conditional cache flushes",
2637         [VMENTER_L1D_FLUSH_ALWAYS]              = "cache flushes",
2638         [VMENTER_L1D_FLUSH_EPT_DISABLED]        = "EPT disabled",
2639         [VMENTER_L1D_FLUSH_NOT_REQUIRED]        = "flush not necessary"
2640 };
2641
2642 static ssize_t l1tf_show_state(char *buf)
2643 {
2644         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO)
2645                 return sysfs_emit(buf, "%s\n", L1TF_DEFAULT_MSG);
2646
2647         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_EPT_DISABLED ||
2648             (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER &&
2649              sched_smt_active())) {
2650                 return sysfs_emit(buf, "%s; VMX: %s\n", L1TF_DEFAULT_MSG,
2651                                   l1tf_vmx_states[l1tf_vmx_mitigation]);
2652         }
2653
2654         return sysfs_emit(buf, "%s; VMX: %s, SMT %s\n", L1TF_DEFAULT_MSG,
2655                           l1tf_vmx_states[l1tf_vmx_mitigation],
2656                           sched_smt_active() ? "vulnerable" : "disabled");
2657 }
2658
2659 static ssize_t itlb_multihit_show_state(char *buf)
2660 {
2661         if (!boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2662             !boot_cpu_has(X86_FEATURE_VMX))
2663                 return sysfs_emit(buf, "KVM: Mitigation: VMX unsupported\n");
2664         else if (!(cr4_read_shadow() & X86_CR4_VMXE))
2665                 return sysfs_emit(buf, "KVM: Mitigation: VMX disabled\n");
2666         else if (itlb_multihit_kvm_mitigation)
2667                 return sysfs_emit(buf, "KVM: Mitigation: Split huge pages\n");
2668         else
2669                 return sysfs_emit(buf, "KVM: Vulnerable\n");
2670 }
2671 #else
2672 static ssize_t l1tf_show_state(char *buf)
2673 {
2674         return sysfs_emit(buf, "%s\n", L1TF_DEFAULT_MSG);
2675 }
2676
2677 static ssize_t itlb_multihit_show_state(char *buf)
2678 {
2679         return sysfs_emit(buf, "Processor vulnerable\n");
2680 }
2681 #endif
2682
2683 static ssize_t mds_show_state(char *buf)
2684 {
2685         if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) {
2686                 return sysfs_emit(buf, "%s; SMT Host state unknown\n",
2687                                   mds_strings[mds_mitigation]);
2688         }
2689
2690         if (boot_cpu_has(X86_BUG_MSBDS_ONLY)) {
2691                 return sysfs_emit(buf, "%s; SMT %s\n", mds_strings[mds_mitigation],
2692                                   (mds_mitigation == MDS_MITIGATION_OFF ? "vulnerable" :
2693                                    sched_smt_active() ? "mitigated" : "disabled"));
2694         }
2695
2696         return sysfs_emit(buf, "%s; SMT %s\n", mds_strings[mds_mitigation],
2697                           sched_smt_active() ? "vulnerable" : "disabled");
2698 }
2699
2700 static ssize_t tsx_async_abort_show_state(char *buf)
2701 {
2702         if ((taa_mitigation == TAA_MITIGATION_TSX_DISABLED) ||
2703             (taa_mitigation == TAA_MITIGATION_OFF))
2704                 return sysfs_emit(buf, "%s\n", taa_strings[taa_mitigation]);
2705
2706         if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) {
2707                 return sysfs_emit(buf, "%s; SMT Host state unknown\n",
2708                                   taa_strings[taa_mitigation]);
2709         }
2710
2711         return sysfs_emit(buf, "%s; SMT %s\n", taa_strings[taa_mitigation],
2712                           sched_smt_active() ? "vulnerable" : "disabled");
2713 }
2714
2715 static ssize_t mmio_stale_data_show_state(char *buf)
2716 {
2717         if (boot_cpu_has_bug(X86_BUG_MMIO_UNKNOWN))
2718                 return sysfs_emit(buf, "Unknown: No mitigations\n");
2719
2720         if (mmio_mitigation == MMIO_MITIGATION_OFF)
2721                 return sysfs_emit(buf, "%s\n", mmio_strings[mmio_mitigation]);
2722
2723         if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) {
2724                 return sysfs_emit(buf, "%s; SMT Host state unknown\n",
2725                                   mmio_strings[mmio_mitigation]);
2726         }
2727
2728         return sysfs_emit(buf, "%s; SMT %s\n", mmio_strings[mmio_mitigation],
2729                           sched_smt_active() ? "vulnerable" : "disabled");
2730 }
2731
2732 static ssize_t rfds_show_state(char *buf)
2733 {
2734         return sysfs_emit(buf, "%s\n", rfds_strings[rfds_mitigation]);
2735 }
2736
2737 static char *stibp_state(void)
2738 {
2739         if (spectre_v2_in_eibrs_mode(spectre_v2_enabled) &&
2740             !boot_cpu_has(X86_FEATURE_AUTOIBRS))
2741                 return "";
2742
2743         switch (spectre_v2_user_stibp) {
2744         case SPECTRE_V2_USER_NONE:
2745                 return "; STIBP: disabled";
2746         case SPECTRE_V2_USER_STRICT:
2747                 return "; STIBP: forced";
2748         case SPECTRE_V2_USER_STRICT_PREFERRED:
2749                 return "; STIBP: always-on";
2750         case SPECTRE_V2_USER_PRCTL:
2751         case SPECTRE_V2_USER_SECCOMP:
2752                 if (static_key_enabled(&switch_to_cond_stibp))
2753                         return "; STIBP: conditional";
2754         }
2755         return "";
2756 }
2757
2758 static char *ibpb_state(void)
2759 {
2760         if (boot_cpu_has(X86_FEATURE_IBPB)) {
2761                 if (static_key_enabled(&switch_mm_always_ibpb))
2762                         return "; IBPB: always-on";
2763                 if (static_key_enabled(&switch_mm_cond_ibpb))
2764                         return "; IBPB: conditional";
2765                 return "; IBPB: disabled";
2766         }
2767         return "";
2768 }
2769
2770 static char *pbrsb_eibrs_state(void)
2771 {
2772         if (boot_cpu_has_bug(X86_BUG_EIBRS_PBRSB)) {
2773                 if (boot_cpu_has(X86_FEATURE_RSB_VMEXIT_LITE) ||
2774                     boot_cpu_has(X86_FEATURE_RSB_VMEXIT))
2775                         return "; PBRSB-eIBRS: SW sequence";
2776                 else
2777                         return "; PBRSB-eIBRS: Vulnerable";
2778         } else {
2779                 return "; PBRSB-eIBRS: Not affected";
2780         }
2781 }
2782
2783 static const char *spectre_bhi_state(void)
2784 {
2785         if (!boot_cpu_has_bug(X86_BUG_BHI))
2786                 return "; BHI: Not affected";
2787         else if (boot_cpu_has(X86_FEATURE_CLEAR_BHB_HW))
2788                 return "; BHI: BHI_DIS_S";
2789         else if (boot_cpu_has(X86_FEATURE_CLEAR_BHB_LOOP))
2790                 return "; BHI: SW loop, KVM: SW loop";
2791         else if (boot_cpu_has(X86_FEATURE_RETPOLINE) &&
2792                  !boot_cpu_has(X86_FEATURE_RETPOLINE_LFENCE) &&
2793                  rrsba_disabled)
2794                 return "; BHI: Retpoline";
2795         else if (boot_cpu_has(X86_FEATURE_CLEAR_BHB_LOOP_ON_VMEXIT))
2796                 return "; BHI: Vulnerable, KVM: SW loop";
2797
2798         return "; BHI: Vulnerable";
2799 }
2800
2801 static ssize_t spectre_v2_show_state(char *buf)
2802 {
2803         if (spectre_v2_enabled == SPECTRE_V2_LFENCE)
2804                 return sysfs_emit(buf, "Vulnerable: LFENCE\n");
2805
2806         if (spectre_v2_enabled == SPECTRE_V2_EIBRS && unprivileged_ebpf_enabled())
2807                 return sysfs_emit(buf, "Vulnerable: eIBRS with unprivileged eBPF\n");
2808
2809         if (sched_smt_active() && unprivileged_ebpf_enabled() &&
2810             spectre_v2_enabled == SPECTRE_V2_EIBRS_LFENCE)
2811                 return sysfs_emit(buf, "Vulnerable: eIBRS+LFENCE with unprivileged eBPF and SMT\n");
2812
2813         return sysfs_emit(buf, "%s%s%s%s%s%s%s%s\n",
2814                           spectre_v2_strings[spectre_v2_enabled],
2815                           ibpb_state(),
2816                           boot_cpu_has(X86_FEATURE_USE_IBRS_FW) ? "; IBRS_FW" : "",
2817                           stibp_state(),
2818                           boot_cpu_has(X86_FEATURE_RSB_CTXSW) ? "; RSB filling" : "",
2819                           pbrsb_eibrs_state(),
2820                           spectre_bhi_state(),
2821                           /* this should always be at the end */
2822                           spectre_v2_module_string());
2823 }
2824
2825 static ssize_t srbds_show_state(char *buf)
2826 {
2827         return sysfs_emit(buf, "%s\n", srbds_strings[srbds_mitigation]);
2828 }
2829
2830 static ssize_t retbleed_show_state(char *buf)
2831 {
2832         if (retbleed_mitigation == RETBLEED_MITIGATION_UNRET ||
2833             retbleed_mitigation == RETBLEED_MITIGATION_IBPB) {
2834                 if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD &&
2835                     boot_cpu_data.x86_vendor != X86_VENDOR_HYGON)
2836                         return sysfs_emit(buf, "Vulnerable: untrained return thunk / IBPB on non-AMD based uarch\n");
2837
2838                 return sysfs_emit(buf, "%s; SMT %s\n", retbleed_strings[retbleed_mitigation],
2839                                   !sched_smt_active() ? "disabled" :
2840                                   spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT ||
2841                                   spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED ?
2842                                   "enabled with STIBP protection" : "vulnerable");
2843         }
2844
2845         return sysfs_emit(buf, "%s\n", retbleed_strings[retbleed_mitigation]);
2846 }
2847
2848 static ssize_t gds_show_state(char *buf)
2849 {
2850         return sysfs_emit(buf, "%s\n", gds_strings[gds_mitigation]);
2851 }
2852
2853 static ssize_t srso_show_state(char *buf)
2854 {
2855         if (boot_cpu_has(X86_FEATURE_SRSO_NO))
2856                 return sysfs_emit(buf, "Mitigation: SMT disabled\n");
2857
2858         return sysfs_emit(buf, "%s%s\n",
2859                           srso_strings[srso_mitigation],
2860                           boot_cpu_has(X86_FEATURE_IBPB_BRTYPE) ? "" : ", no microcode");
2861 }
2862
2863 static ssize_t cpu_show_common(struct device *dev, struct device_attribute *attr,
2864                                char *buf, unsigned int bug)
2865 {
2866         if (!boot_cpu_has_bug(bug))
2867                 return sysfs_emit(buf, "Not affected\n");
2868
2869         switch (bug) {
2870         case X86_BUG_CPU_MELTDOWN:
2871                 if (boot_cpu_has(X86_FEATURE_PTI))
2872                         return sysfs_emit(buf, "Mitigation: PTI\n");
2873
2874                 if (hypervisor_is_type(X86_HYPER_XEN_PV))
2875                         return sysfs_emit(buf, "Unknown (XEN PV detected, hypervisor mitigation required)\n");
2876
2877                 break;
2878
2879         case X86_BUG_SPECTRE_V1:
2880                 return sysfs_emit(buf, "%s\n", spectre_v1_strings[spectre_v1_mitigation]);
2881
2882         case X86_BUG_SPECTRE_V2:
2883                 return spectre_v2_show_state(buf);
2884
2885         case X86_BUG_SPEC_STORE_BYPASS:
2886                 return sysfs_emit(buf, "%s\n", ssb_strings[ssb_mode]);
2887
2888         case X86_BUG_L1TF:
2889                 if (boot_cpu_has(X86_FEATURE_L1TF_PTEINV))
2890                         return l1tf_show_state(buf);
2891                 break;
2892
2893         case X86_BUG_MDS:
2894                 return mds_show_state(buf);
2895
2896         case X86_BUG_TAA:
2897                 return tsx_async_abort_show_state(buf);
2898
2899         case X86_BUG_ITLB_MULTIHIT:
2900                 return itlb_multihit_show_state(buf);
2901
2902         case X86_BUG_SRBDS:
2903                 return srbds_show_state(buf);
2904
2905         case X86_BUG_MMIO_STALE_DATA:
2906         case X86_BUG_MMIO_UNKNOWN:
2907                 return mmio_stale_data_show_state(buf);
2908
2909         case X86_BUG_RETBLEED:
2910                 return retbleed_show_state(buf);
2911
2912         case X86_BUG_GDS:
2913                 return gds_show_state(buf);
2914
2915         case X86_BUG_SRSO:
2916                 return srso_show_state(buf);
2917
2918         case X86_BUG_RFDS:
2919                 return rfds_show_state(buf);
2920
2921         default:
2922                 break;
2923         }
2924
2925         return sysfs_emit(buf, "Vulnerable\n");
2926 }
2927
2928 ssize_t cpu_show_meltdown(struct device *dev, struct device_attribute *attr, char *buf)
2929 {
2930         return cpu_show_common(dev, attr, buf, X86_BUG_CPU_MELTDOWN);
2931 }
2932
2933 ssize_t cpu_show_spectre_v1(struct device *dev, struct device_attribute *attr, char *buf)
2934 {
2935         return cpu_show_common(dev, attr, buf, X86_BUG_SPECTRE_V1);
2936 }
2937
2938 ssize_t cpu_show_spectre_v2(struct device *dev, struct device_attribute *attr, char *buf)
2939 {
2940         return cpu_show_common(dev, attr, buf, X86_BUG_SPECTRE_V2);
2941 }
2942
2943 ssize_t cpu_show_spec_store_bypass(struct device *dev, struct device_attribute *attr, char *buf)
2944 {
2945         return cpu_show_common(dev, attr, buf, X86_BUG_SPEC_STORE_BYPASS);
2946 }
2947
2948 ssize_t cpu_show_l1tf(struct device *dev, struct device_attribute *attr, char *buf)
2949 {
2950         return cpu_show_common(dev, attr, buf, X86_BUG_L1TF);
2951 }
2952
2953 ssize_t cpu_show_mds(struct device *dev, struct device_attribute *attr, char *buf)
2954 {
2955         return cpu_show_common(dev, attr, buf, X86_BUG_MDS);
2956 }
2957
2958 ssize_t cpu_show_tsx_async_abort(struct device *dev, struct device_attribute *attr, char *buf)
2959 {
2960         return cpu_show_common(dev, attr, buf, X86_BUG_TAA);
2961 }
2962
2963 ssize_t cpu_show_itlb_multihit(struct device *dev, struct device_attribute *attr, char *buf)
2964 {
2965         return cpu_show_common(dev, attr, buf, X86_BUG_ITLB_MULTIHIT);
2966 }
2967
2968 ssize_t cpu_show_srbds(struct device *dev, struct device_attribute *attr, char *buf)
2969 {
2970         return cpu_show_common(dev, attr, buf, X86_BUG_SRBDS);
2971 }
2972
2973 ssize_t cpu_show_mmio_stale_data(struct device *dev, struct device_attribute *attr, char *buf)
2974 {
2975         if (boot_cpu_has_bug(X86_BUG_MMIO_UNKNOWN))
2976                 return cpu_show_common(dev, attr, buf, X86_BUG_MMIO_UNKNOWN);
2977         else
2978                 return cpu_show_common(dev, attr, buf, X86_BUG_MMIO_STALE_DATA);
2979 }
2980
2981 ssize_t cpu_show_retbleed(struct device *dev, struct device_attribute *attr, char *buf)
2982 {
2983         return cpu_show_common(dev, attr, buf, X86_BUG_RETBLEED);
2984 }
2985
2986 ssize_t cpu_show_gds(struct device *dev, struct device_attribute *attr, char *buf)
2987 {
2988         return cpu_show_common(dev, attr, buf, X86_BUG_GDS);
2989 }
2990
2991 ssize_t cpu_show_spec_rstack_overflow(struct device *dev, struct device_attribute *attr, char *buf)
2992 {
2993         return cpu_show_common(dev, attr, buf, X86_BUG_SRSO);
2994 }
2995
2996 ssize_t cpu_show_reg_file_data_sampling(struct device *dev, struct device_attribute *attr, char *buf)
2997 {
2998         return cpu_show_common(dev, attr, buf, X86_BUG_RFDS);
2999 }
3000 #endif