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