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