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