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