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