1 /*-
2 * Copyright (c) 1996, by Steve Passe
3 * Copyright (c) 2003, by Peter Wemm
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. The name of the developer may NOT be used to endorse or promote products
12 * derived from this software without specific prior written permission.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27 #include <sys/cdefs.h>
28 #include "opt_acpi.h"
29 #ifdef __i386__
30 #include "opt_apic.h"
31 #endif
32 #include "opt_cpu.h"
33 #include "opt_ddb.h"
34 #include "opt_gdb.h"
35 #include "opt_kstack_pages.h"
36 #include "opt_pmap.h"
37 #include "opt_sched.h"
38 #include "opt_smp.h"
39 #include "opt_stack.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/asan.h>
44 #include <sys/bus.h>
45 #include <sys/cons.h> /* cngetc() */
46 #include <sys/cpuset.h>
47 #include <sys/csan.h>
48 #ifdef GPROF
49 #include <sys/gmon.h>
50 #endif
51 #include <sys/interrupt.h>
52 #include <sys/kdb.h>
53 #include <sys/kernel.h>
54 #include <sys/ktr.h>
55 #include <sys/lock.h>
56 #include <sys/malloc.h>
57 #include <sys/memrange.h>
58 #include <sys/mutex.h>
59 #include <sys/pcpu.h>
60 #include <sys/proc.h>
61 #include <sys/sched.h>
62 #include <sys/smp.h>
63 #include <sys/sysctl.h>
64
65 #include <vm/vm.h>
66 #include <vm/vm_param.h>
67 #include <vm/pmap.h>
68 #include <vm/vm_kern.h>
69 #include <vm/vm_extern.h>
70 #include <vm/vm_map.h>
71
72 #include <x86/apicreg.h>
73 #include <machine/clock.h>
74 #include <machine/cpu.h>
75 #include <machine/cputypes.h>
76 #include <x86/mca.h>
77 #include <machine/md_var.h>
78 #include <machine/pcb.h>
79 #include <machine/psl.h>
80 #include <machine/smp.h>
81 #include <machine/specialreg.h>
82 #include <machine/stack.h>
83 #include <x86/ucode.h>
84
85 #ifdef DEV_ACPI
86 #include <contrib/dev/acpica/include/acpi.h>
87 #include <dev/acpica/acpivar.h>
88 #endif
89
90 static MALLOC_DEFINE(M_CPUS, "cpus", "CPU items");
91
92 /* lock region used by kernel profiling */
93 int mcount_lock;
94
95 int mp_naps; /* # of Applications processors */
96 int boot_cpu_id = -1; /* designated BSP */
97
98 /* AP uses this during bootstrap. Do not staticize. */
99 char *bootSTK;
100 int bootAP;
101
102 /* Free these after use */
103 void *bootstacks[MAXCPU];
104 void *dpcpu;
105
106 struct pcb stoppcbs[MAXCPU];
107 struct susppcb **susppcbs;
108
109 #ifdef COUNT_IPIS
110 /* Interrupt counts. */
111 static u_long *ipi_preempt_counts[MAXCPU];
112 static u_long *ipi_ast_counts[MAXCPU];
113 u_long *ipi_invltlb_counts[MAXCPU];
114 u_long *ipi_invlrng_counts[MAXCPU];
115 u_long *ipi_invlpg_counts[MAXCPU];
116 u_long *ipi_invlcache_counts[MAXCPU];
117 u_long *ipi_rendezvous_counts[MAXCPU];
118 static u_long *ipi_hardclock_counts[MAXCPU];
119 #endif
120
121 /* Default cpu_ops implementation. */
122 struct cpu_ops cpu_ops;
123
124 /*
125 * Local data and functions.
126 */
127
128 static volatile cpuset_t ipi_stop_nmi_pending;
129
130 volatile cpuset_t resuming_cpus;
131 volatile cpuset_t toresume_cpus;
132
133 /* used to hold the AP's until we are ready to release them */
134 struct mtx ap_boot_mtx;
135
136 /* Set to 1 once we're ready to let the APs out of the pen. */
137 volatile int aps_ready = 0;
138
139 /*
140 * Store data from cpu_add() until later in the boot when we actually setup
141 * the APs.
142 */
143 struct cpu_info *cpu_info;
144 int *apic_cpuids;
145 int cpu_apic_ids[MAXCPU];
146 _Static_assert(MAXCPU <= MAX_APIC_ID,
147 "MAXCPU cannot be larger that MAX_APIC_ID");
148 _Static_assert(xAPIC_MAX_APIC_ID <= MAX_APIC_ID,
149 "xAPIC_MAX_APIC_ID cannot be larger that MAX_APIC_ID");
150
151 static void release_aps(void *dummy);
152 static void cpustop_handler_post(u_int cpu);
153
154 static int hyperthreading_allowed = 1;
155 SYSCTL_INT(_machdep, OID_AUTO, hyperthreading_allowed, CTLFLAG_RDTUN,
156 &hyperthreading_allowed, 0, "Use Intel HTT logical CPUs");
157
158 static int hyperthreading_intr_allowed = 0;
159 SYSCTL_INT(_machdep, OID_AUTO, hyperthreading_intr_allowed, CTLFLAG_RDTUN,
160 &hyperthreading_intr_allowed, 0,
161 "Allow interrupts on HTT logical CPUs");
162
163 static struct topo_node topo_root;
164
165 static int pkg_id_shift;
166 static int node_id_shift;
167 static int core_id_shift;
168 static int disabled_cpus;
169
170 struct cache_info {
171 int id_shift;
172 int present;
173 } static caches[MAX_CACHE_LEVELS];
174
175 static bool stop_mwait = false;
176 SYSCTL_BOOL(_machdep, OID_AUTO, stop_mwait, CTLFLAG_RWTUN, &stop_mwait, 0,
177 "Use MONITOR/MWAIT when stopping CPU, if available");
178
179 void
mem_range_AP_init(void)180 mem_range_AP_init(void)
181 {
182
183 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
184 mem_range_softc.mr_op->initAP(&mem_range_softc);
185 }
186
187 /*
188 * Round up to the next power of two, if necessary, and then
189 * take log2.
190 * Returns -1 if argument is zero.
191 */
192 static __inline int
mask_width(u_int x)193 mask_width(u_int x)
194 {
195
196 return (fls(x << (1 - powerof2(x))) - 1);
197 }
198
199 /*
200 * Add a cache level to the cache topology description.
201 */
202 static int
add_deterministic_cache(int type,int level,int share_count)203 add_deterministic_cache(int type, int level, int share_count)
204 {
205
206 if (type == 0)
207 return (0);
208 if (type > 3) {
209 printf("unexpected cache type %d\n", type);
210 return (1);
211 }
212 if (type == 2) /* ignore instruction cache */
213 return (1);
214 if (level == 0 || level > MAX_CACHE_LEVELS) {
215 printf("unexpected cache level %d\n", level);
216 return (1);
217 }
218
219 if (caches[level - 1].present) {
220 printf("WARNING: multiple entries for L%u data cache\n", level);
221 printf("%u => %u\n", caches[level - 1].id_shift,
222 mask_width(share_count));
223 }
224 caches[level - 1].id_shift = mask_width(share_count);
225 caches[level - 1].present = 1;
226
227 if (caches[level - 1].id_shift > pkg_id_shift) {
228 printf("WARNING: L%u data cache covers more "
229 "APIC IDs than a package (%u > %u)\n", level,
230 caches[level - 1].id_shift, pkg_id_shift);
231 caches[level - 1].id_shift = pkg_id_shift;
232 }
233 if (caches[level - 1].id_shift < core_id_shift) {
234 printf("WARNING: L%u data cache covers fewer "
235 "APIC IDs than a core (%u < %u)\n", level,
236 caches[level - 1].id_shift, core_id_shift);
237 caches[level - 1].id_shift = core_id_shift;
238 }
239
240 return (1);
241 }
242
243 /*
244 * Determine topology of processing units and caches for AMD CPUs.
245 * See:
246 * - AMD CPUID Specification (Publication # 25481)
247 * - BKDG for AMD NPT Family 0Fh Processors (Publication # 32559)
248 * - BKDG For AMD Family 10h Processors (Publication # 31116)
249 * - BKDG For AMD Family 15h Models 00h-0Fh Processors (Publication # 42301)
250 * - BKDG For AMD Family 16h Models 00h-0Fh Processors (Publication # 48751)
251 * - PPR For AMD Family 17h Models 00h-0Fh Processors (Publication # 54945)
252 */
253 static void
topo_probe_amd(void)254 topo_probe_amd(void)
255 {
256 u_int p[4];
257 uint64_t v;
258 int level;
259 int nodes_per_socket;
260 int share_count;
261 int type;
262 int i;
263
264 /* No multi-core capability. */
265 if ((amd_feature2 & AMDID2_CMP) == 0)
266 return;
267
268 /* For families 10h and newer. */
269 pkg_id_shift = (cpu_procinfo2 & AMDID_COREID_SIZE) >>
270 AMDID_COREID_SIZE_SHIFT;
271
272 /* For 0Fh family. */
273 if (pkg_id_shift == 0)
274 pkg_id_shift =
275 mask_width((cpu_procinfo2 & AMDID_CMP_CORES) + 1);
276
277 /*
278 * Families prior to 16h define the following value as
279 * cores per compute unit and we don't really care about the AMD
280 * compute units at the moment. Perhaps we should treat them as
281 * cores and cores within the compute units as hardware threads,
282 * but that's up for debate.
283 * Later families define the value as threads per compute unit,
284 * so we are following AMD's nomenclature here.
285 */
286 if ((amd_feature2 & AMDID2_TOPOLOGY) != 0 &&
287 CPUID_TO_FAMILY(cpu_id) >= 0x16) {
288 cpuid_count(0x8000001e, 0, p);
289 share_count = ((p[1] >> 8) & 0xff) + 1;
290 core_id_shift = mask_width(share_count);
291
292 /*
293 * For Zen (17h), gather Nodes per Processor. Each node is a
294 * Zeppelin die; TR and EPYC CPUs will have multiple dies per
295 * package. Communication latency between dies is higher than
296 * within them.
297 */
298 nodes_per_socket = ((p[2] >> 8) & 0x7) + 1;
299 node_id_shift = pkg_id_shift - mask_width(nodes_per_socket);
300 }
301
302 if ((amd_feature2 & AMDID2_TOPOLOGY) != 0) {
303 for (i = 0; ; i++) {
304 cpuid_count(0x8000001d, i, p);
305 type = p[0] & 0x1f;
306 level = (p[0] >> 5) & 0x7;
307 share_count = 1 + ((p[0] >> 14) & 0xfff);
308
309 if (!add_deterministic_cache(type, level, share_count))
310 break;
311 }
312 } else {
313 if (cpu_exthigh >= 0x80000005) {
314 cpuid_count(0x80000005, 0, p);
315 if (((p[2] >> 24) & 0xff) != 0) {
316 caches[0].id_shift = 0;
317 caches[0].present = 1;
318 }
319 }
320 if (cpu_exthigh >= 0x80000006) {
321 cpuid_count(0x80000006, 0, p);
322 if (((p[2] >> 16) & 0xffff) != 0) {
323 caches[1].id_shift = 0;
324 caches[1].present = 1;
325 }
326 if (((p[3] >> 18) & 0x3fff) != 0) {
327 nodes_per_socket = 1;
328 if ((amd_feature2 & AMDID2_NODE_ID) != 0) {
329 /*
330 * Handle multi-node processors that
331 * have multiple chips, each with its
332 * own L3 cache, on the same die.
333 */
334 v = rdmsr(0xc001100c);
335 nodes_per_socket = 1 + ((v >> 3) & 0x7);
336 }
337 caches[2].id_shift =
338 pkg_id_shift - mask_width(nodes_per_socket);
339 caches[2].present = 1;
340 }
341 }
342 }
343 }
344
345 /*
346 * Determine topology of processing units for Intel CPUs
347 * using CPUID Leaf 1 and Leaf 4, if supported.
348 * See:
349 * - Intel 64 Architecture Processor Topology Enumeration
350 * - Intel 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
351 * Volume 3A: System Programming Guide, PROGRAMMING CONSIDERATIONS
352 * FOR HARDWARE MULTI-THREADING CAPABLE PROCESSORS
353 */
354 static void
topo_probe_intel_0x4(void)355 topo_probe_intel_0x4(void)
356 {
357 u_int p[4];
358 int max_cores;
359 int max_logical;
360
361 /* Both zero and one here mean one logical processor per package. */
362 max_logical = (cpu_feature & CPUID_HTT) != 0 ?
363 (cpu_procinfo & CPUID_HTT_CORES) >> 16 : 1;
364 if (max_logical <= 1)
365 return;
366
367 if (cpu_high >= 0x4) {
368 cpuid_count(0x04, 0, p);
369 max_cores = ((p[0] >> 26) & 0x3f) + 1;
370 } else
371 max_cores = 1;
372
373 core_id_shift = mask_width(max_logical/max_cores);
374 KASSERT(core_id_shift >= 0,
375 ("intel topo: max_cores > max_logical\n"));
376 pkg_id_shift = core_id_shift + mask_width(max_cores);
377 }
378
379 /*
380 * Determine topology of processing units for Intel CPUs
381 * using CPUID Leaf 1Fh or 0Bh, if supported.
382 * See:
383 * - Intel 64 Architecture Processor Topology Enumeration
384 * - Intel 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
385 * Volume 3A: System Programming Guide, PROGRAMMING CONSIDERATIONS
386 * FOR HARDWARE MULTI-THREADING CAPABLE PROCESSORS
387 */
388 static void
topo_probe_intel_0xb(void)389 topo_probe_intel_0xb(void)
390 {
391 u_int leaf;
392 u_int p[4] = { 0 };
393 int bits;
394 int type;
395 int i;
396
397 /* Prefer leaf 1Fh (V2 Extended Topology Enumeration). */
398 if (cpu_high >= 0x1f) {
399 leaf = 0x1f;
400 cpuid_count(leaf, 0, p);
401 }
402 /* Fall back to leaf 0Bh (Extended Topology Enumeration). */
403 if (p[1] == 0) {
404 leaf = 0x0b;
405 cpuid_count(leaf, 0, p);
406 }
407 /* Fall back to leaf 04h (Deterministic Cache Parameters). */
408 if (p[1] == 0) {
409 topo_probe_intel_0x4();
410 return;
411 }
412
413 /* We only support three levels for now. */
414 for (i = 0; ; i++) {
415 cpuid_count(leaf, i, p);
416
417 bits = p[0] & 0x1f;
418 type = (p[2] >> 8) & 0xff;
419
420 if (type == 0)
421 break;
422
423 if (type == CPUID_TYPE_SMT)
424 core_id_shift = bits;
425 else if (type == CPUID_TYPE_CORE)
426 pkg_id_shift = bits;
427 else if (bootverbose)
428 printf("Topology level type %d shift: %d\n", type, bits);
429 }
430
431 if (pkg_id_shift < core_id_shift) {
432 printf("WARNING: core covers more APIC IDs than a package\n");
433 core_id_shift = pkg_id_shift;
434 }
435 }
436
437 /*
438 * Determine topology of caches for Intel CPUs.
439 * See:
440 * - Intel 64 Architecture Processor Topology Enumeration
441 * - Intel 64 and IA-32 Architectures Software Developer’s Manual
442 * Volume 2A: Instruction Set Reference, A-M,
443 * CPUID instruction
444 */
445 static void
topo_probe_intel_caches(void)446 topo_probe_intel_caches(void)
447 {
448 u_int p[4];
449 int level;
450 int share_count;
451 int type;
452 int i;
453
454 if (cpu_high < 0x4) {
455 /*
456 * Available cache level and sizes can be determined
457 * via CPUID leaf 2, but that requires a huge table of hardcoded
458 * values, so for now just assume L1 and L2 caches potentially
459 * shared only by HTT processing units, if HTT is present.
460 */
461 caches[0].id_shift = pkg_id_shift;
462 caches[0].present = 1;
463 caches[1].id_shift = pkg_id_shift;
464 caches[1].present = 1;
465 return;
466 }
467
468 for (i = 0; ; i++) {
469 cpuid_count(0x4, i, p);
470 type = p[0] & 0x1f;
471 level = (p[0] >> 5) & 0x7;
472 share_count = 1 + ((p[0] >> 14) & 0xfff);
473
474 if (!add_deterministic_cache(type, level, share_count))
475 break;
476 }
477 }
478
479 /*
480 * Determine topology of processing units and caches for Intel CPUs.
481 * See:
482 * - Intel 64 Architecture Processor Topology Enumeration
483 */
484 static void
topo_probe_intel(void)485 topo_probe_intel(void)
486 {
487
488 /*
489 * Note that 0x1 <= cpu_high < 4 case should be
490 * compatible with topo_probe_intel_0x4() logic when
491 * CPUID.1:EBX[23:16] > 0 (cpu_cores will be 1)
492 * or it should trigger the fallback otherwise.
493 */
494 if (cpu_high >= 0xb)
495 topo_probe_intel_0xb();
496 else if (cpu_high >= 0x1)
497 topo_probe_intel_0x4();
498
499 topo_probe_intel_caches();
500 }
501
502 /*
503 * Topology information is queried only on BSP, on which this
504 * code runs and for which it can query CPUID information.
505 * Then topology is extrapolated on all packages using an
506 * assumption that APIC ID to hardware component ID mapping is
507 * homogenious.
508 * That doesn't necesserily imply that the topology is uniform.
509 */
510 void
topo_probe(void)511 topo_probe(void)
512 {
513 static int cpu_topo_probed = 0;
514 struct x86_topo_layer {
515 int type;
516 int subtype;
517 int id_shift;
518 } topo_layers[MAX_CACHE_LEVELS + 5];
519 struct topo_node *parent;
520 struct topo_node *node;
521 int layer;
522 int nlayers;
523 int node_id;
524 int i;
525 #if defined(DEV_ACPI) && MAXMEMDOM > 1
526 int d, domain;
527 #endif
528
529 if (cpu_topo_probed)
530 return;
531
532 CPU_ZERO(&logical_cpus_mask);
533
534 if (mp_ncpus <= 1)
535 ; /* nothing */
536 else if (cpu_vendor_id == CPU_VENDOR_AMD ||
537 cpu_vendor_id == CPU_VENDOR_HYGON)
538 topo_probe_amd();
539 else if (cpu_vendor_id == CPU_VENDOR_INTEL)
540 topo_probe_intel();
541
542 KASSERT(pkg_id_shift >= core_id_shift,
543 ("bug in APIC topology discovery"));
544
545 nlayers = 0;
546 bzero(topo_layers, sizeof(topo_layers));
547
548 topo_layers[nlayers].type = TOPO_TYPE_PKG;
549 topo_layers[nlayers].id_shift = pkg_id_shift;
550 if (bootverbose)
551 printf("Package ID shift: %u\n", topo_layers[nlayers].id_shift);
552 nlayers++;
553
554 if (pkg_id_shift > node_id_shift && node_id_shift != 0) {
555 topo_layers[nlayers].type = TOPO_TYPE_GROUP;
556 topo_layers[nlayers].id_shift = node_id_shift;
557 if (bootverbose)
558 printf("Node ID shift: %u\n",
559 topo_layers[nlayers].id_shift);
560 nlayers++;
561 }
562
563 /*
564 * Consider all caches to be within a package/chip
565 * and "in front" of all sub-components like
566 * cores and hardware threads.
567 */
568 for (i = MAX_CACHE_LEVELS - 1; i >= 0; --i) {
569 if (caches[i].present) {
570 if (node_id_shift != 0)
571 KASSERT(caches[i].id_shift <= node_id_shift,
572 ("bug in APIC topology discovery"));
573 KASSERT(caches[i].id_shift <= pkg_id_shift,
574 ("bug in APIC topology discovery"));
575 KASSERT(caches[i].id_shift >= core_id_shift,
576 ("bug in APIC topology discovery"));
577
578 topo_layers[nlayers].type = TOPO_TYPE_CACHE;
579 topo_layers[nlayers].subtype = i + 1;
580 topo_layers[nlayers].id_shift = caches[i].id_shift;
581 if (bootverbose)
582 printf("L%u cache ID shift: %u\n",
583 topo_layers[nlayers].subtype,
584 topo_layers[nlayers].id_shift);
585 nlayers++;
586 }
587 }
588
589 if (pkg_id_shift > core_id_shift) {
590 topo_layers[nlayers].type = TOPO_TYPE_CORE;
591 topo_layers[nlayers].id_shift = core_id_shift;
592 if (bootverbose)
593 printf("Core ID shift: %u\n",
594 topo_layers[nlayers].id_shift);
595 nlayers++;
596 }
597
598 topo_layers[nlayers].type = TOPO_TYPE_PU;
599 topo_layers[nlayers].id_shift = 0;
600 nlayers++;
601
602 #if defined(DEV_ACPI) && MAXMEMDOM > 1
603 if (vm_ndomains > 1) {
604 for (layer = 0; layer < nlayers; ++layer) {
605 for (i = 0; i <= max_apic_id; ++i) {
606 if ((i & ((1 << topo_layers[layer].id_shift) - 1)) == 0)
607 domain = -1;
608 if (!cpu_info[i].cpu_present)
609 continue;
610 d = acpi_pxm_get_cpu_locality(i);
611 if (domain >= 0 && domain != d)
612 break;
613 domain = d;
614 }
615 if (i > max_apic_id)
616 break;
617 }
618 KASSERT(layer < nlayers, ("NUMA domain smaller than PU"));
619 memmove(&topo_layers[layer+1], &topo_layers[layer],
620 sizeof(*topo_layers) * (nlayers - layer));
621 topo_layers[layer].type = TOPO_TYPE_NODE;
622 topo_layers[layer].subtype = CG_SHARE_NONE;
623 nlayers++;
624 }
625 #endif
626
627 topo_init_root(&topo_root);
628 for (i = 0; i <= max_apic_id; ++i) {
629 if (!cpu_info[i].cpu_present)
630 continue;
631
632 parent = &topo_root;
633 for (layer = 0; layer < nlayers; ++layer) {
634 #if defined(DEV_ACPI) && MAXMEMDOM > 1
635 if (topo_layers[layer].type == TOPO_TYPE_NODE) {
636 node_id = acpi_pxm_get_cpu_locality(i);
637 } else
638 #endif
639 node_id = i >> topo_layers[layer].id_shift;
640 parent = topo_add_node_by_hwid(parent, node_id,
641 topo_layers[layer].type,
642 topo_layers[layer].subtype);
643 }
644 }
645
646 parent = &topo_root;
647 for (layer = 0; layer < nlayers; ++layer) {
648 #if defined(DEV_ACPI) && MAXMEMDOM > 1
649 if (topo_layers[layer].type == TOPO_TYPE_NODE)
650 node_id = acpi_pxm_get_cpu_locality(boot_cpu_id);
651 else
652 #endif
653 node_id = boot_cpu_id >> topo_layers[layer].id_shift;
654 node = topo_find_node_by_hwid(parent, node_id,
655 topo_layers[layer].type,
656 topo_layers[layer].subtype);
657 topo_promote_child(node);
658 parent = node;
659 }
660
661 cpu_topo_probed = 1;
662 }
663
664 /*
665 * Assign logical CPU IDs to local APICs.
666 */
667 void
assign_cpu_ids(void)668 assign_cpu_ids(void)
669 {
670 struct topo_node *node;
671 u_int smt_mask;
672 int nhyper;
673
674 smt_mask = (1u << core_id_shift) - 1;
675
676 /*
677 * Assign CPU IDs to local APIC IDs and disable any CPUs
678 * beyond MAXCPU. CPU 0 is always assigned to the BSP.
679 */
680 mp_ncpus = 0;
681 nhyper = 0;
682 TOPO_FOREACH(node, &topo_root) {
683 if (node->type != TOPO_TYPE_PU)
684 continue;
685
686 if ((node->hwid & smt_mask) != (boot_cpu_id & smt_mask))
687 cpu_info[node->hwid].cpu_hyperthread = 1;
688
689 if (resource_disabled("lapic", node->hwid)) {
690 if (node->hwid != boot_cpu_id)
691 cpu_info[node->hwid].cpu_disabled = 1;
692 else
693 printf("Cannot disable BSP, APIC ID = %d\n",
694 node->hwid);
695 }
696
697 if (!hyperthreading_allowed &&
698 cpu_info[node->hwid].cpu_hyperthread)
699 cpu_info[node->hwid].cpu_disabled = 1;
700
701 if (mp_ncpus >= MAXCPU)
702 cpu_info[node->hwid].cpu_disabled = 1;
703
704 if (cpu_info[node->hwid].cpu_disabled) {
705 disabled_cpus++;
706 continue;
707 }
708
709 if (cpu_info[node->hwid].cpu_hyperthread)
710 nhyper++;
711
712 cpu_apic_ids[mp_ncpus] = node->hwid;
713 apic_cpuids[node->hwid] = mp_ncpus;
714 topo_set_pu_id(node, mp_ncpus);
715 mp_ncpus++;
716 }
717
718 KASSERT(mp_maxid >= mp_ncpus - 1,
719 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
720 mp_ncpus));
721
722 mp_ncores = mp_ncpus - nhyper;
723 smp_threads_per_core = mp_ncpus / mp_ncores;
724 }
725
726 /*
727 * Print various information about the SMP system hardware and setup.
728 */
729 void
cpu_mp_announce(void)730 cpu_mp_announce(void)
731 {
732 struct topo_node *node;
733 const char *hyperthread;
734 struct topo_analysis topology;
735
736 printf("FreeBSD/SMP: ");
737 if (topo_analyze(&topo_root, 1, &topology)) {
738 printf("%d package(s)", topology.entities[TOPO_LEVEL_PKG]);
739 if (topology.entities[TOPO_LEVEL_GROUP] > 1)
740 printf(" x %d groups",
741 topology.entities[TOPO_LEVEL_GROUP]);
742 if (topology.entities[TOPO_LEVEL_CACHEGROUP] > 1)
743 printf(" x %d cache groups",
744 topology.entities[TOPO_LEVEL_CACHEGROUP]);
745 if (topology.entities[TOPO_LEVEL_CORE] > 0)
746 printf(" x %d core(s)",
747 topology.entities[TOPO_LEVEL_CORE]);
748 if (topology.entities[TOPO_LEVEL_THREAD] > 1)
749 printf(" x %d hardware threads",
750 topology.entities[TOPO_LEVEL_THREAD]);
751 } else {
752 printf("Non-uniform topology");
753 }
754 printf("\n");
755
756 if (disabled_cpus) {
757 printf("FreeBSD/SMP Online: ");
758 if (topo_analyze(&topo_root, 0, &topology)) {
759 printf("%d package(s)",
760 topology.entities[TOPO_LEVEL_PKG]);
761 if (topology.entities[TOPO_LEVEL_GROUP] > 1)
762 printf(" x %d groups",
763 topology.entities[TOPO_LEVEL_GROUP]);
764 if (topology.entities[TOPO_LEVEL_CACHEGROUP] > 1)
765 printf(" x %d cache groups",
766 topology.entities[TOPO_LEVEL_CACHEGROUP]);
767 if (topology.entities[TOPO_LEVEL_CORE] > 0)
768 printf(" x %d core(s)",
769 topology.entities[TOPO_LEVEL_CORE]);
770 if (topology.entities[TOPO_LEVEL_THREAD] > 1)
771 printf(" x %d hardware threads",
772 topology.entities[TOPO_LEVEL_THREAD]);
773 } else {
774 printf("Non-uniform topology");
775 }
776 printf("\n");
777 }
778
779 if (!bootverbose)
780 return;
781
782 TOPO_FOREACH(node, &topo_root) {
783 switch (node->type) {
784 case TOPO_TYPE_PKG:
785 printf("Package HW ID = %u\n", node->hwid);
786 break;
787 case TOPO_TYPE_CORE:
788 printf("\tCore HW ID = %u\n", node->hwid);
789 break;
790 case TOPO_TYPE_PU:
791 if (cpu_info[node->hwid].cpu_hyperthread)
792 hyperthread = "/HT";
793 else
794 hyperthread = "";
795
796 if (node->subtype == 0)
797 printf("\t\tCPU (AP%s): APIC ID: %u"
798 "(disabled)\n", hyperthread, node->hwid);
799 else if (node->id == 0)
800 printf("\t\tCPU0 (BSP): APIC ID: %u\n",
801 node->hwid);
802 else
803 printf("\t\tCPU%u (AP%s): APIC ID: %u\n",
804 node->id, hyperthread, node->hwid);
805 break;
806 default:
807 /* ignored */
808 break;
809 }
810 }
811 }
812
813 /*
814 * Add a scheduling group, a group of logical processors sharing
815 * a particular cache (and, thus having an affinity), to the scheduling
816 * topology.
817 * This function recursively works on lower level caches.
818 */
819 static void
x86topo_add_sched_group(struct topo_node * root,struct cpu_group * cg_root)820 x86topo_add_sched_group(struct topo_node *root, struct cpu_group *cg_root)
821 {
822 struct topo_node *node;
823 int nchildren;
824 int ncores;
825 int i;
826
827 KASSERT(root->type == TOPO_TYPE_SYSTEM || root->type == TOPO_TYPE_CACHE ||
828 root->type == TOPO_TYPE_NODE || root->type == TOPO_TYPE_GROUP,
829 ("x86topo_add_sched_group: bad type: %u", root->type));
830 CPU_COPY(&root->cpuset, &cg_root->cg_mask);
831 cg_root->cg_count = root->cpu_count;
832 if (root->type == TOPO_TYPE_CACHE)
833 cg_root->cg_level = root->subtype;
834 else
835 cg_root->cg_level = CG_SHARE_NONE;
836 if (root->type == TOPO_TYPE_NODE)
837 cg_root->cg_flags = CG_FLAG_NODE;
838 else
839 cg_root->cg_flags = 0;
840
841 /*
842 * Check how many core nodes we have under the given root node.
843 * If we have multiple logical processors, but not multiple
844 * cores, then those processors must be hardware threads.
845 */
846 ncores = 0;
847 node = root;
848 while (node != NULL) {
849 if (node->type != TOPO_TYPE_CORE) {
850 node = topo_next_node(root, node);
851 continue;
852 }
853
854 ncores++;
855 node = topo_next_nonchild_node(root, node);
856 }
857
858 if (cg_root->cg_level != CG_SHARE_NONE &&
859 root->cpu_count > 1 && ncores < 2)
860 cg_root->cg_flags |= CG_FLAG_SMT;
861
862 /*
863 * Find out how many cache nodes we have under the given root node.
864 * We ignore cache nodes that cover all the same processors as the
865 * root node. Also, we do not descend below found cache nodes.
866 * That is, we count top-level "non-redundant" caches under the root
867 * node.
868 */
869 nchildren = 0;
870 node = root;
871 while (node != NULL) {
872 /*
873 * When some APICs are disabled by tunables, nodes can end up
874 * with an empty cpuset. Nodes with an empty cpuset will be
875 * translated into cpu groups with empty cpusets. smp_topo_fill
876 * will then set cg_first and cg_last to -1. This isn't
877 * correctly handled in all functions. E.g. when
878 * cpu_search_lowest and cpu_search_highest loop through all
879 * cpus, they call CPU_ISSET on cpu -1 which ends up in a
880 * general protection fault.
881 *
882 * We could fix the scheduler to handle empty cpu groups
883 * correctly. Nevertheless, empty cpu groups are causing
884 * overhead for no value. So, it makes more sense to just don't
885 * create them.
886 */
887 if (CPU_EMPTY(&node->cpuset)) {
888 node = topo_next_node(root, node);
889 continue;
890 }
891 if (CPU_CMP(&node->cpuset, &root->cpuset) == 0) {
892 if (node->type == TOPO_TYPE_CACHE &&
893 cg_root->cg_level < node->subtype)
894 cg_root->cg_level = node->subtype;
895 if (node->type == TOPO_TYPE_NODE)
896 cg_root->cg_flags |= CG_FLAG_NODE;
897 node = topo_next_node(root, node);
898 continue;
899 }
900 if (node->type != TOPO_TYPE_GROUP &&
901 node->type != TOPO_TYPE_NODE &&
902 node->type != TOPO_TYPE_CACHE) {
903 node = topo_next_node(root, node);
904 continue;
905 }
906 nchildren++;
907 node = topo_next_nonchild_node(root, node);
908 }
909
910 /*
911 * We are not interested in nodes including only one CPU each.
912 */
913 if (nchildren == root->cpu_count)
914 return;
915
916 /*
917 * We are not interested in nodes without children.
918 */
919 cg_root->cg_children = nchildren;
920 if (nchildren == 0)
921 return;
922
923 cg_root->cg_child = smp_topo_alloc(nchildren);
924
925 /*
926 * Now find again the same cache nodes as above and recursively
927 * build scheduling topologies for them.
928 */
929 node = root;
930 i = 0;
931 while (node != NULL) {
932 if ((node->type != TOPO_TYPE_GROUP &&
933 node->type != TOPO_TYPE_NODE &&
934 node->type != TOPO_TYPE_CACHE) ||
935 CPU_CMP(&node->cpuset, &root->cpuset) == 0 ||
936 CPU_EMPTY(&node->cpuset)) {
937 node = topo_next_node(root, node);
938 continue;
939 }
940 cg_root->cg_child[i].cg_parent = cg_root;
941 x86topo_add_sched_group(node, &cg_root->cg_child[i]);
942 i++;
943 node = topo_next_nonchild_node(root, node);
944 }
945 }
946
947 /*
948 * Build the MI scheduling topology from the discovered hardware topology.
949 */
950 struct cpu_group *
cpu_topo(void)951 cpu_topo(void)
952 {
953 struct cpu_group *cg_root;
954
955 if (mp_ncpus <= 1)
956 return (smp_topo_none());
957
958 cg_root = smp_topo_alloc(1);
959 x86topo_add_sched_group(&topo_root, cg_root);
960 return (cg_root);
961 }
962
963 static void
cpu_alloc(void * dummy __unused)964 cpu_alloc(void *dummy __unused)
965 {
966 /*
967 * Dynamically allocate the arrays that depend on the
968 * maximum APIC ID.
969 */
970 cpu_info = malloc(sizeof(*cpu_info) * (max_apic_id + 1), M_CPUS,
971 M_WAITOK | M_ZERO);
972 apic_cpuids = malloc(sizeof(*apic_cpuids) * (max_apic_id + 1), M_CPUS,
973 M_WAITOK | M_ZERO);
974 }
975 SYSINIT(cpu_alloc, SI_SUB_CPU, SI_ORDER_FIRST, cpu_alloc, NULL);
976
977 /*
978 * Add a logical CPU to the topology.
979 */
980 void
cpu_add(u_int apic_id,char boot_cpu)981 cpu_add(u_int apic_id, char boot_cpu)
982 {
983
984 if (apic_id > max_apic_id)
985 panic("SMP: APIC ID %d too high", apic_id);
986
987 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %u added twice",
988 apic_id));
989 cpu_info[apic_id].cpu_present = 1;
990 if (boot_cpu) {
991 KASSERT(boot_cpu_id == -1,
992 ("CPU %u claims to be BSP, but CPU %u already is", apic_id,
993 boot_cpu_id));
994 boot_cpu_id = apic_id;
995 cpu_info[apic_id].cpu_bsp = 1;
996 }
997 if (bootverbose)
998 printf("SMP: Added CPU %u (%s)\n", apic_id, boot_cpu ? "BSP" :
999 "AP");
1000 }
1001
1002 void
cpu_mp_setmaxid(void)1003 cpu_mp_setmaxid(void)
1004 {
1005
1006 /*
1007 * mp_ncpus and mp_maxid should be already set by calls to cpu_add().
1008 * If there were no calls to cpu_add() assume this is a UP system.
1009 */
1010 if (mp_ncpus == 0)
1011 mp_ncpus = 1;
1012 }
1013
1014 int
cpu_mp_probe(void)1015 cpu_mp_probe(void)
1016 {
1017
1018 /*
1019 * Always record BSP in CPU map so that the mbuf init code works
1020 * correctly.
1021 */
1022 CPU_SETOF(0, &all_cpus);
1023 return (mp_ncpus > 1);
1024 }
1025
1026 /*
1027 * AP CPU's call this to initialize themselves.
1028 */
1029 void
init_secondary_tail(void)1030 init_secondary_tail(void)
1031 {
1032 u_int cpuid;
1033
1034 pmap_activate_boot(vmspace_pmap(proc0.p_vmspace));
1035
1036 /*
1037 * On real hardware, switch to x2apic mode if possible. Do it
1038 * after aps_ready was signalled, to avoid manipulating the
1039 * mode while BSP might still want to send some IPI to us
1040 * (second startup IPI is ignored on modern hardware etc).
1041 */
1042 lapic_xapic_mode();
1043
1044 /* Initialize the PAT MSR. */
1045 pmap_init_pat();
1046
1047 /* set up CPU registers and state */
1048 cpu_setregs();
1049
1050 /* set up SSE/NX */
1051 initializecpu();
1052
1053 /* set up FPU state on the AP */
1054 #ifdef __amd64__
1055 fpuinit();
1056 #else
1057 npxinit(false);
1058 #endif
1059
1060 if (cpu_ops.cpu_init)
1061 cpu_ops.cpu_init();
1062
1063 /* A quick check from sanity claus */
1064 cpuid = PCPU_GET(cpuid);
1065 if (PCPU_GET(apic_id) != lapic_id()) {
1066 printf("SMP: cpuid = %d\n", cpuid);
1067 printf("SMP: actual apic_id = %d\n", lapic_id());
1068 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
1069 panic("cpuid mismatch! boom!!");
1070 }
1071
1072 /* Initialize curthread. */
1073 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
1074 PCPU_SET(curthread, PCPU_GET(idlethread));
1075 schedinit_ap();
1076
1077 mtx_lock_spin(&ap_boot_mtx);
1078
1079 mca_init();
1080
1081 /* Init local apic for irq's */
1082 lapic_setup(1);
1083
1084 /* Set memory range attributes for this CPU to match the BSP */
1085 mem_range_AP_init();
1086
1087 smp_cpus++;
1088
1089 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", cpuid);
1090 if (bootverbose)
1091 printf("SMP: AP CPU #%d Launched!\n", cpuid);
1092 else
1093 printf("%s%d%s", smp_cpus == 2 ? "Launching APs: " : "",
1094 cpuid, smp_cpus == mp_ncpus ? "\n" : " ");
1095
1096 /* Determine if we are a logical CPU. */
1097 if (cpu_info[PCPU_GET(apic_id)].cpu_hyperthread)
1098 CPU_SET(cpuid, &logical_cpus_mask);
1099
1100 if (bootverbose)
1101 lapic_dump("AP");
1102
1103 if (smp_cpus == mp_ncpus) {
1104 /* enable IPI's, tlb shootdown, freezes etc */
1105 atomic_store_rel_int(&smp_started, 1);
1106 }
1107
1108 #ifdef __amd64__
1109 if (pmap_pcid_enabled)
1110 load_cr4(rcr4() | CR4_PCIDE);
1111 load_ds(_udatasel);
1112 load_es(_udatasel);
1113 load_fs(_ufssel);
1114 #endif
1115
1116 mtx_unlock_spin(&ap_boot_mtx);
1117
1118 /* Wait until all the AP's are up. */
1119 while (atomic_load_acq_int(&smp_started) == 0)
1120 ia32_pause();
1121
1122 #ifndef EARLY_AP_STARTUP
1123 /* Start per-CPU event timers. */
1124 cpu_initclocks_ap();
1125 #endif
1126
1127 kcsan_cpu_init(cpuid);
1128
1129 sched_throw(NULL);
1130
1131 panic("scheduler returned us to %s", __func__);
1132 /* NOTREACHED */
1133 }
1134
1135 static void
smp_after_idle_runnable(void * arg __unused)1136 smp_after_idle_runnable(void *arg __unused)
1137 {
1138 int cpu;
1139
1140 if (mp_ncpus == 1)
1141 return;
1142
1143 KASSERT(smp_started != 0, ("%s: SMP not started yet", __func__));
1144
1145 /*
1146 * Wait for all APs to handle an interrupt. After that, we know that
1147 * the APs have entered the scheduler at least once, so the boot stacks
1148 * are safe to free.
1149 */
1150 smp_rendezvous(smp_no_rendezvous_barrier, NULL,
1151 smp_no_rendezvous_barrier, NULL);
1152
1153 for (cpu = 1; cpu < mp_ncpus; cpu++) {
1154 kmem_free((vm_offset_t)bootstacks[cpu], kstack_pages *
1155 PAGE_SIZE);
1156 }
1157 }
1158 SYSINIT(smp_after_idle_runnable, SI_SUB_SMP, SI_ORDER_ANY,
1159 smp_after_idle_runnable, NULL);
1160
1161 /*
1162 * We tell the I/O APIC code about all the CPUs we want to receive
1163 * interrupts. If we don't want certain CPUs to receive IRQs we
1164 * can simply not tell the I/O APIC code about them in this function.
1165 * We also do not tell it about the BSP since it tells itself about
1166 * the BSP internally to work with UP kernels and on UP machines.
1167 */
1168 void
set_interrupt_apic_ids(void)1169 set_interrupt_apic_ids(void)
1170 {
1171 u_int i, apic_id;
1172
1173 for (i = 0; i < MAXCPU; i++) {
1174 apic_id = cpu_apic_ids[i];
1175 if (apic_id == -1)
1176 continue;
1177 if (cpu_info[apic_id].cpu_bsp)
1178 continue;
1179 if (cpu_info[apic_id].cpu_disabled)
1180 continue;
1181
1182 /* Don't let hyperthreads service interrupts. */
1183 if (cpu_info[apic_id].cpu_hyperthread &&
1184 !hyperthreading_intr_allowed)
1185 continue;
1186
1187 /*
1188 * Currently Hyper-V only supports intr on first
1189 * 64 cpus.
1190 */
1191 if (vm_guest == VM_GUEST_HV && i > 63)
1192 continue;
1193
1194 intr_add_cpu(i);
1195 }
1196 }
1197
1198 #ifdef COUNT_XINVLTLB_HITS
1199 u_int xhits_gbl[MAXCPU];
1200 u_int xhits_pg[MAXCPU];
1201 u_int xhits_rng[MAXCPU];
1202 static SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1203 "");
1204 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1205 sizeof(xhits_gbl), "IU", "");
1206 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1207 sizeof(xhits_pg), "IU", "");
1208 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1209 sizeof(xhits_rng), "IU", "");
1210
1211 u_int ipi_global;
1212 u_int ipi_page;
1213 u_int ipi_range;
1214 u_int ipi_range_size;
1215 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1216 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1217 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1218 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1219 0, "");
1220 #endif /* COUNT_XINVLTLB_HITS */
1221
1222 /*
1223 * Init and startup IPI.
1224 */
1225 void
ipi_startup(int apic_id,int vector)1226 ipi_startup(int apic_id, int vector)
1227 {
1228
1229 /*
1230 * This attempts to follow the algorithm described in the
1231 * Intel Multiprocessor Specification v1.4 in section B.4.
1232 * For each IPI, we allow the local APIC ~20us to deliver the
1233 * IPI. If that times out, we panic.
1234 */
1235
1236 /*
1237 * first we do an INIT IPI: this INIT IPI might be run, resetting
1238 * and running the target CPU. OR this INIT IPI might be latched (P5
1239 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1240 * ignored.
1241 */
1242 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_LEVEL |
1243 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1244 lapic_ipi_wait(100);
1245
1246 /* Explicitly deassert the INIT IPI. */
1247 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_LEVEL |
1248 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT,
1249 apic_id);
1250
1251 DELAY(10000); /* wait ~10mS */
1252
1253 /*
1254 * next we do a STARTUP IPI: the previous INIT IPI might still be
1255 * latched, (P5 bug) this 1st STARTUP would then terminate
1256 * immediately, and the previously started INIT IPI would continue. OR
1257 * the previous INIT IPI has already run. and this STARTUP IPI will
1258 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1259 * will run.
1260 */
1261 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1262 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1263 vector, apic_id);
1264 if (!lapic_ipi_wait(100))
1265 panic("Failed to deliver first STARTUP IPI to APIC %d",
1266 apic_id);
1267 DELAY(200); /* wait ~200uS */
1268
1269 /*
1270 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1271 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1272 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1273 * recognized after hardware RESET or INIT IPI.
1274 */
1275 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1276 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1277 vector, apic_id);
1278 if (!lapic_ipi_wait(100))
1279 panic("Failed to deliver second STARTUP IPI to APIC %d",
1280 apic_id);
1281
1282 DELAY(200); /* wait ~200uS */
1283 }
1284
1285 static bool
ipi_bitmap_set(int cpu,u_int ipi)1286 ipi_bitmap_set(int cpu, u_int ipi)
1287 {
1288 u_int bitmap, old, new;
1289 u_int *cpu_bitmap;
1290
1291 bitmap = 1 << ipi;
1292 cpu_bitmap = &cpuid_to_pcpu[cpu]->pc_ipi_bitmap;
1293 old = *cpu_bitmap;
1294 for (;;) {
1295 if ((old & bitmap) != 0)
1296 break;
1297 new = old | bitmap;
1298 if (atomic_fcmpset_int(cpu_bitmap, &old, new))
1299 break;
1300 }
1301 return (old != 0);
1302 }
1303
1304 /*
1305 * Send an IPI to specified CPU handling the bitmap logic.
1306 */
1307 static void
ipi_send_cpu(int cpu,u_int ipi)1308 ipi_send_cpu(int cpu, u_int ipi)
1309 {
1310
1311 KASSERT((u_int)cpu < MAXCPU && cpu_apic_ids[cpu] != -1,
1312 ("IPI to non-existent CPU %d", cpu));
1313
1314 if (IPI_IS_BITMAPED(ipi)) {
1315 if (ipi_bitmap_set(cpu, ipi))
1316 return;
1317 ipi = IPI_BITMAP_VECTOR;
1318 }
1319 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1320 }
1321
1322 void
ipi_bitmap_handler(struct trapframe frame)1323 ipi_bitmap_handler(struct trapframe frame)
1324 {
1325 struct trapframe *oldframe;
1326 struct thread *td;
1327 int cpu = PCPU_GET(cpuid);
1328 u_int ipi_bitmap;
1329
1330 kasan_mark(&frame, sizeof(frame), sizeof(frame), 0);
1331
1332 td = curthread;
1333 ipi_bitmap = atomic_readandclear_int(&cpuid_to_pcpu[cpu]->
1334 pc_ipi_bitmap);
1335
1336 /*
1337 * sched_preempt() must be called to clear the pending preempt
1338 * IPI to enable delivery of further preempts. However, the
1339 * critical section will cause extra scheduler lock thrashing
1340 * when used unconditionally. Only critical_enter() if
1341 * hardclock must also run, which requires the section entry.
1342 */
1343 if (ipi_bitmap & (1 << IPI_HARDCLOCK))
1344 critical_enter();
1345
1346 td->td_intr_nesting_level++;
1347 oldframe = td->td_intr_frame;
1348 td->td_intr_frame = &frame;
1349 #if defined(STACK) || defined(DDB)
1350 if (ipi_bitmap & (1 << IPI_TRACE))
1351 stack_capture_intr();
1352 #endif
1353 if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1354 #ifdef COUNT_IPIS
1355 (*ipi_preempt_counts[cpu])++;
1356 #endif
1357 sched_preempt(td);
1358 }
1359 if (ipi_bitmap & (1 << IPI_AST)) {
1360 #ifdef COUNT_IPIS
1361 (*ipi_ast_counts[cpu])++;
1362 #endif
1363 /* Nothing to do for AST */
1364 }
1365 if (ipi_bitmap & (1 << IPI_HARDCLOCK)) {
1366 #ifdef COUNT_IPIS
1367 (*ipi_hardclock_counts[cpu])++;
1368 #endif
1369 hardclockintr();
1370 }
1371 td->td_intr_frame = oldframe;
1372 td->td_intr_nesting_level--;
1373 if (ipi_bitmap & (1 << IPI_HARDCLOCK))
1374 critical_exit();
1375 }
1376
1377 /*
1378 * send an IPI to a set of cpus.
1379 */
1380 void
ipi_selected(cpuset_t cpus,u_int ipi)1381 ipi_selected(cpuset_t cpus, u_int ipi)
1382 {
1383 int cpu;
1384
1385 /*
1386 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1387 * of help in order to understand what is the source.
1388 * Set the mask of receiving CPUs for this purpose.
1389 */
1390 if (ipi == IPI_STOP_HARD)
1391 CPU_OR_ATOMIC(&ipi_stop_nmi_pending, &cpus);
1392
1393 CPU_FOREACH_ISSET(cpu, &cpus) {
1394 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1395 ipi_send_cpu(cpu, ipi);
1396 }
1397 }
1398
1399 /*
1400 * send an IPI to a specific CPU.
1401 */
1402 void
ipi_cpu(int cpu,u_int ipi)1403 ipi_cpu(int cpu, u_int ipi)
1404 {
1405
1406 /*
1407 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1408 * of help in order to understand what is the source.
1409 * Set the mask of receiving CPUs for this purpose.
1410 */
1411 if (ipi == IPI_STOP_HARD)
1412 CPU_SET_ATOMIC(cpu, &ipi_stop_nmi_pending);
1413
1414 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1415 ipi_send_cpu(cpu, ipi);
1416 }
1417
1418 /*
1419 * send an IPI to all CPUs EXCEPT myself
1420 */
1421 void
ipi_all_but_self(u_int ipi)1422 ipi_all_but_self(u_int ipi)
1423 {
1424 cpuset_t other_cpus;
1425 int cpu, c;
1426
1427 if (mp_ncpus == 1)
1428 return;
1429
1430 /*
1431 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1432 * of help in order to understand what is the source.
1433 * Set the mask of receiving CPUs for this purpose.
1434 */
1435 if (ipi == IPI_STOP_HARD) {
1436 other_cpus = all_cpus;
1437 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
1438 CPU_OR_ATOMIC(&ipi_stop_nmi_pending, &other_cpus);
1439 }
1440
1441 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1442 if (IPI_IS_BITMAPED(ipi)) {
1443 cpu = PCPU_GET(cpuid);
1444 CPU_FOREACH(c) {
1445 if (c != cpu)
1446 ipi_bitmap_set(c, ipi);
1447 }
1448 ipi = IPI_BITMAP_VECTOR;
1449 }
1450 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1451 }
1452
1453 void
ipi_self_from_nmi(u_int vector)1454 ipi_self_from_nmi(u_int vector)
1455 {
1456
1457 lapic_ipi_vectored(vector, APIC_IPI_DEST_SELF);
1458
1459 /* Wait for IPI to finish. */
1460 if (!lapic_ipi_wait(50000)) {
1461 if (KERNEL_PANICKED())
1462 return;
1463 else
1464 panic("APIC: IPI is stuck");
1465 }
1466 }
1467
1468 int
ipi_nmi_handler(void)1469 ipi_nmi_handler(void)
1470 {
1471 u_int cpuid;
1472
1473 /*
1474 * As long as there is not a simple way to know about a NMI's
1475 * source, if the bitmask for the current CPU is present in
1476 * the global pending bitword an IPI_STOP_HARD has been issued
1477 * and should be handled.
1478 */
1479 cpuid = PCPU_GET(cpuid);
1480 if (!CPU_ISSET(cpuid, &ipi_stop_nmi_pending))
1481 return (1);
1482
1483 CPU_CLR_ATOMIC(cpuid, &ipi_stop_nmi_pending);
1484 cpustop_handler();
1485 return (0);
1486 }
1487
1488 int nmi_kdb_lock;
1489
1490 void
nmi_call_kdb_smp(u_int type,struct trapframe * frame)1491 nmi_call_kdb_smp(u_int type, struct trapframe *frame)
1492 {
1493 int cpu;
1494 bool call_post;
1495
1496 cpu = PCPU_GET(cpuid);
1497 if (atomic_cmpset_acq_int(&nmi_kdb_lock, 0, 1)) {
1498 nmi_call_kdb(cpu, type, frame);
1499 call_post = false;
1500 } else {
1501 savectx(&stoppcbs[cpu]);
1502 CPU_SET_ATOMIC(cpu, &stopped_cpus);
1503 while (!atomic_cmpset_acq_int(&nmi_kdb_lock, 0, 1))
1504 ia32_pause();
1505 call_post = true;
1506 }
1507 atomic_store_rel_int(&nmi_kdb_lock, 0);
1508 if (call_post)
1509 cpustop_handler_post(cpu);
1510 }
1511
1512 /*
1513 * Handle an IPI_STOP by saving our current context and spinning (or mwaiting,
1514 * if available) until we are resumed.
1515 */
1516 void
cpustop_handler(void)1517 cpustop_handler(void)
1518 {
1519 struct monitorbuf *mb;
1520 u_int cpu;
1521 bool use_mwait;
1522
1523 cpu = PCPU_GET(cpuid);
1524
1525 savectx(&stoppcbs[cpu]);
1526
1527 use_mwait = (stop_mwait && (cpu_feature2 & CPUID2_MON) != 0 &&
1528 !mwait_cpustop_broken);
1529 if (use_mwait) {
1530 mb = PCPU_PTR(monitorbuf);
1531 atomic_store_int(&mb->stop_state,
1532 MONITOR_STOPSTATE_STOPPED);
1533 }
1534
1535 /* Indicate that we are stopped */
1536 CPU_SET_ATOMIC(cpu, &stopped_cpus);
1537
1538 /* Wait for restart */
1539 while (!CPU_ISSET(cpu, &started_cpus)) {
1540 if (use_mwait) {
1541 cpu_monitor(mb, 0, 0);
1542 if (atomic_load_int(&mb->stop_state) ==
1543 MONITOR_STOPSTATE_STOPPED)
1544 cpu_mwait(0, MWAIT_C1);
1545 continue;
1546 }
1547
1548 ia32_pause();
1549
1550 /*
1551 * Halt non-BSP CPUs on panic -- we're never going to need them
1552 * again, and might as well save power / release resources
1553 * (e.g., overprovisioned VM infrastructure).
1554 */
1555 while (__predict_false(!IS_BSP() && KERNEL_PANICKED()))
1556 halt();
1557 }
1558
1559 cpustop_handler_post(cpu);
1560 }
1561
1562 static void
cpustop_handler_post(u_int cpu)1563 cpustop_handler_post(u_int cpu)
1564 {
1565
1566 CPU_CLR_ATOMIC(cpu, &started_cpus);
1567 CPU_CLR_ATOMIC(cpu, &stopped_cpus);
1568
1569 /*
1570 * We don't broadcast TLB invalidations to other CPUs when they are
1571 * stopped. Hence, we clear the TLB before resuming.
1572 */
1573 invltlb_glob();
1574
1575 #if defined(__amd64__) && (defined(DDB) || defined(GDB))
1576 amd64_db_resume_dbreg();
1577 #endif
1578
1579 if (cpu == 0 && cpustop_restartfunc != NULL) {
1580 cpustop_restartfunc();
1581 cpustop_restartfunc = NULL;
1582 }
1583 }
1584
1585 /*
1586 * Handle an IPI_SUSPEND by saving our current context and spinning until we
1587 * are resumed.
1588 */
1589 void
cpususpend_handler(void)1590 cpususpend_handler(void)
1591 {
1592 u_int cpu;
1593
1594 mtx_assert(&smp_ipi_mtx, MA_NOTOWNED);
1595
1596 cpu = PCPU_GET(cpuid);
1597 if (savectx(&susppcbs[cpu]->sp_pcb)) {
1598 #ifdef __amd64__
1599 fpususpend(susppcbs[cpu]->sp_fpususpend);
1600 #else
1601 npxsuspend(susppcbs[cpu]->sp_fpususpend);
1602 #endif
1603 /*
1604 * suspended_cpus is cleared shortly after each AP is restarted
1605 * by a Startup IPI, so that the BSP can proceed to restarting
1606 * the next AP.
1607 *
1608 * resuming_cpus gets cleared when the AP completes
1609 * initialization after having been released by the BSP.
1610 * resuming_cpus is probably not the best name for the
1611 * variable, because it is actually a set of processors that
1612 * haven't resumed yet and haven't necessarily started resuming.
1613 *
1614 * Note that suspended_cpus is meaningful only for ACPI suspend
1615 * as it's not really used for Xen suspend since the APs are
1616 * automatically restored to the running state and the correct
1617 * context. For the same reason resumectx is never called in
1618 * that case.
1619 */
1620 CPU_SET_ATOMIC(cpu, &suspended_cpus);
1621 CPU_SET_ATOMIC(cpu, &resuming_cpus);
1622
1623 /*
1624 * Invalidate the cache after setting the global status bits.
1625 * The last AP to set its bit may end up being an Owner of the
1626 * corresponding cache line in MOESI protocol. The AP may be
1627 * stopped before the cache line is written to the main memory.
1628 */
1629 wbinvd();
1630 } else {
1631 #ifdef __amd64__
1632 fpuresume(susppcbs[cpu]->sp_fpususpend);
1633 #else
1634 npxresume(susppcbs[cpu]->sp_fpususpend);
1635 #endif
1636 pmap_init_pat();
1637 initializecpu();
1638 PCPU_SET(switchtime, 0);
1639 PCPU_SET(switchticks, ticks);
1640
1641 /* Indicate that we have restarted and restored the context. */
1642 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1643 }
1644
1645 /* Wait for resume directive */
1646 while (!CPU_ISSET(cpu, &toresume_cpus))
1647 ia32_pause();
1648
1649 /* Re-apply microcode updates. */
1650 ucode_reload();
1651
1652 #ifdef __i386__
1653 /* Finish removing the identity mapping of low memory for this AP. */
1654 invltlb_glob();
1655 #endif
1656
1657 if (cpu_ops.cpu_resume)
1658 cpu_ops.cpu_resume();
1659 #ifdef __amd64__
1660 if (vmm_resume_p)
1661 vmm_resume_p();
1662 #endif
1663
1664 /* Resume MCA and local APIC */
1665 lapic_xapic_mode();
1666 mca_resume();
1667 lapic_setup(0);
1668
1669 /* Indicate that we are resumed */
1670 CPU_CLR_ATOMIC(cpu, &resuming_cpus);
1671 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1672 CPU_CLR_ATOMIC(cpu, &toresume_cpus);
1673 }
1674
1675 /*
1676 * Handle an IPI_SWI by waking delayed SWI thread.
1677 */
1678 void
ipi_swi_handler(struct trapframe frame)1679 ipi_swi_handler(struct trapframe frame)
1680 {
1681
1682 intr_event_handle(clk_intr_event, &frame);
1683 }
1684
1685 /*
1686 * This is called once the rest of the system is up and running and we're
1687 * ready to let the AP's out of the pen.
1688 */
1689 static void
release_aps(void * dummy __unused)1690 release_aps(void *dummy __unused)
1691 {
1692
1693 if (mp_ncpus == 1)
1694 return;
1695 atomic_store_rel_int(&aps_ready, 1);
1696 while (smp_started == 0)
1697 ia32_pause();
1698 }
1699 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1700
1701 #ifdef COUNT_IPIS
1702 /*
1703 * Setup interrupt counters for IPI handlers.
1704 */
1705 static void
mp_ipi_intrcnt(void * dummy)1706 mp_ipi_intrcnt(void *dummy)
1707 {
1708 char buf[64];
1709 int i;
1710
1711 CPU_FOREACH(i) {
1712 snprintf(buf, sizeof(buf), "cpu%d:invltlb", i);
1713 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1714 snprintf(buf, sizeof(buf), "cpu%d:invlrng", i);
1715 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1716 snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
1717 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1718 snprintf(buf, sizeof(buf), "cpu%d:invlcache", i);
1719 intrcnt_add(buf, &ipi_invlcache_counts[i]);
1720 snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
1721 intrcnt_add(buf, &ipi_preempt_counts[i]);
1722 snprintf(buf, sizeof(buf), "cpu%d:ast", i);
1723 intrcnt_add(buf, &ipi_ast_counts[i]);
1724 snprintf(buf, sizeof(buf), "cpu%d:rendezvous", i);
1725 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1726 snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
1727 intrcnt_add(buf, &ipi_hardclock_counts[i]);
1728 }
1729 }
1730 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);
1731 #endif
1732