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