File Index
Files and directories
Sign in
FILE

smpboot.c

File preview with syntax highlighting.

linux-6.19.14/arch/x86/kernel/smpboot.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2 /*
   3 *	x86 SMP booting functions
   4 *
   5 *	(c) 1995 Alan Cox, Building #3 <alan@lxorguk.ukuu.org.uk>
   6 *	(c) 1998, 1999, 2000, 2009 Ingo Molnar <mingo@redhat.com>
   7 *	Copyright 2001 Andi Kleen, SuSE Labs.
   8 *
   9 *	Much of the core SMP work is based on previous work by Thomas Radke, to
  10 *	whom a great many thanks are extended.
  11 *
  12 *	Thanks to Intel for making available several different Pentium,
  13 *	Pentium Pro and Pentium-II/Xeon MP machines.
  14 *	Original development of Linux SMP code supported by Caldera.
  15 *
  16 *	Fixes
  17 *		Felix Koop	:	NR_CPUS used properly
  18 *		Jose Renau	:	Handle single CPU case.
  19 *		Alan Cox	:	By repeated request 8) - Total BogoMIPS report.
  20 *		Greg Wright	:	Fix for kernel stacks panic.
  21 *		Erich Boleyn	:	MP v1.4 and additional changes.
  22 *	Matthias Sattler	:	Changes for 2.1 kernel map.
  23 *	Michel Lespinasse	:	Changes for 2.1 kernel map.
  24 *	Michael Chastain	:	Change trampoline.S to gnu as.
  25 *		Alan Cox	:	Dumb bug: 'B' step PPro's are fine
  26 *		Ingo Molnar	:	Added APIC timers, based on code
  27 *					from Jose Renau
  28 *		Ingo Molnar	:	various cleanups and rewrites
  29 *		Tigran Aivazian	:	fixed "0.00 in /proc/uptime on SMP" bug.
  30 *	Maciej W. Rozycki	:	Bits for genuine 82489DX APICs
  31 *	Andi Kleen		:	Changed for SMP boot into long mode.
  32 *		Martin J. Bligh	: 	Added support for multi-quad systems
  33 *		Dave Jones	:	Report invalid combinations of Athlon CPUs.
  34 *		Rusty Russell	:	Hacked into shape for new "hotplug" boot process.
  35 *      Andi Kleen              :       Converted to new state machine.
  36 *	Ashok Raj		: 	CPU hotplug support
  37 *	Glauber Costa		:	i386 and x86_64 integration
  38 */
  39
  40#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  41
  42#include <linux/init.h>
  43#include <linux/smp.h>
  44#include <linux/export.h>
  45#include <linux/sched.h>
  46#include <linux/sched/topology.h>
  47#include <linux/sched/hotplug.h>
  48#include <linux/sched/task_stack.h>
  49#include <linux/percpu.h>
  50#include <linux/memblock.h>
  51#include <linux/err.h>
  52#include <linux/nmi.h>
  53#include <linux/tboot.h>
  54#include <linux/gfp.h>
  55#include <linux/cpuidle.h>
  56#include <linux/kexec.h>
  57#include <linux/numa.h>
  58#include <linux/pgtable.h>
  59#include <linux/overflow.h>
  60#include <linux/stackprotector.h>
  61#include <linux/cpuhotplug.h>
  62#include <linux/mc146818rtc.h>
  63#include <linux/acpi.h>
  64
  65#include <asm/acpi.h>
  66#include <asm/cacheinfo.h>
  67#include <asm/cpuid/api.h>
  68#include <asm/desc.h>
  69#include <asm/nmi.h>
  70#include <asm/irq.h>
  71#include <asm/realmode.h>
  72#include <asm/cpu.h>
  73#include <asm/numa.h>
  74#include <asm/tlbflush.h>
  75#include <asm/mtrr.h>
  76#include <asm/mwait.h>
  77#include <asm/apic.h>
  78#include <asm/io_apic.h>
  79#include <asm/fpu/api.h>
  80#include <asm/setup.h>
  81#include <asm/uv/uv.h>
  82#include <asm/microcode.h>
  83#include <asm/i8259.h>
  84#include <asm/misc.h>
  85#include <asm/qspinlock.h>
  86#include <asm/intel-family.h>
  87#include <asm/cpu_device_id.h>
  88#include <asm/spec-ctrl.h>
  89#include <asm/hw_irq.h>
  90#include <asm/stackprotector.h>
  91#include <asm/sev.h>
  92#include <asm/spec-ctrl.h>
  93
  94/* representing HT siblings of each logical CPU */
  95DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_sibling_map);
  96EXPORT_PER_CPU_SYMBOL(cpu_sibling_map);
  97
  98/* representing HT and core siblings of each logical CPU */
  99DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_core_map);
 100EXPORT_PER_CPU_SYMBOL(cpu_core_map);
 101
 102/* representing HT, core, and die siblings of each logical CPU */
 103DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_die_map);
 104EXPORT_PER_CPU_SYMBOL(cpu_die_map);
 105
 106/* Representing CPUs for which sibling maps can be computed */
 107static cpumask_var_t cpu_sibling_setup_mask;
 108
 109struct mwait_cpu_dead {
 110	unsigned int	control;
 111	unsigned int	status;
 112};
 113
 114#define CPUDEAD_MWAIT_WAIT	0xDEADBEEF
 115#define CPUDEAD_MWAIT_KEXEC_HLT	0x4A17DEAD
 116
 117/*
 118 * Cache line aligned data for mwait_play_dead(). Separate on purpose so
 119 * that it's unlikely to be touched by other CPUs.
 120 */
 121static DEFINE_PER_CPU_ALIGNED(struct mwait_cpu_dead, mwait_cpu_dead);
 122
 123/* Maximum number of SMT threads on any online core */
 124int __read_mostly __max_smt_threads = 1;
 125
 126/* Flag to indicate if a complete sched domain rebuild is required */
 127bool x86_topology_update;
 128
 129int arch_update_cpu_topology(void)
 130{
 131	int retval = x86_topology_update;
 132
 133	x86_topology_update = false;
 134	return retval;
 135}
 136
 137static unsigned int smpboot_warm_reset_vector_count;
 138
 139static inline void smpboot_setup_warm_reset_vector(unsigned long start_eip)
 140{
 141	unsigned long flags;
 142
 143	spin_lock_irqsave(&rtc_lock, flags);
 144	if (!smpboot_warm_reset_vector_count++) {
 145		CMOS_WRITE(0xa, 0xf);
 146		*((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_HIGH)) = start_eip >> 4;
 147		*((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) = start_eip & 0xf;
 148	}
 149	spin_unlock_irqrestore(&rtc_lock, flags);
 150}
 151
 152static inline void smpboot_restore_warm_reset_vector(void)
 153{
 154	unsigned long flags;
 155
 156	/*
 157	 * Paranoid:  Set warm reset code and vector here back
 158	 * to default values.
 159	 */
 160	spin_lock_irqsave(&rtc_lock, flags);
 161	if (!--smpboot_warm_reset_vector_count) {
 162		CMOS_WRITE(0, 0xf);
 163		*((volatile u32 *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) = 0;
 164	}
 165	spin_unlock_irqrestore(&rtc_lock, flags);
 166
 167}
 168
 169/* Run the next set of setup steps for the upcoming CPU */
 170static void ap_starting(void)
 171{
 172	int cpuid = smp_processor_id();
 173
 174	/* Mop up eventual mwait_play_dead() wreckage */
 175	this_cpu_write(mwait_cpu_dead.status, 0);
 176	this_cpu_write(mwait_cpu_dead.control, 0);
 177
 178	/*
 179	 * If woken up by an INIT in an 82489DX configuration the alive
 180	 * synchronization guarantees that the CPU does not reach this
 181	 * point before an INIT_deassert IPI reaches the local APIC, so it
 182	 * is now safe to touch the local APIC.
 183	 *
 184	 * Set up this CPU, first the APIC, which is probably redundant on
 185	 * most boards.
 186	 */
 187	apic_ap_setup();
 188
 189	/* Save the processor parameters. */
 190	identify_secondary_cpu(cpuid);
 191
 192	/*
 193	 * The topology information must be up to date before
 194	 * notify_cpu_starting().
 195	 */
 196	set_cpu_sibling_map(cpuid);
 197
 198	ap_init_aperfmperf();
 199
 200	pr_debug("Stack at about %p\n", &cpuid);
 201
 202	wmb();
 203
 204	/*
 205	 * This runs the AP through all the cpuhp states to its target
 206	 * state CPUHP_ONLINE.
 207	 */
 208	notify_cpu_starting(cpuid);
 209}
 210
 211static void ap_calibrate_delay(void)
 212{
 213	/*
 214	 * Calibrate the delay loop and update loops_per_jiffy in cpu_data.
 215	 * identify_secondary_cpu() stored a value that is close but not as
 216	 * accurate as the value just calculated.
 217	 *
 218	 * As this is invoked after the TSC synchronization check,
 219	 * calibrate_delay_is_known() will skip the calibration routine
 220	 * when TSC is synchronized across sockets.
 221	 */
 222	calibrate_delay();
 223	cpu_data(smp_processor_id()).loops_per_jiffy = loops_per_jiffy;
 224}
 225
 226/*
 227 * Activate a secondary processor.
 228 */
 229static void notrace __noendbr start_secondary(void *unused)
 230{
 231	/*
 232	 * Don't put *anything* except direct CPU state initialization
 233	 * before cpu_init(), SMP booting is too fragile that we want to
 234	 * limit the things done here to the most necessary things.
 235	 */
 236	cr4_init();
 237
 238	/*
 239	 * 32-bit specific. 64-bit reaches this code with the correct page
 240	 * table established. Yet another historical divergence.
 241	 */
 242	if (IS_ENABLED(CONFIG_X86_32)) {
 243		/* switch away from the initial page table */
 244		load_cr3(swapper_pg_dir);
 245		__flush_tlb_all();
 246	}
 247
 248	cpu_init_exception_handling(false);
 249
 250	/*
 251	 * Load the microcode before reaching the AP alive synchronization
 252	 * point below so it is not part of the full per CPU serialized
 253	 * bringup part when "parallel" bringup is enabled.
 254	 *
 255	 * That's even safe when hyperthreading is enabled in the CPU as
 256	 * the core code starts the primary threads first and leaves the
 257	 * secondary threads waiting for SIPI. Loading microcode on
 258	 * physical cores concurrently is a safe operation.
 259	 *
 260	 * This covers both the Intel specific issue that concurrent
 261	 * microcode loading on SMT siblings must be prohibited and the
 262	 * vendor independent issue`that microcode loading which changes
 263	 * CPUID, MSRs etc. must be strictly serialized to maintain
 264	 * software state correctness.
 265	 */
 266	load_ucode_ap();
 267
 268	/*
 269	 * Synchronization point with the hotplug core. Sets this CPUs
 270	 * synchronization state to ALIVE and spin-waits for the control CPU to
 271	 * release this CPU for further bringup.
 272	 */
 273	cpuhp_ap_sync_alive();
 274
 275	cpu_init();
 276	fpu__init_cpu();
 277	rcutree_report_cpu_starting(raw_smp_processor_id());
 278	x86_cpuinit.early_percpu_clock_init();
 279
 280	ap_starting();
 281
 282	/* Check TSC synchronization with the control CPU. */
 283	check_tsc_sync_target();
 284
 285	/*
 286	 * Calibrate the delay loop after the TSC synchronization check.
 287	 * This allows to skip the calibration when TSC is synchronized
 288	 * across sockets.
 289	 */
 290	ap_calibrate_delay();
 291
 292	speculative_store_bypass_ht_init();
 293
 294	/*
 295	 * Lock vector_lock, set CPU online and bring the vector
 296	 * allocator online. Online must be set with vector_lock held
 297	 * to prevent a concurrent irq setup/teardown from seeing a
 298	 * half valid vector space.
 299	 */
 300	lock_vector_lock();
 301	set_cpu_online(smp_processor_id(), true);
 302	lapic_online();
 303	unlock_vector_lock();
 304	x86_platform.nmi_init();
 305
 306	/* enable local interrupts */
 307	local_irq_enable();
 308
 309	x86_cpuinit.setup_percpu_clockev();
 310
 311	wmb();
 312	cpu_startup_entry(CPUHP_AP_ONLINE_IDLE);
 313}
 314ANNOTATE_NOENDBR_SYM(start_secondary);
 315
 316static bool
 317topology_same_node(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
 318{
 319	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
 320
 321	return (cpu_to_node(cpu1) == cpu_to_node(cpu2));
 322}
 323
 324static bool
 325topology_sane(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o, const char *name)
 326{
 327	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
 328
 329	return !WARN_ONCE(!topology_same_node(c, o),
 330		"sched: CPU #%d's %s-sibling CPU #%d is not on the same node! "
 331		"[node: %d != %d]. Ignoring dependency.\n",
 332		cpu1, name, cpu2, cpu_to_node(cpu1), cpu_to_node(cpu2));
 333}
 334
 335#define link_mask(mfunc, c1, c2)					\
 336do {									\
 337	cpumask_set_cpu((c1), mfunc(c2));				\
 338	cpumask_set_cpu((c2), mfunc(c1));				\
 339} while (0)
 340
 341static bool match_smt(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
 342{
 343	if (boot_cpu_has(X86_FEATURE_TOPOEXT)) {
 344		int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
 345
 346		if (c->topo.pkg_id == o->topo.pkg_id &&
 347		    c->topo.die_id == o->topo.die_id &&
 348		    c->topo.amd_node_id == o->topo.amd_node_id &&
 349		    per_cpu_llc_id(cpu1) == per_cpu_llc_id(cpu2)) {
 350			if (c->topo.core_id == o->topo.core_id)
 351				return topology_sane(c, o, "smt");
 352
 353			if ((c->topo.cu_id != 0xff) &&
 354			    (o->topo.cu_id != 0xff) &&
 355			    (c->topo.cu_id == o->topo.cu_id))
 356				return topology_sane(c, o, "smt");
 357		}
 358
 359	} else if (c->topo.pkg_id == o->topo.pkg_id &&
 360		   c->topo.die_id == o->topo.die_id &&
 361		   c->topo.core_id == o->topo.core_id) {
 362		return topology_sane(c, o, "smt");
 363	}
 364
 365	return false;
 366}
 367
 368static bool match_die(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
 369{
 370	if (c->topo.pkg_id != o->topo.pkg_id || c->topo.die_id != o->topo.die_id)
 371		return false;
 372
 373	if (cpu_feature_enabled(X86_FEATURE_TOPOEXT) && topology_amd_nodes_per_pkg() > 1)
 374		return c->topo.amd_node_id == o->topo.amd_node_id;
 375
 376	return true;
 377}
 378
 379static bool match_l2c(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
 380{
 381	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
 382
 383	/* If the arch didn't set up l2c_id, fall back to SMT */
 384	if (per_cpu_l2c_id(cpu1) == BAD_APICID)
 385		return match_smt(c, o);
 386
 387	/* Do not match if L2 cache id does not match: */
 388	if (per_cpu_l2c_id(cpu1) != per_cpu_l2c_id(cpu2))
 389		return false;
 390
 391	return topology_sane(c, o, "l2c");
 392}
 393
 394/*
 395 * Unlike the other levels, we do not enforce keeping a
 396 * multicore group inside a NUMA node.  If this happens, we will
 397 * discard the MC level of the topology later.
 398 */
 399static bool match_pkg(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
 400{
 401	if (c->topo.pkg_id == o->topo.pkg_id)
 402		return true;
 403	return false;
 404}
 405
 406/*
 407 * Define intel_cod_cpu[] for Intel COD (Cluster-on-Die) CPUs.
 408 *
 409 * Any Intel CPU that has multiple nodes per package and does not
 410 * match intel_cod_cpu[] has the SNC (Sub-NUMA Cluster) topology.
 411 *
 412 * When in SNC mode, these CPUs enumerate an LLC that is shared
 413 * by multiple NUMA nodes. The LLC is shared for off-package data
 414 * access but private to the NUMA node (half of the package) for
 415 * on-package access. CPUID (the source of the information about
 416 * the LLC) can only enumerate the cache as shared or unshared,
 417 * but not this particular configuration.
 418 */
 419
 420static const struct x86_cpu_id intel_cod_cpu[] = {
 421	X86_MATCH_VFM(INTEL_HASWELL_X,	 0),	/* COD */
 422	X86_MATCH_VFM(INTEL_BROADWELL_X, 0),	/* COD */
 423	X86_MATCH_VFM(INTEL_ANY,	 1),	/* SNC */
 424	{}
 425};
 426
 427static bool match_llc(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
 428{
 429	const struct x86_cpu_id *id = x86_match_cpu(intel_cod_cpu);
 430	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
 431	bool intel_snc = id && id->driver_data;
 432
 433	/* Do not match if we do not have a valid APICID for cpu: */
 434	if (per_cpu_llc_id(cpu1) == BAD_APICID)
 435		return false;
 436
 437	/* Do not match if LLC id does not match: */
 438	if (per_cpu_llc_id(cpu1) != per_cpu_llc_id(cpu2))
 439		return false;
 440
 441	/*
 442	 * Allow the SNC topology without warning. Return of false
 443	 * means 'c' does not share the LLC of 'o'. This will be
 444	 * reflected to userspace.
 445	 */
 446	if (match_pkg(c, o) && !topology_same_node(c, o) && intel_snc)
 447		return false;
 448
 449	return topology_sane(c, o, "llc");
 450}
 451
 452
 453static inline int x86_sched_itmt_flags(void)
 454{
 455	return sysctl_sched_itmt_enabled ? SD_ASYM_PACKING : 0;
 456}
 457
 458#ifdef CONFIG_SCHED_MC
 459static int x86_core_flags(void)
 460{
 461	return cpu_core_flags() | x86_sched_itmt_flags();
 462}
 463#endif
 464#ifdef CONFIG_SCHED_CLUSTER
 465static int x86_cluster_flags(void)
 466{
 467	return cpu_cluster_flags() | x86_sched_itmt_flags();
 468}
 469#endif
 470
 471static struct sched_domain_topology_level x86_topology[] = {
 472	SDTL_INIT(tl_smt_mask, cpu_smt_flags, SMT),
 473#ifdef CONFIG_SCHED_CLUSTER
 474	SDTL_INIT(tl_cls_mask, x86_cluster_flags, CLS),
 475#endif
 476#ifdef CONFIG_SCHED_MC
 477	SDTL_INIT(tl_mc_mask, x86_core_flags, MC),
 478#endif
 479	SDTL_INIT(tl_pkg_mask, x86_sched_itmt_flags, PKG),
 480	{ NULL },
 481};
 482
 483static void __init build_sched_topology(void)
 484{
 485	struct sched_domain_topology_level *topology = x86_topology;
 486
 487	/*
 488	 * When there is NUMA topology inside the package invalidate the
 489	 * PKG domain since the NUMA domains will auto-magically create the
 490	 * right spanning domains based on the SLIT.
 491	 */
 492	if (topology_num_nodes_per_package() > 1) {
 493		unsigned int pkgdom = ARRAY_SIZE(x86_topology) - 2;
 494
 495		memset(&x86_topology[pkgdom], 0, sizeof(x86_topology[pkgdom]));
 496	}
 497
 498	/*
 499	 * Drop the SMT domains if there is only one thread per-core
 500	 * since it'll get degenerated by the scheduler anyways.
 501	 */
 502	if (cpu_smt_num_threads <= 1)
 503		++topology;
 504
 505	set_sched_topology(topology);
 506}
 507
 508#ifdef CONFIG_NUMA
 509/*
 510 * Test if the on-trace cluster at (N,N) is symmetric.
 511 * Uses upper triangle iteration to avoid obvious duplicates.
 512 */
 513static bool slit_cluster_symmetric(int N)
 514{
 515	int u = topology_num_nodes_per_package();
 516
 517	for (int k = 0; k < u; k++) {
 518		for (int l = k; l < u; l++) {
 519			if (node_distance(N + k, N + l) !=
 520			    node_distance(N + l, N + k))
 521				return false;
 522		}
 523	}
 524
 525	return true;
 526}
 527
 528/*
 529 * Return the package-id of the cluster, or ~0 if indeterminate.
 530 * Each node in the on-trace cluster should have the same package-id.
 531 */
 532static u32 slit_cluster_package(int N)
 533{
 534	int u = topology_num_nodes_per_package();
 535	u32 pkg_id = ~0;
 536
 537	for (int n = 0; n < u; n++) {
 538		const struct cpumask *cpus = cpumask_of_node(N + n);
 539		int cpu;
 540
 541		for_each_cpu(cpu, cpus) {
 542			u32 id = topology_logical_package_id(cpu);
 543
 544			if (pkg_id == ~0)
 545				pkg_id = id;
 546			if (pkg_id != id)
 547				return ~0;
 548		}
 549	}
 550
 551	return pkg_id;
 552}
 553
 554/*
 555 * Validate the SLIT table is of the form expected for SNC, specifically:
 556 *
 557 *  - each on-trace cluster should be symmetric,
 558 *  - each on-trace cluster should have a unique package-id.
 559 *
 560 * If you NUMA_EMU on top of SNC, you get to keep the pieces.
 561 */
 562static bool slit_validate(void)
 563{
 564	int u = topology_num_nodes_per_package();
 565	u32 pkg_id, prev_pkg_id = ~0;
 566
 567	for (int pkg = 0; pkg < topology_max_packages(); pkg++) {
 568		int n = pkg * u;
 569
 570		/*
 571		 * Ensure the on-trace cluster is symmetric and each cluster
 572		 * has a different package id.
 573		 */
 574		if (!slit_cluster_symmetric(n))
 575			return false;
 576		pkg_id = slit_cluster_package(n);
 577		if (pkg_id == ~0)
 578			return false;
 579		if (pkg && pkg_id == prev_pkg_id)
 580			return false;
 581
 582		prev_pkg_id = pkg_id;
 583	}
 584
 585	return true;
 586}
 587
 588/*
 589 * Compute a sanitized SLIT table for SNC; notably SNC-3 can end up with
 590 * asymmetric off-trace clusters, reflecting physical assymmetries. However
 591 * this leads to 'unfortunate' sched_domain configurations.
 592 *
 593 * For example dual socket GNR with SNC-3:
 594 *
 595 * node distances:
 596 * node     0    1    2    3    4    5
 597 *     0:   10   15   17   21   28   26
 598 *     1:   15   10   15   23   26   23
 599 *     2:   17   15   10   26   23   21
 600 *     3:   21   28   26   10   15   17
 601 *     4:   23   26   23   15   10   15
 602 *     5:   26   23   21   17   15   10
 603 *
 604 * Fix things up by averaging out the off-trace clusters; resulting in:
 605 *
 606 * node     0    1    2    3    4    5
 607 *     0:   10   15   17   24   24   24
 608 *     1:   15   10   15   24   24   24
 609 *     2:   17   15   10   24   24   24
 610 *     3:   24   24   24   10   15   17
 611 *     4:   24   24   24   15   10   15
 612 *     5:   24   24   24   17   15   10
 613 */
 614static int slit_cluster_distance(int i, int j)
 615{
 616	static int slit_valid = -1;
 617	int u = topology_num_nodes_per_package();
 618	long d = 0;
 619	int x, y;
 620
 621	if (slit_valid < 0) {
 622		slit_valid = slit_validate();
 623		if (!slit_valid)
 624			pr_err(FW_BUG "SLIT table doesn't have the expected form for SNC -- fixup disabled!\n");
 625		else
 626			pr_info("Fixing up SNC SLIT table.\n");
 627	}
 628
 629	/*
 630	 * Is this a unit cluster on the trace?
 631	 */
 632	if ((i / u) == (j / u) || !slit_valid)
 633		return node_distance(i, j);
 634
 635	/*
 636	 * Off-trace cluster.
 637	 *
 638	 * Notably average out the symmetric pair of off-trace clusters to
 639	 * ensure the resulting SLIT table is symmetric.
 640	 */
 641	x = i - (i % u);
 642	y = j - (j % u);
 643
 644	for (i = x; i < x + u; i++) {
 645		for (j = y; j < y + u; j++) {
 646			d += node_distance(i, j);
 647			d += node_distance(j, i);
 648		}
 649	}
 650
 651	return d / (2*u*u);
 652}
 653
 654int arch_sched_node_distance(int from, int to)
 655{
 656	int d = node_distance(from, to);
 657
 658	switch (boot_cpu_data.x86_vfm) {
 659	case INTEL_GRANITERAPIDS_X:
 660	case INTEL_ATOM_DARKMONT_X:
 661		if (topology_max_packages() == 1 ||
 662		    topology_num_nodes_per_package() < 3)
 663			return d;
 664
 665		/*
 666		 * Handle SNC-3 asymmetries.
 667		 */
 668		return slit_cluster_distance(from, to);
 669	}
 670	return d;
 671}
 672#endif /* CONFIG_NUMA */
 673
 674void set_cpu_sibling_map(int cpu)
 675{
 676	bool has_smt = __max_threads_per_core > 1;
 677	bool has_mp = has_smt || topology_num_cores_per_package() > 1;
 678	struct cpuinfo_x86 *c = &cpu_data(cpu);
 679	struct cpuinfo_x86 *o;
 680	int i, threads;
 681
 682	cpumask_set_cpu(cpu, cpu_sibling_setup_mask);
 683
 684	if (!has_mp) {
 685		cpumask_set_cpu(cpu, topology_sibling_cpumask(cpu));
 686		cpumask_set_cpu(cpu, cpu_llc_shared_mask(cpu));
 687		cpumask_set_cpu(cpu, cpu_l2c_shared_mask(cpu));
 688		cpumask_set_cpu(cpu, topology_core_cpumask(cpu));
 689		cpumask_set_cpu(cpu, topology_die_cpumask(cpu));
 690		c->booted_cores = 1;
 691		return;
 692	}
 693
 694	for_each_cpu(i, cpu_sibling_setup_mask) {
 695		o = &cpu_data(i);
 696
 697		if (match_pkg(c, o) && !topology_same_node(c, o))
 698			WARN_ON_ONCE(topology_num_nodes_per_package() == 1);
 699
 700		if ((i == cpu) || (has_smt && match_smt(c, o)))
 701			link_mask(topology_sibling_cpumask, cpu, i);
 702
 703		if ((i == cpu) || (has_mp && match_llc(c, o)))
 704			link_mask(cpu_llc_shared_mask, cpu, i);
 705
 706		if ((i == cpu) || (has_mp && match_l2c(c, o)))
 707			link_mask(cpu_l2c_shared_mask, cpu, i);
 708
 709		if ((i == cpu) || (has_mp && match_die(c, o)))
 710			link_mask(topology_die_cpumask, cpu, i);
 711	}
 712
 713	threads = cpumask_weight(topology_sibling_cpumask(cpu));
 714	if (threads > __max_smt_threads)
 715		__max_smt_threads = threads;
 716
 717	for_each_cpu(i, topology_sibling_cpumask(cpu))
 718		cpu_data(i).smt_active = threads > 1;
 719
 720	/*
 721	 * This needs a separate iteration over the cpus because we rely on all
 722	 * topology_sibling_cpumask links to be set-up.
 723	 */
 724	for_each_cpu(i, cpu_sibling_setup_mask) {
 725		o = &cpu_data(i);
 726
 727		if ((i == cpu) || (has_mp && match_pkg(c, o))) {
 728			link_mask(topology_core_cpumask, cpu, i);
 729
 730			/*
 731			 *  Does this new cpu bringup a new core?
 732			 */
 733			if (threads == 1) {
 734				/*
 735				 * for each core in package, increment
 736				 * the booted_cores for this new cpu
 737				 */
 738				if (cpumask_first(
 739				    topology_sibling_cpumask(i)) == i)
 740					c->booted_cores++;
 741				/*
 742				 * increment the core count for all
 743				 * the other cpus in this package
 744				 */
 745				if (i != cpu)
 746					cpu_data(i).booted_cores++;
 747			} else if (i != cpu && !c->booted_cores)
 748				c->booted_cores = cpu_data(i).booted_cores;
 749		}
 750	}
 751}
 752
 753/* maps the cpu to the sched domain representing multi-core */
 754const struct cpumask *cpu_coregroup_mask(int cpu)
 755{
 756	return cpu_llc_shared_mask(cpu);
 757}
 758
 759const struct cpumask *cpu_clustergroup_mask(int cpu)
 760{
 761	return cpu_l2c_shared_mask(cpu);
 762}
 763EXPORT_SYMBOL_GPL(cpu_clustergroup_mask);
 764
 765static void impress_friends(void)
 766{
 767	int cpu;
 768	unsigned long bogosum = 0;
 769	/*
 770	 * Allow the user to impress friends.
 771	 */
 772	pr_debug("Before bogomips\n");
 773	for_each_online_cpu(cpu)
 774		bogosum += cpu_data(cpu).loops_per_jiffy;
 775
 776	pr_info("Total of %d processors activated (%lu.%02lu BogoMIPS)\n",
 777		num_online_cpus(),
 778		bogosum/(500000/HZ),
 779		(bogosum/(5000/HZ))%100);
 780
 781	pr_debug("Before bogocount - setting activated=1\n");
 782}
 783
 784/*
 785 * The Multiprocessor Specification 1.4 (1997) example code suggests
 786 * that there should be a 10ms delay between the BSP asserting INIT
 787 * and de-asserting INIT, when starting a remote processor.
 788 * But that slows boot and resume on modern processors, which include
 789 * many cores and don't require that delay.
 790 *
 791 * Cmdline "cpu_init_udelay=" is available to override this delay.
 792 */
 793#define UDELAY_10MS_LEGACY 10000
 794
 795static unsigned int init_udelay = UINT_MAX;
 796
 797static int __init cpu_init_udelay(char *str)
 798{
 799	get_option(&str, &init_udelay);
 800
 801	return 0;
 802}
 803early_param("cpu_init_udelay", cpu_init_udelay);
 804
 805static void __init smp_set_init_udelay(void)
 806{
 807	/* if cmdline changed it from default, leave it alone */
 808	if (init_udelay != UINT_MAX)
 809		return;
 810
 811	/* if modern processor, use no delay */
 812	if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL && boot_cpu_data.x86_vfm >= INTEL_PENTIUM_PRO) ||
 813	    (boot_cpu_data.x86_vendor == X86_VENDOR_HYGON && boot_cpu_data.x86 >= 0x18) ||
 814	    (boot_cpu_data.x86_vendor == X86_VENDOR_AMD   && boot_cpu_data.x86 >= 0xF)) {
 815		init_udelay = 0;
 816		return;
 817	}
 818	/* else, use legacy delay */
 819	init_udelay = UDELAY_10MS_LEGACY;
 820}
 821
 822/*
 823 * Wake up AP by INIT, INIT, STARTUP sequence.
 824 */
 825static void send_init_sequence(u32 phys_apicid)
 826{
 827	int maxlvt = lapic_get_maxlvt();
 828
 829	/* Be paranoid about clearing APIC errors. */
 830	if (APIC_INTEGRATED(boot_cpu_apic_version)) {
 831		/* Due to the Pentium erratum 3AP.  */
 832		if (maxlvt > 3)
 833			apic_write(APIC_ESR, 0);
 834		apic_read(APIC_ESR);
 835	}
 836
 837	/* Assert INIT on the target CPU */
 838	apic_icr_write(APIC_INT_LEVELTRIG | APIC_INT_ASSERT | APIC_DM_INIT, phys_apicid);
 839	safe_apic_wait_icr_idle();
 840
 841	udelay(init_udelay);
 842
 843	/* Deassert INIT on the target CPU */
 844	apic_icr_write(APIC_INT_LEVELTRIG | APIC_DM_INIT, phys_apicid);
 845	safe_apic_wait_icr_idle();
 846}
 847
 848/*
 849 * Wake up AP by INIT, INIT, STARTUP sequence.
 850 */
 851static int wakeup_secondary_cpu_via_init(u32 phys_apicid, unsigned long start_eip, unsigned int cpu)
 852{
 853	unsigned long send_status = 0, accept_status = 0;
 854	int num_starts, j, maxlvt;
 855
 856	preempt_disable();
 857	maxlvt = lapic_get_maxlvt();
 858	send_init_sequence(phys_apicid);
 859
 860	mb();
 861
 862	/*
 863	 * Should we send STARTUP IPIs ?
 864	 *
 865	 * Determine this based on the APIC version.
 866	 * If we don't have an integrated APIC, don't send the STARTUP IPIs.
 867	 */
 868	if (APIC_INTEGRATED(boot_cpu_apic_version))
 869		num_starts = 2;
 870	else
 871		num_starts = 0;
 872
 873	/*
 874	 * Run STARTUP IPI loop.
 875	 */
 876	pr_debug("#startup loops: %d\n", num_starts);
 877
 878	for (j = 1; j <= num_starts; j++) {
 879		pr_debug("Sending STARTUP #%d\n", j);
 880		if (maxlvt > 3)		/* Due to the Pentium erratum 3AP.  */
 881			apic_write(APIC_ESR, 0);
 882		apic_read(APIC_ESR);
 883		pr_debug("After apic_write\n");
 884
 885		/*
 886		 * STARTUP IPI
 887		 */
 888
 889		/* Target chip */
 890		/* Boot on the stack */
 891		/* Kick the second */
 892		apic_icr_write(APIC_DM_STARTUP | (start_eip >> 12),
 893			       phys_apicid);
 894
 895		/*
 896		 * Give the other CPU some time to accept the IPI.
 897		 */
 898		if (init_udelay == 0)
 899			udelay(10);
 900		else
 901			udelay(300);
 902
 903		pr_debug("Startup point 1\n");
 904
 905		pr_debug("Waiting for send to finish...\n");
 906		send_status = safe_apic_wait_icr_idle();
 907
 908		/*
 909		 * Give the other CPU some time to accept the IPI.
 910		 */
 911		if (init_udelay == 0)
 912			udelay(10);
 913		else
 914			udelay(200);
 915
 916		if (maxlvt > 3)		/* Due to the Pentium erratum 3AP.  */
 917			apic_write(APIC_ESR, 0);
 918		accept_status = (apic_read(APIC_ESR) & 0xEF);
 919		if (send_status || accept_status)
 920			break;
 921	}
 922	pr_debug("After Startup\n");
 923
 924	if (send_status)
 925		pr_err("APIC never delivered???\n");
 926	if (accept_status)
 927		pr_err("APIC delivery error (%lx)\n", accept_status);
 928
 929	preempt_enable();
 930	return (send_status | accept_status);
 931}
 932
 933/* reduce the number of lines printed when booting a large cpu count system */
 934static void announce_cpu(int cpu, int apicid)
 935{
 936	static int width, node_width, first = 1;
 937	static int current_node = NUMA_NO_NODE;
 938	int node = early_cpu_to_node(cpu);
 939
 940	if (!width)
 941		width = num_digits(num_possible_cpus()) + 1; /* + '#' sign */
 942
 943	if (!node_width)
 944		node_width = num_digits(num_possible_nodes()) + 1; /* + '#' */
 945
 946	if (system_state < SYSTEM_RUNNING) {
 947		if (first)
 948			pr_info("x86: Booting SMP configuration:\n");
 949
 950		if (node != current_node) {
 951			if (current_node > (-1))
 952				pr_cont("\n");
 953			current_node = node;
 954
 955			printk(KERN_INFO ".... node %*s#%d, CPUs:  ",
 956			       node_width - num_digits(node), " ", node);
 957		}
 958
 959		/* Add padding for the BSP */
 960		if (first)
 961			pr_cont("%*s", width + 1, " ");
 962		first = 0;
 963
 964		pr_cont("%*s#%d", width - num_digits(cpu), " ", cpu);
 965	} else
 966		pr_info("Booting Node %d Processor %d APIC 0x%x\n",
 967			node, cpu, apicid);
 968}
 969
 970int common_cpu_up(unsigned int cpu, struct task_struct *idle)
 971{
 972	int ret;
 973
 974	/* Just in case we booted with a single CPU. */
 975	alternatives_enable_smp();
 976
 977	per_cpu(current_task, cpu) = idle;
 978	cpu_init_stack_canary(cpu, idle);
 979
 980	/* Initialize the interrupt stack(s) */
 981	ret = irq_init_percpu_irqstack(cpu);
 982	if (ret)
 983		return ret;
 984
 985#ifdef CONFIG_X86_32
 986	/* Stack for startup_32 can be just as for start_secondary onwards */
 987	per_cpu(cpu_current_top_of_stack, cpu) = task_top_of_stack(idle);
 988#endif
 989	return 0;
 990}
 991
 992/*
 993 * NOTE - on most systems this is a PHYSICAL apic ID, but on multiquad
 994 * (ie clustered apic addressing mode), this is a LOGICAL apic ID.
 995 * Returns zero if startup was successfully sent, else error code from
 996 * ->wakeup_secondary_cpu.
 997 */
 998static int do_boot_cpu(u32 apicid, unsigned int cpu, struct task_struct *idle)
 999{
1000	unsigned long start_ip = real_mode_header->trampoline_start;
1001	int ret;
1002
1003#ifdef CONFIG_X86_64
1004	/* If 64-bit wakeup method exists, use the 64-bit mode trampoline IP */
1005	if (apic->wakeup_secondary_cpu_64)
1006		start_ip = real_mode_header->trampoline_start64;
1007#endif
1008	idle->thread.sp = (unsigned long)task_pt_regs(idle);
1009	initial_code = (unsigned long)start_secondary;
1010
1011	if (IS_ENABLED(CONFIG_X86_32)) {
1012		early_gdt_descr.address = (unsigned long)get_cpu_gdt_rw(cpu);
1013		initial_stack  = idle->thread.sp;
1014	} else if (!(smpboot_control & STARTUP_PARALLEL_MASK)) {
1015		smpboot_control = cpu;
1016	}
1017
1018	/* Enable the espfix hack for this CPU */
1019	init_espfix_ap(cpu);
1020
1021	/* So we see what's up */
1022	announce_cpu(cpu, apicid);
1023
1024	/*
1025	 * This grunge runs the startup process for
1026	 * the targeted processor.
1027	 */
1028	if (x86_platform.legacy.warm_reset) {
1029
1030		pr_debug("Setting warm reset code and vector.\n");
1031
1032		smpboot_setup_warm_reset_vector(start_ip);
1033		/*
1034		 * Be paranoid about clearing APIC errors.
1035		*/
1036		if (APIC_INTEGRATED(boot_cpu_apic_version)) {
1037			apic_write(APIC_ESR, 0);
1038			apic_read(APIC_ESR);
1039		}
1040	}
1041
1042	smp_mb();
1043
1044	/*
1045	 * Wake up a CPU in difference cases:
1046	 * - Use a method from the APIC driver if one defined, with wakeup
1047	 *   straight to 64-bit mode preferred over wakeup to RM.
1048	 * Otherwise,
1049	 * - Use an INIT boot APIC message
1050	 */
1051	if (apic->wakeup_secondary_cpu_64)
1052		ret = apic->wakeup_secondary_cpu_64(apicid, start_ip, cpu);
1053	else if (apic->wakeup_secondary_cpu)
1054		ret = apic->wakeup_secondary_cpu(apicid, start_ip, cpu);
1055	else
1056		ret = wakeup_secondary_cpu_via_init(apicid, start_ip, cpu);
1057
1058	/* If the wakeup mechanism failed, cleanup the warm reset vector */
1059	if (ret)
1060		arch_cpuhp_cleanup_kick_cpu(cpu);
1061	return ret;
1062}
1063
1064int native_kick_ap(unsigned int cpu, struct task_struct *tidle)
1065{
1066	u32 apicid = apic->cpu_present_to_apicid(cpu);
1067	int err;
1068
1069	lockdep_assert_irqs_enabled();
1070
1071	pr_debug("++++++++++++++++++++=_---CPU UP  %u\n", cpu);
1072
1073	if (apicid == BAD_APICID || !apic_id_valid(apicid)) {
1074		pr_err("CPU %u has invalid APIC ID %x. Aborting bringup\n", cpu, apicid);
1075		return -EINVAL;
1076	}
1077
1078	if (!test_bit(apicid, phys_cpu_present_map)) {
1079		pr_err("CPU %u APIC ID %x is not present. Aborting bringup\n", cpu, apicid);
1080		return -EINVAL;
1081	}
1082
1083	/*
1084	 * Save current MTRR state in case it was changed since early boot
1085	 * (e.g. by the ACPI SMI) to initialize new CPUs with MTRRs in sync:
1086	 */
1087	mtrr_save_state();
1088
1089	/* the FPU context is blank, nobody can own it */
1090	per_cpu(fpu_fpregs_owner_ctx, cpu) = NULL;
1091
1092	err = common_cpu_up(cpu, tidle);
1093	if (err)
1094		return err;
1095
1096	err = do_boot_cpu(apicid, cpu, tidle);
1097	if (err)
1098		pr_err("do_boot_cpu failed(%d) to wakeup CPU#%u\n", err, cpu);
1099
1100	return err;
1101}
1102
1103int arch_cpuhp_kick_ap_alive(unsigned int cpu, struct task_struct *tidle)
1104{
1105	return smp_ops.kick_ap_alive(cpu, tidle);
1106}
1107
1108void arch_cpuhp_cleanup_kick_cpu(unsigned int cpu)
1109{
1110	/* Cleanup possible dangling ends... */
1111	if (smp_ops.kick_ap_alive == native_kick_ap && x86_platform.legacy.warm_reset)
1112		smpboot_restore_warm_reset_vector();
1113}
1114
1115void arch_cpuhp_cleanup_dead_cpu(unsigned int cpu)
1116{
1117	if (smp_ops.cleanup_dead_cpu)
1118		smp_ops.cleanup_dead_cpu(cpu);
1119
1120	if (system_state == SYSTEM_RUNNING)
1121		pr_info("CPU %u is now offline\n", cpu);
1122}
1123
1124void arch_cpuhp_sync_state_poll(void)
1125{
1126	if (smp_ops.poll_sync_state)
1127		smp_ops.poll_sync_state();
1128}
1129
1130/**
1131 * arch_disable_smp_support() - Disables SMP support for x86 at boottime
1132 */
1133void __init arch_disable_smp_support(void)
1134{
1135	disable_ioapic_support();
1136}
1137
1138/*
1139 * Fall back to non SMP mode after errors.
1140 *
1141 * RED-PEN audit/test this more. I bet there is more state messed up here.
1142 */
1143static __init void disable_smp(void)
1144{
1145	pr_info("SMP disabled\n");
1146
1147	disable_ioapic_support();
1148	topology_reset_possible_cpus_up();
1149
1150	cpumask_set_cpu(0, topology_sibling_cpumask(0));
1151	cpumask_set_cpu(0, topology_core_cpumask(0));
1152	cpumask_set_cpu(0, topology_die_cpumask(0));
1153}
1154
1155void __init smp_prepare_cpus_common(void)
1156{
1157	unsigned int cpu, node;
1158
1159	/* Mark all except the boot CPU as hotpluggable */
1160	for_each_possible_cpu(cpu) {
1161		if (cpu)
1162			per_cpu(cpu_info.cpu_index, cpu) = nr_cpu_ids;
1163	}
1164
1165	for_each_possible_cpu(cpu) {
1166		node = cpu_to_node(cpu);
1167
1168		zalloc_cpumask_var_node(&per_cpu(cpu_sibling_map,    cpu), GFP_KERNEL, node);
1169		zalloc_cpumask_var_node(&per_cpu(cpu_core_map,       cpu), GFP_KERNEL, node);
1170		zalloc_cpumask_var_node(&per_cpu(cpu_die_map,        cpu), GFP_KERNEL, node);
1171		zalloc_cpumask_var_node(&per_cpu(cpu_llc_shared_map, cpu), GFP_KERNEL, node);
1172		zalloc_cpumask_var_node(&per_cpu(cpu_l2c_shared_map, cpu), GFP_KERNEL, node);
1173	}
1174
1175	set_cpu_sibling_map(0);
1176}
1177
1178void __init smp_prepare_boot_cpu(void)
1179{
1180	smp_ops.smp_prepare_boot_cpu();
1181}
1182
1183#ifdef CONFIG_X86_64
1184/* Establish whether parallel bringup can be supported. */
1185bool __init arch_cpuhp_init_parallel_bringup(void)
1186{
1187	if (!x86_cpuinit.parallel_bringup) {
1188		pr_info("Parallel CPU startup disabled by the platform\n");
1189		return false;
1190	}
1191
1192	smpboot_control = STARTUP_READ_APICID;
1193	pr_debug("Parallel CPU startup enabled: 0x%08x\n", smpboot_control);
1194	return true;
1195}
1196#endif
1197
1198/*
1199 * Prepare for SMP bootup.
1200 * @max_cpus: configured maximum number of CPUs, It is a legacy parameter
1201 *            for common interface support.
1202 */
1203void __init native_smp_prepare_cpus(unsigned int max_cpus)
1204{
1205	smp_prepare_cpus_common();
1206
1207	switch (apic_intr_mode) {
1208	case APIC_PIC:
1209	case APIC_VIRTUAL_WIRE_NO_CONFIG:
1210		disable_smp();
1211		return;
1212	case APIC_SYMMETRIC_IO_NO_ROUTING:
1213		disable_smp();
1214		/* Setup local timer */
1215		x86_init.timers.setup_percpu_clockev();
1216		return;
1217	case APIC_VIRTUAL_WIRE:
1218	case APIC_SYMMETRIC_IO:
1219		break;
1220	}
1221
1222	/* Setup local timer */
1223	x86_init.timers.setup_percpu_clockev();
1224
1225	pr_info("CPU0: ");
1226	print_cpu_info(&cpu_data(0));
1227
1228	uv_system_init();
1229
1230	smp_set_init_udelay();
1231
1232	speculative_store_bypass_ht_init();
1233
1234	snp_set_wakeup_secondary_cpu();
1235}
1236
1237void arch_thaw_secondary_cpus_begin(void)
1238{
1239	set_cache_aps_delayed_init(true);
1240}
1241
1242void arch_thaw_secondary_cpus_end(void)
1243{
1244	cache_aps_init();
1245}
1246
1247/*
1248 * Early setup to make printk work.
1249 */
1250void __init native_smp_prepare_boot_cpu(void)
1251{
1252	int me = smp_processor_id();
1253
1254	/* SMP handles this from setup_per_cpu_areas() */
1255	if (!IS_ENABLED(CONFIG_SMP))
1256		switch_gdt_and_percpu_base(me);
1257
1258	native_pv_lock_init();
1259}
1260
1261void __init native_smp_cpus_done(unsigned int max_cpus)
1262{
1263	pr_debug("Boot done\n");
1264
1265	build_sched_topology();
1266	nmi_selftest();
1267	impress_friends();
1268	cache_aps_init();
1269}
1270
1271/* correctly size the local cpu masks */
1272void __init setup_cpu_local_masks(void)
1273{
1274	alloc_bootmem_cpumask_var(&cpu_sibling_setup_mask);
1275}
1276
1277#ifdef CONFIG_HOTPLUG_CPU
1278
1279/* Recompute SMT state for all CPUs on offline */
1280static void recompute_smt_state(void)
1281{
1282	int max_threads, cpu;
1283
1284	max_threads = 0;
1285	for_each_online_cpu (cpu) {
1286		int threads = cpumask_weight(topology_sibling_cpumask(cpu));
1287
1288		if (threads > max_threads)
1289			max_threads = threads;
1290	}
1291	__max_smt_threads = max_threads;
1292}
1293
1294static void remove_siblinginfo(int cpu)
1295{
1296	int sibling;
1297	struct cpuinfo_x86 *c = &cpu_data(cpu);
1298
1299	for_each_cpu(sibling, topology_core_cpumask(cpu)) {
1300		cpumask_clear_cpu(cpu, topology_core_cpumask(sibling));
1301		/*/
1302		 * last thread sibling in this cpu core going down
1303		 */
1304		if (cpumask_weight(topology_sibling_cpumask(cpu)) == 1)
1305			cpu_data(sibling).booted_cores--;
1306	}
1307
1308	for_each_cpu(sibling, topology_die_cpumask(cpu))
1309		cpumask_clear_cpu(cpu, topology_die_cpumask(sibling));
1310
1311	for_each_cpu(sibling, topology_sibling_cpumask(cpu)) {
1312		cpumask_clear_cpu(cpu, topology_sibling_cpumask(sibling));
1313		if (cpumask_weight(topology_sibling_cpumask(sibling)) == 1)
1314			cpu_data(sibling).smt_active = false;
1315	}
1316
1317	for_each_cpu(sibling, cpu_llc_shared_mask(cpu))
1318		cpumask_clear_cpu(cpu, cpu_llc_shared_mask(sibling));
1319	for_each_cpu(sibling, cpu_l2c_shared_mask(cpu))
1320		cpumask_clear_cpu(cpu, cpu_l2c_shared_mask(sibling));
1321	cpumask_clear(cpu_llc_shared_mask(cpu));
1322	cpumask_clear(cpu_l2c_shared_mask(cpu));
1323	cpumask_clear(topology_sibling_cpumask(cpu));
1324	cpumask_clear(topology_core_cpumask(cpu));
1325	cpumask_clear(topology_die_cpumask(cpu));
1326	c->topo.core_id = 0;
1327	c->booted_cores = 0;
1328	cpumask_clear_cpu(cpu, cpu_sibling_setup_mask);
1329	recompute_smt_state();
1330}
1331
1332static void remove_cpu_from_maps(int cpu)
1333{
1334	set_cpu_online(cpu, false);
1335	numa_remove_cpu(cpu);
1336}
1337
1338void cpu_disable_common(void)
1339{
1340	int cpu = smp_processor_id();
1341
1342	remove_siblinginfo(cpu);
1343
1344	/*
1345	 * Stop allowing kernel-mode FPU. This is needed so that if the CPU is
1346	 * brought online again, the initial state is not allowed:
1347	 */
1348	this_cpu_write(kernel_fpu_allowed, false);
1349
1350	/* It's now safe to remove this processor from the online map */
1351	lock_vector_lock();
1352	remove_cpu_from_maps(cpu);
1353	unlock_vector_lock();
1354	fixup_irqs();
1355	lapic_offline();
1356}
1357
1358int native_cpu_disable(void)
1359{
1360	int ret;
1361
1362	ret = lapic_can_unplug_cpu();
1363	if (ret)
1364		return ret;
1365
1366	cpu_disable_common();
1367
1368        /*
1369         * Disable the local APIC. Otherwise IPI broadcasts will reach
1370         * it. It still responds normally to INIT, NMI, SMI, and SIPI
1371         * messages.
1372         *
1373         * Disabling the APIC must happen after cpu_disable_common()
1374         * which invokes fixup_irqs().
1375         *
1376         * Disabling the APIC preserves already set bits in IRR, but
1377         * an interrupt arriving after disabling the local APIC does not
1378         * set the corresponding IRR bit.
1379         *
1380         * fixup_irqs() scans IRR for set bits so it can raise a not
1381         * yet handled interrupt on the new destination CPU via an IPI
1382         * but obviously it can't do so for IRR bits which are not set.
1383         * IOW, interrupts arriving after disabling the local APIC will
1384         * be lost.
1385         */
1386	apic_soft_disable();
1387
1388	return 0;
1389}
1390
1391void play_dead_common(void)
1392{
1393	idle_task_exit();
1394
1395	cpuhp_ap_report_dead();
1396
1397	local_irq_disable();
1398}
1399
1400/*
1401 * We need to flush the caches before going to sleep, lest we have
1402 * dirty data in our caches when we come back up.
1403 */
1404void __noreturn mwait_play_dead(unsigned int eax_hint)
1405{
1406	struct mwait_cpu_dead *md = this_cpu_ptr(&mwait_cpu_dead);
1407
1408	/* Set up state for the kexec() hack below */
1409	md->status = CPUDEAD_MWAIT_WAIT;
1410	md->control = CPUDEAD_MWAIT_WAIT;
1411
1412	wbinvd();
1413
1414	while (1) {
1415		/*
1416		 * The CLFLUSH is a workaround for erratum AAI65 for
1417		 * the Xeon 7400 series.  It's not clear it is actually
1418		 * needed, but it should be harmless in either case.
1419		 * The WBINVD is insufficient due to the spurious-wakeup
1420		 * case where we return around the loop.
1421		 */
1422		mb();
1423		clflush(md);
1424		mb();
1425		__monitor(md, 0, 0);
1426		mb();
1427		__mwait(eax_hint, 0);
1428
1429		if (READ_ONCE(md->control) == CPUDEAD_MWAIT_KEXEC_HLT) {
1430			/*
1431			 * Kexec is about to happen. Don't go back into mwait() as
1432			 * the kexec kernel might overwrite text and data including
1433			 * page tables and stack. So mwait() would resume when the
1434			 * monitor cache line is written to and then the CPU goes
1435			 * south due to overwritten text, page tables and stack.
1436			 *
1437			 * Note: This does _NOT_ protect against a stray MCE, NMI,
1438			 * SMI. They will resume execution at the instruction
1439			 * following the HLT instruction and run into the problem
1440			 * which this is trying to prevent.
1441			 */
1442			WRITE_ONCE(md->status, CPUDEAD_MWAIT_KEXEC_HLT);
1443			while(1)
1444				native_halt();
1445		}
1446	}
1447}
1448
1449/*
1450 * Kick all "offline" CPUs out of mwait on kexec(). See comment in
1451 * mwait_play_dead().
1452 */
1453void smp_kick_mwait_play_dead(void)
1454{
1455	u32 newstate = CPUDEAD_MWAIT_KEXEC_HLT;
1456	struct mwait_cpu_dead *md;
1457	unsigned int cpu, i;
1458
1459	for_each_cpu_andnot(cpu, cpu_present_mask, cpu_online_mask) {
1460		md = per_cpu_ptr(&mwait_cpu_dead, cpu);
1461
1462		/* Does it sit in mwait_play_dead() ? */
1463		if (READ_ONCE(md->status) != CPUDEAD_MWAIT_WAIT)
1464			continue;
1465
1466		/* Wait up to 5ms */
1467		for (i = 0; READ_ONCE(md->status) != newstate && i < 1000; i++) {
1468			/* Bring it out of mwait */
1469			WRITE_ONCE(md->control, newstate);
1470			udelay(5);
1471		}
1472
1473		if (READ_ONCE(md->status) != newstate)
1474			pr_err_once("CPU%u is stuck in mwait_play_dead()\n", cpu);
1475	}
1476}
1477
1478void __noreturn hlt_play_dead(void)
1479{
1480	if (__this_cpu_read(cpu_info.x86) >= 4)
1481		wbinvd();
1482
1483	while (1)
1484		native_halt();
1485}
1486
1487void __noreturn native_play_dead(void)
1488{
1489	if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS))
1490		__update_spec_ctrl(0);
1491
1492	play_dead_common();
1493	tboot_shutdown(TB_SHUTDOWN_WFS);
1494
1495	/* Below returns only on error. */
1496	cpuidle_play_dead();
1497	hlt_play_dead();
1498}
1499
1500#else /* ... !CONFIG_HOTPLUG_CPU */
1501int native_cpu_disable(void)
1502{
1503	return -ENOSYS;
1504}
1505
1506void __noreturn native_play_dead(void)
1507{
1508	BUG();
1509}
1510
1511#endif
~/ Read-only file preview.