xref: /linux/arch/x86/kernel/cpu/common.c (revision 86e6b1547b3d013bc392adf775b89318441403c2)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* cpu_feature_enabled() cannot be used this early */
3 #define USE_EARLY_PGTABLE_L5
4 
5 #include <linux/memblock.h>
6 #include <linux/linkage.h>
7 #include <linux/bitops.h>
8 #include <linux/kernel.h>
9 #include <linux/export.h>
10 #include <linux/percpu.h>
11 #include <linux/string.h>
12 #include <linux/ctype.h>
13 #include <linux/delay.h>
14 #include <linux/sched/mm.h>
15 #include <linux/sched/clock.h>
16 #include <linux/sched/task.h>
17 #include <linux/sched/smt.h>
18 #include <linux/init.h>
19 #include <linux/kprobes.h>
20 #include <linux/kgdb.h>
21 #include <linux/mem_encrypt.h>
22 #include <linux/smp.h>
23 #include <linux/cpu.h>
24 #include <linux/io.h>
25 #include <linux/syscore_ops.h>
26 #include <linux/pgtable.h>
27 #include <linux/stackprotector.h>
28 #include <linux/utsname.h>
29 
30 #include <asm/alternative.h>
31 #include <asm/cmdline.h>
32 #include <asm/perf_event.h>
33 #include <asm/mmu_context.h>
34 #include <asm/doublefault.h>
35 #include <asm/archrandom.h>
36 #include <asm/hypervisor.h>
37 #include <asm/processor.h>
38 #include <asm/tlbflush.h>
39 #include <asm/debugreg.h>
40 #include <asm/sections.h>
41 #include <asm/vsyscall.h>
42 #include <linux/topology.h>
43 #include <linux/cpumask.h>
44 #include <linux/atomic.h>
45 #include <asm/proto.h>
46 #include <asm/setup.h>
47 #include <asm/apic.h>
48 #include <asm/desc.h>
49 #include <asm/fpu/api.h>
50 #include <asm/mtrr.h>
51 #include <asm/hwcap2.h>
52 #include <linux/numa.h>
53 #include <asm/numa.h>
54 #include <asm/asm.h>
55 #include <asm/bugs.h>
56 #include <asm/cpu.h>
57 #include <asm/mce.h>
58 #include <asm/msr.h>
59 #include <asm/cacheinfo.h>
60 #include <asm/memtype.h>
61 #include <asm/microcode.h>
62 #include <asm/intel-family.h>
63 #include <asm/cpu_device_id.h>
64 #include <asm/fred.h>
65 #include <asm/uv/uv.h>
66 #include <asm/ia32.h>
67 #include <asm/set_memory.h>
68 #include <asm/traps.h>
69 #include <asm/sev.h>
70 #include <asm/tdx.h>
71 #include <asm/posted_intr.h>
72 #include <asm/runtime-const.h>
73 
74 #include "cpu.h"
75 
76 DEFINE_PER_CPU_READ_MOSTLY(struct cpuinfo_x86, cpu_info);
77 EXPORT_PER_CPU_SYMBOL(cpu_info);
78 
79 u32 elf_hwcap2 __read_mostly;
80 
81 /* Number of siblings per CPU package */
82 unsigned int __max_threads_per_core __ro_after_init = 1;
83 EXPORT_SYMBOL(__max_threads_per_core);
84 
85 unsigned int __max_dies_per_package __ro_after_init = 1;
86 EXPORT_SYMBOL(__max_dies_per_package);
87 
88 unsigned int __max_logical_packages __ro_after_init = 1;
89 EXPORT_SYMBOL(__max_logical_packages);
90 
91 unsigned int __num_cores_per_package __ro_after_init = 1;
92 EXPORT_SYMBOL(__num_cores_per_package);
93 
94 unsigned int __num_threads_per_package __ro_after_init = 1;
95 EXPORT_SYMBOL(__num_threads_per_package);
96 
97 static struct ppin_info {
98 	int	feature;
99 	int	msr_ppin_ctl;
100 	int	msr_ppin;
101 } ppin_info[] = {
102 	[X86_VENDOR_INTEL] = {
103 		.feature = X86_FEATURE_INTEL_PPIN,
104 		.msr_ppin_ctl = MSR_PPIN_CTL,
105 		.msr_ppin = MSR_PPIN
106 	},
107 	[X86_VENDOR_AMD] = {
108 		.feature = X86_FEATURE_AMD_PPIN,
109 		.msr_ppin_ctl = MSR_AMD_PPIN_CTL,
110 		.msr_ppin = MSR_AMD_PPIN
111 	},
112 };
113 
114 static const struct x86_cpu_id ppin_cpuids[] = {
115 	X86_MATCH_FEATURE(X86_FEATURE_AMD_PPIN, &ppin_info[X86_VENDOR_AMD]),
116 	X86_MATCH_FEATURE(X86_FEATURE_INTEL_PPIN, &ppin_info[X86_VENDOR_INTEL]),
117 
118 	/* Legacy models without CPUID enumeration */
119 	X86_MATCH_VFM(INTEL_IVYBRIDGE_X, &ppin_info[X86_VENDOR_INTEL]),
120 	X86_MATCH_VFM(INTEL_HASWELL_X, &ppin_info[X86_VENDOR_INTEL]),
121 	X86_MATCH_VFM(INTEL_BROADWELL_D, &ppin_info[X86_VENDOR_INTEL]),
122 	X86_MATCH_VFM(INTEL_BROADWELL_X, &ppin_info[X86_VENDOR_INTEL]),
123 	X86_MATCH_VFM(INTEL_SKYLAKE_X, &ppin_info[X86_VENDOR_INTEL]),
124 	X86_MATCH_VFM(INTEL_ICELAKE_X, &ppin_info[X86_VENDOR_INTEL]),
125 	X86_MATCH_VFM(INTEL_ICELAKE_D, &ppin_info[X86_VENDOR_INTEL]),
126 	X86_MATCH_VFM(INTEL_SAPPHIRERAPIDS_X, &ppin_info[X86_VENDOR_INTEL]),
127 	X86_MATCH_VFM(INTEL_EMERALDRAPIDS_X, &ppin_info[X86_VENDOR_INTEL]),
128 	X86_MATCH_VFM(INTEL_XEON_PHI_KNL, &ppin_info[X86_VENDOR_INTEL]),
129 	X86_MATCH_VFM(INTEL_XEON_PHI_KNM, &ppin_info[X86_VENDOR_INTEL]),
130 
131 	{}
132 };
133 
ppin_init(struct cpuinfo_x86 * c)134 static void ppin_init(struct cpuinfo_x86 *c)
135 {
136 	const struct x86_cpu_id *id;
137 	unsigned long long val;
138 	struct ppin_info *info;
139 
140 	id = x86_match_cpu(ppin_cpuids);
141 	if (!id)
142 		return;
143 
144 	/*
145 	 * Testing the presence of the MSR is not enough. Need to check
146 	 * that the PPIN_CTL allows reading of the PPIN.
147 	 */
148 	info = (struct ppin_info *)id->driver_data;
149 
150 	if (rdmsrl_safe(info->msr_ppin_ctl, &val))
151 		goto clear_ppin;
152 
153 	if ((val & 3UL) == 1UL) {
154 		/* PPIN locked in disabled mode */
155 		goto clear_ppin;
156 	}
157 
158 	/* If PPIN is disabled, try to enable */
159 	if (!(val & 2UL)) {
160 		wrmsrl_safe(info->msr_ppin_ctl,  val | 2UL);
161 		rdmsrl_safe(info->msr_ppin_ctl, &val);
162 	}
163 
164 	/* Is the enable bit set? */
165 	if (val & 2UL) {
166 		c->ppin = __rdmsr(info->msr_ppin);
167 		set_cpu_cap(c, info->feature);
168 		return;
169 	}
170 
171 clear_ppin:
172 	clear_cpu_cap(c, info->feature);
173 }
174 
default_init(struct cpuinfo_x86 * c)175 static void default_init(struct cpuinfo_x86 *c)
176 {
177 #ifdef CONFIG_X86_64
178 	cpu_detect_cache_sizes(c);
179 #else
180 	/* Not much we can do here... */
181 	/* Check if at least it has cpuid */
182 	if (c->cpuid_level == -1) {
183 		/* No cpuid. It must be an ancient CPU */
184 		if (c->x86 == 4)
185 			strcpy(c->x86_model_id, "486");
186 		else if (c->x86 == 3)
187 			strcpy(c->x86_model_id, "386");
188 	}
189 #endif
190 }
191 
192 static const struct cpu_dev default_cpu = {
193 	.c_init		= default_init,
194 	.c_vendor	= "Unknown",
195 	.c_x86_vendor	= X86_VENDOR_UNKNOWN,
196 };
197 
198 static const struct cpu_dev *this_cpu = &default_cpu;
199 
200 DEFINE_PER_CPU_PAGE_ALIGNED(struct gdt_page, gdt_page) = { .gdt = {
201 #ifdef CONFIG_X86_64
202 	/*
203 	 * We need valid kernel segments for data and code in long mode too
204 	 * IRET will check the segment types  kkeil 2000/10/28
205 	 * Also sysret mandates a special GDT layout
206 	 *
207 	 * TLS descriptors are currently at a different place compared to i386.
208 	 * Hopefully nobody expects them at a fixed place (Wine?)
209 	 */
210 	[GDT_ENTRY_KERNEL32_CS]		= GDT_ENTRY_INIT(DESC_CODE32, 0, 0xfffff),
211 	[GDT_ENTRY_KERNEL_CS]		= GDT_ENTRY_INIT(DESC_CODE64, 0, 0xfffff),
212 	[GDT_ENTRY_KERNEL_DS]		= GDT_ENTRY_INIT(DESC_DATA64, 0, 0xfffff),
213 	[GDT_ENTRY_DEFAULT_USER32_CS]	= GDT_ENTRY_INIT(DESC_CODE32 | DESC_USER, 0, 0xfffff),
214 	[GDT_ENTRY_DEFAULT_USER_DS]	= GDT_ENTRY_INIT(DESC_DATA64 | DESC_USER, 0, 0xfffff),
215 	[GDT_ENTRY_DEFAULT_USER_CS]	= GDT_ENTRY_INIT(DESC_CODE64 | DESC_USER, 0, 0xfffff),
216 #else
217 	[GDT_ENTRY_KERNEL_CS]		= GDT_ENTRY_INIT(DESC_CODE32, 0, 0xfffff),
218 	[GDT_ENTRY_KERNEL_DS]		= GDT_ENTRY_INIT(DESC_DATA32, 0, 0xfffff),
219 	[GDT_ENTRY_DEFAULT_USER_CS]	= GDT_ENTRY_INIT(DESC_CODE32 | DESC_USER, 0, 0xfffff),
220 	[GDT_ENTRY_DEFAULT_USER_DS]	= GDT_ENTRY_INIT(DESC_DATA32 | DESC_USER, 0, 0xfffff),
221 	/*
222 	 * Segments used for calling PnP BIOS have byte granularity.
223 	 * They code segments and data segments have fixed 64k limits,
224 	 * the transfer segment sizes are set at run time.
225 	 */
226 	[GDT_ENTRY_PNPBIOS_CS32]	= GDT_ENTRY_INIT(DESC_CODE32_BIOS, 0, 0xffff),
227 	[GDT_ENTRY_PNPBIOS_CS16]	= GDT_ENTRY_INIT(DESC_CODE16, 0, 0xffff),
228 	[GDT_ENTRY_PNPBIOS_DS]		= GDT_ENTRY_INIT(DESC_DATA16, 0, 0xffff),
229 	[GDT_ENTRY_PNPBIOS_TS1]		= GDT_ENTRY_INIT(DESC_DATA16, 0, 0),
230 	[GDT_ENTRY_PNPBIOS_TS2]		= GDT_ENTRY_INIT(DESC_DATA16, 0, 0),
231 	/*
232 	 * The APM segments have byte granularity and their bases
233 	 * are set at run time.  All have 64k limits.
234 	 */
235 	[GDT_ENTRY_APMBIOS_BASE]	= GDT_ENTRY_INIT(DESC_CODE32_BIOS, 0, 0xffff),
236 	[GDT_ENTRY_APMBIOS_BASE+1]	= GDT_ENTRY_INIT(DESC_CODE16, 0, 0xffff),
237 	[GDT_ENTRY_APMBIOS_BASE+2]	= GDT_ENTRY_INIT(DESC_DATA32_BIOS, 0, 0xffff),
238 
239 	[GDT_ENTRY_ESPFIX_SS]		= GDT_ENTRY_INIT(DESC_DATA32, 0, 0xfffff),
240 	[GDT_ENTRY_PERCPU]		= GDT_ENTRY_INIT(DESC_DATA32, 0, 0xfffff),
241 #endif
242 } };
243 EXPORT_PER_CPU_SYMBOL_GPL(gdt_page);
244 
245 #ifdef CONFIG_X86_64
x86_nopcid_setup(char * s)246 static int __init x86_nopcid_setup(char *s)
247 {
248 	/* nopcid doesn't accept parameters */
249 	if (s)
250 		return -EINVAL;
251 
252 	/* do not emit a message if the feature is not present */
253 	if (!boot_cpu_has(X86_FEATURE_PCID))
254 		return 0;
255 
256 	setup_clear_cpu_cap(X86_FEATURE_PCID);
257 	pr_info("nopcid: PCID feature disabled\n");
258 	return 0;
259 }
260 early_param("nopcid", x86_nopcid_setup);
261 #endif
262 
x86_noinvpcid_setup(char * s)263 static int __init x86_noinvpcid_setup(char *s)
264 {
265 	/* noinvpcid doesn't accept parameters */
266 	if (s)
267 		return -EINVAL;
268 
269 	/* do not emit a message if the feature is not present */
270 	if (!boot_cpu_has(X86_FEATURE_INVPCID))
271 		return 0;
272 
273 	setup_clear_cpu_cap(X86_FEATURE_INVPCID);
274 	pr_info("noinvpcid: INVPCID feature disabled\n");
275 	return 0;
276 }
277 early_param("noinvpcid", x86_noinvpcid_setup);
278 
279 #ifdef CONFIG_X86_32
280 static int cachesize_override = -1;
281 static int disable_x86_serial_nr = 1;
282 
cachesize_setup(char * str)283 static int __init cachesize_setup(char *str)
284 {
285 	get_option(&str, &cachesize_override);
286 	return 1;
287 }
288 __setup("cachesize=", cachesize_setup);
289 
290 /* Standard macro to see if a specific flag is changeable */
flag_is_changeable_p(u32 flag)291 static inline int flag_is_changeable_p(u32 flag)
292 {
293 	u32 f1, f2;
294 
295 	/*
296 	 * Cyrix and IDT cpus allow disabling of CPUID
297 	 * so the code below may return different results
298 	 * when it is executed before and after enabling
299 	 * the CPUID. Add "volatile" to not allow gcc to
300 	 * optimize the subsequent calls to this function.
301 	 */
302 	asm volatile ("pushfl		\n\t"
303 		      "pushfl		\n\t"
304 		      "popl %0		\n\t"
305 		      "movl %0, %1	\n\t"
306 		      "xorl %2, %0	\n\t"
307 		      "pushl %0		\n\t"
308 		      "popfl		\n\t"
309 		      "pushfl		\n\t"
310 		      "popl %0		\n\t"
311 		      "popfl		\n\t"
312 
313 		      : "=&r" (f1), "=&r" (f2)
314 		      : "ir" (flag));
315 
316 	return ((f1^f2) & flag) != 0;
317 }
318 
319 /* Probe for the CPUID instruction */
have_cpuid_p(void)320 int have_cpuid_p(void)
321 {
322 	return flag_is_changeable_p(X86_EFLAGS_ID);
323 }
324 
squash_the_stupid_serial_number(struct cpuinfo_x86 * c)325 static void squash_the_stupid_serial_number(struct cpuinfo_x86 *c)
326 {
327 	unsigned long lo, hi;
328 
329 	if (!cpu_has(c, X86_FEATURE_PN) || !disable_x86_serial_nr)
330 		return;
331 
332 	/* Disable processor serial number: */
333 
334 	rdmsr(MSR_IA32_BBL_CR_CTL, lo, hi);
335 	lo |= 0x200000;
336 	wrmsr(MSR_IA32_BBL_CR_CTL, lo, hi);
337 
338 	pr_notice("CPU serial number disabled.\n");
339 	clear_cpu_cap(c, X86_FEATURE_PN);
340 
341 	/* Disabling the serial number may affect the cpuid level */
342 	c->cpuid_level = cpuid_eax(0);
343 }
344 
x86_serial_nr_setup(char * s)345 static int __init x86_serial_nr_setup(char *s)
346 {
347 	disable_x86_serial_nr = 0;
348 	return 1;
349 }
350 __setup("serialnumber", x86_serial_nr_setup);
351 #else
flag_is_changeable_p(u32 flag)352 static inline int flag_is_changeable_p(u32 flag)
353 {
354 	return 1;
355 }
squash_the_stupid_serial_number(struct cpuinfo_x86 * c)356 static inline void squash_the_stupid_serial_number(struct cpuinfo_x86 *c)
357 {
358 }
359 #endif
360 
setup_smep(struct cpuinfo_x86 * c)361 static __always_inline void setup_smep(struct cpuinfo_x86 *c)
362 {
363 	if (cpu_has(c, X86_FEATURE_SMEP))
364 		cr4_set_bits(X86_CR4_SMEP);
365 }
366 
setup_smap(struct cpuinfo_x86 * c)367 static __always_inline void setup_smap(struct cpuinfo_x86 *c)
368 {
369 	unsigned long eflags = native_save_fl();
370 
371 	/* This should have been cleared long ago */
372 	BUG_ON(eflags & X86_EFLAGS_AC);
373 
374 	if (cpu_has(c, X86_FEATURE_SMAP))
375 		cr4_set_bits(X86_CR4_SMAP);
376 }
377 
setup_umip(struct cpuinfo_x86 * c)378 static __always_inline void setup_umip(struct cpuinfo_x86 *c)
379 {
380 	/* Check the boot processor, plus build option for UMIP. */
381 	if (!cpu_feature_enabled(X86_FEATURE_UMIP))
382 		goto out;
383 
384 	/* Check the current processor's cpuid bits. */
385 	if (!cpu_has(c, X86_FEATURE_UMIP))
386 		goto out;
387 
388 	cr4_set_bits(X86_CR4_UMIP);
389 
390 	pr_info_once("x86/cpu: User Mode Instruction Prevention (UMIP) activated\n");
391 
392 	return;
393 
394 out:
395 	/*
396 	 * Make sure UMIP is disabled in case it was enabled in a
397 	 * previous boot (e.g., via kexec).
398 	 */
399 	cr4_clear_bits(X86_CR4_UMIP);
400 }
401 
402 /* These bits should not change their value after CPU init is finished. */
403 static const unsigned long cr4_pinned_mask = X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_UMIP |
404 					     X86_CR4_FSGSBASE | X86_CR4_CET | X86_CR4_FRED;
405 static DEFINE_STATIC_KEY_FALSE_RO(cr_pinning);
406 static unsigned long cr4_pinned_bits __ro_after_init;
407 
native_write_cr0(unsigned long val)408 void native_write_cr0(unsigned long val)
409 {
410 	unsigned long bits_missing = 0;
411 
412 set_register:
413 	asm volatile("mov %0,%%cr0": "+r" (val) : : "memory");
414 
415 	if (static_branch_likely(&cr_pinning)) {
416 		if (unlikely((val & X86_CR0_WP) != X86_CR0_WP)) {
417 			bits_missing = X86_CR0_WP;
418 			val |= bits_missing;
419 			goto set_register;
420 		}
421 		/* Warn after we've set the missing bits. */
422 		WARN_ONCE(bits_missing, "CR0 WP bit went missing!?\n");
423 	}
424 }
425 EXPORT_SYMBOL(native_write_cr0);
426 
native_write_cr4(unsigned long val)427 void __no_profile native_write_cr4(unsigned long val)
428 {
429 	unsigned long bits_changed = 0;
430 
431 set_register:
432 	asm volatile("mov %0,%%cr4": "+r" (val) : : "memory");
433 
434 	if (static_branch_likely(&cr_pinning)) {
435 		if (unlikely((val & cr4_pinned_mask) != cr4_pinned_bits)) {
436 			bits_changed = (val & cr4_pinned_mask) ^ cr4_pinned_bits;
437 			val = (val & ~cr4_pinned_mask) | cr4_pinned_bits;
438 			goto set_register;
439 		}
440 		/* Warn after we've corrected the changed bits. */
441 		WARN_ONCE(bits_changed, "pinned CR4 bits changed: 0x%lx!?\n",
442 			  bits_changed);
443 	}
444 }
445 #if IS_MODULE(CONFIG_LKDTM)
446 EXPORT_SYMBOL_GPL(native_write_cr4);
447 #endif
448 
cr4_update_irqsoff(unsigned long set,unsigned long clear)449 void cr4_update_irqsoff(unsigned long set, unsigned long clear)
450 {
451 	unsigned long newval, cr4 = this_cpu_read(cpu_tlbstate.cr4);
452 
453 	lockdep_assert_irqs_disabled();
454 
455 	newval = (cr4 & ~clear) | set;
456 	if (newval != cr4) {
457 		this_cpu_write(cpu_tlbstate.cr4, newval);
458 		__write_cr4(newval);
459 	}
460 }
461 EXPORT_SYMBOL(cr4_update_irqsoff);
462 
463 /* Read the CR4 shadow. */
cr4_read_shadow(void)464 unsigned long cr4_read_shadow(void)
465 {
466 	return this_cpu_read(cpu_tlbstate.cr4);
467 }
468 EXPORT_SYMBOL_GPL(cr4_read_shadow);
469 
cr4_init(void)470 void cr4_init(void)
471 {
472 	unsigned long cr4 = __read_cr4();
473 
474 	if (boot_cpu_has(X86_FEATURE_PCID))
475 		cr4 |= X86_CR4_PCIDE;
476 	if (static_branch_likely(&cr_pinning))
477 		cr4 = (cr4 & ~cr4_pinned_mask) | cr4_pinned_bits;
478 
479 	__write_cr4(cr4);
480 
481 	/* Initialize cr4 shadow for this CPU. */
482 	this_cpu_write(cpu_tlbstate.cr4, cr4);
483 }
484 
485 /*
486  * Once CPU feature detection is finished (and boot params have been
487  * parsed), record any of the sensitive CR bits that are set, and
488  * enable CR pinning.
489  */
setup_cr_pinning(void)490 static void __init setup_cr_pinning(void)
491 {
492 	cr4_pinned_bits = this_cpu_read(cpu_tlbstate.cr4) & cr4_pinned_mask;
493 	static_key_enable(&cr_pinning.key);
494 }
495 
x86_nofsgsbase_setup(char * arg)496 static __init int x86_nofsgsbase_setup(char *arg)
497 {
498 	/* Require an exact match without trailing characters. */
499 	if (strlen(arg))
500 		return 0;
501 
502 	/* Do not emit a message if the feature is not present. */
503 	if (!boot_cpu_has(X86_FEATURE_FSGSBASE))
504 		return 1;
505 
506 	setup_clear_cpu_cap(X86_FEATURE_FSGSBASE);
507 	pr_info("FSGSBASE disabled via kernel command line\n");
508 	return 1;
509 }
510 __setup("nofsgsbase", x86_nofsgsbase_setup);
511 
512 /*
513  * Protection Keys are not available in 32-bit mode.
514  */
515 static bool pku_disabled;
516 
setup_pku(struct cpuinfo_x86 * c)517 static __always_inline void setup_pku(struct cpuinfo_x86 *c)
518 {
519 	if (c == &boot_cpu_data) {
520 		if (pku_disabled || !cpu_feature_enabled(X86_FEATURE_PKU))
521 			return;
522 		/*
523 		 * Setting CR4.PKE will cause the X86_FEATURE_OSPKE cpuid
524 		 * bit to be set.  Enforce it.
525 		 */
526 		setup_force_cpu_cap(X86_FEATURE_OSPKE);
527 
528 	} else if (!cpu_feature_enabled(X86_FEATURE_OSPKE)) {
529 		return;
530 	}
531 
532 	cr4_set_bits(X86_CR4_PKE);
533 	/* Load the default PKRU value */
534 	pkru_write_default();
535 }
536 
537 #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
setup_disable_pku(char * arg)538 static __init int setup_disable_pku(char *arg)
539 {
540 	/*
541 	 * Do not clear the X86_FEATURE_PKU bit.  All of the
542 	 * runtime checks are against OSPKE so clearing the
543 	 * bit does nothing.
544 	 *
545 	 * This way, we will see "pku" in cpuinfo, but not
546 	 * "ospke", which is exactly what we want.  It shows
547 	 * that the CPU has PKU, but the OS has not enabled it.
548 	 * This happens to be exactly how a system would look
549 	 * if we disabled the config option.
550 	 */
551 	pr_info("x86: 'nopku' specified, disabling Memory Protection Keys\n");
552 	pku_disabled = true;
553 	return 1;
554 }
555 __setup("nopku", setup_disable_pku);
556 #endif
557 
558 #ifdef CONFIG_X86_KERNEL_IBT
559 
ibt_save(bool disable)560 __noendbr u64 ibt_save(bool disable)
561 {
562 	u64 msr = 0;
563 
564 	if (cpu_feature_enabled(X86_FEATURE_IBT)) {
565 		rdmsrl(MSR_IA32_S_CET, msr);
566 		if (disable)
567 			wrmsrl(MSR_IA32_S_CET, msr & ~CET_ENDBR_EN);
568 	}
569 
570 	return msr;
571 }
572 
ibt_restore(u64 save)573 __noendbr void ibt_restore(u64 save)
574 {
575 	u64 msr;
576 
577 	if (cpu_feature_enabled(X86_FEATURE_IBT)) {
578 		rdmsrl(MSR_IA32_S_CET, msr);
579 		msr &= ~CET_ENDBR_EN;
580 		msr |= (save & CET_ENDBR_EN);
581 		wrmsrl(MSR_IA32_S_CET, msr);
582 	}
583 }
584 
585 #endif
586 
setup_cet(struct cpuinfo_x86 * c)587 static __always_inline void setup_cet(struct cpuinfo_x86 *c)
588 {
589 	bool user_shstk, kernel_ibt;
590 
591 	if (!IS_ENABLED(CONFIG_X86_CET))
592 		return;
593 
594 	kernel_ibt = HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT);
595 	user_shstk = cpu_feature_enabled(X86_FEATURE_SHSTK) &&
596 		     IS_ENABLED(CONFIG_X86_USER_SHADOW_STACK);
597 
598 	if (!kernel_ibt && !user_shstk)
599 		return;
600 
601 	if (user_shstk)
602 		set_cpu_cap(c, X86_FEATURE_USER_SHSTK);
603 
604 	if (kernel_ibt)
605 		wrmsrl(MSR_IA32_S_CET, CET_ENDBR_EN);
606 	else
607 		wrmsrl(MSR_IA32_S_CET, 0);
608 
609 	cr4_set_bits(X86_CR4_CET);
610 
611 	if (kernel_ibt && ibt_selftest()) {
612 		pr_err("IBT selftest: Failed!\n");
613 		wrmsrl(MSR_IA32_S_CET, 0);
614 		setup_clear_cpu_cap(X86_FEATURE_IBT);
615 	}
616 }
617 
cet_disable(void)618 __noendbr void cet_disable(void)
619 {
620 	if (!(cpu_feature_enabled(X86_FEATURE_IBT) ||
621 	      cpu_feature_enabled(X86_FEATURE_SHSTK)))
622 		return;
623 
624 	wrmsrl(MSR_IA32_S_CET, 0);
625 	wrmsrl(MSR_IA32_U_CET, 0);
626 }
627 
628 /*
629  * Some CPU features depend on higher CPUID levels, which may not always
630  * be available due to CPUID level capping or broken virtualization
631  * software.  Add those features to this table to auto-disable them.
632  */
633 struct cpuid_dependent_feature {
634 	u32 feature;
635 	u32 level;
636 };
637 
638 static const struct cpuid_dependent_feature
639 cpuid_dependent_features[] = {
640 	{ X86_FEATURE_MWAIT,		0x00000005 },
641 	{ X86_FEATURE_DCA,		0x00000009 },
642 	{ X86_FEATURE_XSAVE,		0x0000000d },
643 	{ 0, 0 }
644 };
645 
filter_cpuid_features(struct cpuinfo_x86 * c,bool warn)646 static void filter_cpuid_features(struct cpuinfo_x86 *c, bool warn)
647 {
648 	const struct cpuid_dependent_feature *df;
649 
650 	for (df = cpuid_dependent_features; df->feature; df++) {
651 
652 		if (!cpu_has(c, df->feature))
653 			continue;
654 		/*
655 		 * Note: cpuid_level is set to -1 if unavailable, but
656 		 * extended_extended_level is set to 0 if unavailable
657 		 * and the legitimate extended levels are all negative
658 		 * when signed; hence the weird messing around with
659 		 * signs here...
660 		 */
661 		if (!((s32)df->level < 0 ?
662 		     (u32)df->level > (u32)c->extended_cpuid_level :
663 		     (s32)df->level > (s32)c->cpuid_level))
664 			continue;
665 
666 		clear_cpu_cap(c, df->feature);
667 		if (!warn)
668 			continue;
669 
670 		pr_warn("CPU: CPU feature " X86_CAP_FMT " disabled, no CPUID level 0x%x\n",
671 			x86_cap_flag(df->feature), df->level);
672 	}
673 }
674 
675 /*
676  * Naming convention should be: <Name> [(<Codename>)]
677  * This table only is used unless init_<vendor>() below doesn't set it;
678  * in particular, if CPUID levels 0x80000002..4 are supported, this
679  * isn't used
680  */
681 
682 /* Look up CPU names by table lookup. */
table_lookup_model(struct cpuinfo_x86 * c)683 static const char *table_lookup_model(struct cpuinfo_x86 *c)
684 {
685 #ifdef CONFIG_X86_32
686 	const struct legacy_cpu_model_info *info;
687 
688 	if (c->x86_model >= 16)
689 		return NULL;	/* Range check */
690 
691 	if (!this_cpu)
692 		return NULL;
693 
694 	info = this_cpu->legacy_models;
695 
696 	while (info->family) {
697 		if (info->family == c->x86)
698 			return info->model_names[c->x86_model];
699 		info++;
700 	}
701 #endif
702 	return NULL;		/* Not found */
703 }
704 
705 /* Aligned to unsigned long to avoid split lock in atomic bitmap ops */
706 __u32 cpu_caps_cleared[NCAPINTS + NBUGINTS] __aligned(sizeof(unsigned long));
707 __u32 cpu_caps_set[NCAPINTS + NBUGINTS] __aligned(sizeof(unsigned long));
708 
709 #ifdef CONFIG_X86_32
710 /* The 32-bit entry code needs to find cpu_entry_area. */
711 DEFINE_PER_CPU(struct cpu_entry_area *, cpu_entry_area);
712 #endif
713 
714 /* Load the original GDT from the per-cpu structure */
load_direct_gdt(int cpu)715 void load_direct_gdt(int cpu)
716 {
717 	struct desc_ptr gdt_descr;
718 
719 	gdt_descr.address = (long)get_cpu_gdt_rw(cpu);
720 	gdt_descr.size = GDT_SIZE - 1;
721 	load_gdt(&gdt_descr);
722 }
723 EXPORT_SYMBOL_GPL(load_direct_gdt);
724 
725 /* Load a fixmap remapping of the per-cpu GDT */
load_fixmap_gdt(int cpu)726 void load_fixmap_gdt(int cpu)
727 {
728 	struct desc_ptr gdt_descr;
729 
730 	gdt_descr.address = (long)get_cpu_gdt_ro(cpu);
731 	gdt_descr.size = GDT_SIZE - 1;
732 	load_gdt(&gdt_descr);
733 }
734 EXPORT_SYMBOL_GPL(load_fixmap_gdt);
735 
736 /**
737  * switch_gdt_and_percpu_base - Switch to direct GDT and runtime per CPU base
738  * @cpu:	The CPU number for which this is invoked
739  *
740  * Invoked during early boot to switch from early GDT and early per CPU to
741  * the direct GDT and the runtime per CPU area. On 32-bit the percpu base
742  * switch is implicit by loading the direct GDT. On 64bit this requires
743  * to update GSBASE.
744  */
switch_gdt_and_percpu_base(int cpu)745 void __init switch_gdt_and_percpu_base(int cpu)
746 {
747 	load_direct_gdt(cpu);
748 
749 #ifdef CONFIG_X86_64
750 	/*
751 	 * No need to load %gs. It is already correct.
752 	 *
753 	 * Writing %gs on 64bit would zero GSBASE which would make any per
754 	 * CPU operation up to the point of the wrmsrl() fault.
755 	 *
756 	 * Set GSBASE to the new offset. Until the wrmsrl() happens the
757 	 * early mapping is still valid. That means the GSBASE update will
758 	 * lose any prior per CPU data which was not copied over in
759 	 * setup_per_cpu_areas().
760 	 *
761 	 * This works even with stackprotector enabled because the
762 	 * per CPU stack canary is 0 in both per CPU areas.
763 	 */
764 	wrmsrl(MSR_GS_BASE, cpu_kernelmode_gs_base(cpu));
765 #else
766 	/*
767 	 * %fs is already set to __KERNEL_PERCPU, but after switching GDT
768 	 * it is required to load FS again so that the 'hidden' part is
769 	 * updated from the new GDT. Up to this point the early per CPU
770 	 * translation is active. Any content of the early per CPU data
771 	 * which was not copied over in setup_per_cpu_areas() is lost.
772 	 */
773 	loadsegment(fs, __KERNEL_PERCPU);
774 #endif
775 }
776 
777 static const struct cpu_dev *cpu_devs[X86_VENDOR_NUM] = {};
778 
get_model_name(struct cpuinfo_x86 * c)779 static void get_model_name(struct cpuinfo_x86 *c)
780 {
781 	unsigned int *v;
782 	char *p, *q, *s;
783 
784 	if (c->extended_cpuid_level < 0x80000004)
785 		return;
786 
787 	v = (unsigned int *)c->x86_model_id;
788 	cpuid(0x80000002, &v[0], &v[1], &v[2], &v[3]);
789 	cpuid(0x80000003, &v[4], &v[5], &v[6], &v[7]);
790 	cpuid(0x80000004, &v[8], &v[9], &v[10], &v[11]);
791 	c->x86_model_id[48] = 0;
792 
793 	/* Trim whitespace */
794 	p = q = s = &c->x86_model_id[0];
795 
796 	while (*p == ' ')
797 		p++;
798 
799 	while (*p) {
800 		/* Note the last non-whitespace index */
801 		if (!isspace(*p))
802 			s = q;
803 
804 		*q++ = *p++;
805 	}
806 
807 	*(s + 1) = '\0';
808 }
809 
cpu_detect_cache_sizes(struct cpuinfo_x86 * c)810 void cpu_detect_cache_sizes(struct cpuinfo_x86 *c)
811 {
812 	unsigned int n, dummy, ebx, ecx, edx, l2size;
813 
814 	n = c->extended_cpuid_level;
815 
816 	if (n >= 0x80000005) {
817 		cpuid(0x80000005, &dummy, &ebx, &ecx, &edx);
818 		c->x86_cache_size = (ecx>>24) + (edx>>24);
819 #ifdef CONFIG_X86_64
820 		/* On K8 L1 TLB is inclusive, so don't count it */
821 		c->x86_tlbsize = 0;
822 #endif
823 	}
824 
825 	if (n < 0x80000006)	/* Some chips just has a large L1. */
826 		return;
827 
828 	cpuid(0x80000006, &dummy, &ebx, &ecx, &edx);
829 	l2size = ecx >> 16;
830 
831 #ifdef CONFIG_X86_64
832 	c->x86_tlbsize += ((ebx >> 16) & 0xfff) + (ebx & 0xfff);
833 #else
834 	/* do processor-specific cache resizing */
835 	if (this_cpu->legacy_cache_size)
836 		l2size = this_cpu->legacy_cache_size(c, l2size);
837 
838 	/* Allow user to override all this if necessary. */
839 	if (cachesize_override != -1)
840 		l2size = cachesize_override;
841 
842 	if (l2size == 0)
843 		return;		/* Again, no L2 cache is possible */
844 #endif
845 
846 	c->x86_cache_size = l2size;
847 }
848 
849 u16 __read_mostly tlb_lli_4k[NR_INFO];
850 u16 __read_mostly tlb_lli_2m[NR_INFO];
851 u16 __read_mostly tlb_lli_4m[NR_INFO];
852 u16 __read_mostly tlb_lld_4k[NR_INFO];
853 u16 __read_mostly tlb_lld_2m[NR_INFO];
854 u16 __read_mostly tlb_lld_4m[NR_INFO];
855 u16 __read_mostly tlb_lld_1g[NR_INFO];
856 
cpu_detect_tlb(struct cpuinfo_x86 * c)857 static void cpu_detect_tlb(struct cpuinfo_x86 *c)
858 {
859 	if (this_cpu->c_detect_tlb)
860 		this_cpu->c_detect_tlb(c);
861 
862 	pr_info("Last level iTLB entries: 4KB %d, 2MB %d, 4MB %d\n",
863 		tlb_lli_4k[ENTRIES], tlb_lli_2m[ENTRIES],
864 		tlb_lli_4m[ENTRIES]);
865 
866 	pr_info("Last level dTLB entries: 4KB %d, 2MB %d, 4MB %d, 1GB %d\n",
867 		tlb_lld_4k[ENTRIES], tlb_lld_2m[ENTRIES],
868 		tlb_lld_4m[ENTRIES], tlb_lld_1g[ENTRIES]);
869 }
870 
get_cpu_vendor(struct cpuinfo_x86 * c)871 static void get_cpu_vendor(struct cpuinfo_x86 *c)
872 {
873 	char *v = c->x86_vendor_id;
874 	int i;
875 
876 	for (i = 0; i < X86_VENDOR_NUM; i++) {
877 		if (!cpu_devs[i])
878 			break;
879 
880 		if (!strcmp(v, cpu_devs[i]->c_ident[0]) ||
881 		    (cpu_devs[i]->c_ident[1] &&
882 		     !strcmp(v, cpu_devs[i]->c_ident[1]))) {
883 
884 			this_cpu = cpu_devs[i];
885 			c->x86_vendor = this_cpu->c_x86_vendor;
886 			return;
887 		}
888 	}
889 
890 	pr_err_once("CPU: vendor_id '%s' unknown, using generic init.\n" \
891 		    "CPU: Your system may be unstable.\n", v);
892 
893 	c->x86_vendor = X86_VENDOR_UNKNOWN;
894 	this_cpu = &default_cpu;
895 }
896 
cpu_detect(struct cpuinfo_x86 * c)897 void cpu_detect(struct cpuinfo_x86 *c)
898 {
899 	/* Get vendor name */
900 	cpuid(0x00000000, (unsigned int *)&c->cpuid_level,
901 	      (unsigned int *)&c->x86_vendor_id[0],
902 	      (unsigned int *)&c->x86_vendor_id[8],
903 	      (unsigned int *)&c->x86_vendor_id[4]);
904 
905 	c->x86 = 4;
906 	/* Intel-defined flags: level 0x00000001 */
907 	if (c->cpuid_level >= 0x00000001) {
908 		u32 junk, tfms, cap0, misc;
909 
910 		cpuid(0x00000001, &tfms, &misc, &junk, &cap0);
911 		c->x86		= x86_family(tfms);
912 		c->x86_model	= x86_model(tfms);
913 		c->x86_stepping	= x86_stepping(tfms);
914 
915 		if (cap0 & (1<<19)) {
916 			c->x86_clflush_size = ((misc >> 8) & 0xff) * 8;
917 			c->x86_cache_alignment = c->x86_clflush_size;
918 		}
919 	}
920 }
921 
apply_forced_caps(struct cpuinfo_x86 * c)922 static void apply_forced_caps(struct cpuinfo_x86 *c)
923 {
924 	int i;
925 
926 	for (i = 0; i < NCAPINTS + NBUGINTS; i++) {
927 		c->x86_capability[i] &= ~cpu_caps_cleared[i];
928 		c->x86_capability[i] |= cpu_caps_set[i];
929 	}
930 }
931 
init_speculation_control(struct cpuinfo_x86 * c)932 static void init_speculation_control(struct cpuinfo_x86 *c)
933 {
934 	/*
935 	 * The Intel SPEC_CTRL CPUID bit implies IBRS and IBPB support,
936 	 * and they also have a different bit for STIBP support. Also,
937 	 * a hypervisor might have set the individual AMD bits even on
938 	 * Intel CPUs, for finer-grained selection of what's available.
939 	 */
940 	if (cpu_has(c, X86_FEATURE_SPEC_CTRL)) {
941 		set_cpu_cap(c, X86_FEATURE_IBRS);
942 		set_cpu_cap(c, X86_FEATURE_IBPB);
943 		set_cpu_cap(c, X86_FEATURE_MSR_SPEC_CTRL);
944 	}
945 
946 	if (cpu_has(c, X86_FEATURE_INTEL_STIBP))
947 		set_cpu_cap(c, X86_FEATURE_STIBP);
948 
949 	if (cpu_has(c, X86_FEATURE_SPEC_CTRL_SSBD) ||
950 	    cpu_has(c, X86_FEATURE_VIRT_SSBD))
951 		set_cpu_cap(c, X86_FEATURE_SSBD);
952 
953 	if (cpu_has(c, X86_FEATURE_AMD_IBRS)) {
954 		set_cpu_cap(c, X86_FEATURE_IBRS);
955 		set_cpu_cap(c, X86_FEATURE_MSR_SPEC_CTRL);
956 	}
957 
958 	if (cpu_has(c, X86_FEATURE_AMD_IBPB))
959 		set_cpu_cap(c, X86_FEATURE_IBPB);
960 
961 	if (cpu_has(c, X86_FEATURE_AMD_STIBP)) {
962 		set_cpu_cap(c, X86_FEATURE_STIBP);
963 		set_cpu_cap(c, X86_FEATURE_MSR_SPEC_CTRL);
964 	}
965 
966 	if (cpu_has(c, X86_FEATURE_AMD_SSBD)) {
967 		set_cpu_cap(c, X86_FEATURE_SSBD);
968 		set_cpu_cap(c, X86_FEATURE_MSR_SPEC_CTRL);
969 		clear_cpu_cap(c, X86_FEATURE_VIRT_SSBD);
970 	}
971 }
972 
get_cpu_cap(struct cpuinfo_x86 * c)973 void get_cpu_cap(struct cpuinfo_x86 *c)
974 {
975 	u32 eax, ebx, ecx, edx;
976 
977 	/* Intel-defined flags: level 0x00000001 */
978 	if (c->cpuid_level >= 0x00000001) {
979 		cpuid(0x00000001, &eax, &ebx, &ecx, &edx);
980 
981 		c->x86_capability[CPUID_1_ECX] = ecx;
982 		c->x86_capability[CPUID_1_EDX] = edx;
983 	}
984 
985 	/* Thermal and Power Management Leaf: level 0x00000006 (eax) */
986 	if (c->cpuid_level >= 0x00000006)
987 		c->x86_capability[CPUID_6_EAX] = cpuid_eax(0x00000006);
988 
989 	/* Additional Intel-defined flags: level 0x00000007 */
990 	if (c->cpuid_level >= 0x00000007) {
991 		cpuid_count(0x00000007, 0, &eax, &ebx, &ecx, &edx);
992 		c->x86_capability[CPUID_7_0_EBX] = ebx;
993 		c->x86_capability[CPUID_7_ECX] = ecx;
994 		c->x86_capability[CPUID_7_EDX] = edx;
995 
996 		/* Check valid sub-leaf index before accessing it */
997 		if (eax >= 1) {
998 			cpuid_count(0x00000007, 1, &eax, &ebx, &ecx, &edx);
999 			c->x86_capability[CPUID_7_1_EAX] = eax;
1000 		}
1001 	}
1002 
1003 	/* Extended state features: level 0x0000000d */
1004 	if (c->cpuid_level >= 0x0000000d) {
1005 		cpuid_count(0x0000000d, 1, &eax, &ebx, &ecx, &edx);
1006 
1007 		c->x86_capability[CPUID_D_1_EAX] = eax;
1008 	}
1009 
1010 	/* AMD-defined flags: level 0x80000001 */
1011 	eax = cpuid_eax(0x80000000);
1012 	c->extended_cpuid_level = eax;
1013 
1014 	if ((eax & 0xffff0000) == 0x80000000) {
1015 		if (eax >= 0x80000001) {
1016 			cpuid(0x80000001, &eax, &ebx, &ecx, &edx);
1017 
1018 			c->x86_capability[CPUID_8000_0001_ECX] = ecx;
1019 			c->x86_capability[CPUID_8000_0001_EDX] = edx;
1020 		}
1021 	}
1022 
1023 	if (c->extended_cpuid_level >= 0x80000007) {
1024 		cpuid(0x80000007, &eax, &ebx, &ecx, &edx);
1025 
1026 		c->x86_capability[CPUID_8000_0007_EBX] = ebx;
1027 		c->x86_power = edx;
1028 	}
1029 
1030 	if (c->extended_cpuid_level >= 0x80000008) {
1031 		cpuid(0x80000008, &eax, &ebx, &ecx, &edx);
1032 		c->x86_capability[CPUID_8000_0008_EBX] = ebx;
1033 	}
1034 
1035 	if (c->extended_cpuid_level >= 0x8000000a)
1036 		c->x86_capability[CPUID_8000_000A_EDX] = cpuid_edx(0x8000000a);
1037 
1038 	if (c->extended_cpuid_level >= 0x8000001f)
1039 		c->x86_capability[CPUID_8000_001F_EAX] = cpuid_eax(0x8000001f);
1040 
1041 	if (c->extended_cpuid_level >= 0x80000021)
1042 		c->x86_capability[CPUID_8000_0021_EAX] = cpuid_eax(0x80000021);
1043 
1044 	init_scattered_cpuid_features(c);
1045 	init_speculation_control(c);
1046 
1047 	/*
1048 	 * Clear/Set all flags overridden by options, after probe.
1049 	 * This needs to happen each time we re-probe, which may happen
1050 	 * several times during CPU initialization.
1051 	 */
1052 	apply_forced_caps(c);
1053 }
1054 
get_cpu_address_sizes(struct cpuinfo_x86 * c)1055 void get_cpu_address_sizes(struct cpuinfo_x86 *c)
1056 {
1057 	u32 eax, ebx, ecx, edx;
1058 
1059 	if (!cpu_has(c, X86_FEATURE_CPUID) ||
1060 	    (c->extended_cpuid_level < 0x80000008)) {
1061 		if (IS_ENABLED(CONFIG_X86_64)) {
1062 			c->x86_clflush_size = 64;
1063 			c->x86_phys_bits = 36;
1064 			c->x86_virt_bits = 48;
1065 		} else {
1066 			c->x86_clflush_size = 32;
1067 			c->x86_virt_bits = 32;
1068 			c->x86_phys_bits = 32;
1069 
1070 			if (cpu_has(c, X86_FEATURE_PAE) ||
1071 			    cpu_has(c, X86_FEATURE_PSE36))
1072 				c->x86_phys_bits = 36;
1073 		}
1074 	} else {
1075 		cpuid(0x80000008, &eax, &ebx, &ecx, &edx);
1076 
1077 		c->x86_virt_bits = (eax >> 8) & 0xff;
1078 		c->x86_phys_bits = eax & 0xff;
1079 
1080 		/* Provide a sane default if not enumerated: */
1081 		if (!c->x86_clflush_size)
1082 			c->x86_clflush_size = 32;
1083 	}
1084 
1085 	c->x86_cache_bits = c->x86_phys_bits;
1086 	c->x86_cache_alignment = c->x86_clflush_size;
1087 }
1088 
identify_cpu_without_cpuid(struct cpuinfo_x86 * c)1089 static void identify_cpu_without_cpuid(struct cpuinfo_x86 *c)
1090 {
1091 #ifdef CONFIG_X86_32
1092 	int i;
1093 
1094 	/*
1095 	 * First of all, decide if this is a 486 or higher
1096 	 * It's a 486 if we can modify the AC flag
1097 	 */
1098 	if (flag_is_changeable_p(X86_EFLAGS_AC))
1099 		c->x86 = 4;
1100 	else
1101 		c->x86 = 3;
1102 
1103 	for (i = 0; i < X86_VENDOR_NUM; i++)
1104 		if (cpu_devs[i] && cpu_devs[i]->c_identify) {
1105 			c->x86_vendor_id[0] = 0;
1106 			cpu_devs[i]->c_identify(c);
1107 			if (c->x86_vendor_id[0]) {
1108 				get_cpu_vendor(c);
1109 				break;
1110 			}
1111 		}
1112 #endif
1113 }
1114 
1115 #define NO_SPECULATION		BIT(0)
1116 #define NO_MELTDOWN		BIT(1)
1117 #define NO_SSB			BIT(2)
1118 #define NO_L1TF			BIT(3)
1119 #define NO_MDS			BIT(4)
1120 #define MSBDS_ONLY		BIT(5)
1121 #define NO_SWAPGS		BIT(6)
1122 #define NO_ITLB_MULTIHIT	BIT(7)
1123 #define NO_SPECTRE_V2		BIT(8)
1124 #define NO_MMIO			BIT(9)
1125 #define NO_EIBRS_PBRSB		BIT(10)
1126 #define NO_BHI			BIT(11)
1127 
1128 #define VULNWL(vendor, family, model, whitelist)	\
1129 	X86_MATCH_VENDOR_FAM_MODEL(vendor, family, model, whitelist)
1130 
1131 #define VULNWL_INTEL(vfm, whitelist)		\
1132 	X86_MATCH_VFM(vfm, whitelist)
1133 
1134 #define VULNWL_AMD(family, whitelist)		\
1135 	VULNWL(AMD, family, X86_MODEL_ANY, whitelist)
1136 
1137 #define VULNWL_HYGON(family, whitelist)		\
1138 	VULNWL(HYGON, family, X86_MODEL_ANY, whitelist)
1139 
1140 static const __initconst struct x86_cpu_id cpu_vuln_whitelist[] = {
1141 	VULNWL(ANY,	4, X86_MODEL_ANY,	NO_SPECULATION),
1142 	VULNWL(CENTAUR,	5, X86_MODEL_ANY,	NO_SPECULATION),
1143 	VULNWL(INTEL,	5, X86_MODEL_ANY,	NO_SPECULATION),
1144 	VULNWL(NSC,	5, X86_MODEL_ANY,	NO_SPECULATION),
1145 	VULNWL(VORTEX,	5, X86_MODEL_ANY,	NO_SPECULATION),
1146 	VULNWL(VORTEX,	6, X86_MODEL_ANY,	NO_SPECULATION),
1147 
1148 	/* Intel Family 6 */
1149 	VULNWL_INTEL(INTEL_TIGERLAKE,		NO_MMIO),
1150 	VULNWL_INTEL(INTEL_TIGERLAKE_L,		NO_MMIO),
1151 	VULNWL_INTEL(INTEL_ALDERLAKE,		NO_MMIO),
1152 	VULNWL_INTEL(INTEL_ALDERLAKE_L,		NO_MMIO),
1153 
1154 	VULNWL_INTEL(INTEL_ATOM_SALTWELL,	NO_SPECULATION | NO_ITLB_MULTIHIT),
1155 	VULNWL_INTEL(INTEL_ATOM_SALTWELL_TABLET, NO_SPECULATION | NO_ITLB_MULTIHIT),
1156 	VULNWL_INTEL(INTEL_ATOM_SALTWELL_MID,	NO_SPECULATION | NO_ITLB_MULTIHIT),
1157 	VULNWL_INTEL(INTEL_ATOM_BONNELL,	NO_SPECULATION | NO_ITLB_MULTIHIT),
1158 	VULNWL_INTEL(INTEL_ATOM_BONNELL_MID,	NO_SPECULATION | NO_ITLB_MULTIHIT),
1159 
1160 	VULNWL_INTEL(INTEL_ATOM_SILVERMONT,	NO_SSB | NO_L1TF | MSBDS_ONLY | NO_SWAPGS | NO_ITLB_MULTIHIT),
1161 	VULNWL_INTEL(INTEL_ATOM_SILVERMONT_D,	NO_SSB | NO_L1TF | MSBDS_ONLY | NO_SWAPGS | NO_ITLB_MULTIHIT),
1162 	VULNWL_INTEL(INTEL_ATOM_SILVERMONT_MID,	NO_SSB | NO_L1TF | MSBDS_ONLY | NO_SWAPGS | NO_ITLB_MULTIHIT),
1163 	VULNWL_INTEL(INTEL_ATOM_AIRMONT,	NO_SSB | NO_L1TF | MSBDS_ONLY | NO_SWAPGS | NO_ITLB_MULTIHIT),
1164 	VULNWL_INTEL(INTEL_XEON_PHI_KNL,	NO_SSB | NO_L1TF | MSBDS_ONLY | NO_SWAPGS | NO_ITLB_MULTIHIT),
1165 	VULNWL_INTEL(INTEL_XEON_PHI_KNM,	NO_SSB | NO_L1TF | MSBDS_ONLY | NO_SWAPGS | NO_ITLB_MULTIHIT),
1166 
1167 	VULNWL_INTEL(INTEL_CORE_YONAH,		NO_SSB),
1168 
1169 	VULNWL_INTEL(INTEL_ATOM_AIRMONT_MID,	NO_SSB | NO_L1TF | NO_SWAPGS | NO_ITLB_MULTIHIT | MSBDS_ONLY),
1170 	VULNWL_INTEL(INTEL_ATOM_AIRMONT_NP,	NO_SSB | NO_L1TF | NO_SWAPGS | NO_ITLB_MULTIHIT),
1171 
1172 	VULNWL_INTEL(INTEL_ATOM_GOLDMONT,	NO_MDS | NO_L1TF | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO),
1173 	VULNWL_INTEL(INTEL_ATOM_GOLDMONT_D,	NO_MDS | NO_L1TF | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO),
1174 	VULNWL_INTEL(INTEL_ATOM_GOLDMONT_PLUS,	NO_MDS | NO_L1TF | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO | NO_EIBRS_PBRSB),
1175 
1176 	/*
1177 	 * Technically, swapgs isn't serializing on AMD (despite it previously
1178 	 * being documented as such in the APM).  But according to AMD, %gs is
1179 	 * updated non-speculatively, and the issuing of %gs-relative memory
1180 	 * operands will be blocked until the %gs update completes, which is
1181 	 * good enough for our purposes.
1182 	 */
1183 
1184 	VULNWL_INTEL(INTEL_ATOM_TREMONT,	NO_EIBRS_PBRSB),
1185 	VULNWL_INTEL(INTEL_ATOM_TREMONT_L,	NO_EIBRS_PBRSB),
1186 	VULNWL_INTEL(INTEL_ATOM_TREMONT_D,	NO_ITLB_MULTIHIT | NO_EIBRS_PBRSB),
1187 
1188 	/* AMD Family 0xf - 0x12 */
1189 	VULNWL_AMD(0x0f,	NO_MELTDOWN | NO_SSB | NO_L1TF | NO_MDS | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO | NO_BHI),
1190 	VULNWL_AMD(0x10,	NO_MELTDOWN | NO_SSB | NO_L1TF | NO_MDS | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO | NO_BHI),
1191 	VULNWL_AMD(0x11,	NO_MELTDOWN | NO_SSB | NO_L1TF | NO_MDS | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO | NO_BHI),
1192 	VULNWL_AMD(0x12,	NO_MELTDOWN | NO_SSB | NO_L1TF | NO_MDS | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO | NO_BHI),
1193 
1194 	/* FAMILY_ANY must be last, otherwise 0x0f - 0x12 matches won't work */
1195 	VULNWL_AMD(X86_FAMILY_ANY,	NO_MELTDOWN | NO_L1TF | NO_MDS | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO | NO_EIBRS_PBRSB | NO_BHI),
1196 	VULNWL_HYGON(X86_FAMILY_ANY,	NO_MELTDOWN | NO_L1TF | NO_MDS | NO_SWAPGS | NO_ITLB_MULTIHIT | NO_MMIO | NO_EIBRS_PBRSB | NO_BHI),
1197 
1198 	/* Zhaoxin Family 7 */
1199 	VULNWL(CENTAUR,	7, X86_MODEL_ANY,	NO_SPECTRE_V2 | NO_SWAPGS | NO_MMIO | NO_BHI),
1200 	VULNWL(ZHAOXIN,	7, X86_MODEL_ANY,	NO_SPECTRE_V2 | NO_SWAPGS | NO_MMIO | NO_BHI),
1201 	{}
1202 };
1203 
1204 #define VULNBL(vendor, family, model, blacklist)	\
1205 	X86_MATCH_VENDOR_FAM_MODEL(vendor, family, model, blacklist)
1206 
1207 #define VULNBL_INTEL_STEPPINGS(vfm, steppings, issues)		   \
1208 	X86_MATCH_VFM_STEPPINGS(vfm, steppings, issues)
1209 
1210 #define VULNBL_AMD(family, blacklist)		\
1211 	VULNBL(AMD, family, X86_MODEL_ANY, blacklist)
1212 
1213 #define VULNBL_HYGON(family, blacklist)		\
1214 	VULNBL(HYGON, family, X86_MODEL_ANY, blacklist)
1215 
1216 #define SRBDS		BIT(0)
1217 /* CPU is affected by X86_BUG_MMIO_STALE_DATA */
1218 #define MMIO		BIT(1)
1219 /* CPU is affected by Shared Buffers Data Sampling (SBDS), a variant of X86_BUG_MMIO_STALE_DATA */
1220 #define MMIO_SBDS	BIT(2)
1221 /* CPU is affected by RETbleed, speculating where you would not expect it */
1222 #define RETBLEED	BIT(3)
1223 /* CPU is affected by SMT (cross-thread) return predictions */
1224 #define SMT_RSB		BIT(4)
1225 /* CPU is affected by SRSO */
1226 #define SRSO		BIT(5)
1227 /* CPU is affected by GDS */
1228 #define GDS		BIT(6)
1229 /* CPU is affected by Register File Data Sampling */
1230 #define RFDS		BIT(7)
1231 
1232 static const struct x86_cpu_id cpu_vuln_blacklist[] __initconst = {
1233 	VULNBL_INTEL_STEPPINGS(INTEL_IVYBRIDGE,		X86_STEPPING_ANY,		SRBDS),
1234 	VULNBL_INTEL_STEPPINGS(INTEL_HASWELL,		X86_STEPPING_ANY,		SRBDS),
1235 	VULNBL_INTEL_STEPPINGS(INTEL_HASWELL_L,		X86_STEPPING_ANY,		SRBDS),
1236 	VULNBL_INTEL_STEPPINGS(INTEL_HASWELL_G,		X86_STEPPING_ANY,		SRBDS),
1237 	VULNBL_INTEL_STEPPINGS(INTEL_HASWELL_X,		X86_STEPPING_ANY,		MMIO),
1238 	VULNBL_INTEL_STEPPINGS(INTEL_BROADWELL_D,	X86_STEPPING_ANY,		MMIO),
1239 	VULNBL_INTEL_STEPPINGS(INTEL_BROADWELL_G,	X86_STEPPING_ANY,		SRBDS),
1240 	VULNBL_INTEL_STEPPINGS(INTEL_BROADWELL_X,	X86_STEPPING_ANY,		MMIO),
1241 	VULNBL_INTEL_STEPPINGS(INTEL_BROADWELL,		X86_STEPPING_ANY,		SRBDS),
1242 	VULNBL_INTEL_STEPPINGS(INTEL_SKYLAKE_X,		X86_STEPPING_ANY,		MMIO | RETBLEED | GDS),
1243 	VULNBL_INTEL_STEPPINGS(INTEL_SKYLAKE_L,		X86_STEPPING_ANY,		MMIO | RETBLEED | GDS | SRBDS),
1244 	VULNBL_INTEL_STEPPINGS(INTEL_SKYLAKE,		X86_STEPPING_ANY,		MMIO | RETBLEED | GDS | SRBDS),
1245 	VULNBL_INTEL_STEPPINGS(INTEL_KABYLAKE_L,	X86_STEPPING_ANY,		MMIO | RETBLEED | GDS | SRBDS),
1246 	VULNBL_INTEL_STEPPINGS(INTEL_KABYLAKE,		X86_STEPPING_ANY,		MMIO | RETBLEED | GDS | SRBDS),
1247 	VULNBL_INTEL_STEPPINGS(INTEL_CANNONLAKE_L,	X86_STEPPING_ANY,		RETBLEED),
1248 	VULNBL_INTEL_STEPPINGS(INTEL_ICELAKE_L,		X86_STEPPING_ANY,		MMIO | MMIO_SBDS | RETBLEED | GDS),
1249 	VULNBL_INTEL_STEPPINGS(INTEL_ICELAKE_D,		X86_STEPPING_ANY,		MMIO | GDS),
1250 	VULNBL_INTEL_STEPPINGS(INTEL_ICELAKE_X,		X86_STEPPING_ANY,		MMIO | GDS),
1251 	VULNBL_INTEL_STEPPINGS(INTEL_COMETLAKE,		X86_STEPPING_ANY,		MMIO | MMIO_SBDS | RETBLEED | GDS),
1252 	VULNBL_INTEL_STEPPINGS(INTEL_COMETLAKE_L,	X86_STEPPINGS(0x0, 0x0),	MMIO | RETBLEED),
1253 	VULNBL_INTEL_STEPPINGS(INTEL_COMETLAKE_L,	X86_STEPPING_ANY,		MMIO | MMIO_SBDS | RETBLEED | GDS),
1254 	VULNBL_INTEL_STEPPINGS(INTEL_TIGERLAKE_L,	X86_STEPPING_ANY,		GDS),
1255 	VULNBL_INTEL_STEPPINGS(INTEL_TIGERLAKE,		X86_STEPPING_ANY,		GDS),
1256 	VULNBL_INTEL_STEPPINGS(INTEL_LAKEFIELD,		X86_STEPPING_ANY,		MMIO | MMIO_SBDS | RETBLEED),
1257 	VULNBL_INTEL_STEPPINGS(INTEL_ROCKETLAKE,	X86_STEPPING_ANY,		MMIO | RETBLEED | GDS),
1258 	VULNBL_INTEL_STEPPINGS(INTEL_ALDERLAKE,		X86_STEPPING_ANY,		RFDS),
1259 	VULNBL_INTEL_STEPPINGS(INTEL_ALDERLAKE_L,	X86_STEPPING_ANY,		RFDS),
1260 	VULNBL_INTEL_STEPPINGS(INTEL_RAPTORLAKE,	X86_STEPPING_ANY,		RFDS),
1261 	VULNBL_INTEL_STEPPINGS(INTEL_RAPTORLAKE_P,	X86_STEPPING_ANY,		RFDS),
1262 	VULNBL_INTEL_STEPPINGS(INTEL_RAPTORLAKE_S,	X86_STEPPING_ANY,		RFDS),
1263 	VULNBL_INTEL_STEPPINGS(INTEL_ATOM_GRACEMONT,	X86_STEPPING_ANY,		RFDS),
1264 	VULNBL_INTEL_STEPPINGS(INTEL_ATOM_TREMONT,	X86_STEPPING_ANY,		MMIO | MMIO_SBDS | RFDS),
1265 	VULNBL_INTEL_STEPPINGS(INTEL_ATOM_TREMONT_D,	X86_STEPPING_ANY,		MMIO | RFDS),
1266 	VULNBL_INTEL_STEPPINGS(INTEL_ATOM_TREMONT_L,	X86_STEPPING_ANY,		MMIO | MMIO_SBDS | RFDS),
1267 	VULNBL_INTEL_STEPPINGS(INTEL_ATOM_GOLDMONT,	X86_STEPPING_ANY,		RFDS),
1268 	VULNBL_INTEL_STEPPINGS(INTEL_ATOM_GOLDMONT_D,	X86_STEPPING_ANY,		RFDS),
1269 	VULNBL_INTEL_STEPPINGS(INTEL_ATOM_GOLDMONT_PLUS, X86_STEPPING_ANY,		RFDS),
1270 
1271 	VULNBL_AMD(0x15, RETBLEED),
1272 	VULNBL_AMD(0x16, RETBLEED),
1273 	VULNBL_AMD(0x17, RETBLEED | SMT_RSB | SRSO),
1274 	VULNBL_HYGON(0x18, RETBLEED | SMT_RSB | SRSO),
1275 	VULNBL_AMD(0x19, SRSO),
1276 	{}
1277 };
1278 
cpu_matches(const struct x86_cpu_id * table,unsigned long which)1279 static bool __init cpu_matches(const struct x86_cpu_id *table, unsigned long which)
1280 {
1281 	const struct x86_cpu_id *m = x86_match_cpu(table);
1282 
1283 	return m && !!(m->driver_data & which);
1284 }
1285 
x86_read_arch_cap_msr(void)1286 u64 x86_read_arch_cap_msr(void)
1287 {
1288 	u64 x86_arch_cap_msr = 0;
1289 
1290 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
1291 		rdmsrl(MSR_IA32_ARCH_CAPABILITIES, x86_arch_cap_msr);
1292 
1293 	return x86_arch_cap_msr;
1294 }
1295 
arch_cap_mmio_immune(u64 x86_arch_cap_msr)1296 static bool arch_cap_mmio_immune(u64 x86_arch_cap_msr)
1297 {
1298 	return (x86_arch_cap_msr & ARCH_CAP_FBSDP_NO &&
1299 		x86_arch_cap_msr & ARCH_CAP_PSDP_NO &&
1300 		x86_arch_cap_msr & ARCH_CAP_SBDR_SSDP_NO);
1301 }
1302 
vulnerable_to_rfds(u64 x86_arch_cap_msr)1303 static bool __init vulnerable_to_rfds(u64 x86_arch_cap_msr)
1304 {
1305 	/* The "immunity" bit trumps everything else: */
1306 	if (x86_arch_cap_msr & ARCH_CAP_RFDS_NO)
1307 		return false;
1308 
1309 	/*
1310 	 * VMMs set ARCH_CAP_RFDS_CLEAR for processors not in the blacklist to
1311 	 * indicate that mitigation is needed because guest is running on a
1312 	 * vulnerable hardware or may migrate to such hardware:
1313 	 */
1314 	if (x86_arch_cap_msr & ARCH_CAP_RFDS_CLEAR)
1315 		return true;
1316 
1317 	/* Only consult the blacklist when there is no enumeration: */
1318 	return cpu_matches(cpu_vuln_blacklist, RFDS);
1319 }
1320 
cpu_set_bug_bits(struct cpuinfo_x86 * c)1321 static void __init cpu_set_bug_bits(struct cpuinfo_x86 *c)
1322 {
1323 	u64 x86_arch_cap_msr = x86_read_arch_cap_msr();
1324 
1325 	/* Set ITLB_MULTIHIT bug if cpu is not in the whitelist and not mitigated */
1326 	if (!cpu_matches(cpu_vuln_whitelist, NO_ITLB_MULTIHIT) &&
1327 	    !(x86_arch_cap_msr & ARCH_CAP_PSCHANGE_MC_NO))
1328 		setup_force_cpu_bug(X86_BUG_ITLB_MULTIHIT);
1329 
1330 	if (cpu_matches(cpu_vuln_whitelist, NO_SPECULATION))
1331 		return;
1332 
1333 	setup_force_cpu_bug(X86_BUG_SPECTRE_V1);
1334 
1335 	if (!cpu_matches(cpu_vuln_whitelist, NO_SPECTRE_V2))
1336 		setup_force_cpu_bug(X86_BUG_SPECTRE_V2);
1337 
1338 	if (!cpu_matches(cpu_vuln_whitelist, NO_SSB) &&
1339 	    !(x86_arch_cap_msr & ARCH_CAP_SSB_NO) &&
1340 	   !cpu_has(c, X86_FEATURE_AMD_SSB_NO))
1341 		setup_force_cpu_bug(X86_BUG_SPEC_STORE_BYPASS);
1342 
1343 	/*
1344 	 * AMD's AutoIBRS is equivalent to Intel's eIBRS - use the Intel feature
1345 	 * flag and protect from vendor-specific bugs via the whitelist.
1346 	 *
1347 	 * Don't use AutoIBRS when SNP is enabled because it degrades host
1348 	 * userspace indirect branch performance.
1349 	 */
1350 	if ((x86_arch_cap_msr & ARCH_CAP_IBRS_ALL) ||
1351 	    (cpu_has(c, X86_FEATURE_AUTOIBRS) &&
1352 	     !cpu_feature_enabled(X86_FEATURE_SEV_SNP))) {
1353 		setup_force_cpu_cap(X86_FEATURE_IBRS_ENHANCED);
1354 		if (!cpu_matches(cpu_vuln_whitelist, NO_EIBRS_PBRSB) &&
1355 		    !(x86_arch_cap_msr & ARCH_CAP_PBRSB_NO))
1356 			setup_force_cpu_bug(X86_BUG_EIBRS_PBRSB);
1357 	}
1358 
1359 	if (!cpu_matches(cpu_vuln_whitelist, NO_MDS) &&
1360 	    !(x86_arch_cap_msr & ARCH_CAP_MDS_NO)) {
1361 		setup_force_cpu_bug(X86_BUG_MDS);
1362 		if (cpu_matches(cpu_vuln_whitelist, MSBDS_ONLY))
1363 			setup_force_cpu_bug(X86_BUG_MSBDS_ONLY);
1364 	}
1365 
1366 	if (!cpu_matches(cpu_vuln_whitelist, NO_SWAPGS))
1367 		setup_force_cpu_bug(X86_BUG_SWAPGS);
1368 
1369 	/*
1370 	 * When the CPU is not mitigated for TAA (TAA_NO=0) set TAA bug when:
1371 	 *	- TSX is supported or
1372 	 *	- TSX_CTRL is present
1373 	 *
1374 	 * TSX_CTRL check is needed for cases when TSX could be disabled before
1375 	 * the kernel boot e.g. kexec.
1376 	 * TSX_CTRL check alone is not sufficient for cases when the microcode
1377 	 * update is not present or running as guest that don't get TSX_CTRL.
1378 	 */
1379 	if (!(x86_arch_cap_msr & ARCH_CAP_TAA_NO) &&
1380 	    (cpu_has(c, X86_FEATURE_RTM) ||
1381 	     (x86_arch_cap_msr & ARCH_CAP_TSX_CTRL_MSR)))
1382 		setup_force_cpu_bug(X86_BUG_TAA);
1383 
1384 	/*
1385 	 * SRBDS affects CPUs which support RDRAND or RDSEED and are listed
1386 	 * in the vulnerability blacklist.
1387 	 *
1388 	 * Some of the implications and mitigation of Shared Buffers Data
1389 	 * Sampling (SBDS) are similar to SRBDS. Give SBDS same treatment as
1390 	 * SRBDS.
1391 	 */
1392 	if ((cpu_has(c, X86_FEATURE_RDRAND) ||
1393 	     cpu_has(c, X86_FEATURE_RDSEED)) &&
1394 	    cpu_matches(cpu_vuln_blacklist, SRBDS | MMIO_SBDS))
1395 		    setup_force_cpu_bug(X86_BUG_SRBDS);
1396 
1397 	/*
1398 	 * Processor MMIO Stale Data bug enumeration
1399 	 *
1400 	 * Affected CPU list is generally enough to enumerate the vulnerability,
1401 	 * but for virtualization case check for ARCH_CAP MSR bits also, VMM may
1402 	 * not want the guest to enumerate the bug.
1403 	 *
1404 	 * Set X86_BUG_MMIO_UNKNOWN for CPUs that are neither in the blacklist,
1405 	 * nor in the whitelist and also don't enumerate MSR ARCH_CAP MMIO bits.
1406 	 */
1407 	if (!arch_cap_mmio_immune(x86_arch_cap_msr)) {
1408 		if (cpu_matches(cpu_vuln_blacklist, MMIO))
1409 			setup_force_cpu_bug(X86_BUG_MMIO_STALE_DATA);
1410 		else if (!cpu_matches(cpu_vuln_whitelist, NO_MMIO))
1411 			setup_force_cpu_bug(X86_BUG_MMIO_UNKNOWN);
1412 	}
1413 
1414 	if (!cpu_has(c, X86_FEATURE_BTC_NO)) {
1415 		if (cpu_matches(cpu_vuln_blacklist, RETBLEED) || (x86_arch_cap_msr & ARCH_CAP_RSBA))
1416 			setup_force_cpu_bug(X86_BUG_RETBLEED);
1417 	}
1418 
1419 	if (cpu_matches(cpu_vuln_blacklist, SMT_RSB))
1420 		setup_force_cpu_bug(X86_BUG_SMT_RSB);
1421 
1422 	if (!cpu_has(c, X86_FEATURE_SRSO_NO)) {
1423 		if (cpu_matches(cpu_vuln_blacklist, SRSO))
1424 			setup_force_cpu_bug(X86_BUG_SRSO);
1425 	}
1426 
1427 	/*
1428 	 * Check if CPU is vulnerable to GDS. If running in a virtual machine on
1429 	 * an affected processor, the VMM may have disabled the use of GATHER by
1430 	 * disabling AVX2. The only way to do this in HW is to clear XCR0[2],
1431 	 * which means that AVX will be disabled.
1432 	 */
1433 	if (cpu_matches(cpu_vuln_blacklist, GDS) && !(x86_arch_cap_msr & ARCH_CAP_GDS_NO) &&
1434 	    boot_cpu_has(X86_FEATURE_AVX))
1435 		setup_force_cpu_bug(X86_BUG_GDS);
1436 
1437 	if (vulnerable_to_rfds(x86_arch_cap_msr))
1438 		setup_force_cpu_bug(X86_BUG_RFDS);
1439 
1440 	/* When virtualized, eIBRS could be hidden, assume vulnerable */
1441 	if (!(x86_arch_cap_msr & ARCH_CAP_BHI_NO) &&
1442 	    !cpu_matches(cpu_vuln_whitelist, NO_BHI) &&
1443 	    (boot_cpu_has(X86_FEATURE_IBRS_ENHANCED) ||
1444 	     boot_cpu_has(X86_FEATURE_HYPERVISOR)))
1445 		setup_force_cpu_bug(X86_BUG_BHI);
1446 
1447 	if (cpu_has(c, X86_FEATURE_AMD_IBPB) && !cpu_has(c, X86_FEATURE_AMD_IBPB_RET))
1448 		setup_force_cpu_bug(X86_BUG_IBPB_NO_RET);
1449 
1450 	if (cpu_matches(cpu_vuln_whitelist, NO_MELTDOWN))
1451 		return;
1452 
1453 	/* Rogue Data Cache Load? No! */
1454 	if (x86_arch_cap_msr & ARCH_CAP_RDCL_NO)
1455 		return;
1456 
1457 	setup_force_cpu_bug(X86_BUG_CPU_MELTDOWN);
1458 
1459 	if (cpu_matches(cpu_vuln_whitelist, NO_L1TF))
1460 		return;
1461 
1462 	setup_force_cpu_bug(X86_BUG_L1TF);
1463 }
1464 
1465 /*
1466  * The NOPL instruction is supposed to exist on all CPUs of family >= 6;
1467  * unfortunately, that's not true in practice because of early VIA
1468  * chips and (more importantly) broken virtualizers that are not easy
1469  * to detect. In the latter case it doesn't even *fail* reliably, so
1470  * probing for it doesn't even work. Disable it completely on 32-bit
1471  * unless we can find a reliable way to detect all the broken cases.
1472  * Enable it explicitly on 64-bit for non-constant inputs of cpu_has().
1473  */
detect_nopl(void)1474 static void detect_nopl(void)
1475 {
1476 #ifdef CONFIG_X86_32
1477 	setup_clear_cpu_cap(X86_FEATURE_NOPL);
1478 #else
1479 	setup_force_cpu_cap(X86_FEATURE_NOPL);
1480 #endif
1481 }
1482 
1483 /*
1484  * We parse cpu parameters early because fpu__init_system() is executed
1485  * before parse_early_param().
1486  */
cpu_parse_early_param(void)1487 static void __init cpu_parse_early_param(void)
1488 {
1489 	char arg[128];
1490 	char *argptr = arg, *opt;
1491 	int arglen, taint = 0;
1492 
1493 #ifdef CONFIG_X86_32
1494 	if (cmdline_find_option_bool(boot_command_line, "no387"))
1495 #ifdef CONFIG_MATH_EMULATION
1496 		setup_clear_cpu_cap(X86_FEATURE_FPU);
1497 #else
1498 		pr_err("Option 'no387' required CONFIG_MATH_EMULATION enabled.\n");
1499 #endif
1500 
1501 	if (cmdline_find_option_bool(boot_command_line, "nofxsr"))
1502 		setup_clear_cpu_cap(X86_FEATURE_FXSR);
1503 #endif
1504 
1505 	if (cmdline_find_option_bool(boot_command_line, "noxsave"))
1506 		setup_clear_cpu_cap(X86_FEATURE_XSAVE);
1507 
1508 	if (cmdline_find_option_bool(boot_command_line, "noxsaveopt"))
1509 		setup_clear_cpu_cap(X86_FEATURE_XSAVEOPT);
1510 
1511 	if (cmdline_find_option_bool(boot_command_line, "noxsaves"))
1512 		setup_clear_cpu_cap(X86_FEATURE_XSAVES);
1513 
1514 	if (cmdline_find_option_bool(boot_command_line, "nousershstk"))
1515 		setup_clear_cpu_cap(X86_FEATURE_USER_SHSTK);
1516 
1517 	/* Minimize the gap between FRED is available and available but disabled. */
1518 	arglen = cmdline_find_option(boot_command_line, "fred", arg, sizeof(arg));
1519 	if (arglen != 2 || strncmp(arg, "on", 2))
1520 		setup_clear_cpu_cap(X86_FEATURE_FRED);
1521 
1522 	arglen = cmdline_find_option(boot_command_line, "clearcpuid", arg, sizeof(arg));
1523 	if (arglen <= 0)
1524 		return;
1525 
1526 	pr_info("Clearing CPUID bits:");
1527 
1528 	while (argptr) {
1529 		bool found __maybe_unused = false;
1530 		unsigned int bit;
1531 
1532 		opt = strsep(&argptr, ",");
1533 
1534 		/*
1535 		 * Handle naked numbers first for feature flags which don't
1536 		 * have names.
1537 		 */
1538 		if (!kstrtouint(opt, 10, &bit)) {
1539 			if (bit < NCAPINTS * 32) {
1540 
1541 				/* empty-string, i.e., ""-defined feature flags */
1542 				if (!x86_cap_flags[bit])
1543 					pr_cont(" " X86_CAP_FMT_NUM, x86_cap_flag_num(bit));
1544 				else
1545 					pr_cont(" " X86_CAP_FMT, x86_cap_flag(bit));
1546 
1547 				setup_clear_cpu_cap(bit);
1548 				taint++;
1549 			}
1550 			/*
1551 			 * The assumption is that there are no feature names with only
1552 			 * numbers in the name thus go to the next argument.
1553 			 */
1554 			continue;
1555 		}
1556 
1557 		for (bit = 0; bit < 32 * NCAPINTS; bit++) {
1558 			if (!x86_cap_flag(bit))
1559 				continue;
1560 
1561 			if (strcmp(x86_cap_flag(bit), opt))
1562 				continue;
1563 
1564 			pr_cont(" %s", opt);
1565 			setup_clear_cpu_cap(bit);
1566 			taint++;
1567 			found = true;
1568 			break;
1569 		}
1570 
1571 		if (!found)
1572 			pr_cont(" (unknown: %s)", opt);
1573 	}
1574 	pr_cont("\n");
1575 
1576 	if (taint)
1577 		add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK);
1578 }
1579 
1580 /*
1581  * Do minimum CPU detection early.
1582  * Fields really needed: vendor, cpuid_level, family, model, mask,
1583  * cache alignment.
1584  * The others are not touched to avoid unwanted side effects.
1585  *
1586  * WARNING: this function is only called on the boot CPU.  Don't add code
1587  * here that is supposed to run on all CPUs.
1588  */
early_identify_cpu(struct cpuinfo_x86 * c)1589 static void __init early_identify_cpu(struct cpuinfo_x86 *c)
1590 {
1591 	memset(&c->x86_capability, 0, sizeof(c->x86_capability));
1592 	c->extended_cpuid_level = 0;
1593 
1594 	if (!have_cpuid_p())
1595 		identify_cpu_without_cpuid(c);
1596 
1597 	/* cyrix could have cpuid enabled via c_identify()*/
1598 	if (have_cpuid_p()) {
1599 		cpu_detect(c);
1600 		get_cpu_vendor(c);
1601 		intel_unlock_cpuid_leafs(c);
1602 		get_cpu_cap(c);
1603 		setup_force_cpu_cap(X86_FEATURE_CPUID);
1604 		get_cpu_address_sizes(c);
1605 		cpu_parse_early_param();
1606 
1607 		cpu_init_topology(c);
1608 
1609 		if (this_cpu->c_early_init)
1610 			this_cpu->c_early_init(c);
1611 
1612 		c->cpu_index = 0;
1613 		filter_cpuid_features(c, false);
1614 
1615 		if (this_cpu->c_bsp_init)
1616 			this_cpu->c_bsp_init(c);
1617 	} else {
1618 		setup_clear_cpu_cap(X86_FEATURE_CPUID);
1619 		get_cpu_address_sizes(c);
1620 		cpu_init_topology(c);
1621 	}
1622 
1623 	setup_force_cpu_cap(X86_FEATURE_ALWAYS);
1624 
1625 	cpu_set_bug_bits(c);
1626 
1627 	sld_setup(c);
1628 
1629 #ifdef CONFIG_X86_32
1630 	/*
1631 	 * Regardless of whether PCID is enumerated, the SDM says
1632 	 * that it can't be enabled in 32-bit mode.
1633 	 */
1634 	setup_clear_cpu_cap(X86_FEATURE_PCID);
1635 #endif
1636 
1637 	/*
1638 	 * Later in the boot process pgtable_l5_enabled() relies on
1639 	 * cpu_feature_enabled(X86_FEATURE_LA57). If 5-level paging is not
1640 	 * enabled by this point we need to clear the feature bit to avoid
1641 	 * false-positives at the later stage.
1642 	 *
1643 	 * pgtable_l5_enabled() can be false here for several reasons:
1644 	 *  - 5-level paging is disabled compile-time;
1645 	 *  - it's 32-bit kernel;
1646 	 *  - machine doesn't support 5-level paging;
1647 	 *  - user specified 'no5lvl' in kernel command line.
1648 	 */
1649 	if (!pgtable_l5_enabled())
1650 		setup_clear_cpu_cap(X86_FEATURE_LA57);
1651 
1652 	detect_nopl();
1653 }
1654 
early_cpu_init(void)1655 void __init early_cpu_init(void)
1656 {
1657 	const struct cpu_dev *const *cdev;
1658 	int count = 0;
1659 
1660 #ifdef CONFIG_PROCESSOR_SELECT
1661 	pr_info("KERNEL supported cpus:\n");
1662 #endif
1663 
1664 	for (cdev = __x86_cpu_dev_start; cdev < __x86_cpu_dev_end; cdev++) {
1665 		const struct cpu_dev *cpudev = *cdev;
1666 
1667 		if (count >= X86_VENDOR_NUM)
1668 			break;
1669 		cpu_devs[count] = cpudev;
1670 		count++;
1671 
1672 #ifdef CONFIG_PROCESSOR_SELECT
1673 		{
1674 			unsigned int j;
1675 
1676 			for (j = 0; j < 2; j++) {
1677 				if (!cpudev->c_ident[j])
1678 					continue;
1679 				pr_info("  %s %s\n", cpudev->c_vendor,
1680 					cpudev->c_ident[j]);
1681 			}
1682 		}
1683 #endif
1684 	}
1685 	early_identify_cpu(&boot_cpu_data);
1686 }
1687 
detect_null_seg_behavior(void)1688 static bool detect_null_seg_behavior(void)
1689 {
1690 	/*
1691 	 * Empirically, writing zero to a segment selector on AMD does
1692 	 * not clear the base, whereas writing zero to a segment
1693 	 * selector on Intel does clear the base.  Intel's behavior
1694 	 * allows slightly faster context switches in the common case
1695 	 * where GS is unused by the prev and next threads.
1696 	 *
1697 	 * Since neither vendor documents this anywhere that I can see,
1698 	 * detect it directly instead of hard-coding the choice by
1699 	 * vendor.
1700 	 *
1701 	 * I've designated AMD's behavior as the "bug" because it's
1702 	 * counterintuitive and less friendly.
1703 	 */
1704 
1705 	unsigned long old_base, tmp;
1706 	rdmsrl(MSR_FS_BASE, old_base);
1707 	wrmsrl(MSR_FS_BASE, 1);
1708 	loadsegment(fs, 0);
1709 	rdmsrl(MSR_FS_BASE, tmp);
1710 	wrmsrl(MSR_FS_BASE, old_base);
1711 	return tmp == 0;
1712 }
1713 
check_null_seg_clears_base(struct cpuinfo_x86 * c)1714 void check_null_seg_clears_base(struct cpuinfo_x86 *c)
1715 {
1716 	/* BUG_NULL_SEG is only relevant with 64bit userspace */
1717 	if (!IS_ENABLED(CONFIG_X86_64))
1718 		return;
1719 
1720 	if (cpu_has(c, X86_FEATURE_NULL_SEL_CLR_BASE))
1721 		return;
1722 
1723 	/*
1724 	 * CPUID bit above wasn't set. If this kernel is still running
1725 	 * as a HV guest, then the HV has decided not to advertize
1726 	 * that CPUID bit for whatever reason.	For example, one
1727 	 * member of the migration pool might be vulnerable.  Which
1728 	 * means, the bug is present: set the BUG flag and return.
1729 	 */
1730 	if (cpu_has(c, X86_FEATURE_HYPERVISOR)) {
1731 		set_cpu_bug(c, X86_BUG_NULL_SEG);
1732 		return;
1733 	}
1734 
1735 	/*
1736 	 * Zen2 CPUs also have this behaviour, but no CPUID bit.
1737 	 * 0x18 is the respective family for Hygon.
1738 	 */
1739 	if ((c->x86 == 0x17 || c->x86 == 0x18) &&
1740 	    detect_null_seg_behavior())
1741 		return;
1742 
1743 	/* All the remaining ones are affected */
1744 	set_cpu_bug(c, X86_BUG_NULL_SEG);
1745 }
1746 
generic_identify(struct cpuinfo_x86 * c)1747 static void generic_identify(struct cpuinfo_x86 *c)
1748 {
1749 	c->extended_cpuid_level = 0;
1750 
1751 	if (!have_cpuid_p())
1752 		identify_cpu_without_cpuid(c);
1753 
1754 	/* cyrix could have cpuid enabled via c_identify()*/
1755 	if (!have_cpuid_p())
1756 		return;
1757 
1758 	cpu_detect(c);
1759 
1760 	get_cpu_vendor(c);
1761 	intel_unlock_cpuid_leafs(c);
1762 	get_cpu_cap(c);
1763 
1764 	get_cpu_address_sizes(c);
1765 
1766 	get_model_name(c); /* Default name */
1767 
1768 	/*
1769 	 * ESPFIX is a strange bug.  All real CPUs have it.  Paravirt
1770 	 * systems that run Linux at CPL > 0 may or may not have the
1771 	 * issue, but, even if they have the issue, there's absolutely
1772 	 * nothing we can do about it because we can't use the real IRET
1773 	 * instruction.
1774 	 *
1775 	 * NB: For the time being, only 32-bit kernels support
1776 	 * X86_BUG_ESPFIX as such.  64-bit kernels directly choose
1777 	 * whether to apply espfix using paravirt hooks.  If any
1778 	 * non-paravirt system ever shows up that does *not* have the
1779 	 * ESPFIX issue, we can change this.
1780 	 */
1781 #ifdef CONFIG_X86_32
1782 	set_cpu_bug(c, X86_BUG_ESPFIX);
1783 #endif
1784 }
1785 
1786 /*
1787  * This does the hard work of actually picking apart the CPU stuff...
1788  */
identify_cpu(struct cpuinfo_x86 * c)1789 static void identify_cpu(struct cpuinfo_x86 *c)
1790 {
1791 	int i;
1792 
1793 	c->loops_per_jiffy = loops_per_jiffy;
1794 	c->x86_cache_size = 0;
1795 	c->x86_vendor = X86_VENDOR_UNKNOWN;
1796 	c->x86_model = c->x86_stepping = 0;	/* So far unknown... */
1797 	c->x86_vendor_id[0] = '\0'; /* Unset */
1798 	c->x86_model_id[0] = '\0';  /* Unset */
1799 #ifdef CONFIG_X86_64
1800 	c->x86_clflush_size = 64;
1801 	c->x86_phys_bits = 36;
1802 	c->x86_virt_bits = 48;
1803 #else
1804 	c->cpuid_level = -1;	/* CPUID not detected */
1805 	c->x86_clflush_size = 32;
1806 	c->x86_phys_bits = 32;
1807 	c->x86_virt_bits = 32;
1808 #endif
1809 	c->x86_cache_alignment = c->x86_clflush_size;
1810 	memset(&c->x86_capability, 0, sizeof(c->x86_capability));
1811 #ifdef CONFIG_X86_VMX_FEATURE_NAMES
1812 	memset(&c->vmx_capability, 0, sizeof(c->vmx_capability));
1813 #endif
1814 
1815 	generic_identify(c);
1816 
1817 	cpu_parse_topology(c);
1818 
1819 	if (this_cpu->c_identify)
1820 		this_cpu->c_identify(c);
1821 
1822 	/* Clear/Set all flags overridden by options, after probe */
1823 	apply_forced_caps(c);
1824 
1825 	/*
1826 	 * Set default APIC and TSC_DEADLINE MSR fencing flag. AMD and
1827 	 * Hygon will clear it in ->c_init() below.
1828 	 */
1829 	set_cpu_cap(c, X86_FEATURE_APIC_MSRS_FENCE);
1830 
1831 	/*
1832 	 * Vendor-specific initialization.  In this section we
1833 	 * canonicalize the feature flags, meaning if there are
1834 	 * features a certain CPU supports which CPUID doesn't
1835 	 * tell us, CPUID claiming incorrect flags, or other bugs,
1836 	 * we handle them here.
1837 	 *
1838 	 * At the end of this section, c->x86_capability better
1839 	 * indicate the features this CPU genuinely supports!
1840 	 */
1841 	if (this_cpu->c_init)
1842 		this_cpu->c_init(c);
1843 
1844 	/* Disable the PN if appropriate */
1845 	squash_the_stupid_serial_number(c);
1846 
1847 	/* Set up SMEP/SMAP/UMIP */
1848 	setup_smep(c);
1849 	setup_smap(c);
1850 	setup_umip(c);
1851 
1852 	/* Enable FSGSBASE instructions if available. */
1853 	if (cpu_has(c, X86_FEATURE_FSGSBASE)) {
1854 		cr4_set_bits(X86_CR4_FSGSBASE);
1855 		elf_hwcap2 |= HWCAP2_FSGSBASE;
1856 	}
1857 
1858 	/*
1859 	 * The vendor-specific functions might have changed features.
1860 	 * Now we do "generic changes."
1861 	 */
1862 
1863 	/* Filter out anything that depends on CPUID levels we don't have */
1864 	filter_cpuid_features(c, true);
1865 
1866 	/* If the model name is still unset, do table lookup. */
1867 	if (!c->x86_model_id[0]) {
1868 		const char *p;
1869 		p = table_lookup_model(c);
1870 		if (p)
1871 			strcpy(c->x86_model_id, p);
1872 		else
1873 			/* Last resort... */
1874 			sprintf(c->x86_model_id, "%02x/%02x",
1875 				c->x86, c->x86_model);
1876 	}
1877 
1878 	x86_init_rdrand(c);
1879 	setup_pku(c);
1880 	setup_cet(c);
1881 
1882 	/*
1883 	 * Clear/Set all flags overridden by options, need do it
1884 	 * before following smp all cpus cap AND.
1885 	 */
1886 	apply_forced_caps(c);
1887 
1888 	/*
1889 	 * On SMP, boot_cpu_data holds the common feature set between
1890 	 * all CPUs; so make sure that we indicate which features are
1891 	 * common between the CPUs.  The first time this routine gets
1892 	 * executed, c == &boot_cpu_data.
1893 	 */
1894 	if (c != &boot_cpu_data) {
1895 		/* AND the already accumulated flags with these */
1896 		for (i = 0; i < NCAPINTS; i++)
1897 			boot_cpu_data.x86_capability[i] &= c->x86_capability[i];
1898 
1899 		/* OR, i.e. replicate the bug flags */
1900 		for (i = NCAPINTS; i < NCAPINTS + NBUGINTS; i++)
1901 			c->x86_capability[i] |= boot_cpu_data.x86_capability[i];
1902 	}
1903 
1904 	ppin_init(c);
1905 
1906 	/* Init Machine Check Exception if available. */
1907 	mcheck_cpu_init(c);
1908 
1909 #ifdef CONFIG_NUMA
1910 	numa_add_cpu(smp_processor_id());
1911 #endif
1912 }
1913 
1914 /*
1915  * Set up the CPU state needed to execute SYSENTER/SYSEXIT instructions
1916  * on 32-bit kernels:
1917  */
1918 #ifdef CONFIG_X86_32
enable_sep_cpu(void)1919 void enable_sep_cpu(void)
1920 {
1921 	struct tss_struct *tss;
1922 	int cpu;
1923 
1924 	if (!boot_cpu_has(X86_FEATURE_SEP))
1925 		return;
1926 
1927 	cpu = get_cpu();
1928 	tss = &per_cpu(cpu_tss_rw, cpu);
1929 
1930 	/*
1931 	 * We cache MSR_IA32_SYSENTER_CS's value in the TSS's ss1 field --
1932 	 * see the big comment in struct x86_hw_tss's definition.
1933 	 */
1934 
1935 	tss->x86_tss.ss1 = __KERNEL_CS;
1936 	wrmsr(MSR_IA32_SYSENTER_CS, tss->x86_tss.ss1, 0);
1937 	wrmsr(MSR_IA32_SYSENTER_ESP, (unsigned long)(cpu_entry_stack(cpu) + 1), 0);
1938 	wrmsr(MSR_IA32_SYSENTER_EIP, (unsigned long)entry_SYSENTER_32, 0);
1939 
1940 	put_cpu();
1941 }
1942 #endif
1943 
identify_boot_cpu(void)1944 static __init void identify_boot_cpu(void)
1945 {
1946 	identify_cpu(&boot_cpu_data);
1947 	if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT))
1948 		pr_info("CET detected: Indirect Branch Tracking enabled\n");
1949 #ifdef CONFIG_X86_32
1950 	enable_sep_cpu();
1951 #endif
1952 	cpu_detect_tlb(&boot_cpu_data);
1953 	setup_cr_pinning();
1954 
1955 	tsx_init();
1956 	tdx_init();
1957 	lkgs_init();
1958 }
1959 
identify_secondary_cpu(struct cpuinfo_x86 * c)1960 void identify_secondary_cpu(struct cpuinfo_x86 *c)
1961 {
1962 	BUG_ON(c == &boot_cpu_data);
1963 	identify_cpu(c);
1964 #ifdef CONFIG_X86_32
1965 	enable_sep_cpu();
1966 #endif
1967 	x86_spec_ctrl_setup_ap();
1968 	update_srbds_msr();
1969 	if (boot_cpu_has_bug(X86_BUG_GDS))
1970 		update_gds_msr();
1971 
1972 	tsx_ap_init();
1973 }
1974 
print_cpu_info(struct cpuinfo_x86 * c)1975 void print_cpu_info(struct cpuinfo_x86 *c)
1976 {
1977 	const char *vendor = NULL;
1978 
1979 	if (c->x86_vendor < X86_VENDOR_NUM) {
1980 		vendor = this_cpu->c_vendor;
1981 	} else {
1982 		if (c->cpuid_level >= 0)
1983 			vendor = c->x86_vendor_id;
1984 	}
1985 
1986 	if (vendor && !strstr(c->x86_model_id, vendor))
1987 		pr_cont("%s ", vendor);
1988 
1989 	if (c->x86_model_id[0])
1990 		pr_cont("%s", c->x86_model_id);
1991 	else
1992 		pr_cont("%d86", c->x86);
1993 
1994 	pr_cont(" (family: 0x%x, model: 0x%x", c->x86, c->x86_model);
1995 
1996 	if (c->x86_stepping || c->cpuid_level >= 0)
1997 		pr_cont(", stepping: 0x%x)\n", c->x86_stepping);
1998 	else
1999 		pr_cont(")\n");
2000 }
2001 
2002 /*
2003  * clearcpuid= was already parsed in cpu_parse_early_param().  This dummy
2004  * function prevents it from becoming an environment variable for init.
2005  */
setup_clearcpuid(char * arg)2006 static __init int setup_clearcpuid(char *arg)
2007 {
2008 	return 1;
2009 }
2010 __setup("clearcpuid=", setup_clearcpuid);
2011 
2012 DEFINE_PER_CPU_ALIGNED(struct pcpu_hot, pcpu_hot) = {
2013 	.current_task	= &init_task,
2014 	.preempt_count	= INIT_PREEMPT_COUNT,
2015 	.top_of_stack	= TOP_OF_INIT_STACK,
2016 };
2017 EXPORT_PER_CPU_SYMBOL(pcpu_hot);
2018 EXPORT_PER_CPU_SYMBOL(const_pcpu_hot);
2019 
2020 #ifdef CONFIG_X86_64
2021 DEFINE_PER_CPU_FIRST(struct fixed_percpu_data,
2022 		     fixed_percpu_data) __aligned(PAGE_SIZE) __visible;
2023 EXPORT_PER_CPU_SYMBOL_GPL(fixed_percpu_data);
2024 
wrmsrl_cstar(unsigned long val)2025 static void wrmsrl_cstar(unsigned long val)
2026 {
2027 	/*
2028 	 * Intel CPUs do not support 32-bit SYSCALL. Writing to MSR_CSTAR
2029 	 * is so far ignored by the CPU, but raises a #VE trap in a TDX
2030 	 * guest. Avoid the pointless write on all Intel CPUs.
2031 	 */
2032 	if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
2033 		wrmsrl(MSR_CSTAR, val);
2034 }
2035 
idt_syscall_init(void)2036 static inline void idt_syscall_init(void)
2037 {
2038 	wrmsrl(MSR_LSTAR, (unsigned long)entry_SYSCALL_64);
2039 
2040 	if (ia32_enabled()) {
2041 		wrmsrl_cstar((unsigned long)entry_SYSCALL_compat);
2042 		/*
2043 		 * This only works on Intel CPUs.
2044 		 * On AMD CPUs these MSRs are 32-bit, CPU truncates MSR_IA32_SYSENTER_EIP.
2045 		 * This does not cause SYSENTER to jump to the wrong location, because
2046 		 * AMD doesn't allow SYSENTER in long mode (either 32- or 64-bit).
2047 		 */
2048 		wrmsrl_safe(MSR_IA32_SYSENTER_CS, (u64)__KERNEL_CS);
2049 		wrmsrl_safe(MSR_IA32_SYSENTER_ESP,
2050 			    (unsigned long)(cpu_entry_stack(smp_processor_id()) + 1));
2051 		wrmsrl_safe(MSR_IA32_SYSENTER_EIP, (u64)entry_SYSENTER_compat);
2052 	} else {
2053 		wrmsrl_cstar((unsigned long)entry_SYSCALL32_ignore);
2054 		wrmsrl_safe(MSR_IA32_SYSENTER_CS, (u64)GDT_ENTRY_INVALID_SEG);
2055 		wrmsrl_safe(MSR_IA32_SYSENTER_ESP, 0ULL);
2056 		wrmsrl_safe(MSR_IA32_SYSENTER_EIP, 0ULL);
2057 	}
2058 
2059 	/*
2060 	 * Flags to clear on syscall; clear as much as possible
2061 	 * to minimize user space-kernel interference.
2062 	 */
2063 	wrmsrl(MSR_SYSCALL_MASK,
2064 	       X86_EFLAGS_CF|X86_EFLAGS_PF|X86_EFLAGS_AF|
2065 	       X86_EFLAGS_ZF|X86_EFLAGS_SF|X86_EFLAGS_TF|
2066 	       X86_EFLAGS_IF|X86_EFLAGS_DF|X86_EFLAGS_OF|
2067 	       X86_EFLAGS_IOPL|X86_EFLAGS_NT|X86_EFLAGS_RF|
2068 	       X86_EFLAGS_AC|X86_EFLAGS_ID);
2069 }
2070 
2071 /* May not be marked __init: used by software suspend */
syscall_init(void)2072 void syscall_init(void)
2073 {
2074 	/* The default user and kernel segments */
2075 	wrmsr(MSR_STAR, 0, (__USER32_CS << 16) | __KERNEL_CS);
2076 
2077 	/*
2078 	 * Except the IA32_STAR MSR, there is NO need to setup SYSCALL and
2079 	 * SYSENTER MSRs for FRED, because FRED uses the ring 3 FRED
2080 	 * entrypoint for SYSCALL and SYSENTER, and ERETU is the only legit
2081 	 * instruction to return to ring 3 (both sysexit and sysret cause
2082 	 * #UD when FRED is enabled).
2083 	 */
2084 	if (!cpu_feature_enabled(X86_FEATURE_FRED))
2085 		idt_syscall_init();
2086 }
2087 
2088 #else	/* CONFIG_X86_64 */
2089 
2090 #ifdef CONFIG_STACKPROTECTOR
2091 DEFINE_PER_CPU(unsigned long, __stack_chk_guard);
2092 EXPORT_PER_CPU_SYMBOL(__stack_chk_guard);
2093 #endif
2094 
2095 #endif	/* CONFIG_X86_64 */
2096 
2097 /*
2098  * Clear all 6 debug registers:
2099  */
clear_all_debug_regs(void)2100 static void clear_all_debug_regs(void)
2101 {
2102 	int i;
2103 
2104 	for (i = 0; i < 8; i++) {
2105 		/* Ignore db4, db5 */
2106 		if ((i == 4) || (i == 5))
2107 			continue;
2108 
2109 		set_debugreg(0, i);
2110 	}
2111 }
2112 
2113 #ifdef CONFIG_KGDB
2114 /*
2115  * Restore debug regs if using kgdbwait and you have a kernel debugger
2116  * connection established.
2117  */
dbg_restore_debug_regs(void)2118 static void dbg_restore_debug_regs(void)
2119 {
2120 	if (unlikely(kgdb_connected && arch_kgdb_ops.correct_hw_break))
2121 		arch_kgdb_ops.correct_hw_break();
2122 }
2123 #else /* ! CONFIG_KGDB */
2124 #define dbg_restore_debug_regs()
2125 #endif /* ! CONFIG_KGDB */
2126 
setup_getcpu(int cpu)2127 static inline void setup_getcpu(int cpu)
2128 {
2129 	unsigned long cpudata = vdso_encode_cpunode(cpu, early_cpu_to_node(cpu));
2130 	struct desc_struct d = { };
2131 
2132 	if (boot_cpu_has(X86_FEATURE_RDTSCP) || boot_cpu_has(X86_FEATURE_RDPID))
2133 		wrmsr(MSR_TSC_AUX, cpudata, 0);
2134 
2135 	/* Store CPU and node number in limit. */
2136 	d.limit0 = cpudata;
2137 	d.limit1 = cpudata >> 16;
2138 
2139 	d.type = 5;		/* RO data, expand down, accessed */
2140 	d.dpl = 3;		/* Visible to user code */
2141 	d.s = 1;		/* Not a system segment */
2142 	d.p = 1;		/* Present */
2143 	d.d = 1;		/* 32-bit */
2144 
2145 	write_gdt_entry(get_cpu_gdt_rw(cpu), GDT_ENTRY_CPUNODE, &d, DESCTYPE_S);
2146 }
2147 
2148 #ifdef CONFIG_X86_64
tss_setup_ist(struct tss_struct * tss)2149 static inline void tss_setup_ist(struct tss_struct *tss)
2150 {
2151 	/* Set up the per-CPU TSS IST stacks */
2152 	tss->x86_tss.ist[IST_INDEX_DF] = __this_cpu_ist_top_va(DF);
2153 	tss->x86_tss.ist[IST_INDEX_NMI] = __this_cpu_ist_top_va(NMI);
2154 	tss->x86_tss.ist[IST_INDEX_DB] = __this_cpu_ist_top_va(DB);
2155 	tss->x86_tss.ist[IST_INDEX_MCE] = __this_cpu_ist_top_va(MCE);
2156 	/* Only mapped when SEV-ES is active */
2157 	tss->x86_tss.ist[IST_INDEX_VC] = __this_cpu_ist_top_va(VC);
2158 }
2159 #else /* CONFIG_X86_64 */
tss_setup_ist(struct tss_struct * tss)2160 static inline void tss_setup_ist(struct tss_struct *tss) { }
2161 #endif /* !CONFIG_X86_64 */
2162 
tss_setup_io_bitmap(struct tss_struct * tss)2163 static inline void tss_setup_io_bitmap(struct tss_struct *tss)
2164 {
2165 	tss->x86_tss.io_bitmap_base = IO_BITMAP_OFFSET_INVALID;
2166 
2167 #ifdef CONFIG_X86_IOPL_IOPERM
2168 	tss->io_bitmap.prev_max = 0;
2169 	tss->io_bitmap.prev_sequence = 0;
2170 	memset(tss->io_bitmap.bitmap, 0xff, sizeof(tss->io_bitmap.bitmap));
2171 	/*
2172 	 * Invalidate the extra array entry past the end of the all
2173 	 * permission bitmap as required by the hardware.
2174 	 */
2175 	tss->io_bitmap.mapall[IO_BITMAP_LONGS] = ~0UL;
2176 #endif
2177 }
2178 
2179 /*
2180  * Setup everything needed to handle exceptions from the IDT, including the IST
2181  * exceptions which use paranoid_entry().
2182  */
cpu_init_exception_handling(bool boot_cpu)2183 void cpu_init_exception_handling(bool boot_cpu)
2184 {
2185 	struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw);
2186 	int cpu = raw_smp_processor_id();
2187 
2188 	/* paranoid_entry() gets the CPU number from the GDT */
2189 	setup_getcpu(cpu);
2190 
2191 	/* For IDT mode, IST vectors need to be set in TSS. */
2192 	if (!cpu_feature_enabled(X86_FEATURE_FRED))
2193 		tss_setup_ist(tss);
2194 	tss_setup_io_bitmap(tss);
2195 	set_tss_desc(cpu, &get_cpu_entry_area(cpu)->tss.x86_tss);
2196 
2197 	load_TR_desc();
2198 
2199 	/* GHCB needs to be setup to handle #VC. */
2200 	setup_ghcb();
2201 
2202 	if (cpu_feature_enabled(X86_FEATURE_FRED)) {
2203 		/* The boot CPU has enabled FRED during early boot */
2204 		if (!boot_cpu)
2205 			cpu_init_fred_exceptions();
2206 
2207 		cpu_init_fred_rsps();
2208 	} else {
2209 		load_current_idt();
2210 	}
2211 }
2212 
cpu_init_replace_early_idt(void)2213 void __init cpu_init_replace_early_idt(void)
2214 {
2215 	if (cpu_feature_enabled(X86_FEATURE_FRED))
2216 		cpu_init_fred_exceptions();
2217 	else
2218 		idt_setup_early_pf();
2219 }
2220 
2221 /*
2222  * cpu_init() initializes state that is per-CPU. Some data is already
2223  * initialized (naturally) in the bootstrap process, such as the GDT.  We
2224  * reload it nevertheless, this function acts as a 'CPU state barrier',
2225  * nothing should get across.
2226  */
cpu_init(void)2227 void cpu_init(void)
2228 {
2229 	struct task_struct *cur = current;
2230 	int cpu = raw_smp_processor_id();
2231 
2232 #ifdef CONFIG_NUMA
2233 	if (this_cpu_read(numa_node) == 0 &&
2234 	    early_cpu_to_node(cpu) != NUMA_NO_NODE)
2235 		set_numa_node(early_cpu_to_node(cpu));
2236 #endif
2237 	pr_debug("Initializing CPU#%d\n", cpu);
2238 
2239 	if (IS_ENABLED(CONFIG_X86_64) || cpu_feature_enabled(X86_FEATURE_VME) ||
2240 	    boot_cpu_has(X86_FEATURE_TSC) || boot_cpu_has(X86_FEATURE_DE))
2241 		cr4_clear_bits(X86_CR4_VME|X86_CR4_PVI|X86_CR4_TSD|X86_CR4_DE);
2242 
2243 	if (IS_ENABLED(CONFIG_X86_64)) {
2244 		loadsegment(fs, 0);
2245 		memset(cur->thread.tls_array, 0, GDT_ENTRY_TLS_ENTRIES * 8);
2246 		syscall_init();
2247 
2248 		wrmsrl(MSR_FS_BASE, 0);
2249 		wrmsrl(MSR_KERNEL_GS_BASE, 0);
2250 		barrier();
2251 
2252 		x2apic_setup();
2253 
2254 		intel_posted_msi_init();
2255 	}
2256 
2257 	mmgrab(&init_mm);
2258 	cur->active_mm = &init_mm;
2259 	BUG_ON(cur->mm);
2260 	initialize_tlbstate_and_flush();
2261 	enter_lazy_tlb(&init_mm, cur);
2262 
2263 	/*
2264 	 * sp0 points to the entry trampoline stack regardless of what task
2265 	 * is running.
2266 	 */
2267 	load_sp0((unsigned long)(cpu_entry_stack(cpu) + 1));
2268 
2269 	load_mm_ldt(&init_mm);
2270 
2271 	clear_all_debug_regs();
2272 	dbg_restore_debug_regs();
2273 
2274 	doublefault_init_cpu_tss();
2275 
2276 	if (is_uv_system())
2277 		uv_cpu_init();
2278 
2279 	load_fixmap_gdt(cpu);
2280 }
2281 
2282 #ifdef CONFIG_MICROCODE_LATE_LOADING
2283 /**
2284  * store_cpu_caps() - Store a snapshot of CPU capabilities
2285  * @curr_info: Pointer where to store it
2286  *
2287  * Returns: None
2288  */
store_cpu_caps(struct cpuinfo_x86 * curr_info)2289 void store_cpu_caps(struct cpuinfo_x86 *curr_info)
2290 {
2291 	/* Reload CPUID max function as it might've changed. */
2292 	curr_info->cpuid_level = cpuid_eax(0);
2293 
2294 	/* Copy all capability leafs and pick up the synthetic ones. */
2295 	memcpy(&curr_info->x86_capability, &boot_cpu_data.x86_capability,
2296 	       sizeof(curr_info->x86_capability));
2297 
2298 	/* Get the hardware CPUID leafs */
2299 	get_cpu_cap(curr_info);
2300 }
2301 
2302 /**
2303  * microcode_check() - Check if any CPU capabilities changed after an update.
2304  * @prev_info:	CPU capabilities stored before an update.
2305  *
2306  * The microcode loader calls this upon late microcode load to recheck features,
2307  * only when microcode has been updated. Caller holds and CPU hotplug lock.
2308  *
2309  * Return: None
2310  */
microcode_check(struct cpuinfo_x86 * prev_info)2311 void microcode_check(struct cpuinfo_x86 *prev_info)
2312 {
2313 	struct cpuinfo_x86 curr_info;
2314 
2315 	perf_check_microcode();
2316 
2317 	amd_check_microcode();
2318 
2319 	store_cpu_caps(&curr_info);
2320 
2321 	if (!memcmp(&prev_info->x86_capability, &curr_info.x86_capability,
2322 		    sizeof(prev_info->x86_capability)))
2323 		return;
2324 
2325 	pr_warn("x86/CPU: CPU features have changed after loading microcode, but might not take effect.\n");
2326 	pr_warn("x86/CPU: Please consider either early loading through initrd/built-in or a potential BIOS update.\n");
2327 }
2328 #endif
2329 
2330 /*
2331  * Invoked from core CPU hotplug code after hotplug operations
2332  */
arch_smt_update(void)2333 void arch_smt_update(void)
2334 {
2335 	/* Handle the speculative execution misfeatures */
2336 	cpu_bugs_smt_update();
2337 	/* Check whether IPI broadcasting can be enabled */
2338 	apic_smt_update();
2339 }
2340 
arch_cpu_finalize_init(void)2341 void __init arch_cpu_finalize_init(void)
2342 {
2343 	struct cpuinfo_x86 *c = this_cpu_ptr(&cpu_info);
2344 
2345 	identify_boot_cpu();
2346 
2347 	select_idle_routine();
2348 
2349 	/*
2350 	 * identify_boot_cpu() initialized SMT support information, let the
2351 	 * core code know.
2352 	 */
2353 	cpu_smt_set_num_threads(__max_threads_per_core, __max_threads_per_core);
2354 
2355 	if (!IS_ENABLED(CONFIG_SMP)) {
2356 		pr_info("CPU: ");
2357 		print_cpu_info(&boot_cpu_data);
2358 	}
2359 
2360 	cpu_select_mitigations();
2361 
2362 	arch_smt_update();
2363 
2364 	if (IS_ENABLED(CONFIG_X86_32)) {
2365 		/*
2366 		 * Check whether this is a real i386 which is not longer
2367 		 * supported and fixup the utsname.
2368 		 */
2369 		if (boot_cpu_data.x86 < 4)
2370 			panic("Kernel requires i486+ for 'invlpg' and other features");
2371 
2372 		init_utsname()->machine[1] =
2373 			'0' + (boot_cpu_data.x86 > 6 ? 6 : boot_cpu_data.x86);
2374 	}
2375 
2376 	/*
2377 	 * Must be before alternatives because it might set or clear
2378 	 * feature bits.
2379 	 */
2380 	fpu__init_system();
2381 	fpu__init_cpu();
2382 
2383 	/*
2384 	 * Ensure that access to the per CPU representation has the initial
2385 	 * boot CPU configuration.
2386 	 */
2387 	*c = boot_cpu_data;
2388 	c->initialized = true;
2389 
2390 	alternative_instructions();
2391 
2392 	if (IS_ENABLED(CONFIG_X86_64)) {
2393 		unsigned long USER_PTR_MAX = TASK_SIZE_MAX-1;
2394 
2395 		/*
2396 		 * Enable this when LAM is gated on LASS support
2397 		if (cpu_feature_enabled(X86_FEATURE_LAM))
2398 			USER_PTR_MAX = (1ul << 63) - PAGE_SIZE - 1;
2399 		 */
2400 		runtime_const_init(ptr, USER_PTR_MAX);
2401 
2402 		/*
2403 		 * Make sure the first 2MB area is not mapped by huge pages
2404 		 * There are typically fixed size MTRRs in there and overlapping
2405 		 * MTRRs into large pages causes slow downs.
2406 		 *
2407 		 * Right now we don't do that with gbpages because there seems
2408 		 * very little benefit for that case.
2409 		 */
2410 		if (!direct_gbpages)
2411 			set_memory_4k((unsigned long)__va(0), 1);
2412 	} else {
2413 		fpu__init_check_bugs();
2414 	}
2415 
2416 	/*
2417 	 * This needs to be called before any devices perform DMA
2418 	 * operations that might use the SWIOTLB bounce buffers. It will
2419 	 * mark the bounce buffers as decrypted so that their usage will
2420 	 * not cause "plain-text" data to be decrypted when accessed. It
2421 	 * must be called after late_time_init() so that Hyper-V x86/x64
2422 	 * hypercalls work when the SWIOTLB bounce buffers are decrypted.
2423 	 */
2424 	mem_encrypt_init();
2425 }
2426