File Index
Files and directories
Sign in
FILE

common.c

File preview with syntax highlighting.

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