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