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