xref: /openbmc/linux/arch/x86/kernel/smpboot.c (revision aaa880f8)
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/desc.h>
68 #include <asm/nmi.h>
69 #include <asm/irq.h>
70 #include <asm/realmode.h>
71 #include <asm/cpu.h>
72 #include <asm/numa.h>
73 #include <asm/tlbflush.h>
74 #include <asm/mtrr.h>
75 #include <asm/mwait.h>
76 #include <asm/apic.h>
77 #include <asm/io_apic.h>
78 #include <asm/fpu/api.h>
79 #include <asm/setup.h>
80 #include <asm/uv/uv.h>
81 #include <asm/microcode.h>
82 #include <asm/i8259.h>
83 #include <asm/misc.h>
84 #include <asm/qspinlock.h>
85 #include <asm/intel-family.h>
86 #include <asm/cpu_device_id.h>
87 #include <asm/spec-ctrl.h>
88 #include <asm/hw_irq.h>
89 #include <asm/stackprotector.h>
90 #include <asm/sev.h>
91 
92 /* representing HT siblings of each logical CPU */
93 DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_sibling_map);
94 EXPORT_PER_CPU_SYMBOL(cpu_sibling_map);
95 
96 /* representing HT and core siblings of each logical CPU */
97 DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_core_map);
98 EXPORT_PER_CPU_SYMBOL(cpu_core_map);
99 
100 /* representing HT, core, and die siblings of each logical CPU */
101 DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_die_map);
102 EXPORT_PER_CPU_SYMBOL(cpu_die_map);
103 
104 /* Per CPU bogomips and other parameters */
105 DEFINE_PER_CPU_READ_MOSTLY(struct cpuinfo_x86, cpu_info);
106 EXPORT_PER_CPU_SYMBOL(cpu_info);
107 
108 /* CPUs which are the primary SMT threads */
109 struct cpumask __cpu_primary_thread_mask __read_mostly;
110 
111 /* Representing CPUs for which sibling maps can be computed */
112 static cpumask_var_t cpu_sibling_setup_mask;
113 
114 struct mwait_cpu_dead {
115 	unsigned int	control;
116 	unsigned int	status;
117 };
118 
119 #define CPUDEAD_MWAIT_WAIT	0xDEADBEEF
120 #define CPUDEAD_MWAIT_KEXEC_HLT	0x4A17DEAD
121 
122 /*
123  * Cache line aligned data for mwait_play_dead(). Separate on purpose so
124  * that it's unlikely to be touched by other CPUs.
125  */
126 static DEFINE_PER_CPU_ALIGNED(struct mwait_cpu_dead, mwait_cpu_dead);
127 
128 /* Logical package management. We might want to allocate that dynamically */
129 unsigned int __max_logical_packages __read_mostly;
130 EXPORT_SYMBOL(__max_logical_packages);
131 static unsigned int logical_packages __read_mostly;
132 static unsigned int logical_die __read_mostly;
133 
134 /* Maximum number of SMT threads on any online core */
135 int __read_mostly __max_smt_threads = 1;
136 
137 /* Flag to indicate if a complete sched domain rebuild is required */
138 bool x86_topology_update;
139 
140 int arch_update_cpu_topology(void)
141 {
142 	int retval = x86_topology_update;
143 
144 	x86_topology_update = false;
145 	return retval;
146 }
147 
148 static unsigned int smpboot_warm_reset_vector_count;
149 
150 static inline void smpboot_setup_warm_reset_vector(unsigned long start_eip)
151 {
152 	unsigned long flags;
153 
154 	spin_lock_irqsave(&rtc_lock, flags);
155 	if (!smpboot_warm_reset_vector_count++) {
156 		CMOS_WRITE(0xa, 0xf);
157 		*((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_HIGH)) = start_eip >> 4;
158 		*((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) = start_eip & 0xf;
159 	}
160 	spin_unlock_irqrestore(&rtc_lock, flags);
161 }
162 
163 static inline void smpboot_restore_warm_reset_vector(void)
164 {
165 	unsigned long flags;
166 
167 	/*
168 	 * Paranoid:  Set warm reset code and vector here back
169 	 * to default values.
170 	 */
171 	spin_lock_irqsave(&rtc_lock, flags);
172 	if (!--smpboot_warm_reset_vector_count) {
173 		CMOS_WRITE(0, 0xf);
174 		*((volatile u32 *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) = 0;
175 	}
176 	spin_unlock_irqrestore(&rtc_lock, flags);
177 
178 }
179 
180 /* Run the next set of setup steps for the upcoming CPU */
181 static void ap_starting(void)
182 {
183 	int cpuid = smp_processor_id();
184 
185 	/* Mop up eventual mwait_play_dead() wreckage */
186 	this_cpu_write(mwait_cpu_dead.status, 0);
187 	this_cpu_write(mwait_cpu_dead.control, 0);
188 
189 	/*
190 	 * If woken up by an INIT in an 82489DX configuration the alive
191 	 * synchronization guarantees that the CPU does not reach this
192 	 * point before an INIT_deassert IPI reaches the local APIC, so it
193 	 * is now safe to touch the local APIC.
194 	 *
195 	 * Set up this CPU, first the APIC, which is probably redundant on
196 	 * most boards.
197 	 */
198 	apic_ap_setup();
199 
200 	/* Save the processor parameters. */
201 	smp_store_cpu_info(cpuid);
202 
203 	/*
204 	 * The topology information must be up to date before
205 	 * notify_cpu_starting().
206 	 */
207 	set_cpu_sibling_map(cpuid);
208 
209 	ap_init_aperfmperf();
210 
211 	pr_debug("Stack at about %p\n", &cpuid);
212 
213 	wmb();
214 
215 	/*
216 	 * This runs the AP through all the cpuhp states to its target
217 	 * state CPUHP_ONLINE.
218 	 */
219 	notify_cpu_starting(cpuid);
220 }
221 
222 static void ap_calibrate_delay(void)
223 {
224 	/*
225 	 * Calibrate the delay loop and update loops_per_jiffy in cpu_data.
226 	 * smp_store_cpu_info() stored a value that is close but not as
227 	 * accurate as the value just calculated.
228 	 *
229 	 * As this is invoked after the TSC synchronization check,
230 	 * calibrate_delay_is_known() will skip the calibration routine
231 	 * when TSC is synchronized across sockets.
232 	 */
233 	calibrate_delay();
234 	cpu_data(smp_processor_id()).loops_per_jiffy = loops_per_jiffy;
235 }
236 
237 /*
238  * Activate a secondary processor.
239  */
240 static void notrace start_secondary(void *unused)
241 {
242 	/*
243 	 * Don't put *anything* except direct CPU state initialization
244 	 * before cpu_init(), SMP booting is too fragile that we want to
245 	 * limit the things done here to the most necessary things.
246 	 */
247 	cr4_init();
248 
249 	/*
250 	 * 32-bit specific. 64-bit reaches this code with the correct page
251 	 * table established. Yet another historical divergence.
252 	 */
253 	if (IS_ENABLED(CONFIG_X86_32)) {
254 		/* switch away from the initial page table */
255 		load_cr3(swapper_pg_dir);
256 		__flush_tlb_all();
257 	}
258 
259 	cpu_init_exception_handling();
260 
261 	/*
262 	 * 32-bit systems load the microcode from the ASM startup code for
263 	 * historical reasons.
264 	 *
265 	 * On 64-bit systems load it before reaching the AP alive
266 	 * synchronization point below so it is not part of the full per
267 	 * CPU serialized bringup part when "parallel" bringup is enabled.
268 	 *
269 	 * That's even safe when hyperthreading is enabled in the CPU as
270 	 * the core code starts the primary threads first and leaves the
271 	 * secondary threads waiting for SIPI. Loading microcode on
272 	 * physical cores concurrently is a safe operation.
273 	 *
274 	 * This covers both the Intel specific issue that concurrent
275 	 * microcode loading on SMT siblings must be prohibited and the
276 	 * vendor independent issue`that microcode loading which changes
277 	 * CPUID, MSRs etc. must be strictly serialized to maintain
278 	 * software state correctness.
279 	 */
280 	if (IS_ENABLED(CONFIG_X86_64))
281 		load_ucode_ap();
282 
283 	/*
284 	 * Synchronization point with the hotplug core. Sets this CPUs
285 	 * synchronization state to ALIVE and spin-waits for the control CPU to
286 	 * release this CPU for further bringup.
287 	 */
288 	cpuhp_ap_sync_alive();
289 
290 	cpu_init();
291 	fpu__init_cpu();
292 	rcu_cpu_starting(raw_smp_processor_id());
293 	x86_cpuinit.early_percpu_clock_init();
294 
295 	ap_starting();
296 
297 	/* Check TSC synchronization with the control CPU. */
298 	check_tsc_sync_target();
299 
300 	/*
301 	 * Calibrate the delay loop after the TSC synchronization check.
302 	 * This allows to skip the calibration when TSC is synchronized
303 	 * across sockets.
304 	 */
305 	ap_calibrate_delay();
306 
307 	speculative_store_bypass_ht_init();
308 
309 	/*
310 	 * Lock vector_lock, set CPU online and bring the vector
311 	 * allocator online. Online must be set with vector_lock held
312 	 * to prevent a concurrent irq setup/teardown from seeing a
313 	 * half valid vector space.
314 	 */
315 	lock_vector_lock();
316 	set_cpu_online(smp_processor_id(), true);
317 	lapic_online();
318 	unlock_vector_lock();
319 	x86_platform.nmi_init();
320 
321 	/* enable local interrupts */
322 	local_irq_enable();
323 
324 	x86_cpuinit.setup_percpu_clockev();
325 
326 	wmb();
327 	cpu_startup_entry(CPUHP_AP_ONLINE_IDLE);
328 }
329 
330 /**
331  * topology_phys_to_logical_pkg - Map a physical package id to a logical
332  * @phys_pkg:	The physical package id to map
333  *
334  * Returns logical package id or -1 if not found
335  */
336 int topology_phys_to_logical_pkg(unsigned int phys_pkg)
337 {
338 	int cpu;
339 
340 	for_each_possible_cpu(cpu) {
341 		struct cpuinfo_x86 *c = &cpu_data(cpu);
342 
343 		if (c->initialized && c->phys_proc_id == phys_pkg)
344 			return c->logical_proc_id;
345 	}
346 	return -1;
347 }
348 EXPORT_SYMBOL(topology_phys_to_logical_pkg);
349 
350 /**
351  * topology_phys_to_logical_die - Map a physical die id to logical
352  * @die_id:	The physical die id to map
353  * @cur_cpu:	The CPU for which the mapping is done
354  *
355  * Returns logical die id or -1 if not found
356  */
357 static int topology_phys_to_logical_die(unsigned int die_id, unsigned int cur_cpu)
358 {
359 	int cpu, proc_id = cpu_data(cur_cpu).phys_proc_id;
360 
361 	for_each_possible_cpu(cpu) {
362 		struct cpuinfo_x86 *c = &cpu_data(cpu);
363 
364 		if (c->initialized && c->cpu_die_id == die_id &&
365 		    c->phys_proc_id == proc_id)
366 			return c->logical_die_id;
367 	}
368 	return -1;
369 }
370 
371 /**
372  * topology_update_package_map - Update the physical to logical package map
373  * @pkg:	The physical package id as retrieved via CPUID
374  * @cpu:	The cpu for which this is updated
375  */
376 int topology_update_package_map(unsigned int pkg, unsigned int cpu)
377 {
378 	int new;
379 
380 	/* Already available somewhere? */
381 	new = topology_phys_to_logical_pkg(pkg);
382 	if (new >= 0)
383 		goto found;
384 
385 	new = logical_packages++;
386 	if (new != pkg) {
387 		pr_info("CPU %u Converting physical %u to logical package %u\n",
388 			cpu, pkg, new);
389 	}
390 found:
391 	cpu_data(cpu).logical_proc_id = new;
392 	return 0;
393 }
394 /**
395  * topology_update_die_map - Update the physical to logical die map
396  * @die:	The die id as retrieved via CPUID
397  * @cpu:	The cpu for which this is updated
398  */
399 int topology_update_die_map(unsigned int die, unsigned int cpu)
400 {
401 	int new;
402 
403 	/* Already available somewhere? */
404 	new = topology_phys_to_logical_die(die, cpu);
405 	if (new >= 0)
406 		goto found;
407 
408 	new = logical_die++;
409 	if (new != die) {
410 		pr_info("CPU %u Converting physical %u to logical die %u\n",
411 			cpu, die, new);
412 	}
413 found:
414 	cpu_data(cpu).logical_die_id = new;
415 	return 0;
416 }
417 
418 static void __init smp_store_boot_cpu_info(void)
419 {
420 	int id = 0; /* CPU 0 */
421 	struct cpuinfo_x86 *c = &cpu_data(id);
422 
423 	*c = boot_cpu_data;
424 	c->cpu_index = id;
425 	topology_update_package_map(c->phys_proc_id, id);
426 	topology_update_die_map(c->cpu_die_id, id);
427 	c->initialized = true;
428 }
429 
430 /*
431  * The bootstrap kernel entry code has set these up. Save them for
432  * a given CPU
433  */
434 void smp_store_cpu_info(int id)
435 {
436 	struct cpuinfo_x86 *c = &cpu_data(id);
437 
438 	/* Copy boot_cpu_data only on the first bringup */
439 	if (!c->initialized)
440 		*c = boot_cpu_data;
441 	c->cpu_index = id;
442 	/*
443 	 * During boot time, CPU0 has this setup already. Save the info when
444 	 * bringing up an AP.
445 	 */
446 	identify_secondary_cpu(c);
447 	c->initialized = true;
448 }
449 
450 static bool
451 topology_same_node(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
452 {
453 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
454 
455 	return (cpu_to_node(cpu1) == cpu_to_node(cpu2));
456 }
457 
458 static bool
459 topology_sane(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o, const char *name)
460 {
461 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
462 
463 	return !WARN_ONCE(!topology_same_node(c, o),
464 		"sched: CPU #%d's %s-sibling CPU #%d is not on the same node! "
465 		"[node: %d != %d]. Ignoring dependency.\n",
466 		cpu1, name, cpu2, cpu_to_node(cpu1), cpu_to_node(cpu2));
467 }
468 
469 #define link_mask(mfunc, c1, c2)					\
470 do {									\
471 	cpumask_set_cpu((c1), mfunc(c2));				\
472 	cpumask_set_cpu((c2), mfunc(c1));				\
473 } while (0)
474 
475 static bool match_smt(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
476 {
477 	if (boot_cpu_has(X86_FEATURE_TOPOEXT)) {
478 		int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
479 
480 		if (c->phys_proc_id == o->phys_proc_id &&
481 		    c->cpu_die_id == o->cpu_die_id &&
482 		    per_cpu(cpu_llc_id, cpu1) == per_cpu(cpu_llc_id, cpu2)) {
483 			if (c->cpu_core_id == o->cpu_core_id)
484 				return topology_sane(c, o, "smt");
485 
486 			if ((c->cu_id != 0xff) &&
487 			    (o->cu_id != 0xff) &&
488 			    (c->cu_id == o->cu_id))
489 				return topology_sane(c, o, "smt");
490 		}
491 
492 	} else if (c->phys_proc_id == o->phys_proc_id &&
493 		   c->cpu_die_id == o->cpu_die_id &&
494 		   c->cpu_core_id == o->cpu_core_id) {
495 		return topology_sane(c, o, "smt");
496 	}
497 
498 	return false;
499 }
500 
501 static bool match_die(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
502 {
503 	if (c->phys_proc_id == o->phys_proc_id &&
504 	    c->cpu_die_id == o->cpu_die_id)
505 		return true;
506 	return false;
507 }
508 
509 static bool match_l2c(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
510 {
511 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
512 
513 	/* If the arch didn't set up l2c_id, fall back to SMT */
514 	if (per_cpu(cpu_l2c_id, cpu1) == BAD_APICID)
515 		return match_smt(c, o);
516 
517 	/* Do not match if L2 cache id does not match: */
518 	if (per_cpu(cpu_l2c_id, cpu1) != per_cpu(cpu_l2c_id, cpu2))
519 		return false;
520 
521 	return topology_sane(c, o, "l2c");
522 }
523 
524 /*
525  * Unlike the other levels, we do not enforce keeping a
526  * multicore group inside a NUMA node.  If this happens, we will
527  * discard the MC level of the topology later.
528  */
529 static bool match_pkg(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
530 {
531 	if (c->phys_proc_id == o->phys_proc_id)
532 		return true;
533 	return false;
534 }
535 
536 /*
537  * Define intel_cod_cpu[] for Intel COD (Cluster-on-Die) CPUs.
538  *
539  * Any Intel CPU that has multiple nodes per package and does not
540  * match intel_cod_cpu[] has the SNC (Sub-NUMA Cluster) topology.
541  *
542  * When in SNC mode, these CPUs enumerate an LLC that is shared
543  * by multiple NUMA nodes. The LLC is shared for off-package data
544  * access but private to the NUMA node (half of the package) for
545  * on-package access. CPUID (the source of the information about
546  * the LLC) can only enumerate the cache as shared or unshared,
547  * but not this particular configuration.
548  */
549 
550 static const struct x86_cpu_id intel_cod_cpu[] = {
551 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_X, 0),	/* COD */
552 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_X, 0),	/* COD */
553 	X86_MATCH_INTEL_FAM6_MODEL(ANY, 1),		/* SNC */
554 	{}
555 };
556 
557 static bool match_llc(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
558 {
559 	const struct x86_cpu_id *id = x86_match_cpu(intel_cod_cpu);
560 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
561 	bool intel_snc = id && id->driver_data;
562 
563 	/* Do not match if we do not have a valid APICID for cpu: */
564 	if (per_cpu(cpu_llc_id, cpu1) == BAD_APICID)
565 		return false;
566 
567 	/* Do not match if LLC id does not match: */
568 	if (per_cpu(cpu_llc_id, cpu1) != per_cpu(cpu_llc_id, cpu2))
569 		return false;
570 
571 	/*
572 	 * Allow the SNC topology without warning. Return of false
573 	 * means 'c' does not share the LLC of 'o'. This will be
574 	 * reflected to userspace.
575 	 */
576 	if (match_pkg(c, o) && !topology_same_node(c, o) && intel_snc)
577 		return false;
578 
579 	return topology_sane(c, o, "llc");
580 }
581 
582 
583 static inline int x86_sched_itmt_flags(void)
584 {
585 	return sysctl_sched_itmt_enabled ? SD_ASYM_PACKING : 0;
586 }
587 
588 #ifdef CONFIG_SCHED_MC
589 static int x86_core_flags(void)
590 {
591 	return cpu_core_flags() | x86_sched_itmt_flags();
592 }
593 #endif
594 #ifdef CONFIG_SCHED_SMT
595 static int x86_smt_flags(void)
596 {
597 	return cpu_smt_flags();
598 }
599 #endif
600 #ifdef CONFIG_SCHED_CLUSTER
601 static int x86_cluster_flags(void)
602 {
603 	return cpu_cluster_flags() | x86_sched_itmt_flags();
604 }
605 #endif
606 
607 static int x86_die_flags(void)
608 {
609 	if (cpu_feature_enabled(X86_FEATURE_HYBRID_CPU))
610 	       return x86_sched_itmt_flags();
611 
612 	return 0;
613 }
614 
615 /*
616  * Set if a package/die has multiple NUMA nodes inside.
617  * AMD Magny-Cours, Intel Cluster-on-Die, and Intel
618  * Sub-NUMA Clustering have this.
619  */
620 static bool x86_has_numa_in_package;
621 
622 static struct sched_domain_topology_level x86_topology[6];
623 
624 static void __init build_sched_topology(void)
625 {
626 	int i = 0;
627 
628 #ifdef CONFIG_SCHED_SMT
629 	x86_topology[i++] = (struct sched_domain_topology_level){
630 		cpu_smt_mask, x86_smt_flags, SD_INIT_NAME(SMT)
631 	};
632 #endif
633 #ifdef CONFIG_SCHED_CLUSTER
634 	x86_topology[i++] = (struct sched_domain_topology_level){
635 		cpu_clustergroup_mask, x86_cluster_flags, SD_INIT_NAME(CLS)
636 	};
637 #endif
638 #ifdef CONFIG_SCHED_MC
639 	x86_topology[i++] = (struct sched_domain_topology_level){
640 		cpu_coregroup_mask, x86_core_flags, SD_INIT_NAME(MC)
641 	};
642 #endif
643 	/*
644 	 * When there is NUMA topology inside the package skip the DIE domain
645 	 * since the NUMA domains will auto-magically create the right spanning
646 	 * domains based on the SLIT.
647 	 */
648 	if (!x86_has_numa_in_package) {
649 		x86_topology[i++] = (struct sched_domain_topology_level){
650 			cpu_cpu_mask, x86_die_flags, SD_INIT_NAME(DIE)
651 		};
652 	}
653 
654 	/*
655 	 * There must be one trailing NULL entry left.
656 	 */
657 	BUG_ON(i >= ARRAY_SIZE(x86_topology)-1);
658 
659 	set_sched_topology(x86_topology);
660 }
661 
662 void set_cpu_sibling_map(int cpu)
663 {
664 	bool has_smt = smp_num_siblings > 1;
665 	bool has_mp = has_smt || boot_cpu_data.x86_max_cores > 1;
666 	struct cpuinfo_x86 *c = &cpu_data(cpu);
667 	struct cpuinfo_x86 *o;
668 	int i, threads;
669 
670 	cpumask_set_cpu(cpu, cpu_sibling_setup_mask);
671 
672 	if (!has_mp) {
673 		cpumask_set_cpu(cpu, topology_sibling_cpumask(cpu));
674 		cpumask_set_cpu(cpu, cpu_llc_shared_mask(cpu));
675 		cpumask_set_cpu(cpu, cpu_l2c_shared_mask(cpu));
676 		cpumask_set_cpu(cpu, topology_core_cpumask(cpu));
677 		cpumask_set_cpu(cpu, topology_die_cpumask(cpu));
678 		c->booted_cores = 1;
679 		return;
680 	}
681 
682 	for_each_cpu(i, cpu_sibling_setup_mask) {
683 		o = &cpu_data(i);
684 
685 		if (match_pkg(c, o) && !topology_same_node(c, o))
686 			x86_has_numa_in_package = true;
687 
688 		if ((i == cpu) || (has_smt && match_smt(c, o)))
689 			link_mask(topology_sibling_cpumask, cpu, i);
690 
691 		if ((i == cpu) || (has_mp && match_llc(c, o)))
692 			link_mask(cpu_llc_shared_mask, cpu, i);
693 
694 		if ((i == cpu) || (has_mp && match_l2c(c, o)))
695 			link_mask(cpu_l2c_shared_mask, cpu, i);
696 
697 		if ((i == cpu) || (has_mp && match_die(c, o)))
698 			link_mask(topology_die_cpumask, cpu, i);
699 	}
700 
701 	threads = cpumask_weight(topology_sibling_cpumask(cpu));
702 	if (threads > __max_smt_threads)
703 		__max_smt_threads = threads;
704 
705 	for_each_cpu(i, topology_sibling_cpumask(cpu))
706 		cpu_data(i).smt_active = threads > 1;
707 
708 	/*
709 	 * This needs a separate iteration over the cpus because we rely on all
710 	 * topology_sibling_cpumask links to be set-up.
711 	 */
712 	for_each_cpu(i, cpu_sibling_setup_mask) {
713 		o = &cpu_data(i);
714 
715 		if ((i == cpu) || (has_mp && match_pkg(c, o))) {
716 			link_mask(topology_core_cpumask, cpu, i);
717 
718 			/*
719 			 *  Does this new cpu bringup a new core?
720 			 */
721 			if (threads == 1) {
722 				/*
723 				 * for each core in package, increment
724 				 * the booted_cores for this new cpu
725 				 */
726 				if (cpumask_first(
727 				    topology_sibling_cpumask(i)) == i)
728 					c->booted_cores++;
729 				/*
730 				 * increment the core count for all
731 				 * the other cpus in this package
732 				 */
733 				if (i != cpu)
734 					cpu_data(i).booted_cores++;
735 			} else if (i != cpu && !c->booted_cores)
736 				c->booted_cores = cpu_data(i).booted_cores;
737 		}
738 	}
739 }
740 
741 /* maps the cpu to the sched domain representing multi-core */
742 const struct cpumask *cpu_coregroup_mask(int cpu)
743 {
744 	return cpu_llc_shared_mask(cpu);
745 }
746 
747 const struct cpumask *cpu_clustergroup_mask(int cpu)
748 {
749 	return cpu_l2c_shared_mask(cpu);
750 }
751 
752 static void impress_friends(void)
753 {
754 	int cpu;
755 	unsigned long bogosum = 0;
756 	/*
757 	 * Allow the user to impress friends.
758 	 */
759 	pr_debug("Before bogomips\n");
760 	for_each_online_cpu(cpu)
761 		bogosum += cpu_data(cpu).loops_per_jiffy;
762 
763 	pr_info("Total of %d processors activated (%lu.%02lu BogoMIPS)\n",
764 		num_online_cpus(),
765 		bogosum/(500000/HZ),
766 		(bogosum/(5000/HZ))%100);
767 
768 	pr_debug("Before bogocount - setting activated=1\n");
769 }
770 
771 /*
772  * The Multiprocessor Specification 1.4 (1997) example code suggests
773  * that there should be a 10ms delay between the BSP asserting INIT
774  * and de-asserting INIT, when starting a remote processor.
775  * But that slows boot and resume on modern processors, which include
776  * many cores and don't require that delay.
777  *
778  * Cmdline "init_cpu_udelay=" is available to over-ride this delay.
779  * Modern processor families are quirked to remove the delay entirely.
780  */
781 #define UDELAY_10MS_DEFAULT 10000
782 
783 static unsigned int init_udelay = UINT_MAX;
784 
785 static int __init cpu_init_udelay(char *str)
786 {
787 	get_option(&str, &init_udelay);
788 
789 	return 0;
790 }
791 early_param("cpu_init_udelay", cpu_init_udelay);
792 
793 static void __init smp_quirk_init_udelay(void)
794 {
795 	/* if cmdline changed it from default, leave it alone */
796 	if (init_udelay != UINT_MAX)
797 		return;
798 
799 	/* if modern processor, use no delay */
800 	if (((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) && (boot_cpu_data.x86 == 6)) ||
801 	    ((boot_cpu_data.x86_vendor == X86_VENDOR_HYGON) && (boot_cpu_data.x86 >= 0x18)) ||
802 	    ((boot_cpu_data.x86_vendor == X86_VENDOR_AMD) && (boot_cpu_data.x86 >= 0xF))) {
803 		init_udelay = 0;
804 		return;
805 	}
806 	/* else, use legacy delay */
807 	init_udelay = UDELAY_10MS_DEFAULT;
808 }
809 
810 /*
811  * Wake up AP by INIT, INIT, STARTUP sequence.
812  */
813 static void send_init_sequence(int phys_apicid)
814 {
815 	int maxlvt = lapic_get_maxlvt();
816 
817 	/* Be paranoid about clearing APIC errors. */
818 	if (APIC_INTEGRATED(boot_cpu_apic_version)) {
819 		/* Due to the Pentium erratum 3AP.  */
820 		if (maxlvt > 3)
821 			apic_write(APIC_ESR, 0);
822 		apic_read(APIC_ESR);
823 	}
824 
825 	/* Assert INIT on the target CPU */
826 	apic_icr_write(APIC_INT_LEVELTRIG | APIC_INT_ASSERT | APIC_DM_INIT, phys_apicid);
827 	safe_apic_wait_icr_idle();
828 
829 	udelay(init_udelay);
830 
831 	/* Deassert INIT on the target CPU */
832 	apic_icr_write(APIC_INT_LEVELTRIG | APIC_DM_INIT, phys_apicid);
833 	safe_apic_wait_icr_idle();
834 }
835 
836 /*
837  * Wake up AP by INIT, INIT, STARTUP sequence.
838  */
839 static int wakeup_secondary_cpu_via_init(int phys_apicid, unsigned long start_eip)
840 {
841 	unsigned long send_status = 0, accept_status = 0;
842 	int num_starts, j, maxlvt;
843 
844 	preempt_disable();
845 	maxlvt = lapic_get_maxlvt();
846 	send_init_sequence(phys_apicid);
847 
848 	mb();
849 
850 	/*
851 	 * Should we send STARTUP IPIs ?
852 	 *
853 	 * Determine this based on the APIC version.
854 	 * If we don't have an integrated APIC, don't send the STARTUP IPIs.
855 	 */
856 	if (APIC_INTEGRATED(boot_cpu_apic_version))
857 		num_starts = 2;
858 	else
859 		num_starts = 0;
860 
861 	/*
862 	 * Run STARTUP IPI loop.
863 	 */
864 	pr_debug("#startup loops: %d\n", num_starts);
865 
866 	for (j = 1; j <= num_starts; j++) {
867 		pr_debug("Sending STARTUP #%d\n", j);
868 		if (maxlvt > 3)		/* Due to the Pentium erratum 3AP.  */
869 			apic_write(APIC_ESR, 0);
870 		apic_read(APIC_ESR);
871 		pr_debug("After apic_write\n");
872 
873 		/*
874 		 * STARTUP IPI
875 		 */
876 
877 		/* Target chip */
878 		/* Boot on the stack */
879 		/* Kick the second */
880 		apic_icr_write(APIC_DM_STARTUP | (start_eip >> 12),
881 			       phys_apicid);
882 
883 		/*
884 		 * Give the other CPU some time to accept the IPI.
885 		 */
886 		if (init_udelay == 0)
887 			udelay(10);
888 		else
889 			udelay(300);
890 
891 		pr_debug("Startup point 1\n");
892 
893 		pr_debug("Waiting for send to finish...\n");
894 		send_status = safe_apic_wait_icr_idle();
895 
896 		/*
897 		 * Give the other CPU some time to accept the IPI.
898 		 */
899 		if (init_udelay == 0)
900 			udelay(10);
901 		else
902 			udelay(200);
903 
904 		if (maxlvt > 3)		/* Due to the Pentium erratum 3AP.  */
905 			apic_write(APIC_ESR, 0);
906 		accept_status = (apic_read(APIC_ESR) & 0xEF);
907 		if (send_status || accept_status)
908 			break;
909 	}
910 	pr_debug("After Startup\n");
911 
912 	if (send_status)
913 		pr_err("APIC never delivered???\n");
914 	if (accept_status)
915 		pr_err("APIC delivery error (%lx)\n", accept_status);
916 
917 	preempt_enable();
918 	return (send_status | accept_status);
919 }
920 
921 /* reduce the number of lines printed when booting a large cpu count system */
922 static void announce_cpu(int cpu, int apicid)
923 {
924 	static int width, node_width, first = 1;
925 	static int current_node = NUMA_NO_NODE;
926 	int node = early_cpu_to_node(cpu);
927 
928 	if (!width)
929 		width = num_digits(num_possible_cpus()) + 1; /* + '#' sign */
930 
931 	if (!node_width)
932 		node_width = num_digits(num_possible_nodes()) + 1; /* + '#' */
933 
934 	if (system_state < SYSTEM_RUNNING) {
935 		if (first)
936 			pr_info("x86: Booting SMP configuration:\n");
937 
938 		if (node != current_node) {
939 			if (current_node > (-1))
940 				pr_cont("\n");
941 			current_node = node;
942 
943 			printk(KERN_INFO ".... node %*s#%d, CPUs:  ",
944 			       node_width - num_digits(node), " ", node);
945 		}
946 
947 		/* Add padding for the BSP */
948 		if (first)
949 			pr_cont("%*s", width + 1, " ");
950 		first = 0;
951 
952 		pr_cont("%*s#%d", width - num_digits(cpu), " ", cpu);
953 	} else
954 		pr_info("Booting Node %d Processor %d APIC 0x%x\n",
955 			node, cpu, apicid);
956 }
957 
958 int common_cpu_up(unsigned int cpu, struct task_struct *idle)
959 {
960 	int ret;
961 
962 	/* Just in case we booted with a single CPU. */
963 	alternatives_enable_smp();
964 
965 	per_cpu(pcpu_hot.current_task, cpu) = idle;
966 	cpu_init_stack_canary(cpu, idle);
967 
968 	/* Initialize the interrupt stack(s) */
969 	ret = irq_init_percpu_irqstack(cpu);
970 	if (ret)
971 		return ret;
972 
973 #ifdef CONFIG_X86_32
974 	/* Stack for startup_32 can be just as for start_secondary onwards */
975 	per_cpu(pcpu_hot.top_of_stack, cpu) = task_top_of_stack(idle);
976 #endif
977 	return 0;
978 }
979 
980 /*
981  * NOTE - on most systems this is a PHYSICAL apic ID, but on multiquad
982  * (ie clustered apic addressing mode), this is a LOGICAL apic ID.
983  * Returns zero if startup was successfully sent, else error code from
984  * ->wakeup_secondary_cpu.
985  */
986 static int do_boot_cpu(int apicid, int cpu, struct task_struct *idle)
987 {
988 	unsigned long start_ip = real_mode_header->trampoline_start;
989 	int ret;
990 
991 #ifdef CONFIG_X86_64
992 	/* If 64-bit wakeup method exists, use the 64-bit mode trampoline IP */
993 	if (apic->wakeup_secondary_cpu_64)
994 		start_ip = real_mode_header->trampoline_start64;
995 #endif
996 	idle->thread.sp = (unsigned long)task_pt_regs(idle);
997 	initial_code = (unsigned long)start_secondary;
998 
999 	if (IS_ENABLED(CONFIG_X86_32)) {
1000 		early_gdt_descr.address = (unsigned long)get_cpu_gdt_rw(cpu);
1001 		initial_stack  = idle->thread.sp;
1002 	} else if (!(smpboot_control & STARTUP_PARALLEL_MASK)) {
1003 		smpboot_control = cpu;
1004 	}
1005 
1006 	/* Enable the espfix hack for this CPU */
1007 	init_espfix_ap(cpu);
1008 
1009 	/* So we see what's up */
1010 	announce_cpu(cpu, apicid);
1011 
1012 	/*
1013 	 * This grunge runs the startup process for
1014 	 * the targeted processor.
1015 	 */
1016 	if (x86_platform.legacy.warm_reset) {
1017 
1018 		pr_debug("Setting warm reset code and vector.\n");
1019 
1020 		smpboot_setup_warm_reset_vector(start_ip);
1021 		/*
1022 		 * Be paranoid about clearing APIC errors.
1023 		*/
1024 		if (APIC_INTEGRATED(boot_cpu_apic_version)) {
1025 			apic_write(APIC_ESR, 0);
1026 			apic_read(APIC_ESR);
1027 		}
1028 	}
1029 
1030 	smp_mb();
1031 
1032 	/*
1033 	 * Wake up a CPU in difference cases:
1034 	 * - Use a method from the APIC driver if one defined, with wakeup
1035 	 *   straight to 64-bit mode preferred over wakeup to RM.
1036 	 * Otherwise,
1037 	 * - Use an INIT boot APIC message
1038 	 */
1039 	if (apic->wakeup_secondary_cpu_64)
1040 		ret = apic->wakeup_secondary_cpu_64(apicid, start_ip);
1041 	else if (apic->wakeup_secondary_cpu)
1042 		ret = apic->wakeup_secondary_cpu(apicid, start_ip);
1043 	else
1044 		ret = wakeup_secondary_cpu_via_init(apicid, start_ip);
1045 
1046 	/* If the wakeup mechanism failed, cleanup the warm reset vector */
1047 	if (ret)
1048 		arch_cpuhp_cleanup_kick_cpu(cpu);
1049 	return ret;
1050 }
1051 
1052 int native_kick_ap(unsigned int cpu, struct task_struct *tidle)
1053 {
1054 	int apicid = apic->cpu_present_to_apicid(cpu);
1055 	int err;
1056 
1057 	lockdep_assert_irqs_enabled();
1058 
1059 	pr_debug("++++++++++++++++++++=_---CPU UP  %u\n", cpu);
1060 
1061 	if (apicid == BAD_APICID || !physid_isset(apicid, phys_cpu_present_map) ||
1062 	    !apic_id_valid(apicid)) {
1063 		pr_err("%s: bad cpu %d\n", __func__, cpu);
1064 		return -EINVAL;
1065 	}
1066 
1067 	/*
1068 	 * Save current MTRR state in case it was changed since early boot
1069 	 * (e.g. by the ACPI SMI) to initialize new CPUs with MTRRs in sync:
1070 	 */
1071 	mtrr_save_state();
1072 
1073 	/* the FPU context is blank, nobody can own it */
1074 	per_cpu(fpu_fpregs_owner_ctx, cpu) = NULL;
1075 
1076 	err = common_cpu_up(cpu, tidle);
1077 	if (err)
1078 		return err;
1079 
1080 	err = do_boot_cpu(apicid, cpu, tidle);
1081 	if (err)
1082 		pr_err("do_boot_cpu failed(%d) to wakeup CPU#%u\n", err, cpu);
1083 
1084 	return err;
1085 }
1086 
1087 int arch_cpuhp_kick_ap_alive(unsigned int cpu, struct task_struct *tidle)
1088 {
1089 	return smp_ops.kick_ap_alive(cpu, tidle);
1090 }
1091 
1092 void arch_cpuhp_cleanup_kick_cpu(unsigned int cpu)
1093 {
1094 	/* Cleanup possible dangling ends... */
1095 	if (smp_ops.kick_ap_alive == native_kick_ap && x86_platform.legacy.warm_reset)
1096 		smpboot_restore_warm_reset_vector();
1097 }
1098 
1099 void arch_cpuhp_cleanup_dead_cpu(unsigned int cpu)
1100 {
1101 	if (smp_ops.cleanup_dead_cpu)
1102 		smp_ops.cleanup_dead_cpu(cpu);
1103 
1104 	if (system_state == SYSTEM_RUNNING)
1105 		pr_info("CPU %u is now offline\n", cpu);
1106 }
1107 
1108 void arch_cpuhp_sync_state_poll(void)
1109 {
1110 	if (smp_ops.poll_sync_state)
1111 		smp_ops.poll_sync_state();
1112 }
1113 
1114 /**
1115  * arch_disable_smp_support() - Disables SMP support for x86 at boottime
1116  */
1117 void __init arch_disable_smp_support(void)
1118 {
1119 	disable_ioapic_support();
1120 }
1121 
1122 /*
1123  * Fall back to non SMP mode after errors.
1124  *
1125  * RED-PEN audit/test this more. I bet there is more state messed up here.
1126  */
1127 static __init void disable_smp(void)
1128 {
1129 	pr_info("SMP disabled\n");
1130 
1131 	disable_ioapic_support();
1132 
1133 	init_cpu_present(cpumask_of(0));
1134 	init_cpu_possible(cpumask_of(0));
1135 
1136 	if (smp_found_config)
1137 		physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map);
1138 	else
1139 		physid_set_mask_of_physid(0, &phys_cpu_present_map);
1140 	cpumask_set_cpu(0, topology_sibling_cpumask(0));
1141 	cpumask_set_cpu(0, topology_core_cpumask(0));
1142 	cpumask_set_cpu(0, topology_die_cpumask(0));
1143 }
1144 
1145 static void __init smp_cpu_index_default(void)
1146 {
1147 	int i;
1148 	struct cpuinfo_x86 *c;
1149 
1150 	for_each_possible_cpu(i) {
1151 		c = &cpu_data(i);
1152 		/* mark all to hotplug */
1153 		c->cpu_index = nr_cpu_ids;
1154 	}
1155 }
1156 
1157 void __init smp_prepare_cpus_common(void)
1158 {
1159 	unsigned int i;
1160 
1161 	smp_cpu_index_default();
1162 
1163 	/*
1164 	 * Setup boot CPU information
1165 	 */
1166 	smp_store_boot_cpu_info(); /* Final full version of the data */
1167 	mb();
1168 
1169 	for_each_possible_cpu(i) {
1170 		zalloc_cpumask_var(&per_cpu(cpu_sibling_map, i), GFP_KERNEL);
1171 		zalloc_cpumask_var(&per_cpu(cpu_core_map, i), GFP_KERNEL);
1172 		zalloc_cpumask_var(&per_cpu(cpu_die_map, i), GFP_KERNEL);
1173 		zalloc_cpumask_var(&per_cpu(cpu_llc_shared_map, i), GFP_KERNEL);
1174 		zalloc_cpumask_var(&per_cpu(cpu_l2c_shared_map, i), GFP_KERNEL);
1175 	}
1176 
1177 	set_cpu_sibling_map(0);
1178 }
1179 
1180 #ifdef CONFIG_X86_64
1181 /* Establish whether parallel bringup can be supported. */
1182 bool __init arch_cpuhp_init_parallel_bringup(void)
1183 {
1184 	if (!x86_cpuinit.parallel_bringup) {
1185 		pr_info("Parallel CPU startup disabled by the platform\n");
1186 		return false;
1187 	}
1188 
1189 	smpboot_control = STARTUP_READ_APICID;
1190 	pr_debug("Parallel CPU startup enabled: 0x%08x\n", smpboot_control);
1191 	return true;
1192 }
1193 #endif
1194 
1195 /*
1196  * Prepare for SMP bootup.
1197  * @max_cpus: configured maximum number of CPUs, It is a legacy parameter
1198  *            for common interface support.
1199  */
1200 void __init native_smp_prepare_cpus(unsigned int max_cpus)
1201 {
1202 	smp_prepare_cpus_common();
1203 
1204 	switch (apic_intr_mode) {
1205 	case APIC_PIC:
1206 	case APIC_VIRTUAL_WIRE_NO_CONFIG:
1207 		disable_smp();
1208 		return;
1209 	case APIC_SYMMETRIC_IO_NO_ROUTING:
1210 		disable_smp();
1211 		/* Setup local timer */
1212 		x86_init.timers.setup_percpu_clockev();
1213 		return;
1214 	case APIC_VIRTUAL_WIRE:
1215 	case APIC_SYMMETRIC_IO:
1216 		break;
1217 	}
1218 
1219 	/* Setup local timer */
1220 	x86_init.timers.setup_percpu_clockev();
1221 
1222 	pr_info("CPU0: ");
1223 	print_cpu_info(&cpu_data(0));
1224 
1225 	uv_system_init();
1226 
1227 	smp_quirk_init_udelay();
1228 
1229 	speculative_store_bypass_ht_init();
1230 
1231 	snp_set_wakeup_secondary_cpu();
1232 }
1233 
1234 void arch_thaw_secondary_cpus_begin(void)
1235 {
1236 	set_cache_aps_delayed_init(true);
1237 }
1238 
1239 void arch_thaw_secondary_cpus_end(void)
1240 {
1241 	cache_aps_init();
1242 }
1243 
1244 /*
1245  * Early setup to make printk work.
1246  */
1247 void __init native_smp_prepare_boot_cpu(void)
1248 {
1249 	int me = smp_processor_id();
1250 
1251 	/* SMP handles this from setup_per_cpu_areas() */
1252 	if (!IS_ENABLED(CONFIG_SMP))
1253 		switch_gdt_and_percpu_base(me);
1254 
1255 	native_pv_lock_init();
1256 }
1257 
1258 void __init calculate_max_logical_packages(void)
1259 {
1260 	int ncpus;
1261 
1262 	/*
1263 	 * Today neither Intel nor AMD support heterogeneous systems so
1264 	 * extrapolate the boot cpu's data to all packages.
1265 	 */
1266 	ncpus = cpu_data(0).booted_cores * topology_max_smt_threads();
1267 	__max_logical_packages = DIV_ROUND_UP(total_cpus, ncpus);
1268 	pr_info("Max logical packages: %u\n", __max_logical_packages);
1269 }
1270 
1271 void __init native_smp_cpus_done(unsigned int max_cpus)
1272 {
1273 	pr_debug("Boot done\n");
1274 
1275 	calculate_max_logical_packages();
1276 	build_sched_topology();
1277 	nmi_selftest();
1278 	impress_friends();
1279 	cache_aps_init();
1280 }
1281 
1282 static int __initdata setup_possible_cpus = -1;
1283 static int __init _setup_possible_cpus(char *str)
1284 {
1285 	get_option(&str, &setup_possible_cpus);
1286 	return 0;
1287 }
1288 early_param("possible_cpus", _setup_possible_cpus);
1289 
1290 
1291 /*
1292  * cpu_possible_mask should be static, it cannot change as cpu's
1293  * are onlined, or offlined. The reason is per-cpu data-structures
1294  * are allocated by some modules at init time, and don't expect to
1295  * do this dynamically on cpu arrival/departure.
1296  * cpu_present_mask on the other hand can change dynamically.
1297  * In case when cpu_hotplug is not compiled, then we resort to current
1298  * behaviour, which is cpu_possible == cpu_present.
1299  * - Ashok Raj
1300  *
1301  * Three ways to find out the number of additional hotplug CPUs:
1302  * - If the BIOS specified disabled CPUs in ACPI/mptables use that.
1303  * - The user can overwrite it with possible_cpus=NUM
1304  * - Otherwise don't reserve additional CPUs.
1305  * We do this because additional CPUs waste a lot of memory.
1306  * -AK
1307  */
1308 __init void prefill_possible_map(void)
1309 {
1310 	int i, possible;
1311 
1312 	i = setup_max_cpus ?: 1;
1313 	if (setup_possible_cpus == -1) {
1314 		possible = num_processors;
1315 #ifdef CONFIG_HOTPLUG_CPU
1316 		if (setup_max_cpus)
1317 			possible += disabled_cpus;
1318 #else
1319 		if (possible > i)
1320 			possible = i;
1321 #endif
1322 	} else
1323 		possible = setup_possible_cpus;
1324 
1325 	total_cpus = max_t(int, possible, num_processors + disabled_cpus);
1326 
1327 	/* nr_cpu_ids could be reduced via nr_cpus= */
1328 	if (possible > nr_cpu_ids) {
1329 		pr_warn("%d Processors exceeds NR_CPUS limit of %u\n",
1330 			possible, nr_cpu_ids);
1331 		possible = nr_cpu_ids;
1332 	}
1333 
1334 #ifdef CONFIG_HOTPLUG_CPU
1335 	if (!setup_max_cpus)
1336 #endif
1337 	if (possible > i) {
1338 		pr_warn("%d Processors exceeds max_cpus limit of %u\n",
1339 			possible, setup_max_cpus);
1340 		possible = i;
1341 	}
1342 
1343 	set_nr_cpu_ids(possible);
1344 
1345 	pr_info("Allowing %d CPUs, %d hotplug CPUs\n",
1346 		possible, max_t(int, possible - num_processors, 0));
1347 
1348 	reset_cpu_possible_mask();
1349 
1350 	for (i = 0; i < possible; i++)
1351 		set_cpu_possible(i, true);
1352 }
1353 
1354 /* correctly size the local cpu masks */
1355 void __init setup_cpu_local_masks(void)
1356 {
1357 	alloc_bootmem_cpumask_var(&cpu_sibling_setup_mask);
1358 }
1359 
1360 #ifdef CONFIG_HOTPLUG_CPU
1361 
1362 /* Recompute SMT state for all CPUs on offline */
1363 static void recompute_smt_state(void)
1364 {
1365 	int max_threads, cpu;
1366 
1367 	max_threads = 0;
1368 	for_each_online_cpu (cpu) {
1369 		int threads = cpumask_weight(topology_sibling_cpumask(cpu));
1370 
1371 		if (threads > max_threads)
1372 			max_threads = threads;
1373 	}
1374 	__max_smt_threads = max_threads;
1375 }
1376 
1377 static void remove_siblinginfo(int cpu)
1378 {
1379 	int sibling;
1380 	struct cpuinfo_x86 *c = &cpu_data(cpu);
1381 
1382 	for_each_cpu(sibling, topology_core_cpumask(cpu)) {
1383 		cpumask_clear_cpu(cpu, topology_core_cpumask(sibling));
1384 		/*/
1385 		 * last thread sibling in this cpu core going down
1386 		 */
1387 		if (cpumask_weight(topology_sibling_cpumask(cpu)) == 1)
1388 			cpu_data(sibling).booted_cores--;
1389 	}
1390 
1391 	for_each_cpu(sibling, topology_die_cpumask(cpu))
1392 		cpumask_clear_cpu(cpu, topology_die_cpumask(sibling));
1393 
1394 	for_each_cpu(sibling, topology_sibling_cpumask(cpu)) {
1395 		cpumask_clear_cpu(cpu, topology_sibling_cpumask(sibling));
1396 		if (cpumask_weight(topology_sibling_cpumask(sibling)) == 1)
1397 			cpu_data(sibling).smt_active = false;
1398 	}
1399 
1400 	for_each_cpu(sibling, cpu_llc_shared_mask(cpu))
1401 		cpumask_clear_cpu(cpu, cpu_llc_shared_mask(sibling));
1402 	for_each_cpu(sibling, cpu_l2c_shared_mask(cpu))
1403 		cpumask_clear_cpu(cpu, cpu_l2c_shared_mask(sibling));
1404 	cpumask_clear(cpu_llc_shared_mask(cpu));
1405 	cpumask_clear(cpu_l2c_shared_mask(cpu));
1406 	cpumask_clear(topology_sibling_cpumask(cpu));
1407 	cpumask_clear(topology_core_cpumask(cpu));
1408 	cpumask_clear(topology_die_cpumask(cpu));
1409 	c->cpu_core_id = 0;
1410 	c->booted_cores = 0;
1411 	cpumask_clear_cpu(cpu, cpu_sibling_setup_mask);
1412 	recompute_smt_state();
1413 }
1414 
1415 static void remove_cpu_from_maps(int cpu)
1416 {
1417 	set_cpu_online(cpu, false);
1418 	numa_remove_cpu(cpu);
1419 }
1420 
1421 void cpu_disable_common(void)
1422 {
1423 	int cpu = smp_processor_id();
1424 
1425 	remove_siblinginfo(cpu);
1426 
1427 	/* It's now safe to remove this processor from the online map */
1428 	lock_vector_lock();
1429 	remove_cpu_from_maps(cpu);
1430 	unlock_vector_lock();
1431 	fixup_irqs();
1432 	lapic_offline();
1433 }
1434 
1435 int native_cpu_disable(void)
1436 {
1437 	int ret;
1438 
1439 	ret = lapic_can_unplug_cpu();
1440 	if (ret)
1441 		return ret;
1442 
1443 	cpu_disable_common();
1444 
1445         /*
1446          * Disable the local APIC. Otherwise IPI broadcasts will reach
1447          * it. It still responds normally to INIT, NMI, SMI, and SIPI
1448          * messages.
1449          *
1450          * Disabling the APIC must happen after cpu_disable_common()
1451          * which invokes fixup_irqs().
1452          *
1453          * Disabling the APIC preserves already set bits in IRR, but
1454          * an interrupt arriving after disabling the local APIC does not
1455          * set the corresponding IRR bit.
1456          *
1457          * fixup_irqs() scans IRR for set bits so it can raise a not
1458          * yet handled interrupt on the new destination CPU via an IPI
1459          * but obviously it can't do so for IRR bits which are not set.
1460          * IOW, interrupts arriving after disabling the local APIC will
1461          * be lost.
1462          */
1463 	apic_soft_disable();
1464 
1465 	return 0;
1466 }
1467 
1468 void play_dead_common(void)
1469 {
1470 	idle_task_exit();
1471 
1472 	cpuhp_ap_report_dead();
1473 
1474 	local_irq_disable();
1475 }
1476 
1477 /*
1478  * We need to flush the caches before going to sleep, lest we have
1479  * dirty data in our caches when we come back up.
1480  */
1481 static inline void mwait_play_dead(void)
1482 {
1483 	struct mwait_cpu_dead *md = this_cpu_ptr(&mwait_cpu_dead);
1484 	unsigned int eax, ebx, ecx, edx;
1485 	unsigned int highest_cstate = 0;
1486 	unsigned int highest_subcstate = 0;
1487 	int i;
1488 
1489 	if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
1490 	    boot_cpu_data.x86_vendor == X86_VENDOR_HYGON)
1491 		return;
1492 	if (!this_cpu_has(X86_FEATURE_MWAIT))
1493 		return;
1494 	if (!this_cpu_has(X86_FEATURE_CLFLUSH))
1495 		return;
1496 	if (__this_cpu_read(cpu_info.cpuid_level) < CPUID_MWAIT_LEAF)
1497 		return;
1498 
1499 	eax = CPUID_MWAIT_LEAF;
1500 	ecx = 0;
1501 	native_cpuid(&eax, &ebx, &ecx, &edx);
1502 
1503 	/*
1504 	 * eax will be 0 if EDX enumeration is not valid.
1505 	 * Initialized below to cstate, sub_cstate value when EDX is valid.
1506 	 */
1507 	if (!(ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED)) {
1508 		eax = 0;
1509 	} else {
1510 		edx >>= MWAIT_SUBSTATE_SIZE;
1511 		for (i = 0; i < 7 && edx; i++, edx >>= MWAIT_SUBSTATE_SIZE) {
1512 			if (edx & MWAIT_SUBSTATE_MASK) {
1513 				highest_cstate = i;
1514 				highest_subcstate = edx & MWAIT_SUBSTATE_MASK;
1515 			}
1516 		}
1517 		eax = (highest_cstate << MWAIT_SUBSTATE_SIZE) |
1518 			(highest_subcstate - 1);
1519 	}
1520 
1521 	/* Set up state for the kexec() hack below */
1522 	md->status = CPUDEAD_MWAIT_WAIT;
1523 	md->control = CPUDEAD_MWAIT_WAIT;
1524 
1525 	wbinvd();
1526 
1527 	while (1) {
1528 		/*
1529 		 * The CLFLUSH is a workaround for erratum AAI65 for
1530 		 * the Xeon 7400 series.  It's not clear it is actually
1531 		 * needed, but it should be harmless in either case.
1532 		 * The WBINVD is insufficient due to the spurious-wakeup
1533 		 * case where we return around the loop.
1534 		 */
1535 		mb();
1536 		clflush(md);
1537 		mb();
1538 		__monitor(md, 0, 0);
1539 		mb();
1540 		__mwait(eax, 0);
1541 
1542 		if (READ_ONCE(md->control) == CPUDEAD_MWAIT_KEXEC_HLT) {
1543 			/*
1544 			 * Kexec is about to happen. Don't go back into mwait() as
1545 			 * the kexec kernel might overwrite text and data including
1546 			 * page tables and stack. So mwait() would resume when the
1547 			 * monitor cache line is written to and then the CPU goes
1548 			 * south due to overwritten text, page tables and stack.
1549 			 *
1550 			 * Note: This does _NOT_ protect against a stray MCE, NMI,
1551 			 * SMI. They will resume execution at the instruction
1552 			 * following the HLT instruction and run into the problem
1553 			 * which this is trying to prevent.
1554 			 */
1555 			WRITE_ONCE(md->status, CPUDEAD_MWAIT_KEXEC_HLT);
1556 			while(1)
1557 				native_halt();
1558 		}
1559 	}
1560 }
1561 
1562 /*
1563  * Kick all "offline" CPUs out of mwait on kexec(). See comment in
1564  * mwait_play_dead().
1565  */
1566 void smp_kick_mwait_play_dead(void)
1567 {
1568 	u32 newstate = CPUDEAD_MWAIT_KEXEC_HLT;
1569 	struct mwait_cpu_dead *md;
1570 	unsigned int cpu, i;
1571 
1572 	for_each_cpu_andnot(cpu, cpu_present_mask, cpu_online_mask) {
1573 		md = per_cpu_ptr(&mwait_cpu_dead, cpu);
1574 
1575 		/* Does it sit in mwait_play_dead() ? */
1576 		if (READ_ONCE(md->status) != CPUDEAD_MWAIT_WAIT)
1577 			continue;
1578 
1579 		/* Wait up to 5ms */
1580 		for (i = 0; READ_ONCE(md->status) != newstate && i < 1000; i++) {
1581 			/* Bring it out of mwait */
1582 			WRITE_ONCE(md->control, newstate);
1583 			udelay(5);
1584 		}
1585 
1586 		if (READ_ONCE(md->status) != newstate)
1587 			pr_err_once("CPU%u is stuck in mwait_play_dead()\n", cpu);
1588 	}
1589 }
1590 
1591 void __noreturn hlt_play_dead(void)
1592 {
1593 	if (__this_cpu_read(cpu_info.x86) >= 4)
1594 		wbinvd();
1595 
1596 	while (1)
1597 		native_halt();
1598 }
1599 
1600 void native_play_dead(void)
1601 {
1602 	play_dead_common();
1603 	tboot_shutdown(TB_SHUTDOWN_WFS);
1604 
1605 	mwait_play_dead();
1606 	if (cpuidle_play_dead())
1607 		hlt_play_dead();
1608 }
1609 
1610 #else /* ... !CONFIG_HOTPLUG_CPU */
1611 int native_cpu_disable(void)
1612 {
1613 	return -ENOSYS;
1614 }
1615 
1616 void native_play_dead(void)
1617 {
1618 	BUG();
1619 }
1620 
1621 #endif
1622