]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/x86/mp_x86.c
smp_targeted_tlb_shootdown has to pin the CPU on i386
[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/interrupt.h>
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 /* Holds pending bitmap based IPIs per CPU */
142 volatile u_int cpu_ipi_pending[MAXCPU];
143
144 static void     release_aps(void *dummy);
145 static void     cpustop_handler_post(u_int cpu);
146
147 static int      hyperthreading_allowed = 1;
148 SYSCTL_INT(_machdep, OID_AUTO, hyperthreading_allowed, CTLFLAG_RDTUN,
149         &hyperthreading_allowed, 0, "Use Intel HTT logical CPUs");
150
151 static struct topo_node topo_root;
152
153 static int pkg_id_shift;
154 static int node_id_shift;
155 static int core_id_shift;
156 static int disabled_cpus;
157
158 struct cache_info {
159         int     id_shift;
160         int     present;
161 } static caches[MAX_CACHE_LEVELS];
162
163 unsigned int boot_address;
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             cpu_vendor_id == CPU_VENDOR_HYGON)
514                 topo_probe_amd();
515         else if (cpu_vendor_id == CPU_VENDOR_INTEL)
516                 topo_probe_intel();
517
518         KASSERT(pkg_id_shift >= core_id_shift,
519             ("bug in APIC topology discovery"));
520
521         nlayers = 0;
522         bzero(topo_layers, sizeof(topo_layers));
523
524         topo_layers[nlayers].type = TOPO_TYPE_PKG;
525         topo_layers[nlayers].id_shift = pkg_id_shift;
526         if (bootverbose)
527                 printf("Package ID shift: %u\n", topo_layers[nlayers].id_shift);
528         nlayers++;
529
530         if (pkg_id_shift > node_id_shift && node_id_shift != 0) {
531                 topo_layers[nlayers].type = TOPO_TYPE_GROUP;
532                 topo_layers[nlayers].id_shift = node_id_shift;
533                 if (bootverbose)
534                         printf("Node ID shift: %u\n",
535                             topo_layers[nlayers].id_shift);
536                 nlayers++;
537         }
538
539         /*
540          * Consider all caches to be within a package/chip
541          * and "in front" of all sub-components like
542          * cores and hardware threads.
543          */
544         for (i = MAX_CACHE_LEVELS - 1; i >= 0; --i) {
545                 if (caches[i].present) {
546                         if (node_id_shift != 0)
547                                 KASSERT(caches[i].id_shift <= node_id_shift,
548                                         ("bug in APIC topology discovery"));
549                         KASSERT(caches[i].id_shift <= pkg_id_shift,
550                                 ("bug in APIC topology discovery"));
551                         KASSERT(caches[i].id_shift >= core_id_shift,
552                                 ("bug in APIC topology discovery"));
553
554                         topo_layers[nlayers].type = TOPO_TYPE_CACHE;
555                         topo_layers[nlayers].subtype = i + 1;
556                         topo_layers[nlayers].id_shift = caches[i].id_shift;
557                         if (bootverbose)
558                                 printf("L%u cache ID shift: %u\n",
559                                     topo_layers[nlayers].subtype,
560                                     topo_layers[nlayers].id_shift);
561                         nlayers++;
562                 }
563         }
564
565         if (pkg_id_shift > core_id_shift) {
566                 topo_layers[nlayers].type = TOPO_TYPE_CORE;
567                 topo_layers[nlayers].id_shift = core_id_shift;
568                 if (bootverbose)
569                         printf("Core ID shift: %u\n",
570                             topo_layers[nlayers].id_shift);
571                 nlayers++;
572         }
573
574         topo_layers[nlayers].type = TOPO_TYPE_PU;
575         topo_layers[nlayers].id_shift = 0;
576         nlayers++;
577
578         topo_init_root(&topo_root);
579         for (i = 0; i <= max_apic_id; ++i) {
580                 if (!cpu_info[i].cpu_present)
581                         continue;
582
583                 parent = &topo_root;
584                 for (layer = 0; layer < nlayers; ++layer) {
585                         node_id = i >> topo_layers[layer].id_shift;
586                         parent = topo_add_node_by_hwid(parent, node_id,
587                             topo_layers[layer].type,
588                             topo_layers[layer].subtype);
589                 }
590         }
591
592         parent = &topo_root;
593         for (layer = 0; layer < nlayers; ++layer) {
594                 node_id = boot_cpu_id >> topo_layers[layer].id_shift;
595                 node = topo_find_node_by_hwid(parent, node_id,
596                     topo_layers[layer].type,
597                     topo_layers[layer].subtype);
598                 topo_promote_child(node);
599                 parent = node;
600         }
601
602         cpu_topo_probed = 1;
603 }
604
605 /*
606  * Assign logical CPU IDs to local APICs.
607  */
608 void
609 assign_cpu_ids(void)
610 {
611         struct topo_node *node;
612         u_int smt_mask;
613         int nhyper;
614
615         smt_mask = (1u << core_id_shift) - 1;
616
617         /*
618          * Assign CPU IDs to local APIC IDs and disable any CPUs
619          * beyond MAXCPU.  CPU 0 is always assigned to the BSP.
620          */
621         mp_ncpus = 0;
622         nhyper = 0;
623         TOPO_FOREACH(node, &topo_root) {
624                 if (node->type != TOPO_TYPE_PU)
625                         continue;
626
627                 if ((node->hwid & smt_mask) != (boot_cpu_id & smt_mask))
628                         cpu_info[node->hwid].cpu_hyperthread = 1;
629
630                 if (resource_disabled("lapic", node->hwid)) {
631                         if (node->hwid != boot_cpu_id)
632                                 cpu_info[node->hwid].cpu_disabled = 1;
633                         else
634                                 printf("Cannot disable BSP, APIC ID = %d\n",
635                                     node->hwid);
636                 }
637
638                 if (!hyperthreading_allowed &&
639                     cpu_info[node->hwid].cpu_hyperthread)
640                         cpu_info[node->hwid].cpu_disabled = 1;
641
642                 if (mp_ncpus >= MAXCPU)
643                         cpu_info[node->hwid].cpu_disabled = 1;
644
645                 if (cpu_info[node->hwid].cpu_disabled) {
646                         disabled_cpus++;
647                         continue;
648                 }
649
650                 if (cpu_info[node->hwid].cpu_hyperthread)
651                         nhyper++;
652
653                 cpu_apic_ids[mp_ncpus] = node->hwid;
654                 apic_cpuids[node->hwid] = mp_ncpus;
655                 topo_set_pu_id(node, mp_ncpus);
656                 mp_ncpus++;
657         }
658
659         KASSERT(mp_maxid >= mp_ncpus - 1,
660             ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
661             mp_ncpus));
662
663         mp_ncores = mp_ncpus - nhyper;
664         smp_threads_per_core = mp_ncpus / mp_ncores;
665 }
666
667 /*
668  * Print various information about the SMP system hardware and setup.
669  */
670 void
671 cpu_mp_announce(void)
672 {
673         struct topo_node *node;
674         const char *hyperthread;
675         struct topo_analysis topology;
676
677         printf("FreeBSD/SMP: ");
678         if (topo_analyze(&topo_root, 1, &topology)) {
679                 printf("%d package(s)", topology.entities[TOPO_LEVEL_PKG]);
680                 if (topology.entities[TOPO_LEVEL_GROUP] > 1)
681                         printf(" x %d groups",
682                             topology.entities[TOPO_LEVEL_GROUP]);
683                 if (topology.entities[TOPO_LEVEL_CACHEGROUP] > 1)
684                         printf(" x %d cache groups",
685                             topology.entities[TOPO_LEVEL_CACHEGROUP]);
686                 if (topology.entities[TOPO_LEVEL_CORE] > 0)
687                         printf(" x %d core(s)",
688                             topology.entities[TOPO_LEVEL_CORE]);
689                 if (topology.entities[TOPO_LEVEL_THREAD] > 1)
690                         printf(" x %d hardware threads",
691                             topology.entities[TOPO_LEVEL_THREAD]);
692         } else {
693                 printf("Non-uniform topology");
694         }
695         printf("\n");
696
697         if (disabled_cpus) {
698                 printf("FreeBSD/SMP Online: ");
699                 if (topo_analyze(&topo_root, 0, &topology)) {
700                         printf("%d package(s)",
701                             topology.entities[TOPO_LEVEL_PKG]);
702                         if (topology.entities[TOPO_LEVEL_GROUP] > 1)
703                                 printf(" x %d groups",
704                                     topology.entities[TOPO_LEVEL_GROUP]);
705                         if (topology.entities[TOPO_LEVEL_CACHEGROUP] > 1)
706                                 printf(" x %d cache groups",
707                                     topology.entities[TOPO_LEVEL_CACHEGROUP]);
708                         if (topology.entities[TOPO_LEVEL_CORE] > 0)
709                                 printf(" x %d core(s)",
710                                     topology.entities[TOPO_LEVEL_CORE]);
711                         if (topology.entities[TOPO_LEVEL_THREAD] > 1)
712                                 printf(" x %d hardware threads",
713                                     topology.entities[TOPO_LEVEL_THREAD]);
714                 } else {
715                         printf("Non-uniform topology");
716                 }
717                 printf("\n");
718         }
719
720         if (!bootverbose)
721                 return;
722
723         TOPO_FOREACH(node, &topo_root) {
724                 switch (node->type) {
725                 case TOPO_TYPE_PKG:
726                         printf("Package HW ID = %u\n", node->hwid);
727                         break;
728                 case TOPO_TYPE_CORE:
729                         printf("\tCore HW ID = %u\n", node->hwid);
730                         break;
731                 case TOPO_TYPE_PU:
732                         if (cpu_info[node->hwid].cpu_hyperthread)
733                                 hyperthread = "/HT";
734                         else
735                                 hyperthread = "";
736
737                         if (node->subtype == 0)
738                                 printf("\t\tCPU (AP%s): APIC ID: %u"
739                                     "(disabled)\n", hyperthread, node->hwid);
740                         else if (node->id == 0)
741                                 printf("\t\tCPU0 (BSP): APIC ID: %u\n",
742                                     node->hwid);
743                         else
744                                 printf("\t\tCPU%u (AP%s): APIC ID: %u\n",
745                                     node->id, hyperthread, node->hwid);
746                         break;
747                 default:
748                         /* ignored */
749                         break;
750                 }
751         }
752 }
753
754 /*
755  * Add a scheduling group, a group of logical processors sharing
756  * a particular cache (and, thus having an affinity), to the scheduling
757  * topology.
758  * This function recursively works on lower level caches.
759  */
760 static void
761 x86topo_add_sched_group(struct topo_node *root, struct cpu_group *cg_root)
762 {
763         struct topo_node *node;
764         int nchildren;
765         int ncores;
766         int i;
767
768         KASSERT(root->type == TOPO_TYPE_SYSTEM || root->type == TOPO_TYPE_CACHE ||
769             root->type == TOPO_TYPE_GROUP,
770             ("x86topo_add_sched_group: bad type: %u", root->type));
771         CPU_COPY(&root->cpuset, &cg_root->cg_mask);
772         cg_root->cg_count = root->cpu_count;
773         if (root->type == TOPO_TYPE_SYSTEM)
774                 cg_root->cg_level = CG_SHARE_NONE;
775         else
776                 cg_root->cg_level = root->subtype;
777
778         /*
779          * Check how many core nodes we have under the given root node.
780          * If we have multiple logical processors, but not multiple
781          * cores, then those processors must be hardware threads.
782          */
783         ncores = 0;
784         node = root;
785         while (node != NULL) {
786                 if (node->type != TOPO_TYPE_CORE) {
787                         node = topo_next_node(root, node);
788                         continue;
789                 }
790
791                 ncores++;
792                 node = topo_next_nonchild_node(root, node);
793         }
794
795         if (cg_root->cg_level != CG_SHARE_NONE &&
796             root->cpu_count > 1 && ncores < 2)
797                 cg_root->cg_flags = CG_FLAG_SMT;
798
799         /*
800          * Find out how many cache nodes we have under the given root node.
801          * We ignore cache nodes that cover all the same processors as the
802          * root node.  Also, we do not descend below found cache nodes.
803          * That is, we count top-level "non-redundant" caches under the root
804          * node.
805          */
806         nchildren = 0;
807         node = root;
808         while (node != NULL) {
809                 if ((node->type != TOPO_TYPE_GROUP &&
810                     node->type != TOPO_TYPE_CACHE) ||
811                     (root->type != TOPO_TYPE_SYSTEM &&
812                     CPU_CMP(&node->cpuset, &root->cpuset) == 0)) {
813                         node = topo_next_node(root, node);
814                         continue;
815                 }
816                 nchildren++;
817                 node = topo_next_nonchild_node(root, node);
818         }
819
820         cg_root->cg_child = smp_topo_alloc(nchildren);
821         cg_root->cg_children = nchildren;
822
823         /*
824          * Now find again the same cache nodes as above and recursively
825          * build scheduling topologies for them.
826          */
827         node = root;
828         i = 0;
829         while (node != NULL) {
830                 if ((node->type != TOPO_TYPE_GROUP &&
831                     node->type != TOPO_TYPE_CACHE) ||
832                     (root->type != TOPO_TYPE_SYSTEM &&
833                     CPU_CMP(&node->cpuset, &root->cpuset) == 0)) {
834                         node = topo_next_node(root, node);
835                         continue;
836                 }
837                 cg_root->cg_child[i].cg_parent = cg_root;
838                 x86topo_add_sched_group(node, &cg_root->cg_child[i]);
839                 i++;
840                 node = topo_next_nonchild_node(root, node);
841         }
842 }
843
844 /*
845  * Build the MI scheduling topology from the discovered hardware topology.
846  */
847 struct cpu_group *
848 cpu_topo(void)
849 {
850         struct cpu_group *cg_root;
851
852         if (mp_ncpus <= 1)
853                 return (smp_topo_none());
854
855         cg_root = smp_topo_alloc(1);
856         x86topo_add_sched_group(&topo_root, cg_root);
857         return (cg_root);
858 }
859
860 static void
861 cpu_alloc(void *dummy __unused)
862 {
863         /*
864          * Dynamically allocate the arrays that depend on the
865          * maximum APIC ID.
866          */
867         cpu_info = malloc(sizeof(*cpu_info) * (max_apic_id + 1), M_CPUS,
868             M_WAITOK | M_ZERO);
869         apic_cpuids = malloc(sizeof(*apic_cpuids) * (max_apic_id + 1), M_CPUS,
870             M_WAITOK | M_ZERO);
871 }
872 SYSINIT(cpu_alloc, SI_SUB_CPU, SI_ORDER_FIRST, cpu_alloc, NULL);
873
874 /*
875  * Add a logical CPU to the topology.
876  */
877 void
878 cpu_add(u_int apic_id, char boot_cpu)
879 {
880
881         if (apic_id > max_apic_id) {
882                 panic("SMP: APIC ID %d too high", apic_id);
883                 return;
884         }
885         KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %u added twice",
886             apic_id));
887         cpu_info[apic_id].cpu_present = 1;
888         if (boot_cpu) {
889                 KASSERT(boot_cpu_id == -1,
890                     ("CPU %u claims to be BSP, but CPU %u already is", apic_id,
891                     boot_cpu_id));
892                 boot_cpu_id = apic_id;
893                 cpu_info[apic_id].cpu_bsp = 1;
894         }
895         if (bootverbose)
896                 printf("SMP: Added CPU %u (%s)\n", apic_id, boot_cpu ? "BSP" :
897                     "AP");
898 }
899
900 void
901 cpu_mp_setmaxid(void)
902 {
903
904         /*
905          * mp_ncpus and mp_maxid should be already set by calls to cpu_add().
906          * If there were no calls to cpu_add() assume this is a UP system.
907          */
908         if (mp_ncpus == 0)
909                 mp_ncpus = 1;
910 }
911
912 int
913 cpu_mp_probe(void)
914 {
915
916         /*
917          * Always record BSP in CPU map so that the mbuf init code works
918          * correctly.
919          */
920         CPU_SETOF(0, &all_cpus);
921         return (mp_ncpus > 1);
922 }
923
924 /* Allocate memory for the AP trampoline. */
925 void
926 alloc_ap_trampoline(vm_paddr_t *physmap, unsigned int *physmap_idx)
927 {
928         unsigned int i;
929         bool allocated;
930
931         allocated = false;
932         for (i = *physmap_idx; i <= *physmap_idx; i -= 2) {
933                 /*
934                  * Find a memory region big enough and below the 1MB boundary
935                  * for the trampoline code.
936                  * NB: needs to be page aligned.
937                  */
938                 if (physmap[i] >= MiB(1) ||
939                     (trunc_page(physmap[i + 1]) - round_page(physmap[i])) <
940                     round_page(bootMP_size))
941                         continue;
942
943                 allocated = true;
944                 /*
945                  * Try to steal from the end of the region to mimic previous
946                  * behaviour, else fallback to steal from the start.
947                  */
948                 if (physmap[i + 1] < MiB(1)) {
949                         boot_address = trunc_page(physmap[i + 1]);
950                         if ((physmap[i + 1] - boot_address) < bootMP_size)
951                                 boot_address -= round_page(bootMP_size);
952                         physmap[i + 1] = boot_address;
953                 } else {
954                         boot_address = round_page(physmap[i]);
955                         physmap[i] = boot_address + round_page(bootMP_size);
956                 }
957                 if (physmap[i] == physmap[i + 1] && *physmap_idx != 0) {
958                         memmove(&physmap[i], &physmap[i + 2],
959                             sizeof(*physmap) * (*physmap_idx - i + 2));
960                         *physmap_idx -= 2;
961                 }
962                 break;
963         }
964
965         if (!allocated) {
966                 boot_address = basemem * 1024 - bootMP_size;
967                 if (bootverbose)
968                         printf(
969 "Cannot find enough space for the boot trampoline, placing it at %#x",
970                             boot_address);
971         }
972 }
973
974 /*
975  * AP CPU's call this to initialize themselves.
976  */
977 void
978 init_secondary_tail(void)
979 {
980         u_int cpuid;
981
982         pmap_activate_boot(vmspace_pmap(proc0.p_vmspace));
983
984         /*
985          * On real hardware, switch to x2apic mode if possible.  Do it
986          * after aps_ready was signalled, to avoid manipulating the
987          * mode while BSP might still want to send some IPI to us
988          * (second startup IPI is ignored on modern hardware etc).
989          */
990         lapic_xapic_mode();
991
992         /* Initialize the PAT MSR. */
993         pmap_init_pat();
994
995         /* set up CPU registers and state */
996         cpu_setregs();
997
998         /* set up SSE/NX */
999         initializecpu();
1000
1001         /* set up FPU state on the AP */
1002 #ifdef __amd64__
1003         fpuinit();
1004 #else
1005         npxinit(false);
1006 #endif
1007
1008         if (cpu_ops.cpu_init)
1009                 cpu_ops.cpu_init();
1010
1011         /* A quick check from sanity claus */
1012         cpuid = PCPU_GET(cpuid);
1013         if (PCPU_GET(apic_id) != lapic_id()) {
1014                 printf("SMP: cpuid = %d\n", cpuid);
1015                 printf("SMP: actual apic_id = %d\n", lapic_id());
1016                 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
1017                 panic("cpuid mismatch! boom!!");
1018         }
1019
1020         /* Initialize curthread. */
1021         KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
1022         PCPU_SET(curthread, PCPU_GET(idlethread));
1023
1024         mtx_lock_spin(&ap_boot_mtx);
1025
1026         mca_init();
1027
1028         /* Init local apic for irq's */
1029         lapic_setup(1);
1030
1031         /* Set memory range attributes for this CPU to match the BSP */
1032         mem_range_AP_init();
1033
1034         smp_cpus++;
1035
1036         CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", cpuid);
1037         if (bootverbose)
1038                 printf("SMP: AP CPU #%d Launched!\n", cpuid);
1039         else
1040                 printf("%s%d%s", smp_cpus == 2 ? "Launching APs: " : "",
1041                     cpuid, smp_cpus == mp_ncpus ? "\n" : " ");
1042
1043         /* Determine if we are a logical CPU. */
1044         if (cpu_info[PCPU_GET(apic_id)].cpu_hyperthread)
1045                 CPU_SET(cpuid, &logical_cpus_mask);
1046
1047         if (bootverbose)
1048                 lapic_dump("AP");
1049
1050         if (smp_cpus == mp_ncpus) {
1051                 /* enable IPI's, tlb shootdown, freezes etc */
1052                 atomic_store_rel_int(&smp_started, 1);
1053         }
1054
1055 #ifdef __amd64__
1056         /*
1057          * Enable global pages TLB extension
1058          * This also implicitly flushes the TLB 
1059          */
1060         load_cr4(rcr4() | CR4_PGE);
1061         if (pmap_pcid_enabled)
1062                 load_cr4(rcr4() | CR4_PCIDE);
1063         load_ds(_udatasel);
1064         load_es(_udatasel);
1065         load_fs(_ufssel);
1066 #endif
1067
1068         mtx_unlock_spin(&ap_boot_mtx);
1069
1070         /* Wait until all the AP's are up. */
1071         while (atomic_load_acq_int(&smp_started) == 0)
1072                 ia32_pause();
1073
1074 #ifndef EARLY_AP_STARTUP
1075         /* Start per-CPU event timers. */
1076         cpu_initclocks_ap();
1077 #endif
1078
1079         /*
1080          * Assert that smp_after_idle_runnable condition is reasonable.
1081          */
1082         MPASS(PCPU_GET(curpcb) == NULL);
1083
1084         sched_throw(NULL);
1085
1086         panic("scheduler returned us to %s", __func__);
1087         /* NOTREACHED */
1088 }
1089
1090 static void
1091 smp_after_idle_runnable(void *arg __unused)
1092 {
1093         struct pcpu *pc;
1094         int cpu;
1095
1096         for (cpu = 1; cpu < mp_ncpus; cpu++) {
1097                 pc = pcpu_find(cpu);
1098                 while (atomic_load_ptr(&pc->pc_curpcb) == (uintptr_t)NULL)
1099                         cpu_spinwait();
1100                 kmem_free((vm_offset_t)bootstacks[cpu], kstack_pages *
1101                     PAGE_SIZE);
1102         }
1103 }
1104 SYSINIT(smp_after_idle_runnable, SI_SUB_SMP, SI_ORDER_ANY,
1105     smp_after_idle_runnable, NULL);
1106
1107 /*
1108  * We tell the I/O APIC code about all the CPUs we want to receive
1109  * interrupts.  If we don't want certain CPUs to receive IRQs we
1110  * can simply not tell the I/O APIC code about them in this function.
1111  * We also do not tell it about the BSP since it tells itself about
1112  * the BSP internally to work with UP kernels and on UP machines.
1113  */
1114 void
1115 set_interrupt_apic_ids(void)
1116 {
1117         u_int i, apic_id;
1118
1119         for (i = 0; i < MAXCPU; i++) {
1120                 apic_id = cpu_apic_ids[i];
1121                 if (apic_id == -1)
1122                         continue;
1123                 if (cpu_info[apic_id].cpu_bsp)
1124                         continue;
1125                 if (cpu_info[apic_id].cpu_disabled)
1126                         continue;
1127
1128                 /* Don't let hyperthreads service interrupts. */
1129                 if (cpu_info[apic_id].cpu_hyperthread)
1130                         continue;
1131
1132                 intr_add_cpu(i);
1133         }
1134 }
1135
1136
1137 #ifdef COUNT_XINVLTLB_HITS
1138 u_int xhits_gbl[MAXCPU];
1139 u_int xhits_pg[MAXCPU];
1140 u_int xhits_rng[MAXCPU];
1141 static SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1142 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1143     sizeof(xhits_gbl), "IU", "");
1144 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1145     sizeof(xhits_pg), "IU", "");
1146 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1147     sizeof(xhits_rng), "IU", "");
1148
1149 u_int ipi_global;
1150 u_int ipi_page;
1151 u_int ipi_range;
1152 u_int ipi_range_size;
1153 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1154 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1155 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1156 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1157     0, "");
1158 #endif /* COUNT_XINVLTLB_HITS */
1159
1160 /*
1161  * Init and startup IPI.
1162  */
1163 void
1164 ipi_startup(int apic_id, int vector)
1165 {
1166
1167         /*
1168          * This attempts to follow the algorithm described in the
1169          * Intel Multiprocessor Specification v1.4 in section B.4.
1170          * For each IPI, we allow the local APIC ~20us to deliver the
1171          * IPI.  If that times out, we panic.
1172          */
1173
1174         /*
1175          * first we do an INIT IPI: this INIT IPI might be run, resetting
1176          * and running the target CPU. OR this INIT IPI might be latched (P5
1177          * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1178          * ignored.
1179          */
1180         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_LEVEL |
1181             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1182         lapic_ipi_wait(100);
1183
1184         /* Explicitly deassert the INIT IPI. */
1185         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_LEVEL |
1186             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT,
1187             apic_id);
1188
1189         DELAY(10000);           /* wait ~10mS */
1190
1191         /*
1192          * next we do a STARTUP IPI: the previous INIT IPI might still be
1193          * latched, (P5 bug) this 1st STARTUP would then terminate
1194          * immediately, and the previously started INIT IPI would continue. OR
1195          * the previous INIT IPI has already run. and this STARTUP IPI will
1196          * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1197          * will run.
1198          */
1199         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1200             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1201             vector, apic_id);
1202         if (!lapic_ipi_wait(100))
1203                 panic("Failed to deliver first STARTUP IPI to APIC %d",
1204                     apic_id);
1205         DELAY(200);             /* wait ~200uS */
1206
1207         /*
1208          * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1209          * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1210          * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1211          * recognized after hardware RESET or INIT IPI.
1212          */
1213         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1214             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1215             vector, apic_id);
1216         if (!lapic_ipi_wait(100))
1217                 panic("Failed to deliver second STARTUP IPI to APIC %d",
1218                     apic_id);
1219
1220         DELAY(200);             /* wait ~200uS */
1221 }
1222
1223 /*
1224  * Send an IPI to specified CPU handling the bitmap logic.
1225  */
1226 void
1227 ipi_send_cpu(int cpu, u_int ipi)
1228 {
1229         u_int bitmap, old_pending, new_pending;
1230
1231         KASSERT(cpu_apic_ids[cpu] != -1, ("IPI to non-existent CPU %d", cpu));
1232
1233         if (IPI_IS_BITMAPED(ipi)) {
1234                 bitmap = 1 << ipi;
1235                 ipi = IPI_BITMAP_VECTOR;
1236                 do {
1237                         old_pending = cpu_ipi_pending[cpu];
1238                         new_pending = old_pending | bitmap;
1239                 } while  (!atomic_cmpset_int(&cpu_ipi_pending[cpu],
1240                     old_pending, new_pending)); 
1241                 if (old_pending)
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(&cpu_ipi_pending[cpu]);
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 void
1355 ipi_self_from_nmi(u_int vector)
1356 {
1357
1358         lapic_ipi_vectored(vector, APIC_IPI_DEST_SELF);
1359
1360         /* Wait for IPI to finish. */
1361         if (!lapic_ipi_wait(50000)) {
1362                 if (panicstr != NULL)
1363                         return;
1364                 else
1365                         panic("APIC: IPI is stuck");
1366         }
1367 }
1368
1369 int
1370 ipi_nmi_handler(void)
1371 {
1372         u_int cpuid;
1373
1374         /*
1375          * As long as there is not a simple way to know about a NMI's
1376          * source, if the bitmask for the current CPU is present in
1377          * the global pending bitword an IPI_STOP_HARD has been issued
1378          * and should be handled.
1379          */
1380         cpuid = PCPU_GET(cpuid);
1381         if (!CPU_ISSET(cpuid, &ipi_stop_nmi_pending))
1382                 return (1);
1383
1384         CPU_CLR_ATOMIC(cpuid, &ipi_stop_nmi_pending);
1385         cpustop_handler();
1386         return (0);
1387 }
1388
1389 int nmi_kdb_lock;
1390
1391 void
1392 nmi_call_kdb_smp(u_int type, struct trapframe *frame)
1393 {
1394         int cpu;
1395         bool call_post;
1396
1397         cpu = PCPU_GET(cpuid);
1398         if (atomic_cmpset_acq_int(&nmi_kdb_lock, 0, 1)) {
1399                 nmi_call_kdb(cpu, type, frame);
1400                 call_post = false;
1401         } else {
1402                 savectx(&stoppcbs[cpu]);
1403                 CPU_SET_ATOMIC(cpu, &stopped_cpus);
1404                 while (!atomic_cmpset_acq_int(&nmi_kdb_lock, 0, 1))
1405                         ia32_pause();
1406                 call_post = true;
1407         }
1408         atomic_store_rel_int(&nmi_kdb_lock, 0);
1409         if (call_post)
1410                 cpustop_handler_post(cpu);
1411 }
1412
1413 /*
1414  * Handle an IPI_STOP by saving our current context and spinning until we
1415  * are resumed.
1416  */
1417 void
1418 cpustop_handler(void)
1419 {
1420         u_int cpu;
1421
1422         cpu = PCPU_GET(cpuid);
1423
1424         savectx(&stoppcbs[cpu]);
1425
1426         /* Indicate that we are stopped */
1427         CPU_SET_ATOMIC(cpu, &stopped_cpus);
1428
1429         /* Wait for restart */
1430         while (!CPU_ISSET(cpu, &started_cpus))
1431             ia32_pause();
1432
1433         cpustop_handler_post(cpu);
1434 }
1435
1436 static void
1437 cpustop_handler_post(u_int cpu)
1438 {
1439
1440         CPU_CLR_ATOMIC(cpu, &started_cpus);
1441         CPU_CLR_ATOMIC(cpu, &stopped_cpus);
1442
1443         /*
1444          * We don't broadcast TLB invalidations to other CPUs when they are
1445          * stopped. Hence, we clear the TLB before resuming.
1446          */
1447         invltlb_glob();
1448
1449 #if defined(__amd64__) && defined(DDB)
1450         amd64_db_resume_dbreg();
1451 #endif
1452
1453         if (cpu == 0 && cpustop_restartfunc != NULL) {
1454                 cpustop_restartfunc();
1455                 cpustop_restartfunc = NULL;
1456         }
1457 }
1458
1459 /*
1460  * Handle an IPI_SUSPEND by saving our current context and spinning until we
1461  * are resumed.
1462  */
1463 void
1464 cpususpend_handler(void)
1465 {
1466         u_int cpu;
1467
1468         mtx_assert(&smp_ipi_mtx, MA_NOTOWNED);
1469
1470         cpu = PCPU_GET(cpuid);
1471         if (savectx(&susppcbs[cpu]->sp_pcb)) {
1472 #ifdef __amd64__
1473                 fpususpend(susppcbs[cpu]->sp_fpususpend);
1474 #else
1475                 npxsuspend(susppcbs[cpu]->sp_fpususpend);
1476 #endif
1477                 /*
1478                  * suspended_cpus is cleared shortly after each AP is restarted
1479                  * by a Startup IPI, so that the BSP can proceed to restarting
1480                  * the next AP.
1481                  *
1482                  * resuming_cpus gets cleared when the AP completes
1483                  * initialization after having been released by the BSP.
1484                  * resuming_cpus is probably not the best name for the
1485                  * variable, because it is actually a set of processors that
1486                  * haven't resumed yet and haven't necessarily started resuming.
1487                  *
1488                  * Note that suspended_cpus is meaningful only for ACPI suspend
1489                  * as it's not really used for Xen suspend since the APs are
1490                  * automatically restored to the running state and the correct
1491                  * context.  For the same reason resumectx is never called in
1492                  * that case.
1493                  */
1494                 CPU_SET_ATOMIC(cpu, &suspended_cpus);
1495                 CPU_SET_ATOMIC(cpu, &resuming_cpus);
1496
1497                 /*
1498                  * Invalidate the cache after setting the global status bits.
1499                  * The last AP to set its bit may end up being an Owner of the
1500                  * corresponding cache line in MOESI protocol.  The AP may be
1501                  * stopped before the cache line is written to the main memory.
1502                  */
1503                 wbinvd();
1504         } else {
1505 #ifdef __amd64__
1506                 fpuresume(susppcbs[cpu]->sp_fpususpend);
1507 #else
1508                 npxresume(susppcbs[cpu]->sp_fpususpend);
1509 #endif
1510                 pmap_init_pat();
1511                 initializecpu();
1512                 PCPU_SET(switchtime, 0);
1513                 PCPU_SET(switchticks, ticks);
1514
1515                 /* Indicate that we have restarted and restored the context. */
1516                 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1517         }
1518
1519         /* Wait for resume directive */
1520         while (!CPU_ISSET(cpu, &toresume_cpus))
1521                 ia32_pause();
1522
1523         /* Re-apply microcode updates. */
1524         ucode_reload();
1525
1526 #ifdef __i386__
1527         /* Finish removing the identity mapping of low memory for this AP. */
1528         invltlb_glob();
1529 #endif
1530
1531         if (cpu_ops.cpu_resume)
1532                 cpu_ops.cpu_resume();
1533 #ifdef __amd64__
1534         if (vmm_resume_p)
1535                 vmm_resume_p();
1536 #endif
1537
1538         /* Resume MCA and local APIC */
1539         lapic_xapic_mode();
1540         mca_resume();
1541         lapic_setup(0);
1542
1543         /* Indicate that we are resumed */
1544         CPU_CLR_ATOMIC(cpu, &resuming_cpus);
1545         CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1546         CPU_CLR_ATOMIC(cpu, &toresume_cpus);
1547 }
1548
1549
1550 void
1551 invlcache_handler(void)
1552 {
1553         uint32_t generation;
1554
1555 #ifdef COUNT_IPIS
1556         (*ipi_invlcache_counts[PCPU_GET(cpuid)])++;
1557 #endif /* COUNT_IPIS */
1558
1559         /*
1560          * Reading the generation here allows greater parallelism
1561          * since wbinvd is a serializing instruction.  Without the
1562          * temporary, we'd wait for wbinvd to complete, then the read
1563          * would execute, then the dependent write, which must then
1564          * complete before return from interrupt.
1565          */
1566         generation = smp_tlb_generation;
1567         wbinvd();
1568         PCPU_SET(smp_tlb_done, generation);
1569 }
1570
1571 /*
1572  * Handle an IPI_SWI by waking delayed SWI thread.
1573  */
1574 void
1575 ipi_swi_handler(struct trapframe frame)
1576 {
1577
1578         intr_event_handle(clk_intr_event, &frame);
1579 }
1580
1581 /*
1582  * This is called once the rest of the system is up and running and we're
1583  * ready to let the AP's out of the pen.
1584  */
1585 static void
1586 release_aps(void *dummy __unused)
1587 {
1588
1589         if (mp_ncpus == 1) 
1590                 return;
1591         atomic_store_rel_int(&aps_ready, 1);
1592         while (smp_started == 0)
1593                 ia32_pause();
1594 }
1595 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1596
1597 #ifdef COUNT_IPIS
1598 /*
1599  * Setup interrupt counters for IPI handlers.
1600  */
1601 static void
1602 mp_ipi_intrcnt(void *dummy)
1603 {
1604         char buf[64];
1605         int i;
1606
1607         CPU_FOREACH(i) {
1608                 snprintf(buf, sizeof(buf), "cpu%d:invltlb", i);
1609                 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1610                 snprintf(buf, sizeof(buf), "cpu%d:invlrng", i);
1611                 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1612                 snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
1613                 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1614                 snprintf(buf, sizeof(buf), "cpu%d:invlcache", i);
1615                 intrcnt_add(buf, &ipi_invlcache_counts[i]);
1616                 snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
1617                 intrcnt_add(buf, &ipi_preempt_counts[i]);
1618                 snprintf(buf, sizeof(buf), "cpu%d:ast", i);
1619                 intrcnt_add(buf, &ipi_ast_counts[i]);
1620                 snprintf(buf, sizeof(buf), "cpu%d:rendezvous", i);
1621                 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1622                 snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
1623                 intrcnt_add(buf, &ipi_hardclock_counts[i]);
1624         }               
1625 }
1626 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);
1627 #endif
1628
1629 /*
1630  * Flush the TLB on other CPU's
1631  */
1632
1633 /* Variables needed for SMP tlb shootdown. */
1634 vm_offset_t smp_tlb_addr1, smp_tlb_addr2;
1635 pmap_t smp_tlb_pmap;
1636 volatile uint32_t smp_tlb_generation;
1637
1638 #ifdef __amd64__
1639 #define read_eflags() read_rflags()
1640 #endif
1641
1642 /*
1643  * Used by pmap to request invalidation of TLB or cache on local and
1644  * remote processors.  Mask provides the set of remote CPUs which are
1645  * to be signalled with the IPI specified by vector.  The curcpu_cb
1646  * callback is invoked on the calling CPU in a critical section while
1647  * waiting for remote CPUs to complete the operation.
1648  *
1649  * The callback function is called unconditionally on the caller's
1650  * underlying processor, even when this processor is not set in the
1651  * mask.  So, the callback function must be prepared to handle such
1652  * spurious invocations.
1653  *
1654  * This function must be called with the thread pinned, and it unpins on
1655  * completion.
1656  */
1657 static void
1658 smp_targeted_tlb_shootdown(cpuset_t mask, u_int vector, pmap_t pmap,
1659     vm_offset_t addr1, vm_offset_t addr2, smp_invl_cb_t curcpu_cb)
1660 {
1661         cpuset_t other_cpus;
1662         volatile uint32_t *p_cpudone;
1663         uint32_t generation;
1664         int cpu;
1665
1666 #ifdef __i386__
1667         sched_pin();
1668 #endif
1669
1670         /*
1671          * It is not necessary to signal other CPUs while booting or
1672          * when in the debugger.
1673          */
1674         if (kdb_active || panicstr != NULL || !smp_started)
1675                 goto local_cb;
1676
1677         KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
1678
1679         /*
1680          * Check for other cpus.  Return if none.
1681          */
1682         if (CPU_ISFULLSET(&mask)) {
1683                 if (mp_ncpus <= 1)
1684                         goto local_cb;
1685         } else {
1686                 CPU_CLR(PCPU_GET(cpuid), &mask);
1687                 if (CPU_EMPTY(&mask))
1688                         goto local_cb;
1689         }
1690
1691         if (!(read_eflags() & PSL_I))
1692                 panic("%s: interrupts disabled", __func__);
1693         mtx_lock_spin(&smp_ipi_mtx);
1694         smp_tlb_addr1 = addr1;
1695         smp_tlb_addr2 = addr2;
1696         smp_tlb_pmap = pmap;
1697         generation = ++smp_tlb_generation;
1698         if (CPU_ISFULLSET(&mask)) {
1699                 ipi_all_but_self(vector);
1700                 other_cpus = all_cpus;
1701                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
1702         } else {
1703                 other_cpus = mask;
1704                 while ((cpu = CPU_FFS(&mask)) != 0) {
1705                         cpu--;
1706                         CPU_CLR(cpu, &mask);
1707                         CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__,
1708                             cpu, vector);
1709                         ipi_send_cpu(cpu, vector);
1710                 }
1711         }
1712         curcpu_cb(pmap, addr1, addr2);
1713         while ((cpu = CPU_FFS(&other_cpus)) != 0) {
1714                 cpu--;
1715                 CPU_CLR(cpu, &other_cpus);
1716                 p_cpudone = &cpuid_to_pcpu[cpu]->pc_smp_tlb_done;
1717                 while (*p_cpudone != generation)
1718                         ia32_pause();
1719         }
1720
1721         /*
1722          * Unpin before unlocking smp_ipi_mtx.  If the thread owes
1723          * preemption, this allows scheduler to select thread on any
1724          * CPU from its cpuset.
1725          */
1726         sched_unpin();
1727         mtx_unlock_spin(&smp_ipi_mtx);
1728
1729         return;
1730
1731 local_cb:
1732         critical_enter();
1733         curcpu_cb(pmap, addr1, addr2);
1734         sched_unpin();
1735         critical_exit();
1736 }
1737
1738 void
1739 smp_masked_invltlb(cpuset_t mask, pmap_t pmap, smp_invl_cb_t curcpu_cb)
1740 {
1741
1742         smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, pmap, 0, 0, curcpu_cb);
1743 #ifdef COUNT_XINVLTLB_HITS
1744         ipi_global++;
1745 #endif
1746 }
1747
1748 void
1749 smp_masked_invlpg(cpuset_t mask, vm_offset_t addr, pmap_t pmap,
1750     smp_invl_cb_t curcpu_cb)
1751 {
1752
1753         smp_targeted_tlb_shootdown(mask, IPI_INVLPG, pmap, addr, 0, curcpu_cb);
1754 #ifdef COUNT_XINVLTLB_HITS
1755         ipi_page++;
1756 #endif
1757 }
1758
1759 void
1760 smp_masked_invlpg_range(cpuset_t mask, vm_offset_t addr1, vm_offset_t addr2,
1761     pmap_t pmap, smp_invl_cb_t curcpu_cb)
1762 {
1763
1764         smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, pmap, addr1, addr2,
1765             curcpu_cb);
1766 #ifdef COUNT_XINVLTLB_HITS
1767         ipi_range++;
1768         ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1769 #endif
1770 }
1771
1772 void
1773 smp_cache_flush(smp_invl_cb_t curcpu_cb)
1774 {
1775
1776         smp_targeted_tlb_shootdown(all_cpus, IPI_INVLCACHE, NULL, 0, 0,
1777             curcpu_cb);
1778 }
1779
1780 /*
1781  * Handlers for TLB related IPIs
1782  */
1783 void
1784 invltlb_handler(void)
1785 {
1786         uint32_t generation;
1787   
1788 #ifdef COUNT_XINVLTLB_HITS
1789         xhits_gbl[PCPU_GET(cpuid)]++;
1790 #endif /* COUNT_XINVLTLB_HITS */
1791 #ifdef COUNT_IPIS
1792         (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
1793 #endif /* COUNT_IPIS */
1794
1795         /*
1796          * Reading the generation here allows greater parallelism
1797          * since invalidating the TLB is a serializing operation.
1798          */
1799         generation = smp_tlb_generation;
1800         if (smp_tlb_pmap == kernel_pmap)
1801                 invltlb_glob();
1802 #ifdef __amd64__
1803         else
1804                 invltlb();
1805 #endif
1806         PCPU_SET(smp_tlb_done, generation);
1807 }
1808
1809 void
1810 invlpg_handler(void)
1811 {
1812         uint32_t generation;
1813
1814 #ifdef COUNT_XINVLTLB_HITS
1815         xhits_pg[PCPU_GET(cpuid)]++;
1816 #endif /* COUNT_XINVLTLB_HITS */
1817 #ifdef COUNT_IPIS
1818         (*ipi_invlpg_counts[PCPU_GET(cpuid)])++;
1819 #endif /* COUNT_IPIS */
1820
1821         generation = smp_tlb_generation;        /* Overlap with serialization */
1822 #ifdef __i386__
1823         if (smp_tlb_pmap == kernel_pmap)
1824 #endif
1825                 invlpg(smp_tlb_addr1);
1826         PCPU_SET(smp_tlb_done, generation);
1827 }
1828
1829 void
1830 invlrng_handler(void)
1831 {
1832         vm_offset_t addr, addr2;
1833         uint32_t generation;
1834
1835 #ifdef COUNT_XINVLTLB_HITS
1836         xhits_rng[PCPU_GET(cpuid)]++;
1837 #endif /* COUNT_XINVLTLB_HITS */
1838 #ifdef COUNT_IPIS
1839         (*ipi_invlrng_counts[PCPU_GET(cpuid)])++;
1840 #endif /* COUNT_IPIS */
1841
1842         addr = smp_tlb_addr1;
1843         addr2 = smp_tlb_addr2;
1844         generation = smp_tlb_generation;        /* Overlap with serialization */
1845 #ifdef __i386__
1846         if (smp_tlb_pmap == kernel_pmap)
1847 #endif
1848                 do {
1849                         invlpg(addr);
1850                         addr += PAGE_SIZE;
1851                 } while (addr < addr2);
1852
1853         PCPU_SET(smp_tlb_done, generation);
1854 }