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