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