xref: /linux/arch/x86/kernel/cpu/common.c (revision 720c857907530e6cdc86c9bc1102ea6b372fbfb6)
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 	if ((ia32_cap & ARCH_CAP_IBRS_ALL) || cpu_has(c, X86_FEATURE_AUTOIBRS)) {
1314 		setup_force_cpu_cap(X86_FEATURE_IBRS_ENHANCED);
1315 		if (!cpu_matches(cpu_vuln_whitelist, NO_EIBRS_PBRSB) &&
1316 		    !(ia32_cap & ARCH_CAP_PBRSB_NO))
1317 			setup_force_cpu_bug(X86_BUG_EIBRS_PBRSB);
1318 	}
1319 
1320 	if (!cpu_matches(cpu_vuln_whitelist, NO_MDS) &&
1321 	    !(ia32_cap & ARCH_CAP_MDS_NO)) {
1322 		setup_force_cpu_bug(X86_BUG_MDS);
1323 		if (cpu_matches(cpu_vuln_whitelist, MSBDS_ONLY))
1324 			setup_force_cpu_bug(X86_BUG_MSBDS_ONLY);
1325 	}
1326 
1327 	if (!cpu_matches(cpu_vuln_whitelist, NO_SWAPGS))
1328 		setup_force_cpu_bug(X86_BUG_SWAPGS);
1329 
1330 	/*
1331 	 * When the CPU is not mitigated for TAA (TAA_NO=0) set TAA bug when:
1332 	 *	- TSX is supported or
1333 	 *	- TSX_CTRL is present
1334 	 *
1335 	 * TSX_CTRL check is needed for cases when TSX could be disabled before
1336 	 * the kernel boot e.g. kexec.
1337 	 * TSX_CTRL check alone is not sufficient for cases when the microcode
1338 	 * update is not present or running as guest that don't get TSX_CTRL.
1339 	 */
1340 	if (!(ia32_cap & ARCH_CAP_TAA_NO) &&
1341 	    (cpu_has(c, X86_FEATURE_RTM) ||
1342 	     (ia32_cap & ARCH_CAP_TSX_CTRL_MSR)))
1343 		setup_force_cpu_bug(X86_BUG_TAA);
1344 
1345 	/*
1346 	 * SRBDS affects CPUs which support RDRAND or RDSEED and are listed
1347 	 * in the vulnerability blacklist.
1348 	 *
1349 	 * Some of the implications and mitigation of Shared Buffers Data
1350 	 * Sampling (SBDS) are similar to SRBDS. Give SBDS same treatment as
1351 	 * SRBDS.
1352 	 */
1353 	if ((cpu_has(c, X86_FEATURE_RDRAND) ||
1354 	     cpu_has(c, X86_FEATURE_RDSEED)) &&
1355 	    cpu_matches(cpu_vuln_blacklist, SRBDS | MMIO_SBDS))
1356 		    setup_force_cpu_bug(X86_BUG_SRBDS);
1357 
1358 	/*
1359 	 * Processor MMIO Stale Data bug enumeration
1360 	 *
1361 	 * Affected CPU list is generally enough to enumerate the vulnerability,
1362 	 * but for virtualization case check for ARCH_CAP MSR bits also, VMM may
1363 	 * not want the guest to enumerate the bug.
1364 	 *
1365 	 * Set X86_BUG_MMIO_UNKNOWN for CPUs that are neither in the blacklist,
1366 	 * nor in the whitelist and also don't enumerate MSR ARCH_CAP MMIO bits.
1367 	 */
1368 	if (!arch_cap_mmio_immune(ia32_cap)) {
1369 		if (cpu_matches(cpu_vuln_blacklist, MMIO))
1370 			setup_force_cpu_bug(X86_BUG_MMIO_STALE_DATA);
1371 		else if (!cpu_matches(cpu_vuln_whitelist, NO_MMIO))
1372 			setup_force_cpu_bug(X86_BUG_MMIO_UNKNOWN);
1373 	}
1374 
1375 	if (!cpu_has(c, X86_FEATURE_BTC_NO)) {
1376 		if (cpu_matches(cpu_vuln_blacklist, RETBLEED) || (ia32_cap & ARCH_CAP_RSBA))
1377 			setup_force_cpu_bug(X86_BUG_RETBLEED);
1378 	}
1379 
1380 	if (cpu_matches(cpu_vuln_blacklist, SMT_RSB))
1381 		setup_force_cpu_bug(X86_BUG_SMT_RSB);
1382 
1383 	if (!cpu_has(c, X86_FEATURE_SRSO_NO)) {
1384 		if (cpu_matches(cpu_vuln_blacklist, SRSO))
1385 			setup_force_cpu_bug(X86_BUG_SRSO);
1386 	}
1387 
1388 	/*
1389 	 * Check if CPU is vulnerable to GDS. If running in a virtual machine on
1390 	 * an affected processor, the VMM may have disabled the use of GATHER by
1391 	 * disabling AVX2. The only way to do this in HW is to clear XCR0[2],
1392 	 * which means that AVX will be disabled.
1393 	 */
1394 	if (cpu_matches(cpu_vuln_blacklist, GDS) && !(ia32_cap & ARCH_CAP_GDS_NO) &&
1395 	    boot_cpu_has(X86_FEATURE_AVX))
1396 		setup_force_cpu_bug(X86_BUG_GDS);
1397 
1398 	if (cpu_matches(cpu_vuln_whitelist, NO_MELTDOWN))
1399 		return;
1400 
1401 	/* Rogue Data Cache Load? No! */
1402 	if (ia32_cap & ARCH_CAP_RDCL_NO)
1403 		return;
1404 
1405 	setup_force_cpu_bug(X86_BUG_CPU_MELTDOWN);
1406 
1407 	if (cpu_matches(cpu_vuln_whitelist, NO_L1TF))
1408 		return;
1409 
1410 	setup_force_cpu_bug(X86_BUG_L1TF);
1411 }
1412 
1413 /*
1414  * The NOPL instruction is supposed to exist on all CPUs of family >= 6;
1415  * unfortunately, that's not true in practice because of early VIA
1416  * chips and (more importantly) broken virtualizers that are not easy
1417  * to detect. In the latter case it doesn't even *fail* reliably, so
1418  * probing for it doesn't even work. Disable it completely on 32-bit
1419  * unless we can find a reliable way to detect all the broken cases.
1420  * Enable it explicitly on 64-bit for non-constant inputs of cpu_has().
1421  */
1422 static void detect_nopl(void)
1423 {
1424 #ifdef CONFIG_X86_32
1425 	setup_clear_cpu_cap(X86_FEATURE_NOPL);
1426 #else
1427 	setup_force_cpu_cap(X86_FEATURE_NOPL);
1428 #endif
1429 }
1430 
1431 /*
1432  * We parse cpu parameters early because fpu__init_system() is executed
1433  * before parse_early_param().
1434  */
1435 static void __init cpu_parse_early_param(void)
1436 {
1437 	char arg[128];
1438 	char *argptr = arg, *opt;
1439 	int arglen, taint = 0;
1440 
1441 #ifdef CONFIG_X86_32
1442 	if (cmdline_find_option_bool(boot_command_line, "no387"))
1443 #ifdef CONFIG_MATH_EMULATION
1444 		setup_clear_cpu_cap(X86_FEATURE_FPU);
1445 #else
1446 		pr_err("Option 'no387' required CONFIG_MATH_EMULATION enabled.\n");
1447 #endif
1448 
1449 	if (cmdline_find_option_bool(boot_command_line, "nofxsr"))
1450 		setup_clear_cpu_cap(X86_FEATURE_FXSR);
1451 #endif
1452 
1453 	if (cmdline_find_option_bool(boot_command_line, "noxsave"))
1454 		setup_clear_cpu_cap(X86_FEATURE_XSAVE);
1455 
1456 	if (cmdline_find_option_bool(boot_command_line, "noxsaveopt"))
1457 		setup_clear_cpu_cap(X86_FEATURE_XSAVEOPT);
1458 
1459 	if (cmdline_find_option_bool(boot_command_line, "noxsaves"))
1460 		setup_clear_cpu_cap(X86_FEATURE_XSAVES);
1461 
1462 	if (cmdline_find_option_bool(boot_command_line, "nousershstk"))
1463 		setup_clear_cpu_cap(X86_FEATURE_USER_SHSTK);
1464 
1465 	arglen = cmdline_find_option(boot_command_line, "clearcpuid", arg, sizeof(arg));
1466 	if (arglen <= 0)
1467 		return;
1468 
1469 	pr_info("Clearing CPUID bits:");
1470 
1471 	while (argptr) {
1472 		bool found __maybe_unused = false;
1473 		unsigned int bit;
1474 
1475 		opt = strsep(&argptr, ",");
1476 
1477 		/*
1478 		 * Handle naked numbers first for feature flags which don't
1479 		 * have names.
1480 		 */
1481 		if (!kstrtouint(opt, 10, &bit)) {
1482 			if (bit < NCAPINTS * 32) {
1483 
1484 				/* empty-string, i.e., ""-defined feature flags */
1485 				if (!x86_cap_flags[bit])
1486 					pr_cont(" " X86_CAP_FMT_NUM, x86_cap_flag_num(bit));
1487 				else
1488 					pr_cont(" " X86_CAP_FMT, x86_cap_flag(bit));
1489 
1490 				setup_clear_cpu_cap(bit);
1491 				taint++;
1492 			}
1493 			/*
1494 			 * The assumption is that there are no feature names with only
1495 			 * numbers in the name thus go to the next argument.
1496 			 */
1497 			continue;
1498 		}
1499 
1500 		for (bit = 0; bit < 32 * NCAPINTS; bit++) {
1501 			if (!x86_cap_flag(bit))
1502 				continue;
1503 
1504 			if (strcmp(x86_cap_flag(bit), opt))
1505 				continue;
1506 
1507 			pr_cont(" %s", opt);
1508 			setup_clear_cpu_cap(bit);
1509 			taint++;
1510 			found = true;
1511 			break;
1512 		}
1513 
1514 		if (!found)
1515 			pr_cont(" (unknown: %s)", opt);
1516 	}
1517 	pr_cont("\n");
1518 
1519 	if (taint)
1520 		add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK);
1521 }
1522 
1523 /*
1524  * Do minimum CPU detection early.
1525  * Fields really needed: vendor, cpuid_level, family, model, mask,
1526  * cache alignment.
1527  * The others are not touched to avoid unwanted side effects.
1528  *
1529  * WARNING: this function is only called on the boot CPU.  Don't add code
1530  * here that is supposed to run on all CPUs.
1531  */
1532 static void __init early_identify_cpu(struct cpuinfo_x86 *c)
1533 {
1534 	memset(&c->x86_capability, 0, sizeof(c->x86_capability));
1535 	c->extended_cpuid_level = 0;
1536 
1537 	if (!have_cpuid_p())
1538 		identify_cpu_without_cpuid(c);
1539 
1540 	/* cyrix could have cpuid enabled via c_identify()*/
1541 	if (have_cpuid_p()) {
1542 		cpu_detect(c);
1543 		get_cpu_vendor(c);
1544 		get_cpu_cap(c);
1545 		setup_force_cpu_cap(X86_FEATURE_CPUID);
1546 		get_cpu_address_sizes(c);
1547 		cpu_parse_early_param();
1548 
1549 		cpu_init_topology(c);
1550 
1551 		if (this_cpu->c_early_init)
1552 			this_cpu->c_early_init(c);
1553 
1554 		c->cpu_index = 0;
1555 		filter_cpuid_features(c, false);
1556 
1557 		if (this_cpu->c_bsp_init)
1558 			this_cpu->c_bsp_init(c);
1559 	} else {
1560 		setup_clear_cpu_cap(X86_FEATURE_CPUID);
1561 		get_cpu_address_sizes(c);
1562 		cpu_init_topology(c);
1563 	}
1564 
1565 	setup_force_cpu_cap(X86_FEATURE_ALWAYS);
1566 
1567 	cpu_set_bug_bits(c);
1568 
1569 	sld_setup(c);
1570 
1571 #ifdef CONFIG_X86_32
1572 	/*
1573 	 * Regardless of whether PCID is enumerated, the SDM says
1574 	 * that it can't be enabled in 32-bit mode.
1575 	 */
1576 	setup_clear_cpu_cap(X86_FEATURE_PCID);
1577 #endif
1578 
1579 	/*
1580 	 * Later in the boot process pgtable_l5_enabled() relies on
1581 	 * cpu_feature_enabled(X86_FEATURE_LA57). If 5-level paging is not
1582 	 * enabled by this point we need to clear the feature bit to avoid
1583 	 * false-positives at the later stage.
1584 	 *
1585 	 * pgtable_l5_enabled() can be false here for several reasons:
1586 	 *  - 5-level paging is disabled compile-time;
1587 	 *  - it's 32-bit kernel;
1588 	 *  - machine doesn't support 5-level paging;
1589 	 *  - user specified 'no5lvl' in kernel command line.
1590 	 */
1591 	if (!pgtable_l5_enabled())
1592 		setup_clear_cpu_cap(X86_FEATURE_LA57);
1593 
1594 	detect_nopl();
1595 }
1596 
1597 void __init early_cpu_init(void)
1598 {
1599 	const struct cpu_dev *const *cdev;
1600 	int count = 0;
1601 
1602 #ifdef CONFIG_PROCESSOR_SELECT
1603 	pr_info("KERNEL supported cpus:\n");
1604 #endif
1605 
1606 	for (cdev = __x86_cpu_dev_start; cdev < __x86_cpu_dev_end; cdev++) {
1607 		const struct cpu_dev *cpudev = *cdev;
1608 
1609 		if (count >= X86_VENDOR_NUM)
1610 			break;
1611 		cpu_devs[count] = cpudev;
1612 		count++;
1613 
1614 #ifdef CONFIG_PROCESSOR_SELECT
1615 		{
1616 			unsigned int j;
1617 
1618 			for (j = 0; j < 2; j++) {
1619 				if (!cpudev->c_ident[j])
1620 					continue;
1621 				pr_info("  %s %s\n", cpudev->c_vendor,
1622 					cpudev->c_ident[j]);
1623 			}
1624 		}
1625 #endif
1626 	}
1627 	early_identify_cpu(&boot_cpu_data);
1628 }
1629 
1630 static bool detect_null_seg_behavior(void)
1631 {
1632 	/*
1633 	 * Empirically, writing zero to a segment selector on AMD does
1634 	 * not clear the base, whereas writing zero to a segment
1635 	 * selector on Intel does clear the base.  Intel's behavior
1636 	 * allows slightly faster context switches in the common case
1637 	 * where GS is unused by the prev and next threads.
1638 	 *
1639 	 * Since neither vendor documents this anywhere that I can see,
1640 	 * detect it directly instead of hard-coding the choice by
1641 	 * vendor.
1642 	 *
1643 	 * I've designated AMD's behavior as the "bug" because it's
1644 	 * counterintuitive and less friendly.
1645 	 */
1646 
1647 	unsigned long old_base, tmp;
1648 	rdmsrl(MSR_FS_BASE, old_base);
1649 	wrmsrl(MSR_FS_BASE, 1);
1650 	loadsegment(fs, 0);
1651 	rdmsrl(MSR_FS_BASE, tmp);
1652 	wrmsrl(MSR_FS_BASE, old_base);
1653 	return tmp == 0;
1654 }
1655 
1656 void check_null_seg_clears_base(struct cpuinfo_x86 *c)
1657 {
1658 	/* BUG_NULL_SEG is only relevant with 64bit userspace */
1659 	if (!IS_ENABLED(CONFIG_X86_64))
1660 		return;
1661 
1662 	if (cpu_has(c, X86_FEATURE_NULL_SEL_CLR_BASE))
1663 		return;
1664 
1665 	/*
1666 	 * CPUID bit above wasn't set. If this kernel is still running
1667 	 * as a HV guest, then the HV has decided not to advertize
1668 	 * that CPUID bit for whatever reason.	For example, one
1669 	 * member of the migration pool might be vulnerable.  Which
1670 	 * means, the bug is present: set the BUG flag and return.
1671 	 */
1672 	if (cpu_has(c, X86_FEATURE_HYPERVISOR)) {
1673 		set_cpu_bug(c, X86_BUG_NULL_SEG);
1674 		return;
1675 	}
1676 
1677 	/*
1678 	 * Zen2 CPUs also have this behaviour, but no CPUID bit.
1679 	 * 0x18 is the respective family for Hygon.
1680 	 */
1681 	if ((c->x86 == 0x17 || c->x86 == 0x18) &&
1682 	    detect_null_seg_behavior())
1683 		return;
1684 
1685 	/* All the remaining ones are affected */
1686 	set_cpu_bug(c, X86_BUG_NULL_SEG);
1687 }
1688 
1689 static void generic_identify(struct cpuinfo_x86 *c)
1690 {
1691 	c->extended_cpuid_level = 0;
1692 
1693 	if (!have_cpuid_p())
1694 		identify_cpu_without_cpuid(c);
1695 
1696 	/* cyrix could have cpuid enabled via c_identify()*/
1697 	if (!have_cpuid_p())
1698 		return;
1699 
1700 	cpu_detect(c);
1701 
1702 	get_cpu_vendor(c);
1703 
1704 	get_cpu_cap(c);
1705 
1706 	get_cpu_address_sizes(c);
1707 
1708 	get_model_name(c); /* Default name */
1709 
1710 	/*
1711 	 * ESPFIX is a strange bug.  All real CPUs have it.  Paravirt
1712 	 * systems that run Linux at CPL > 0 may or may not have the
1713 	 * issue, but, even if they have the issue, there's absolutely
1714 	 * nothing we can do about it because we can't use the real IRET
1715 	 * instruction.
1716 	 *
1717 	 * NB: For the time being, only 32-bit kernels support
1718 	 * X86_BUG_ESPFIX as such.  64-bit kernels directly choose
1719 	 * whether to apply espfix using paravirt hooks.  If any
1720 	 * non-paravirt system ever shows up that does *not* have the
1721 	 * ESPFIX issue, we can change this.
1722 	 */
1723 #ifdef CONFIG_X86_32
1724 	set_cpu_bug(c, X86_BUG_ESPFIX);
1725 #endif
1726 }
1727 
1728 /*
1729  * This does the hard work of actually picking apart the CPU stuff...
1730  */
1731 static void identify_cpu(struct cpuinfo_x86 *c)
1732 {
1733 	int i;
1734 
1735 	c->loops_per_jiffy = loops_per_jiffy;
1736 	c->x86_cache_size = 0;
1737 	c->x86_vendor = X86_VENDOR_UNKNOWN;
1738 	c->x86_model = c->x86_stepping = 0;	/* So far unknown... */
1739 	c->x86_vendor_id[0] = '\0'; /* Unset */
1740 	c->x86_model_id[0] = '\0';  /* Unset */
1741 #ifdef CONFIG_X86_64
1742 	c->x86_clflush_size = 64;
1743 	c->x86_phys_bits = 36;
1744 	c->x86_virt_bits = 48;
1745 #else
1746 	c->cpuid_level = -1;	/* CPUID not detected */
1747 	c->x86_clflush_size = 32;
1748 	c->x86_phys_bits = 32;
1749 	c->x86_virt_bits = 32;
1750 #endif
1751 	c->x86_cache_alignment = c->x86_clflush_size;
1752 	memset(&c->x86_capability, 0, sizeof(c->x86_capability));
1753 #ifdef CONFIG_X86_VMX_FEATURE_NAMES
1754 	memset(&c->vmx_capability, 0, sizeof(c->vmx_capability));
1755 #endif
1756 
1757 	generic_identify(c);
1758 
1759 	cpu_parse_topology(c);
1760 
1761 	if (this_cpu->c_identify)
1762 		this_cpu->c_identify(c);
1763 
1764 	/* Clear/Set all flags overridden by options, after probe */
1765 	apply_forced_caps(c);
1766 
1767 	/*
1768 	 * Set default APIC and TSC_DEADLINE MSR fencing flag. AMD and
1769 	 * Hygon will clear it in ->c_init() below.
1770 	 */
1771 	set_cpu_cap(c, X86_FEATURE_APIC_MSRS_FENCE);
1772 
1773 	/*
1774 	 * Vendor-specific initialization.  In this section we
1775 	 * canonicalize the feature flags, meaning if there are
1776 	 * features a certain CPU supports which CPUID doesn't
1777 	 * tell us, CPUID claiming incorrect flags, or other bugs,
1778 	 * we handle them here.
1779 	 *
1780 	 * At the end of this section, c->x86_capability better
1781 	 * indicate the features this CPU genuinely supports!
1782 	 */
1783 	if (this_cpu->c_init)
1784 		this_cpu->c_init(c);
1785 
1786 	/* Disable the PN if appropriate */
1787 	squash_the_stupid_serial_number(c);
1788 
1789 	/* Set up SMEP/SMAP/UMIP */
1790 	setup_smep(c);
1791 	setup_smap(c);
1792 	setup_umip(c);
1793 
1794 	/* Enable FSGSBASE instructions if available. */
1795 	if (cpu_has(c, X86_FEATURE_FSGSBASE)) {
1796 		cr4_set_bits(X86_CR4_FSGSBASE);
1797 		elf_hwcap2 |= HWCAP2_FSGSBASE;
1798 	}
1799 
1800 	/*
1801 	 * The vendor-specific functions might have changed features.
1802 	 * Now we do "generic changes."
1803 	 */
1804 
1805 	/* Filter out anything that depends on CPUID levels we don't have */
1806 	filter_cpuid_features(c, true);
1807 
1808 	/* If the model name is still unset, do table lookup. */
1809 	if (!c->x86_model_id[0]) {
1810 		const char *p;
1811 		p = table_lookup_model(c);
1812 		if (p)
1813 			strcpy(c->x86_model_id, p);
1814 		else
1815 			/* Last resort... */
1816 			sprintf(c->x86_model_id, "%02x/%02x",
1817 				c->x86, c->x86_model);
1818 	}
1819 
1820 	x86_init_rdrand(c);
1821 	setup_pku(c);
1822 	setup_cet(c);
1823 
1824 	/*
1825 	 * Clear/Set all flags overridden by options, need do it
1826 	 * before following smp all cpus cap AND.
1827 	 */
1828 	apply_forced_caps(c);
1829 
1830 	/*
1831 	 * On SMP, boot_cpu_data holds the common feature set between
1832 	 * all CPUs; so make sure that we indicate which features are
1833 	 * common between the CPUs.  The first time this routine gets
1834 	 * executed, c == &boot_cpu_data.
1835 	 */
1836 	if (c != &boot_cpu_data) {
1837 		/* AND the already accumulated flags with these */
1838 		for (i = 0; i < NCAPINTS; i++)
1839 			boot_cpu_data.x86_capability[i] &= c->x86_capability[i];
1840 
1841 		/* OR, i.e. replicate the bug flags */
1842 		for (i = NCAPINTS; i < NCAPINTS + NBUGINTS; i++)
1843 			c->x86_capability[i] |= boot_cpu_data.x86_capability[i];
1844 	}
1845 
1846 	ppin_init(c);
1847 
1848 	/* Init Machine Check Exception if available. */
1849 	mcheck_cpu_init(c);
1850 
1851 	select_idle_routine(c);
1852 
1853 #ifdef CONFIG_NUMA
1854 	numa_add_cpu(smp_processor_id());
1855 #endif
1856 }
1857 
1858 /*
1859  * Set up the CPU state needed to execute SYSENTER/SYSEXIT instructions
1860  * on 32-bit kernels:
1861  */
1862 #ifdef CONFIG_X86_32
1863 void enable_sep_cpu(void)
1864 {
1865 	struct tss_struct *tss;
1866 	int cpu;
1867 
1868 	if (!boot_cpu_has(X86_FEATURE_SEP))
1869 		return;
1870 
1871 	cpu = get_cpu();
1872 	tss = &per_cpu(cpu_tss_rw, cpu);
1873 
1874 	/*
1875 	 * We cache MSR_IA32_SYSENTER_CS's value in the TSS's ss1 field --
1876 	 * see the big comment in struct x86_hw_tss's definition.
1877 	 */
1878 
1879 	tss->x86_tss.ss1 = __KERNEL_CS;
1880 	wrmsr(MSR_IA32_SYSENTER_CS, tss->x86_tss.ss1, 0);
1881 	wrmsr(MSR_IA32_SYSENTER_ESP, (unsigned long)(cpu_entry_stack(cpu) + 1), 0);
1882 	wrmsr(MSR_IA32_SYSENTER_EIP, (unsigned long)entry_SYSENTER_32, 0);
1883 
1884 	put_cpu();
1885 }
1886 #endif
1887 
1888 static __init void identify_boot_cpu(void)
1889 {
1890 	identify_cpu(&boot_cpu_data);
1891 	if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT))
1892 		pr_info("CET detected: Indirect Branch Tracking enabled\n");
1893 #ifdef CONFIG_X86_32
1894 	enable_sep_cpu();
1895 #endif
1896 	cpu_detect_tlb(&boot_cpu_data);
1897 	setup_cr_pinning();
1898 
1899 	tsx_init();
1900 	tdx_init();
1901 	lkgs_init();
1902 }
1903 
1904 void identify_secondary_cpu(struct cpuinfo_x86 *c)
1905 {
1906 	BUG_ON(c == &boot_cpu_data);
1907 	identify_cpu(c);
1908 #ifdef CONFIG_X86_32
1909 	enable_sep_cpu();
1910 #endif
1911 	x86_spec_ctrl_setup_ap();
1912 	update_srbds_msr();
1913 	if (boot_cpu_has_bug(X86_BUG_GDS))
1914 		update_gds_msr();
1915 
1916 	tsx_ap_init();
1917 }
1918 
1919 void print_cpu_info(struct cpuinfo_x86 *c)
1920 {
1921 	const char *vendor = NULL;
1922 
1923 	if (c->x86_vendor < X86_VENDOR_NUM) {
1924 		vendor = this_cpu->c_vendor;
1925 	} else {
1926 		if (c->cpuid_level >= 0)
1927 			vendor = c->x86_vendor_id;
1928 	}
1929 
1930 	if (vendor && !strstr(c->x86_model_id, vendor))
1931 		pr_cont("%s ", vendor);
1932 
1933 	if (c->x86_model_id[0])
1934 		pr_cont("%s", c->x86_model_id);
1935 	else
1936 		pr_cont("%d86", c->x86);
1937 
1938 	pr_cont(" (family: 0x%x, model: 0x%x", c->x86, c->x86_model);
1939 
1940 	if (c->x86_stepping || c->cpuid_level >= 0)
1941 		pr_cont(", stepping: 0x%x)\n", c->x86_stepping);
1942 	else
1943 		pr_cont(")\n");
1944 }
1945 
1946 /*
1947  * clearcpuid= was already parsed in cpu_parse_early_param().  This dummy
1948  * function prevents it from becoming an environment variable for init.
1949  */
1950 static __init int setup_clearcpuid(char *arg)
1951 {
1952 	return 1;
1953 }
1954 __setup("clearcpuid=", setup_clearcpuid);
1955 
1956 DEFINE_PER_CPU_ALIGNED(struct pcpu_hot, pcpu_hot) = {
1957 	.current_task	= &init_task,
1958 	.preempt_count	= INIT_PREEMPT_COUNT,
1959 	.top_of_stack	= TOP_OF_INIT_STACK,
1960 };
1961 EXPORT_PER_CPU_SYMBOL(pcpu_hot);
1962 
1963 #ifdef CONFIG_X86_64
1964 DEFINE_PER_CPU_FIRST(struct fixed_percpu_data,
1965 		     fixed_percpu_data) __aligned(PAGE_SIZE) __visible;
1966 EXPORT_PER_CPU_SYMBOL_GPL(fixed_percpu_data);
1967 
1968 static void wrmsrl_cstar(unsigned long val)
1969 {
1970 	/*
1971 	 * Intel CPUs do not support 32-bit SYSCALL. Writing to MSR_CSTAR
1972 	 * is so far ignored by the CPU, but raises a #VE trap in a TDX
1973 	 * guest. Avoid the pointless write on all Intel CPUs.
1974 	 */
1975 	if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
1976 		wrmsrl(MSR_CSTAR, val);
1977 }
1978 
1979 static inline void idt_syscall_init(void)
1980 {
1981 	wrmsrl(MSR_LSTAR, (unsigned long)entry_SYSCALL_64);
1982 
1983 	if (ia32_enabled()) {
1984 		wrmsrl_cstar((unsigned long)entry_SYSCALL_compat);
1985 		/*
1986 		 * This only works on Intel CPUs.
1987 		 * On AMD CPUs these MSRs are 32-bit, CPU truncates MSR_IA32_SYSENTER_EIP.
1988 		 * This does not cause SYSENTER to jump to the wrong location, because
1989 		 * AMD doesn't allow SYSENTER in long mode (either 32- or 64-bit).
1990 		 */
1991 		wrmsrl_safe(MSR_IA32_SYSENTER_CS, (u64)__KERNEL_CS);
1992 		wrmsrl_safe(MSR_IA32_SYSENTER_ESP,
1993 			    (unsigned long)(cpu_entry_stack(smp_processor_id()) + 1));
1994 		wrmsrl_safe(MSR_IA32_SYSENTER_EIP, (u64)entry_SYSENTER_compat);
1995 	} else {
1996 		wrmsrl_cstar((unsigned long)entry_SYSCALL32_ignore);
1997 		wrmsrl_safe(MSR_IA32_SYSENTER_CS, (u64)GDT_ENTRY_INVALID_SEG);
1998 		wrmsrl_safe(MSR_IA32_SYSENTER_ESP, 0ULL);
1999 		wrmsrl_safe(MSR_IA32_SYSENTER_EIP, 0ULL);
2000 	}
2001 
2002 	/*
2003 	 * Flags to clear on syscall; clear as much as possible
2004 	 * to minimize user space-kernel interference.
2005 	 */
2006 	wrmsrl(MSR_SYSCALL_MASK,
2007 	       X86_EFLAGS_CF|X86_EFLAGS_PF|X86_EFLAGS_AF|
2008 	       X86_EFLAGS_ZF|X86_EFLAGS_SF|X86_EFLAGS_TF|
2009 	       X86_EFLAGS_IF|X86_EFLAGS_DF|X86_EFLAGS_OF|
2010 	       X86_EFLAGS_IOPL|X86_EFLAGS_NT|X86_EFLAGS_RF|
2011 	       X86_EFLAGS_AC|X86_EFLAGS_ID);
2012 }
2013 
2014 /* May not be marked __init: used by software suspend */
2015 void syscall_init(void)
2016 {
2017 	/* The default user and kernel segments */
2018 	wrmsr(MSR_STAR, 0, (__USER32_CS << 16) | __KERNEL_CS);
2019 
2020 	/*
2021 	 * Except the IA32_STAR MSR, there is NO need to setup SYSCALL and
2022 	 * SYSENTER MSRs for FRED, because FRED uses the ring 3 FRED
2023 	 * entrypoint for SYSCALL and SYSENTER, and ERETU is the only legit
2024 	 * instruction to return to ring 3 (both sysexit and sysret cause
2025 	 * #UD when FRED is enabled).
2026 	 */
2027 	if (!cpu_feature_enabled(X86_FEATURE_FRED))
2028 		idt_syscall_init();
2029 }
2030 
2031 #else	/* CONFIG_X86_64 */
2032 
2033 #ifdef CONFIG_STACKPROTECTOR
2034 DEFINE_PER_CPU(unsigned long, __stack_chk_guard);
2035 EXPORT_PER_CPU_SYMBOL(__stack_chk_guard);
2036 #endif
2037 
2038 #endif	/* CONFIG_X86_64 */
2039 
2040 /*
2041  * Clear all 6 debug registers:
2042  */
2043 static void clear_all_debug_regs(void)
2044 {
2045 	int i;
2046 
2047 	for (i = 0; i < 8; i++) {
2048 		/* Ignore db4, db5 */
2049 		if ((i == 4) || (i == 5))
2050 			continue;
2051 
2052 		set_debugreg(0, i);
2053 	}
2054 }
2055 
2056 #ifdef CONFIG_KGDB
2057 /*
2058  * Restore debug regs if using kgdbwait and you have a kernel debugger
2059  * connection established.
2060  */
2061 static void dbg_restore_debug_regs(void)
2062 {
2063 	if (unlikely(kgdb_connected && arch_kgdb_ops.correct_hw_break))
2064 		arch_kgdb_ops.correct_hw_break();
2065 }
2066 #else /* ! CONFIG_KGDB */
2067 #define dbg_restore_debug_regs()
2068 #endif /* ! CONFIG_KGDB */
2069 
2070 static inline void setup_getcpu(int cpu)
2071 {
2072 	unsigned long cpudata = vdso_encode_cpunode(cpu, early_cpu_to_node(cpu));
2073 	struct desc_struct d = { };
2074 
2075 	if (boot_cpu_has(X86_FEATURE_RDTSCP) || boot_cpu_has(X86_FEATURE_RDPID))
2076 		wrmsr(MSR_TSC_AUX, cpudata, 0);
2077 
2078 	/* Store CPU and node number in limit. */
2079 	d.limit0 = cpudata;
2080 	d.limit1 = cpudata >> 16;
2081 
2082 	d.type = 5;		/* RO data, expand down, accessed */
2083 	d.dpl = 3;		/* Visible to user code */
2084 	d.s = 1;		/* Not a system segment */
2085 	d.p = 1;		/* Present */
2086 	d.d = 1;		/* 32-bit */
2087 
2088 	write_gdt_entry(get_cpu_gdt_rw(cpu), GDT_ENTRY_CPUNODE, &d, DESCTYPE_S);
2089 }
2090 
2091 #ifdef CONFIG_X86_64
2092 static inline void tss_setup_ist(struct tss_struct *tss)
2093 {
2094 	/* Set up the per-CPU TSS IST stacks */
2095 	tss->x86_tss.ist[IST_INDEX_DF] = __this_cpu_ist_top_va(DF);
2096 	tss->x86_tss.ist[IST_INDEX_NMI] = __this_cpu_ist_top_va(NMI);
2097 	tss->x86_tss.ist[IST_INDEX_DB] = __this_cpu_ist_top_va(DB);
2098 	tss->x86_tss.ist[IST_INDEX_MCE] = __this_cpu_ist_top_va(MCE);
2099 	/* Only mapped when SEV-ES is active */
2100 	tss->x86_tss.ist[IST_INDEX_VC] = __this_cpu_ist_top_va(VC);
2101 }
2102 #else /* CONFIG_X86_64 */
2103 static inline void tss_setup_ist(struct tss_struct *tss) { }
2104 #endif /* !CONFIG_X86_64 */
2105 
2106 static inline void tss_setup_io_bitmap(struct tss_struct *tss)
2107 {
2108 	tss->x86_tss.io_bitmap_base = IO_BITMAP_OFFSET_INVALID;
2109 
2110 #ifdef CONFIG_X86_IOPL_IOPERM
2111 	tss->io_bitmap.prev_max = 0;
2112 	tss->io_bitmap.prev_sequence = 0;
2113 	memset(tss->io_bitmap.bitmap, 0xff, sizeof(tss->io_bitmap.bitmap));
2114 	/*
2115 	 * Invalidate the extra array entry past the end of the all
2116 	 * permission bitmap as required by the hardware.
2117 	 */
2118 	tss->io_bitmap.mapall[IO_BITMAP_LONGS] = ~0UL;
2119 #endif
2120 }
2121 
2122 /*
2123  * Setup everything needed to handle exceptions from the IDT, including the IST
2124  * exceptions which use paranoid_entry().
2125  */
2126 void cpu_init_exception_handling(void)
2127 {
2128 	struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw);
2129 	int cpu = raw_smp_processor_id();
2130 
2131 	/* paranoid_entry() gets the CPU number from the GDT */
2132 	setup_getcpu(cpu);
2133 
2134 	/* For IDT mode, IST vectors need to be set in TSS. */
2135 	if (!cpu_feature_enabled(X86_FEATURE_FRED))
2136 		tss_setup_ist(tss);
2137 	tss_setup_io_bitmap(tss);
2138 	set_tss_desc(cpu, &get_cpu_entry_area(cpu)->tss.x86_tss);
2139 
2140 	load_TR_desc();
2141 
2142 	/* GHCB needs to be setup to handle #VC. */
2143 	setup_ghcb();
2144 
2145 	if (cpu_feature_enabled(X86_FEATURE_FRED))
2146 		cpu_init_fred_exceptions();
2147 	else
2148 		load_current_idt();
2149 }
2150 
2151 /*
2152  * cpu_init() initializes state that is per-CPU. Some data is already
2153  * initialized (naturally) in the bootstrap process, such as the GDT.  We
2154  * reload it nevertheless, this function acts as a 'CPU state barrier',
2155  * nothing should get across.
2156  */
2157 void cpu_init(void)
2158 {
2159 	struct task_struct *cur = current;
2160 	int cpu = raw_smp_processor_id();
2161 
2162 #ifdef CONFIG_NUMA
2163 	if (this_cpu_read(numa_node) == 0 &&
2164 	    early_cpu_to_node(cpu) != NUMA_NO_NODE)
2165 		set_numa_node(early_cpu_to_node(cpu));
2166 #endif
2167 	pr_debug("Initializing CPU#%d\n", cpu);
2168 
2169 	if (IS_ENABLED(CONFIG_X86_64) || cpu_feature_enabled(X86_FEATURE_VME) ||
2170 	    boot_cpu_has(X86_FEATURE_TSC) || boot_cpu_has(X86_FEATURE_DE))
2171 		cr4_clear_bits(X86_CR4_VME|X86_CR4_PVI|X86_CR4_TSD|X86_CR4_DE);
2172 
2173 	if (IS_ENABLED(CONFIG_X86_64)) {
2174 		loadsegment(fs, 0);
2175 		memset(cur->thread.tls_array, 0, GDT_ENTRY_TLS_ENTRIES * 8);
2176 		syscall_init();
2177 
2178 		wrmsrl(MSR_FS_BASE, 0);
2179 		wrmsrl(MSR_KERNEL_GS_BASE, 0);
2180 		barrier();
2181 
2182 		x2apic_setup();
2183 	}
2184 
2185 	mmgrab(&init_mm);
2186 	cur->active_mm = &init_mm;
2187 	BUG_ON(cur->mm);
2188 	initialize_tlbstate_and_flush();
2189 	enter_lazy_tlb(&init_mm, cur);
2190 
2191 	/*
2192 	 * sp0 points to the entry trampoline stack regardless of what task
2193 	 * is running.
2194 	 */
2195 	load_sp0((unsigned long)(cpu_entry_stack(cpu) + 1));
2196 
2197 	load_mm_ldt(&init_mm);
2198 
2199 	clear_all_debug_regs();
2200 	dbg_restore_debug_regs();
2201 
2202 	doublefault_init_cpu_tss();
2203 
2204 	if (is_uv_system())
2205 		uv_cpu_init();
2206 
2207 	load_fixmap_gdt(cpu);
2208 }
2209 
2210 #ifdef CONFIG_MICROCODE_LATE_LOADING
2211 /**
2212  * store_cpu_caps() - Store a snapshot of CPU capabilities
2213  * @curr_info: Pointer where to store it
2214  *
2215  * Returns: None
2216  */
2217 void store_cpu_caps(struct cpuinfo_x86 *curr_info)
2218 {
2219 	/* Reload CPUID max function as it might've changed. */
2220 	curr_info->cpuid_level = cpuid_eax(0);
2221 
2222 	/* Copy all capability leafs and pick up the synthetic ones. */
2223 	memcpy(&curr_info->x86_capability, &boot_cpu_data.x86_capability,
2224 	       sizeof(curr_info->x86_capability));
2225 
2226 	/* Get the hardware CPUID leafs */
2227 	get_cpu_cap(curr_info);
2228 }
2229 
2230 /**
2231  * microcode_check() - Check if any CPU capabilities changed after an update.
2232  * @prev_info:	CPU capabilities stored before an update.
2233  *
2234  * The microcode loader calls this upon late microcode load to recheck features,
2235  * only when microcode has been updated. Caller holds and CPU hotplug lock.
2236  *
2237  * Return: None
2238  */
2239 void microcode_check(struct cpuinfo_x86 *prev_info)
2240 {
2241 	struct cpuinfo_x86 curr_info;
2242 
2243 	perf_check_microcode();
2244 
2245 	amd_check_microcode();
2246 
2247 	store_cpu_caps(&curr_info);
2248 
2249 	if (!memcmp(&prev_info->x86_capability, &curr_info.x86_capability,
2250 		    sizeof(prev_info->x86_capability)))
2251 		return;
2252 
2253 	pr_warn("x86/CPU: CPU features have changed after loading microcode, but might not take effect.\n");
2254 	pr_warn("x86/CPU: Please consider either early loading through initrd/built-in or a potential BIOS update.\n");
2255 }
2256 #endif
2257 
2258 /*
2259  * Invoked from core CPU hotplug code after hotplug operations
2260  */
2261 void arch_smt_update(void)
2262 {
2263 	/* Handle the speculative execution misfeatures */
2264 	cpu_bugs_smt_update();
2265 	/* Check whether IPI broadcasting can be enabled */
2266 	apic_smt_update();
2267 }
2268 
2269 void __init arch_cpu_finalize_init(void)
2270 {
2271 	identify_boot_cpu();
2272 
2273 	/*
2274 	 * identify_boot_cpu() initialized SMT support information, let the
2275 	 * core code know.
2276 	 */
2277 	cpu_smt_set_num_threads(__max_threads_per_core, __max_threads_per_core);
2278 
2279 	if (!IS_ENABLED(CONFIG_SMP)) {
2280 		pr_info("CPU: ");
2281 		print_cpu_info(&boot_cpu_data);
2282 	}
2283 
2284 	cpu_select_mitigations();
2285 
2286 	arch_smt_update();
2287 
2288 	if (IS_ENABLED(CONFIG_X86_32)) {
2289 		/*
2290 		 * Check whether this is a real i386 which is not longer
2291 		 * supported and fixup the utsname.
2292 		 */
2293 		if (boot_cpu_data.x86 < 4)
2294 			panic("Kernel requires i486+ for 'invlpg' and other features");
2295 
2296 		init_utsname()->machine[1] =
2297 			'0' + (boot_cpu_data.x86 > 6 ? 6 : boot_cpu_data.x86);
2298 	}
2299 
2300 	/*
2301 	 * Must be before alternatives because it might set or clear
2302 	 * feature bits.
2303 	 */
2304 	fpu__init_system();
2305 	fpu__init_cpu();
2306 
2307 	alternative_instructions();
2308 
2309 	if (IS_ENABLED(CONFIG_X86_64)) {
2310 		/*
2311 		 * Make sure the first 2MB area is not mapped by huge pages
2312 		 * There are typically fixed size MTRRs in there and overlapping
2313 		 * MTRRs into large pages causes slow downs.
2314 		 *
2315 		 * Right now we don't do that with gbpages because there seems
2316 		 * very little benefit for that case.
2317 		 */
2318 		if (!direct_gbpages)
2319 			set_memory_4k((unsigned long)__va(0), 1);
2320 	} else {
2321 		fpu__init_check_bugs();
2322 	}
2323 
2324 	/*
2325 	 * This needs to be called before any devices perform DMA
2326 	 * operations that might use the SWIOTLB bounce buffers. It will
2327 	 * mark the bounce buffers as decrypted so that their usage will
2328 	 * not cause "plain-text" data to be decrypted when accessed. It
2329 	 * must be called after late_time_init() so that Hyper-V x86/x64
2330 	 * hypercalls work when the SWIOTLB bounce buffers are decrypted.
2331 	 */
2332 	mem_encrypt_init();
2333 }
2334