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