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