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