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