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/numa.h>
57 #include <linux/pgtable.h>
58 #include <linux/overflow.h>
59 
60 #include <asm/acpi.h>
61 #include <asm/desc.h>
62 #include <asm/nmi.h>
63 #include <asm/irq.h>
64 #include <asm/realmode.h>
65 #include <asm/cpu.h>
66 #include <asm/numa.h>
67 #include <asm/tlbflush.h>
68 #include <asm/mtrr.h>
69 #include <asm/mwait.h>
70 #include <asm/apic.h>
71 #include <asm/io_apic.h>
72 #include <asm/fpu/api.h>
73 #include <asm/setup.h>
74 #include <asm/uv/uv.h>
75 #include <linux/mc146818rtc.h>
76 #include <asm/i8259.h>
77 #include <asm/misc.h>
78 #include <asm/qspinlock.h>
79 #include <asm/intel-family.h>
80 #include <asm/cpu_device_id.h>
81 #include <asm/spec-ctrl.h>
82 #include <asm/hw_irq.h>
83 #include <asm/stackprotector.h>
84 #include <asm/sev.h>
85 
86 /* representing HT siblings of each logical CPU */
87 DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_sibling_map);
88 EXPORT_PER_CPU_SYMBOL(cpu_sibling_map);
89 
90 /* representing HT and core siblings of each logical CPU */
91 DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_core_map);
92 EXPORT_PER_CPU_SYMBOL(cpu_core_map);
93 
94 /* representing HT, core, and die siblings of each logical CPU */
95 DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_die_map);
96 EXPORT_PER_CPU_SYMBOL(cpu_die_map);
97 
98 /* Per CPU bogomips and other parameters */
99 DEFINE_PER_CPU_READ_MOSTLY(struct cpuinfo_x86, cpu_info);
100 EXPORT_PER_CPU_SYMBOL(cpu_info);
101 
102 /* Logical package management. We might want to allocate that dynamically */
103 unsigned int __max_logical_packages __read_mostly;
104 EXPORT_SYMBOL(__max_logical_packages);
105 static unsigned int logical_packages __read_mostly;
106 static unsigned int logical_die __read_mostly;
107 
108 /* Maximum number of SMT threads on any online core */
109 int __read_mostly __max_smt_threads = 1;
110 
111 /* Flag to indicate if a complete sched domain rebuild is required */
112 bool x86_topology_update;
113 
arch_update_cpu_topology(void)114 int arch_update_cpu_topology(void)
115 {
116 	int retval = x86_topology_update;
117 
118 	x86_topology_update = false;
119 	return retval;
120 }
121 
smpboot_setup_warm_reset_vector(unsigned long start_eip)122 static inline void smpboot_setup_warm_reset_vector(unsigned long start_eip)
123 {
124 	unsigned long flags;
125 
126 	spin_lock_irqsave(&rtc_lock, flags);
127 	CMOS_WRITE(0xa, 0xf);
128 	spin_unlock_irqrestore(&rtc_lock, flags);
129 	*((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_HIGH)) =
130 							start_eip >> 4;
131 	*((volatile unsigned short *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) =
132 							start_eip & 0xf;
133 }
134 
smpboot_restore_warm_reset_vector(void)135 static inline void smpboot_restore_warm_reset_vector(void)
136 {
137 	unsigned long flags;
138 
139 	/*
140 	 * Paranoid:  Set warm reset code and vector here back
141 	 * to default values.
142 	 */
143 	spin_lock_irqsave(&rtc_lock, flags);
144 	CMOS_WRITE(0, 0xf);
145 	spin_unlock_irqrestore(&rtc_lock, flags);
146 
147 	*((volatile u32 *)phys_to_virt(TRAMPOLINE_PHYS_LOW)) = 0;
148 }
149 
150 /*
151  * Report back to the Boot Processor during boot time or to the caller processor
152  * during CPU online.
153  */
smp_callin(void)154 static void smp_callin(void)
155 {
156 	int cpuid;
157 
158 	/*
159 	 * If waken up by an INIT in an 82489DX configuration
160 	 * cpu_callout_mask guarantees we don't get here before
161 	 * an INIT_deassert IPI reaches our local APIC, so it is
162 	 * now safe to touch our local APIC.
163 	 */
164 	cpuid = smp_processor_id();
165 
166 	/*
167 	 * the boot CPU has finished the init stage and is spinning
168 	 * on callin_map until we finish. We are free to set up this
169 	 * CPU, first the APIC. (this is probably redundant on most
170 	 * boards)
171 	 */
172 	apic_ap_setup();
173 
174 	/*
175 	 * Save our processor parameters. Note: this information
176 	 * is needed for clock calibration.
177 	 */
178 	smp_store_cpu_info(cpuid);
179 
180 	/*
181 	 * The topology information must be up to date before
182 	 * calibrate_delay() and notify_cpu_starting().
183 	 */
184 	set_cpu_sibling_map(raw_smp_processor_id());
185 
186 	ap_init_aperfmperf();
187 
188 	/*
189 	 * Get our bogomips.
190 	 * Update loops_per_jiffy in cpu_data. Previous call to
191 	 * smp_store_cpu_info() stored a value that is close but not as
192 	 * accurate as the value just calculated.
193 	 */
194 	calibrate_delay();
195 	cpu_data(cpuid).loops_per_jiffy = loops_per_jiffy;
196 	pr_debug("Stack at about %p\n", &cpuid);
197 
198 	wmb();
199 
200 	notify_cpu_starting(cpuid);
201 
202 	/*
203 	 * Allow the master to continue.
204 	 */
205 	cpumask_set_cpu(cpuid, cpu_callin_mask);
206 }
207 
208 static int cpu0_logical_apicid;
209 static int enable_start_cpu0;
210 /*
211  * Activate a secondary processor.
212  */
start_secondary(void * unused)213 static void notrace start_secondary(void *unused)
214 {
215 	/*
216 	 * Don't put *anything* except direct CPU state initialization
217 	 * before cpu_init(), SMP booting is too fragile that we want to
218 	 * limit the things done here to the most necessary things.
219 	 */
220 	cr4_init();
221 
222 #ifdef CONFIG_X86_32
223 	/* switch away from the initial page table */
224 	load_cr3(swapper_pg_dir);
225 	__flush_tlb_all();
226 #endif
227 	cpu_init_secondary();
228 	rcu_cpu_starting(raw_smp_processor_id());
229 	x86_cpuinit.early_percpu_clock_init();
230 	smp_callin();
231 
232 	enable_start_cpu0 = 0;
233 
234 	/* otherwise gcc will move up smp_processor_id before the cpu_init */
235 	barrier();
236 	/*
237 	 * Check TSC synchronization with the boot CPU:
238 	 */
239 	check_tsc_sync_target();
240 
241 	speculative_store_bypass_ht_init();
242 
243 	/*
244 	 * Lock vector_lock, set CPU online and bring the vector
245 	 * allocator online. Online must be set with vector_lock held
246 	 * to prevent a concurrent irq setup/teardown from seeing a
247 	 * half valid vector space.
248 	 */
249 	lock_vector_lock();
250 	set_cpu_online(smp_processor_id(), true);
251 	lapic_online();
252 	unlock_vector_lock();
253 	cpu_set_state_online(smp_processor_id());
254 	x86_platform.nmi_init();
255 
256 	/* enable local interrupts */
257 	local_irq_enable();
258 
259 	x86_cpuinit.setup_percpu_clockev();
260 
261 	wmb();
262 	cpu_startup_entry(CPUHP_AP_ONLINE_IDLE);
263 }
264 
265 /**
266  * topology_is_primary_thread - Check whether CPU is the primary SMT thread
267  * @cpu:	CPU to check
268  */
topology_is_primary_thread(unsigned int cpu)269 bool topology_is_primary_thread(unsigned int cpu)
270 {
271 	return apic_id_is_primary_thread(per_cpu(x86_cpu_to_apicid, cpu));
272 }
273 
274 /**
275  * topology_smt_supported - Check whether SMT is supported by the CPUs
276  */
topology_smt_supported(void)277 bool topology_smt_supported(void)
278 {
279 	return smp_num_siblings > 1;
280 }
281 
282 /**
283  * topology_phys_to_logical_pkg - Map a physical package id to a logical
284  *
285  * Returns logical package id or -1 if not found
286  */
topology_phys_to_logical_pkg(unsigned int phys_pkg)287 int topology_phys_to_logical_pkg(unsigned int phys_pkg)
288 {
289 	int cpu;
290 
291 	for_each_possible_cpu(cpu) {
292 		struct cpuinfo_x86 *c = &cpu_data(cpu);
293 
294 		if (c->initialized && c->phys_proc_id == phys_pkg)
295 			return c->logical_proc_id;
296 	}
297 	return -1;
298 }
299 EXPORT_SYMBOL(topology_phys_to_logical_pkg);
300 /**
301  * topology_phys_to_logical_die - Map a physical die id to logical
302  *
303  * Returns logical die id or -1 if not found
304  */
topology_phys_to_logical_die(unsigned int die_id,unsigned int cur_cpu)305 int topology_phys_to_logical_die(unsigned int die_id, unsigned int cur_cpu)
306 {
307 	int cpu;
308 	int proc_id = cpu_data(cur_cpu).phys_proc_id;
309 
310 	for_each_possible_cpu(cpu) {
311 		struct cpuinfo_x86 *c = &cpu_data(cpu);
312 
313 		if (c->initialized && c->cpu_die_id == die_id &&
314 		    c->phys_proc_id == proc_id)
315 			return c->logical_die_id;
316 	}
317 	return -1;
318 }
319 EXPORT_SYMBOL(topology_phys_to_logical_die);
320 
321 /**
322  * topology_update_package_map - Update the physical to logical package map
323  * @pkg:	The physical package id as retrieved via CPUID
324  * @cpu:	The cpu for which this is updated
325  */
topology_update_package_map(unsigned int pkg,unsigned int cpu)326 int topology_update_package_map(unsigned int pkg, unsigned int cpu)
327 {
328 	int new;
329 
330 	/* Already available somewhere? */
331 	new = topology_phys_to_logical_pkg(pkg);
332 	if (new >= 0)
333 		goto found;
334 
335 	new = logical_packages++;
336 	if (new != pkg) {
337 		pr_info("CPU %u Converting physical %u to logical package %u\n",
338 			cpu, pkg, new);
339 	}
340 found:
341 	cpu_data(cpu).logical_proc_id = new;
342 	return 0;
343 }
344 /**
345  * topology_update_die_map - Update the physical to logical die map
346  * @die:	The die id as retrieved via CPUID
347  * @cpu:	The cpu for which this is updated
348  */
topology_update_die_map(unsigned int die,unsigned int cpu)349 int topology_update_die_map(unsigned int die, unsigned int cpu)
350 {
351 	int new;
352 
353 	/* Already available somewhere? */
354 	new = topology_phys_to_logical_die(die, cpu);
355 	if (new >= 0)
356 		goto found;
357 
358 	new = logical_die++;
359 	if (new != die) {
360 		pr_info("CPU %u Converting physical %u to logical die %u\n",
361 			cpu, die, new);
362 	}
363 found:
364 	cpu_data(cpu).logical_die_id = new;
365 	return 0;
366 }
367 
smp_store_boot_cpu_info(void)368 void __init smp_store_boot_cpu_info(void)
369 {
370 	int id = 0; /* CPU 0 */
371 	struct cpuinfo_x86 *c = &cpu_data(id);
372 
373 	*c = boot_cpu_data;
374 	c->cpu_index = id;
375 	topology_update_package_map(c->phys_proc_id, id);
376 	topology_update_die_map(c->cpu_die_id, id);
377 	c->initialized = true;
378 }
379 
380 /*
381  * The bootstrap kernel entry code has set these up. Save them for
382  * a given CPU
383  */
smp_store_cpu_info(int id)384 void smp_store_cpu_info(int id)
385 {
386 	struct cpuinfo_x86 *c = &cpu_data(id);
387 
388 	/* Copy boot_cpu_data only on the first bringup */
389 	if (!c->initialized)
390 		*c = boot_cpu_data;
391 	c->cpu_index = id;
392 	/*
393 	 * During boot time, CPU0 has this setup already. Save the info when
394 	 * bringing up AP or offlined CPU0.
395 	 */
396 	identify_secondary_cpu(c);
397 	c->initialized = true;
398 }
399 
400 static bool
topology_same_node(struct cpuinfo_x86 * c,struct cpuinfo_x86 * o)401 topology_same_node(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
402 {
403 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
404 
405 	return (cpu_to_node(cpu1) == cpu_to_node(cpu2));
406 }
407 
408 static bool
topology_sane(struct cpuinfo_x86 * c,struct cpuinfo_x86 * o,const char * name)409 topology_sane(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o, const char *name)
410 {
411 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
412 
413 	return !WARN_ONCE(!topology_same_node(c, o),
414 		"sched: CPU #%d's %s-sibling CPU #%d is not on the same node! "
415 		"[node: %d != %d]. Ignoring dependency.\n",
416 		cpu1, name, cpu2, cpu_to_node(cpu1), cpu_to_node(cpu2));
417 }
418 
419 #define link_mask(mfunc, c1, c2)					\
420 do {									\
421 	cpumask_set_cpu((c1), mfunc(c2));				\
422 	cpumask_set_cpu((c2), mfunc(c1));				\
423 } while (0)
424 
match_smt(struct cpuinfo_x86 * c,struct cpuinfo_x86 * o)425 static bool match_smt(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
426 {
427 	if (boot_cpu_has(X86_FEATURE_TOPOEXT)) {
428 		int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
429 
430 		if (c->phys_proc_id == o->phys_proc_id &&
431 		    c->cpu_die_id == o->cpu_die_id &&
432 		    per_cpu(cpu_llc_id, cpu1) == per_cpu(cpu_llc_id, cpu2)) {
433 			if (c->cpu_core_id == o->cpu_core_id)
434 				return topology_sane(c, o, "smt");
435 
436 			if ((c->cu_id != 0xff) &&
437 			    (o->cu_id != 0xff) &&
438 			    (c->cu_id == o->cu_id))
439 				return topology_sane(c, o, "smt");
440 		}
441 
442 	} else if (c->phys_proc_id == o->phys_proc_id &&
443 		   c->cpu_die_id == o->cpu_die_id &&
444 		   c->cpu_core_id == o->cpu_core_id) {
445 		return topology_sane(c, o, "smt");
446 	}
447 
448 	return false;
449 }
450 
match_die(struct cpuinfo_x86 * c,struct cpuinfo_x86 * o)451 static bool match_die(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
452 {
453 	if (c->phys_proc_id == o->phys_proc_id &&
454 	    c->cpu_die_id == o->cpu_die_id)
455 		return true;
456 	return false;
457 }
458 
match_l2c(struct cpuinfo_x86 * c,struct cpuinfo_x86 * o)459 static bool match_l2c(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
460 {
461 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
462 
463 	/* If the arch didn't set up l2c_id, fall back to SMT */
464 	if (per_cpu(cpu_l2c_id, cpu1) == BAD_APICID)
465 		return match_smt(c, o);
466 
467 	/* Do not match if L2 cache id does not match: */
468 	if (per_cpu(cpu_l2c_id, cpu1) != per_cpu(cpu_l2c_id, cpu2))
469 		return false;
470 
471 	return topology_sane(c, o, "l2c");
472 }
473 
474 /*
475  * Unlike the other levels, we do not enforce keeping a
476  * multicore group inside a NUMA node.  If this happens, we will
477  * discard the MC level of the topology later.
478  */
match_pkg(struct cpuinfo_x86 * c,struct cpuinfo_x86 * o)479 static bool match_pkg(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
480 {
481 	if (c->phys_proc_id == o->phys_proc_id)
482 		return true;
483 	return false;
484 }
485 
486 /*
487  * Define intel_cod_cpu[] for Intel COD (Cluster-on-Die) CPUs.
488  *
489  * Any Intel CPU that has multiple nodes per package and does not
490  * match intel_cod_cpu[] has the SNC (Sub-NUMA Cluster) topology.
491  *
492  * When in SNC mode, these CPUs enumerate an LLC that is shared
493  * by multiple NUMA nodes. The LLC is shared for off-package data
494  * access but private to the NUMA node (half of the package) for
495  * on-package access. CPUID (the source of the information about
496  * the LLC) can only enumerate the cache as shared or unshared,
497  * but not this particular configuration.
498  */
499 
500 static const struct x86_cpu_id intel_cod_cpu[] = {
501 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_X, 0),	/* COD */
502 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_X, 0),	/* COD */
503 	X86_MATCH_INTEL_FAM6_MODEL(ANY, 1),		/* SNC */
504 	{}
505 };
506 
match_llc(struct cpuinfo_x86 * c,struct cpuinfo_x86 * o)507 static bool match_llc(struct cpuinfo_x86 *c, struct cpuinfo_x86 *o)
508 {
509 	const struct x86_cpu_id *id = x86_match_cpu(intel_cod_cpu);
510 	int cpu1 = c->cpu_index, cpu2 = o->cpu_index;
511 	bool intel_snc = id && id->driver_data;
512 
513 	/* Do not match if we do not have a valid APICID for cpu: */
514 	if (per_cpu(cpu_llc_id, cpu1) == BAD_APICID)
515 		return false;
516 
517 	/* Do not match if LLC id does not match: */
518 	if (per_cpu(cpu_llc_id, cpu1) != per_cpu(cpu_llc_id, cpu2))
519 		return false;
520 
521 	/*
522 	 * Allow the SNC topology without warning. Return of false
523 	 * means 'c' does not share the LLC of 'o'. This will be
524 	 * reflected to userspace.
525 	 */
526 	if (match_pkg(c, o) && !topology_same_node(c, o) && intel_snc)
527 		return false;
528 
529 	return topology_sane(c, o, "llc");
530 }
531 
532 
533 #if defined(CONFIG_SCHED_SMT) || defined(CONFIG_SCHED_CLUSTER) || defined(CONFIG_SCHED_MC)
x86_sched_itmt_flags(void)534 static inline int x86_sched_itmt_flags(void)
535 {
536 	return sysctl_sched_itmt_enabled ? SD_ASYM_PACKING : 0;
537 }
538 
539 #ifdef CONFIG_SCHED_MC
x86_core_flags(void)540 static int x86_core_flags(void)
541 {
542 	return cpu_core_flags() | x86_sched_itmt_flags();
543 }
544 #endif
545 #ifdef CONFIG_SCHED_SMT
x86_smt_flags(void)546 static int x86_smt_flags(void)
547 {
548 	return cpu_smt_flags() | x86_sched_itmt_flags();
549 }
550 #endif
551 #ifdef CONFIG_SCHED_CLUSTER
x86_cluster_flags(void)552 static int x86_cluster_flags(void)
553 {
554 	return cpu_cluster_flags() | x86_sched_itmt_flags();
555 }
556 #endif
557 #endif
558 
559 static struct sched_domain_topology_level x86_numa_in_package_topology[] = {
560 #ifdef CONFIG_SCHED_SMT
561 	{ cpu_smt_mask, x86_smt_flags, SD_INIT_NAME(SMT) },
562 #endif
563 #ifdef CONFIG_SCHED_CLUSTER
564 	{ cpu_clustergroup_mask, x86_cluster_flags, SD_INIT_NAME(CLS) },
565 #endif
566 #ifdef CONFIG_SCHED_MC
567 	{ cpu_coregroup_mask, x86_core_flags, SD_INIT_NAME(MC) },
568 #endif
569 	{ NULL, },
570 };
571 
572 static struct sched_domain_topology_level x86_hybrid_topology[] = {
573 #ifdef CONFIG_SCHED_SMT
574 	{ cpu_smt_mask, x86_smt_flags, SD_INIT_NAME(SMT) },
575 #endif
576 #ifdef CONFIG_SCHED_MC
577 	{ cpu_coregroup_mask, x86_core_flags, SD_INIT_NAME(MC) },
578 #endif
579 	{ cpu_cpu_mask, SD_INIT_NAME(DIE) },
580 	{ NULL, },
581 };
582 
583 static struct sched_domain_topology_level x86_topology[] = {
584 #ifdef CONFIG_SCHED_SMT
585 	{ cpu_smt_mask, x86_smt_flags, SD_INIT_NAME(SMT) },
586 #endif
587 #ifdef CONFIG_SCHED_CLUSTER
588 	{ cpu_clustergroup_mask, x86_cluster_flags, SD_INIT_NAME(CLS) },
589 #endif
590 #ifdef CONFIG_SCHED_MC
591 	{ cpu_coregroup_mask, x86_core_flags, SD_INIT_NAME(MC) },
592 #endif
593 	{ cpu_cpu_mask, SD_INIT_NAME(DIE) },
594 	{ NULL, },
595 };
596 
597 /*
598  * Set if a package/die has multiple NUMA nodes inside.
599  * AMD Magny-Cours, Intel Cluster-on-Die, and Intel
600  * Sub-NUMA Clustering have this.
601  */
602 static bool x86_has_numa_in_package;
603 
set_cpu_sibling_map(int cpu)604 void set_cpu_sibling_map(int cpu)
605 {
606 	bool has_smt = smp_num_siblings > 1;
607 	bool has_mp = has_smt || boot_cpu_data.x86_max_cores > 1;
608 	struct cpuinfo_x86 *c = &cpu_data(cpu);
609 	struct cpuinfo_x86 *o;
610 	int i, threads;
611 
612 	cpumask_set_cpu(cpu, cpu_sibling_setup_mask);
613 
614 	if (!has_mp) {
615 		cpumask_set_cpu(cpu, topology_sibling_cpumask(cpu));
616 		cpumask_set_cpu(cpu, cpu_llc_shared_mask(cpu));
617 		cpumask_set_cpu(cpu, cpu_l2c_shared_mask(cpu));
618 		cpumask_set_cpu(cpu, topology_core_cpumask(cpu));
619 		cpumask_set_cpu(cpu, topology_die_cpumask(cpu));
620 		c->booted_cores = 1;
621 		return;
622 	}
623 
624 	for_each_cpu(i, cpu_sibling_setup_mask) {
625 		o = &cpu_data(i);
626 
627 		if (match_pkg(c, o) && !topology_same_node(c, o))
628 			x86_has_numa_in_package = true;
629 
630 		if ((i == cpu) || (has_smt && match_smt(c, o)))
631 			link_mask(topology_sibling_cpumask, cpu, i);
632 
633 		if ((i == cpu) || (has_mp && match_llc(c, o)))
634 			link_mask(cpu_llc_shared_mask, cpu, i);
635 
636 		if ((i == cpu) || (has_mp && match_l2c(c, o)))
637 			link_mask(cpu_l2c_shared_mask, cpu, i);
638 
639 		if ((i == cpu) || (has_mp && match_die(c, o)))
640 			link_mask(topology_die_cpumask, cpu, i);
641 	}
642 
643 	threads = cpumask_weight(topology_sibling_cpumask(cpu));
644 	if (threads > __max_smt_threads)
645 		__max_smt_threads = threads;
646 
647 	for_each_cpu(i, topology_sibling_cpumask(cpu))
648 		cpu_data(i).smt_active = threads > 1;
649 
650 	/*
651 	 * This needs a separate iteration over the cpus because we rely on all
652 	 * topology_sibling_cpumask links to be set-up.
653 	 */
654 	for_each_cpu(i, cpu_sibling_setup_mask) {
655 		o = &cpu_data(i);
656 
657 		if ((i == cpu) || (has_mp && match_pkg(c, o))) {
658 			link_mask(topology_core_cpumask, cpu, i);
659 
660 			/*
661 			 *  Does this new cpu bringup a new core?
662 			 */
663 			if (threads == 1) {
664 				/*
665 				 * for each core in package, increment
666 				 * the booted_cores for this new cpu
667 				 */
668 				if (cpumask_first(
669 				    topology_sibling_cpumask(i)) == i)
670 					c->booted_cores++;
671 				/*
672 				 * increment the core count for all
673 				 * the other cpus in this package
674 				 */
675 				if (i != cpu)
676 					cpu_data(i).booted_cores++;
677 			} else if (i != cpu && !c->booted_cores)
678 				c->booted_cores = cpu_data(i).booted_cores;
679 		}
680 	}
681 }
682 
683 /* maps the cpu to the sched domain representing multi-core */
cpu_coregroup_mask(int cpu)684 const struct cpumask *cpu_coregroup_mask(int cpu)
685 {
686 	return cpu_llc_shared_mask(cpu);
687 }
688 
cpu_clustergroup_mask(int cpu)689 const struct cpumask *cpu_clustergroup_mask(int cpu)
690 {
691 	return cpu_l2c_shared_mask(cpu);
692 }
693 
impress_friends(void)694 static void impress_friends(void)
695 {
696 	int cpu;
697 	unsigned long bogosum = 0;
698 	/*
699 	 * Allow the user to impress friends.
700 	 */
701 	pr_debug("Before bogomips\n");
702 	for_each_possible_cpu(cpu)
703 		if (cpumask_test_cpu(cpu, cpu_callout_mask))
704 			bogosum += cpu_data(cpu).loops_per_jiffy;
705 	pr_info("Total of %d processors activated (%lu.%02lu BogoMIPS)\n",
706 		num_online_cpus(),
707 		bogosum/(500000/HZ),
708 		(bogosum/(5000/HZ))%100);
709 
710 	pr_debug("Before bogocount - setting activated=1\n");
711 }
712 
__inquire_remote_apic(int apicid)713 void __inquire_remote_apic(int apicid)
714 {
715 	unsigned i, regs[] = { APIC_ID >> 4, APIC_LVR >> 4, APIC_SPIV >> 4 };
716 	const char * const names[] = { "ID", "VERSION", "SPIV" };
717 	int timeout;
718 	u32 status;
719 
720 	pr_info("Inquiring remote APIC 0x%x...\n", apicid);
721 
722 	for (i = 0; i < ARRAY_SIZE(regs); i++) {
723 		pr_info("... APIC 0x%x %s: ", apicid, names[i]);
724 
725 		/*
726 		 * Wait for idle.
727 		 */
728 		status = safe_apic_wait_icr_idle();
729 		if (status)
730 			pr_cont("a previous APIC delivery may have failed\n");
731 
732 		apic_icr_write(APIC_DM_REMRD | regs[i], apicid);
733 
734 		timeout = 0;
735 		do {
736 			udelay(100);
737 			status = apic_read(APIC_ICR) & APIC_ICR_RR_MASK;
738 		} while (status == APIC_ICR_RR_INPROG && timeout++ < 1000);
739 
740 		switch (status) {
741 		case APIC_ICR_RR_VALID:
742 			status = apic_read(APIC_RRR);
743 			pr_cont("%08x\n", status);
744 			break;
745 		default:
746 			pr_cont("failed\n");
747 		}
748 	}
749 }
750 
751 /*
752  * The Multiprocessor Specification 1.4 (1997) example code suggests
753  * that there should be a 10ms delay between the BSP asserting INIT
754  * and de-asserting INIT, when starting a remote processor.
755  * But that slows boot and resume on modern processors, which include
756  * many cores and don't require that delay.
757  *
758  * Cmdline "init_cpu_udelay=" is available to over-ride this delay.
759  * Modern processor families are quirked to remove the delay entirely.
760  */
761 #define UDELAY_10MS_DEFAULT 10000
762 
763 static unsigned int init_udelay = UINT_MAX;
764 
cpu_init_udelay(char * str)765 static int __init cpu_init_udelay(char *str)
766 {
767 	get_option(&str, &init_udelay);
768 
769 	return 0;
770 }
771 early_param("cpu_init_udelay", cpu_init_udelay);
772 
smp_quirk_init_udelay(void)773 static void __init smp_quirk_init_udelay(void)
774 {
775 	/* if cmdline changed it from default, leave it alone */
776 	if (init_udelay != UINT_MAX)
777 		return;
778 
779 	/* if modern processor, use no delay */
780 	if (((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) && (boot_cpu_data.x86 == 6)) ||
781 	    ((boot_cpu_data.x86_vendor == X86_VENDOR_HYGON) && (boot_cpu_data.x86 >= 0x18)) ||
782 	    ((boot_cpu_data.x86_vendor == X86_VENDOR_AMD) && (boot_cpu_data.x86 >= 0xF))) {
783 		init_udelay = 0;
784 		return;
785 	}
786 	/* else, use legacy delay */
787 	init_udelay = UDELAY_10MS_DEFAULT;
788 }
789 
790 /*
791  * Poke the other CPU in the eye via NMI to wake it up. Remember that the normal
792  * INIT, INIT, STARTUP sequence will reset the chip hard for us, and this
793  * won't ... remember to clear down the APIC, etc later.
794  */
795 int
wakeup_secondary_cpu_via_nmi(int apicid,unsigned long start_eip)796 wakeup_secondary_cpu_via_nmi(int apicid, unsigned long start_eip)
797 {
798 	u32 dm = apic->dest_mode_logical ? APIC_DEST_LOGICAL : APIC_DEST_PHYSICAL;
799 	unsigned long send_status, accept_status = 0;
800 	int maxlvt;
801 
802 	/* Target chip */
803 	/* Boot on the stack */
804 	/* Kick the second */
805 	apic_icr_write(APIC_DM_NMI | dm, apicid);
806 
807 	pr_debug("Waiting for send to finish...\n");
808 	send_status = safe_apic_wait_icr_idle();
809 
810 	/*
811 	 * Give the other CPU some time to accept the IPI.
812 	 */
813 	udelay(200);
814 	if (APIC_INTEGRATED(boot_cpu_apic_version)) {
815 		maxlvt = lapic_get_maxlvt();
816 		if (maxlvt > 3)			/* Due to the Pentium erratum 3AP.  */
817 			apic_write(APIC_ESR, 0);
818 		accept_status = (apic_read(APIC_ESR) & 0xEF);
819 	}
820 	pr_debug("NMI sent\n");
821 
822 	if (send_status)
823 		pr_err("APIC never delivered???\n");
824 	if (accept_status)
825 		pr_err("APIC delivery error (%lx)\n", accept_status);
826 
827 	return (send_status | accept_status);
828 }
829 
830 static int
wakeup_secondary_cpu_via_init(int phys_apicid,unsigned long start_eip)831 wakeup_secondary_cpu_via_init(int phys_apicid, unsigned long start_eip)
832 {
833 	unsigned long send_status = 0, accept_status = 0;
834 	int maxlvt, num_starts, j;
835 
836 	maxlvt = lapic_get_maxlvt();
837 
838 	/*
839 	 * Be paranoid about clearing APIC errors.
840 	 */
841 	if (APIC_INTEGRATED(boot_cpu_apic_version)) {
842 		if (maxlvt > 3)		/* Due to the Pentium erratum 3AP.  */
843 			apic_write(APIC_ESR, 0);
844 		apic_read(APIC_ESR);
845 	}
846 
847 	pr_debug("Asserting INIT\n");
848 
849 	/*
850 	 * Turn INIT on target chip
851 	 */
852 	/*
853 	 * Send IPI
854 	 */
855 	apic_icr_write(APIC_INT_LEVELTRIG | APIC_INT_ASSERT | APIC_DM_INIT,
856 		       phys_apicid);
857 
858 	pr_debug("Waiting for send to finish...\n");
859 	send_status = safe_apic_wait_icr_idle();
860 
861 	udelay(init_udelay);
862 
863 	pr_debug("Deasserting INIT\n");
864 
865 	/* Target chip */
866 	/* Send IPI */
867 	apic_icr_write(APIC_INT_LEVELTRIG | APIC_DM_INIT, phys_apicid);
868 
869 	pr_debug("Waiting for send to finish...\n");
870 	send_status = safe_apic_wait_icr_idle();
871 
872 	mb();
873 
874 	/*
875 	 * Should we send STARTUP IPIs ?
876 	 *
877 	 * Determine this based on the APIC version.
878 	 * If we don't have an integrated APIC, don't send the STARTUP IPIs.
879 	 */
880 	if (APIC_INTEGRATED(boot_cpu_apic_version))
881 		num_starts = 2;
882 	else
883 		num_starts = 0;
884 
885 	/*
886 	 * Run STARTUP IPI loop.
887 	 */
888 	pr_debug("#startup loops: %d\n", num_starts);
889 
890 	for (j = 1; j <= num_starts; j++) {
891 		pr_debug("Sending STARTUP #%d\n", j);
892 		if (maxlvt > 3)		/* Due to the Pentium erratum 3AP.  */
893 			apic_write(APIC_ESR, 0);
894 		apic_read(APIC_ESR);
895 		pr_debug("After apic_write\n");
896 
897 		/*
898 		 * STARTUP IPI
899 		 */
900 
901 		/* Target chip */
902 		/* Boot on the stack */
903 		/* Kick the second */
904 		apic_icr_write(APIC_DM_STARTUP | (start_eip >> 12),
905 			       phys_apicid);
906 
907 		/*
908 		 * Give the other CPU some time to accept the IPI.
909 		 */
910 		if (init_udelay == 0)
911 			udelay(10);
912 		else
913 			udelay(300);
914 
915 		pr_debug("Startup point 1\n");
916 
917 		pr_debug("Waiting for send to finish...\n");
918 		send_status = safe_apic_wait_icr_idle();
919 
920 		/*
921 		 * Give the other CPU some time to accept the IPI.
922 		 */
923 		if (init_udelay == 0)
924 			udelay(10);
925 		else
926 			udelay(200);
927 
928 		if (maxlvt > 3)		/* Due to the Pentium erratum 3AP.  */
929 			apic_write(APIC_ESR, 0);
930 		accept_status = (apic_read(APIC_ESR) & 0xEF);
931 		if (send_status || accept_status)
932 			break;
933 	}
934 	pr_debug("After Startup\n");
935 
936 	if (send_status)
937 		pr_err("APIC never delivered???\n");
938 	if (accept_status)
939 		pr_err("APIC delivery error (%lx)\n", accept_status);
940 
941 	return (send_status | accept_status);
942 }
943 
944 /* reduce the number of lines printed when booting a large cpu count system */
announce_cpu(int cpu,int apicid)945 static void announce_cpu(int cpu, int apicid)
946 {
947 	static int current_node = NUMA_NO_NODE;
948 	int node = early_cpu_to_node(cpu);
949 	static int width, node_width;
950 
951 	if (!width)
952 		width = num_digits(num_possible_cpus()) + 1; /* + '#' sign */
953 
954 	if (!node_width)
955 		node_width = num_digits(num_possible_nodes()) + 1; /* + '#' */
956 
957 	if (cpu == 1)
958 		printk(KERN_INFO "x86: Booting SMP configuration:\n");
959 
960 	if (system_state < SYSTEM_RUNNING) {
961 		if (node != current_node) {
962 			if (current_node > (-1))
963 				pr_cont("\n");
964 			current_node = node;
965 
966 			printk(KERN_INFO ".... node %*s#%d, CPUs:  ",
967 			       node_width - num_digits(node), " ", node);
968 		}
969 
970 		/* Add padding for the BSP */
971 		if (cpu == 1)
972 			pr_cont("%*s", width + 1, " ");
973 
974 		pr_cont("%*s#%d", width - num_digits(cpu), " ", cpu);
975 
976 	} else
977 		pr_info("Booting Node %d Processor %d APIC 0x%x\n",
978 			node, cpu, apicid);
979 }
980 
wakeup_cpu0_nmi(unsigned int cmd,struct pt_regs * regs)981 static int wakeup_cpu0_nmi(unsigned int cmd, struct pt_regs *regs)
982 {
983 	int cpu;
984 
985 	cpu = smp_processor_id();
986 	if (cpu == 0 && !cpu_online(cpu) && enable_start_cpu0)
987 		return NMI_HANDLED;
988 
989 	return NMI_DONE;
990 }
991 
992 /*
993  * Wake up AP by INIT, INIT, STARTUP sequence.
994  *
995  * Instead of waiting for STARTUP after INITs, BSP will execute the BIOS
996  * boot-strap code which is not a desired behavior for waking up BSP. To
997  * void the boot-strap code, wake up CPU0 by NMI instead.
998  *
999  * This works to wake up soft offlined CPU0 only. If CPU0 is hard offlined
1000  * (i.e. physically hot removed and then hot added), NMI won't wake it up.
1001  * We'll change this code in the future to wake up hard offlined CPU0 if
1002  * real platform and request are available.
1003  */
1004 static int
wakeup_cpu_via_init_nmi(int cpu,unsigned long start_ip,int apicid,int * cpu0_nmi_registered)1005 wakeup_cpu_via_init_nmi(int cpu, unsigned long start_ip, int apicid,
1006 	       int *cpu0_nmi_registered)
1007 {
1008 	int id;
1009 	int boot_error;
1010 
1011 	preempt_disable();
1012 
1013 	/*
1014 	 * Wake up AP by INIT, INIT, STARTUP sequence.
1015 	 */
1016 	if (cpu) {
1017 		boot_error = wakeup_secondary_cpu_via_init(apicid, start_ip);
1018 		goto out;
1019 	}
1020 
1021 	/*
1022 	 * Wake up BSP by nmi.
1023 	 *
1024 	 * Register a NMI handler to help wake up CPU0.
1025 	 */
1026 	boot_error = register_nmi_handler(NMI_LOCAL,
1027 					  wakeup_cpu0_nmi, 0, "wake_cpu0");
1028 
1029 	if (!boot_error) {
1030 		enable_start_cpu0 = 1;
1031 		*cpu0_nmi_registered = 1;
1032 		id = apic->dest_mode_logical ? cpu0_logical_apicid : apicid;
1033 		boot_error = wakeup_secondary_cpu_via_nmi(id, start_ip);
1034 	}
1035 
1036 out:
1037 	preempt_enable();
1038 
1039 	return boot_error;
1040 }
1041 
common_cpu_up(unsigned int cpu,struct task_struct * idle)1042 int common_cpu_up(unsigned int cpu, struct task_struct *idle)
1043 {
1044 	int ret;
1045 
1046 	/* Just in case we booted with a single CPU. */
1047 	alternatives_enable_smp();
1048 
1049 	per_cpu(current_task, cpu) = idle;
1050 	cpu_init_stack_canary(cpu, idle);
1051 
1052 	/* Initialize the interrupt stack(s) */
1053 	ret = irq_init_percpu_irqstack(cpu);
1054 	if (ret)
1055 		return ret;
1056 
1057 #ifdef CONFIG_X86_32
1058 	/* Stack for startup_32 can be just as for start_secondary onwards */
1059 	per_cpu(cpu_current_top_of_stack, cpu) = task_top_of_stack(idle);
1060 #else
1061 	initial_gs = per_cpu_offset(cpu);
1062 #endif
1063 	return 0;
1064 }
1065 
1066 /*
1067  * NOTE - on most systems this is a PHYSICAL apic ID, but on multiquad
1068  * (ie clustered apic addressing mode), this is a LOGICAL apic ID.
1069  * Returns zero if CPU booted OK, else error code from
1070  * ->wakeup_secondary_cpu.
1071  */
do_boot_cpu(int apicid,int cpu,struct task_struct * idle,int * cpu0_nmi_registered)1072 static int do_boot_cpu(int apicid, int cpu, struct task_struct *idle,
1073 		       int *cpu0_nmi_registered)
1074 {
1075 	/* start_ip had better be page-aligned! */
1076 	unsigned long start_ip = real_mode_header->trampoline_start;
1077 
1078 	unsigned long boot_error = 0;
1079 	unsigned long timeout;
1080 
1081 #ifdef CONFIG_X86_64
1082 	/* If 64-bit wakeup method exists, use the 64-bit mode trampoline IP */
1083 	if (apic->wakeup_secondary_cpu_64)
1084 		start_ip = real_mode_header->trampoline_start64;
1085 #endif
1086 	idle->thread.sp = (unsigned long)task_pt_regs(idle);
1087 	early_gdt_descr.address = (unsigned long)get_cpu_gdt_rw(cpu);
1088 	initial_code = (unsigned long)start_secondary;
1089 	initial_stack  = idle->thread.sp;
1090 
1091 	/* Enable the espfix hack for this CPU */
1092 	init_espfix_ap(cpu);
1093 
1094 	/* So we see what's up */
1095 	announce_cpu(cpu, apicid);
1096 
1097 	/*
1098 	 * This grunge runs the startup process for
1099 	 * the targeted processor.
1100 	 */
1101 
1102 	if (x86_platform.legacy.warm_reset) {
1103 
1104 		pr_debug("Setting warm reset code and vector.\n");
1105 
1106 		smpboot_setup_warm_reset_vector(start_ip);
1107 		/*
1108 		 * Be paranoid about clearing APIC errors.
1109 		*/
1110 		if (APIC_INTEGRATED(boot_cpu_apic_version)) {
1111 			apic_write(APIC_ESR, 0);
1112 			apic_read(APIC_ESR);
1113 		}
1114 	}
1115 
1116 	/*
1117 	 * AP might wait on cpu_callout_mask in cpu_init() with
1118 	 * cpu_initialized_mask set if previous attempt to online
1119 	 * it timed-out. Clear cpu_initialized_mask so that after
1120 	 * INIT/SIPI it could start with a clean state.
1121 	 */
1122 	cpumask_clear_cpu(cpu, cpu_initialized_mask);
1123 	smp_mb();
1124 
1125 	/*
1126 	 * Wake up a CPU in difference cases:
1127 	 * - Use a method from the APIC driver if one defined, with wakeup
1128 	 *   straight to 64-bit mode preferred over wakeup to RM.
1129 	 * Otherwise,
1130 	 * - Use an INIT boot APIC message for APs or NMI for BSP.
1131 	 */
1132 	if (apic->wakeup_secondary_cpu_64)
1133 		boot_error = apic->wakeup_secondary_cpu_64(apicid, start_ip);
1134 	else if (apic->wakeup_secondary_cpu)
1135 		boot_error = apic->wakeup_secondary_cpu(apicid, start_ip);
1136 	else
1137 		boot_error = wakeup_cpu_via_init_nmi(cpu, start_ip, apicid,
1138 						     cpu0_nmi_registered);
1139 
1140 	if (!boot_error) {
1141 		/*
1142 		 * Wait 10s total for first sign of life from AP
1143 		 */
1144 		boot_error = -1;
1145 		timeout = jiffies + 10*HZ;
1146 		while (time_before(jiffies, timeout)) {
1147 			if (cpumask_test_cpu(cpu, cpu_initialized_mask)) {
1148 				/*
1149 				 * Tell AP to proceed with initialization
1150 				 */
1151 				cpumask_set_cpu(cpu, cpu_callout_mask);
1152 				boot_error = 0;
1153 				break;
1154 			}
1155 			schedule();
1156 		}
1157 	}
1158 
1159 	if (!boot_error) {
1160 		/*
1161 		 * Wait till AP completes initial initialization
1162 		 */
1163 		while (!cpumask_test_cpu(cpu, cpu_callin_mask)) {
1164 			/*
1165 			 * Allow other tasks to run while we wait for the
1166 			 * AP to come online. This also gives a chance
1167 			 * for the MTRR work(triggered by the AP coming online)
1168 			 * to be completed in the stop machine context.
1169 			 */
1170 			schedule();
1171 		}
1172 	}
1173 
1174 	if (x86_platform.legacy.warm_reset) {
1175 		/*
1176 		 * Cleanup possible dangling ends...
1177 		 */
1178 		smpboot_restore_warm_reset_vector();
1179 	}
1180 
1181 	return boot_error;
1182 }
1183 
native_cpu_up(unsigned int cpu,struct task_struct * tidle)1184 int native_cpu_up(unsigned int cpu, struct task_struct *tidle)
1185 {
1186 	int apicid = apic->cpu_present_to_apicid(cpu);
1187 	int cpu0_nmi_registered = 0;
1188 	unsigned long flags;
1189 	int err, ret = 0;
1190 
1191 	lockdep_assert_irqs_enabled();
1192 
1193 	pr_debug("++++++++++++++++++++=_---CPU UP  %u\n", cpu);
1194 
1195 	if (apicid == BAD_APICID ||
1196 	    !physid_isset(apicid, phys_cpu_present_map) ||
1197 	    !apic->apic_id_valid(apicid)) {
1198 		pr_err("%s: bad cpu %d\n", __func__, cpu);
1199 		return -EINVAL;
1200 	}
1201 
1202 	/*
1203 	 * Already booted CPU?
1204 	 */
1205 	if (cpumask_test_cpu(cpu, cpu_callin_mask)) {
1206 		pr_debug("do_boot_cpu %d Already started\n", cpu);
1207 		return -ENOSYS;
1208 	}
1209 
1210 	/*
1211 	 * Save current MTRR state in case it was changed since early boot
1212 	 * (e.g. by the ACPI SMI) to initialize new CPUs with MTRRs in sync:
1213 	 */
1214 	mtrr_save_state();
1215 
1216 	/* x86 CPUs take themselves offline, so delayed offline is OK. */
1217 	err = cpu_check_up_prepare(cpu);
1218 	if (err && err != -EBUSY)
1219 		return err;
1220 
1221 	/* the FPU context is blank, nobody can own it */
1222 	per_cpu(fpu_fpregs_owner_ctx, cpu) = NULL;
1223 
1224 	err = common_cpu_up(cpu, tidle);
1225 	if (err)
1226 		return err;
1227 
1228 	err = do_boot_cpu(apicid, cpu, tidle, &cpu0_nmi_registered);
1229 	if (err) {
1230 		pr_err("do_boot_cpu failed(%d) to wakeup CPU#%u\n", err, cpu);
1231 		ret = -EIO;
1232 		goto unreg_nmi;
1233 	}
1234 
1235 	/*
1236 	 * Check TSC synchronization with the AP (keep irqs disabled
1237 	 * while doing so):
1238 	 */
1239 	local_irq_save(flags);
1240 	check_tsc_sync_source(cpu);
1241 	local_irq_restore(flags);
1242 
1243 	while (!cpu_online(cpu)) {
1244 		cpu_relax();
1245 		touch_nmi_watchdog();
1246 	}
1247 
1248 unreg_nmi:
1249 	/*
1250 	 * Clean up the nmi handler. Do this after the callin and callout sync
1251 	 * to avoid impact of possible long unregister time.
1252 	 */
1253 	if (cpu0_nmi_registered)
1254 		unregister_nmi_handler(NMI_LOCAL, "wake_cpu0");
1255 
1256 	return ret;
1257 }
1258 
1259 /**
1260  * arch_disable_smp_support() - disables SMP support for x86 at runtime
1261  */
arch_disable_smp_support(void)1262 void arch_disable_smp_support(void)
1263 {
1264 	disable_ioapic_support();
1265 }
1266 
1267 /*
1268  * Fall back to non SMP mode after errors.
1269  *
1270  * RED-PEN audit/test this more. I bet there is more state messed up here.
1271  */
disable_smp(void)1272 static __init void disable_smp(void)
1273 {
1274 	pr_info("SMP disabled\n");
1275 
1276 	disable_ioapic_support();
1277 
1278 	init_cpu_present(cpumask_of(0));
1279 	init_cpu_possible(cpumask_of(0));
1280 
1281 	if (smp_found_config)
1282 		physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map);
1283 	else
1284 		physid_set_mask_of_physid(0, &phys_cpu_present_map);
1285 	cpumask_set_cpu(0, topology_sibling_cpumask(0));
1286 	cpumask_set_cpu(0, topology_core_cpumask(0));
1287 	cpumask_set_cpu(0, topology_die_cpumask(0));
1288 }
1289 
1290 /*
1291  * Various sanity checks.
1292  */
smp_sanity_check(void)1293 static void __init smp_sanity_check(void)
1294 {
1295 	preempt_disable();
1296 
1297 #if !defined(CONFIG_X86_BIGSMP) && defined(CONFIG_X86_32)
1298 	if (def_to_bigsmp && nr_cpu_ids > 8) {
1299 		unsigned int cpu;
1300 		unsigned nr;
1301 
1302 		pr_warn("More than 8 CPUs detected - skipping them\n"
1303 			"Use CONFIG_X86_BIGSMP\n");
1304 
1305 		nr = 0;
1306 		for_each_present_cpu(cpu) {
1307 			if (nr >= 8)
1308 				set_cpu_present(cpu, false);
1309 			nr++;
1310 		}
1311 
1312 		nr = 0;
1313 		for_each_possible_cpu(cpu) {
1314 			if (nr >= 8)
1315 				set_cpu_possible(cpu, false);
1316 			nr++;
1317 		}
1318 
1319 		set_nr_cpu_ids(8);
1320 	}
1321 #endif
1322 
1323 	if (!physid_isset(hard_smp_processor_id(), phys_cpu_present_map)) {
1324 		pr_warn("weird, boot CPU (#%d) not listed by the BIOS\n",
1325 			hard_smp_processor_id());
1326 
1327 		physid_set(hard_smp_processor_id(), phys_cpu_present_map);
1328 	}
1329 
1330 	/*
1331 	 * Should not be necessary because the MP table should list the boot
1332 	 * CPU too, but we do it for the sake of robustness anyway.
1333 	 */
1334 	if (!apic->check_phys_apicid_present(boot_cpu_physical_apicid)) {
1335 		pr_notice("weird, boot CPU (#%d) not listed by the BIOS\n",
1336 			  boot_cpu_physical_apicid);
1337 		physid_set(hard_smp_processor_id(), phys_cpu_present_map);
1338 	}
1339 	preempt_enable();
1340 }
1341 
smp_cpu_index_default(void)1342 static void __init smp_cpu_index_default(void)
1343 {
1344 	int i;
1345 	struct cpuinfo_x86 *c;
1346 
1347 	for_each_possible_cpu(i) {
1348 		c = &cpu_data(i);
1349 		/* mark all to hotplug */
1350 		c->cpu_index = nr_cpu_ids;
1351 	}
1352 }
1353 
smp_get_logical_apicid(void)1354 static void __init smp_get_logical_apicid(void)
1355 {
1356 	if (x2apic_mode)
1357 		cpu0_logical_apicid = apic_read(APIC_LDR);
1358 	else
1359 		cpu0_logical_apicid = GET_APIC_LOGICAL_ID(apic_read(APIC_LDR));
1360 }
1361 
smp_prepare_cpus_common(void)1362 void __init smp_prepare_cpus_common(void)
1363 {
1364 	unsigned int i;
1365 
1366 	smp_cpu_index_default();
1367 
1368 	/*
1369 	 * Setup boot CPU information
1370 	 */
1371 	smp_store_boot_cpu_info(); /* Final full version of the data */
1372 	cpumask_copy(cpu_callin_mask, cpumask_of(0));
1373 	mb();
1374 
1375 	for_each_possible_cpu(i) {
1376 		zalloc_cpumask_var(&per_cpu(cpu_sibling_map, i), GFP_KERNEL);
1377 		zalloc_cpumask_var(&per_cpu(cpu_core_map, i), GFP_KERNEL);
1378 		zalloc_cpumask_var(&per_cpu(cpu_die_map, i), GFP_KERNEL);
1379 		zalloc_cpumask_var(&per_cpu(cpu_llc_shared_map, i), GFP_KERNEL);
1380 		zalloc_cpumask_var(&per_cpu(cpu_l2c_shared_map, i), GFP_KERNEL);
1381 	}
1382 
1383 	/*
1384 	 * Set 'default' x86 topology, this matches default_topology() in that
1385 	 * it has NUMA nodes as a topology level. See also
1386 	 * native_smp_cpus_done().
1387 	 *
1388 	 * Must be done before set_cpus_sibling_map() is ran.
1389 	 */
1390 	set_sched_topology(x86_topology);
1391 
1392 	set_cpu_sibling_map(0);
1393 }
1394 
1395 /*
1396  * Prepare for SMP bootup.
1397  * @max_cpus: configured maximum number of CPUs, It is a legacy parameter
1398  *            for common interface support.
1399  */
native_smp_prepare_cpus(unsigned int max_cpus)1400 void __init native_smp_prepare_cpus(unsigned int max_cpus)
1401 {
1402 	smp_prepare_cpus_common();
1403 
1404 	smp_sanity_check();
1405 
1406 	switch (apic_intr_mode) {
1407 	case APIC_PIC:
1408 	case APIC_VIRTUAL_WIRE_NO_CONFIG:
1409 		disable_smp();
1410 		return;
1411 	case APIC_SYMMETRIC_IO_NO_ROUTING:
1412 		disable_smp();
1413 		/* Setup local timer */
1414 		x86_init.timers.setup_percpu_clockev();
1415 		return;
1416 	case APIC_VIRTUAL_WIRE:
1417 	case APIC_SYMMETRIC_IO:
1418 		break;
1419 	}
1420 
1421 	/* Setup local timer */
1422 	x86_init.timers.setup_percpu_clockev();
1423 
1424 	smp_get_logical_apicid();
1425 
1426 	pr_info("CPU0: ");
1427 	print_cpu_info(&cpu_data(0));
1428 
1429 	uv_system_init();
1430 
1431 	set_mtrr_aps_delayed_init();
1432 
1433 	smp_quirk_init_udelay();
1434 
1435 	speculative_store_bypass_ht_init();
1436 
1437 	snp_set_wakeup_secondary_cpu();
1438 }
1439 
arch_thaw_secondary_cpus_begin(void)1440 void arch_thaw_secondary_cpus_begin(void)
1441 {
1442 	set_mtrr_aps_delayed_init();
1443 }
1444 
arch_thaw_secondary_cpus_end(void)1445 void arch_thaw_secondary_cpus_end(void)
1446 {
1447 	mtrr_aps_init();
1448 }
1449 
1450 /*
1451  * Early setup to make printk work.
1452  */
native_smp_prepare_boot_cpu(void)1453 void __init native_smp_prepare_boot_cpu(void)
1454 {
1455 	int me = smp_processor_id();
1456 	switch_to_new_gdt(me);
1457 	/* already set me in cpu_online_mask in boot_cpu_init() */
1458 	cpumask_set_cpu(me, cpu_callout_mask);
1459 	cpu_set_state_online(me);
1460 	native_pv_lock_init();
1461 }
1462 
calculate_max_logical_packages(void)1463 void __init calculate_max_logical_packages(void)
1464 {
1465 	int ncpus;
1466 
1467 	/*
1468 	 * Today neither Intel nor AMD support heterogeneous systems so
1469 	 * extrapolate the boot cpu's data to all packages.
1470 	 */
1471 	ncpus = cpu_data(0).booted_cores * topology_max_smt_threads();
1472 	__max_logical_packages = DIV_ROUND_UP(total_cpus, ncpus);
1473 	pr_info("Max logical packages: %u\n", __max_logical_packages);
1474 }
1475 
native_smp_cpus_done(unsigned int max_cpus)1476 void __init native_smp_cpus_done(unsigned int max_cpus)
1477 {
1478 	pr_debug("Boot done\n");
1479 
1480 	calculate_max_logical_packages();
1481 
1482 	/* XXX for now assume numa-in-package and hybrid don't overlap */
1483 	if (x86_has_numa_in_package)
1484 		set_sched_topology(x86_numa_in_package_topology);
1485 	if (cpu_feature_enabled(X86_FEATURE_HYBRID_CPU))
1486 		set_sched_topology(x86_hybrid_topology);
1487 
1488 	nmi_selftest();
1489 	impress_friends();
1490 	mtrr_aps_init();
1491 }
1492 
1493 static int __initdata setup_possible_cpus = -1;
_setup_possible_cpus(char * str)1494 static int __init _setup_possible_cpus(char *str)
1495 {
1496 	get_option(&str, &setup_possible_cpus);
1497 	return 0;
1498 }
1499 early_param("possible_cpus", _setup_possible_cpus);
1500 
1501 
1502 /*
1503  * cpu_possible_mask should be static, it cannot change as cpu's
1504  * are onlined, or offlined. The reason is per-cpu data-structures
1505  * are allocated by some modules at init time, and don't expect to
1506  * do this dynamically on cpu arrival/departure.
1507  * cpu_present_mask on the other hand can change dynamically.
1508  * In case when cpu_hotplug is not compiled, then we resort to current
1509  * behaviour, which is cpu_possible == cpu_present.
1510  * - Ashok Raj
1511  *
1512  * Three ways to find out the number of additional hotplug CPUs:
1513  * - If the BIOS specified disabled CPUs in ACPI/mptables use that.
1514  * - The user can overwrite it with possible_cpus=NUM
1515  * - Otherwise don't reserve additional CPUs.
1516  * We do this because additional CPUs waste a lot of memory.
1517  * -AK
1518  */
prefill_possible_map(void)1519 __init void prefill_possible_map(void)
1520 {
1521 	int i, possible;
1522 
1523 	/* No boot processor was found in mptable or ACPI MADT */
1524 	if (!num_processors) {
1525 		if (boot_cpu_has(X86_FEATURE_APIC)) {
1526 			int apicid = boot_cpu_physical_apicid;
1527 			int cpu = hard_smp_processor_id();
1528 
1529 			pr_warn("Boot CPU (id %d) not listed by BIOS\n", cpu);
1530 
1531 			/* Make sure boot cpu is enumerated */
1532 			if (apic->cpu_present_to_apicid(0) == BAD_APICID &&
1533 			    apic->apic_id_valid(apicid))
1534 				generic_processor_info(apicid, boot_cpu_apic_version);
1535 		}
1536 
1537 		if (!num_processors)
1538 			num_processors = 1;
1539 	}
1540 
1541 	i = setup_max_cpus ?: 1;
1542 	if (setup_possible_cpus == -1) {
1543 		possible = num_processors;
1544 #ifdef CONFIG_HOTPLUG_CPU
1545 		if (setup_max_cpus)
1546 			possible += disabled_cpus;
1547 #else
1548 		if (possible > i)
1549 			possible = i;
1550 #endif
1551 	} else
1552 		possible = setup_possible_cpus;
1553 
1554 	total_cpus = max_t(int, possible, num_processors + disabled_cpus);
1555 
1556 	/* nr_cpu_ids could be reduced via nr_cpus= */
1557 	if (possible > nr_cpu_ids) {
1558 		pr_warn("%d Processors exceeds NR_CPUS limit of %u\n",
1559 			possible, nr_cpu_ids);
1560 		possible = nr_cpu_ids;
1561 	}
1562 
1563 #ifdef CONFIG_HOTPLUG_CPU
1564 	if (!setup_max_cpus)
1565 #endif
1566 	if (possible > i) {
1567 		pr_warn("%d Processors exceeds max_cpus limit of %u\n",
1568 			possible, setup_max_cpus);
1569 		possible = i;
1570 	}
1571 
1572 	set_nr_cpu_ids(possible);
1573 
1574 	pr_info("Allowing %d CPUs, %d hotplug CPUs\n",
1575 		possible, max_t(int, possible - num_processors, 0));
1576 
1577 	reset_cpu_possible_mask();
1578 
1579 	for (i = 0; i < possible; i++)
1580 		set_cpu_possible(i, true);
1581 }
1582 
1583 #ifdef CONFIG_HOTPLUG_CPU
1584 
1585 /* Recompute SMT state for all CPUs on offline */
recompute_smt_state(void)1586 static void recompute_smt_state(void)
1587 {
1588 	int max_threads, cpu;
1589 
1590 	max_threads = 0;
1591 	for_each_online_cpu (cpu) {
1592 		int threads = cpumask_weight(topology_sibling_cpumask(cpu));
1593 
1594 		if (threads > max_threads)
1595 			max_threads = threads;
1596 	}
1597 	__max_smt_threads = max_threads;
1598 }
1599 
remove_siblinginfo(int cpu)1600 static void remove_siblinginfo(int cpu)
1601 {
1602 	int sibling;
1603 	struct cpuinfo_x86 *c = &cpu_data(cpu);
1604 
1605 	for_each_cpu(sibling, topology_core_cpumask(cpu)) {
1606 		cpumask_clear_cpu(cpu, topology_core_cpumask(sibling));
1607 		/*/
1608 		 * last thread sibling in this cpu core going down
1609 		 */
1610 		if (cpumask_weight(topology_sibling_cpumask(cpu)) == 1)
1611 			cpu_data(sibling).booted_cores--;
1612 	}
1613 
1614 	for_each_cpu(sibling, topology_die_cpumask(cpu))
1615 		cpumask_clear_cpu(cpu, topology_die_cpumask(sibling));
1616 
1617 	for_each_cpu(sibling, topology_sibling_cpumask(cpu)) {
1618 		cpumask_clear_cpu(cpu, topology_sibling_cpumask(sibling));
1619 		if (cpumask_weight(topology_sibling_cpumask(sibling)) == 1)
1620 			cpu_data(sibling).smt_active = false;
1621 	}
1622 
1623 	for_each_cpu(sibling, cpu_llc_shared_mask(cpu))
1624 		cpumask_clear_cpu(cpu, cpu_llc_shared_mask(sibling));
1625 	for_each_cpu(sibling, cpu_l2c_shared_mask(cpu))
1626 		cpumask_clear_cpu(cpu, cpu_l2c_shared_mask(sibling));
1627 	cpumask_clear(cpu_llc_shared_mask(cpu));
1628 	cpumask_clear(cpu_l2c_shared_mask(cpu));
1629 	cpumask_clear(topology_sibling_cpumask(cpu));
1630 	cpumask_clear(topology_core_cpumask(cpu));
1631 	cpumask_clear(topology_die_cpumask(cpu));
1632 	c->cpu_core_id = 0;
1633 	c->booted_cores = 0;
1634 	cpumask_clear_cpu(cpu, cpu_sibling_setup_mask);
1635 	recompute_smt_state();
1636 }
1637 
remove_cpu_from_maps(int cpu)1638 static void remove_cpu_from_maps(int cpu)
1639 {
1640 	set_cpu_online(cpu, false);
1641 	cpumask_clear_cpu(cpu, cpu_callout_mask);
1642 	cpumask_clear_cpu(cpu, cpu_callin_mask);
1643 	/* was set by cpu_init() */
1644 	cpumask_clear_cpu(cpu, cpu_initialized_mask);
1645 	numa_remove_cpu(cpu);
1646 }
1647 
cpu_disable_common(void)1648 void cpu_disable_common(void)
1649 {
1650 	int cpu = smp_processor_id();
1651 
1652 	remove_siblinginfo(cpu);
1653 
1654 	/* It's now safe to remove this processor from the online map */
1655 	lock_vector_lock();
1656 	remove_cpu_from_maps(cpu);
1657 	unlock_vector_lock();
1658 	fixup_irqs();
1659 	lapic_offline();
1660 }
1661 
native_cpu_disable(void)1662 int native_cpu_disable(void)
1663 {
1664 	int ret;
1665 
1666 	ret = lapic_can_unplug_cpu();
1667 	if (ret)
1668 		return ret;
1669 
1670 	cpu_disable_common();
1671 
1672         /*
1673          * Disable the local APIC. Otherwise IPI broadcasts will reach
1674          * it. It still responds normally to INIT, NMI, SMI, and SIPI
1675          * messages.
1676          *
1677          * Disabling the APIC must happen after cpu_disable_common()
1678          * which invokes fixup_irqs().
1679          *
1680          * Disabling the APIC preserves already set bits in IRR, but
1681          * an interrupt arriving after disabling the local APIC does not
1682          * set the corresponding IRR bit.
1683          *
1684          * fixup_irqs() scans IRR for set bits so it can raise a not
1685          * yet handled interrupt on the new destination CPU via an IPI
1686          * but obviously it can't do so for IRR bits which are not set.
1687          * IOW, interrupts arriving after disabling the local APIC will
1688          * be lost.
1689          */
1690 	apic_soft_disable();
1691 
1692 	return 0;
1693 }
1694 
common_cpu_die(unsigned int cpu)1695 int common_cpu_die(unsigned int cpu)
1696 {
1697 	int ret = 0;
1698 
1699 	/* We don't do anything here: idle task is faking death itself. */
1700 
1701 	/* They ack this in play_dead() by setting CPU_DEAD */
1702 	if (cpu_wait_death(cpu, 5)) {
1703 		if (system_state == SYSTEM_RUNNING)
1704 			pr_info("CPU %u is now offline\n", cpu);
1705 	} else {
1706 		pr_err("CPU %u didn't die...\n", cpu);
1707 		ret = -1;
1708 	}
1709 
1710 	return ret;
1711 }
1712 
native_cpu_die(unsigned int cpu)1713 void native_cpu_die(unsigned int cpu)
1714 {
1715 	common_cpu_die(cpu);
1716 }
1717 
play_dead_common(void)1718 void play_dead_common(void)
1719 {
1720 	idle_task_exit();
1721 
1722 	/* Ack it */
1723 	(void)cpu_report_death();
1724 
1725 	/*
1726 	 * With physical CPU hotplug, we should halt the cpu
1727 	 */
1728 	local_irq_disable();
1729 }
1730 
1731 /**
1732  * cond_wakeup_cpu0 - Wake up CPU0 if needed.
1733  *
1734  * If NMI wants to wake up CPU0, start CPU0.
1735  */
cond_wakeup_cpu0(void)1736 void cond_wakeup_cpu0(void)
1737 {
1738 	if (smp_processor_id() == 0 && enable_start_cpu0)
1739 		start_cpu0();
1740 }
1741 EXPORT_SYMBOL_GPL(cond_wakeup_cpu0);
1742 
1743 /*
1744  * We need to flush the caches before going to sleep, lest we have
1745  * dirty data in our caches when we come back up.
1746  */
mwait_play_dead(void)1747 static inline void mwait_play_dead(void)
1748 {
1749 	unsigned int eax, ebx, ecx, edx;
1750 	unsigned int highest_cstate = 0;
1751 	unsigned int highest_subcstate = 0;
1752 	void *mwait_ptr;
1753 	int i;
1754 
1755 	if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
1756 	    boot_cpu_data.x86_vendor == X86_VENDOR_HYGON)
1757 		return;
1758 	if (!this_cpu_has(X86_FEATURE_MWAIT))
1759 		return;
1760 	if (!this_cpu_has(X86_FEATURE_CLFLUSH))
1761 		return;
1762 	if (__this_cpu_read(cpu_info.cpuid_level) < CPUID_MWAIT_LEAF)
1763 		return;
1764 
1765 	eax = CPUID_MWAIT_LEAF;
1766 	ecx = 0;
1767 	native_cpuid(&eax, &ebx, &ecx, &edx);
1768 
1769 	/*
1770 	 * eax will be 0 if EDX enumeration is not valid.
1771 	 * Initialized below to cstate, sub_cstate value when EDX is valid.
1772 	 */
1773 	if (!(ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED)) {
1774 		eax = 0;
1775 	} else {
1776 		edx >>= MWAIT_SUBSTATE_SIZE;
1777 		for (i = 0; i < 7 && edx; i++, edx >>= MWAIT_SUBSTATE_SIZE) {
1778 			if (edx & MWAIT_SUBSTATE_MASK) {
1779 				highest_cstate = i;
1780 				highest_subcstate = edx & MWAIT_SUBSTATE_MASK;
1781 			}
1782 		}
1783 		eax = (highest_cstate << MWAIT_SUBSTATE_SIZE) |
1784 			(highest_subcstate - 1);
1785 	}
1786 
1787 	/*
1788 	 * This should be a memory location in a cache line which is
1789 	 * unlikely to be touched by other processors.  The actual
1790 	 * content is immaterial as it is not actually modified in any way.
1791 	 */
1792 	mwait_ptr = &current_thread_info()->flags;
1793 
1794 	wbinvd();
1795 
1796 	while (1) {
1797 		/*
1798 		 * The CLFLUSH is a workaround for erratum AAI65 for
1799 		 * the Xeon 7400 series.  It's not clear it is actually
1800 		 * needed, but it should be harmless in either case.
1801 		 * The WBINVD is insufficient due to the spurious-wakeup
1802 		 * case where we return around the loop.
1803 		 */
1804 		mb();
1805 		clflush(mwait_ptr);
1806 		mb();
1807 		__monitor(mwait_ptr, 0, 0);
1808 		mb();
1809 		__mwait(eax, 0);
1810 
1811 		cond_wakeup_cpu0();
1812 	}
1813 }
1814 
hlt_play_dead(void)1815 void hlt_play_dead(void)
1816 {
1817 	if (__this_cpu_read(cpu_info.x86) >= 4)
1818 		wbinvd();
1819 
1820 	while (1) {
1821 		native_halt();
1822 
1823 		cond_wakeup_cpu0();
1824 	}
1825 }
1826 
native_play_dead(void)1827 void native_play_dead(void)
1828 {
1829 	play_dead_common();
1830 	tboot_shutdown(TB_SHUTDOWN_WFS);
1831 
1832 	mwait_play_dead();	/* Only returns on failure */
1833 	if (cpuidle_play_dead())
1834 		hlt_play_dead();
1835 }
1836 
1837 #else /* ... !CONFIG_HOTPLUG_CPU */
native_cpu_disable(void)1838 int native_cpu_disable(void)
1839 {
1840 	return -ENOSYS;
1841 }
1842 
native_cpu_die(unsigned int cpu)1843 void native_cpu_die(unsigned int cpu)
1844 {
1845 	/* We said "no" in __cpu_disable */
1846 	BUG();
1847 }
1848 
native_play_dead(void)1849 void native_play_dead(void)
1850 {
1851 	BUG();
1852 }
1853 
1854 #endif
1855