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