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