]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/mp_machdep.c
MFH: r278968-r280640
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / mp_machdep.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 #include "opt_cpu.h"
31 #include "opt_ddb.h"
32 #include "opt_kstack_pages.h"
33 #include "opt_sched.h"
34 #include "opt_smp.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/bus.h>
39 #include <sys/cpuset.h>
40 #ifdef GPROF 
41 #include <sys/gmon.h>
42 #endif
43 #include <sys/kernel.h>
44 #include <sys/ktr.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/memrange.h>
48 #include <sys/mutex.h>
49 #include <sys/pcpu.h>
50 #include <sys/proc.h>
51 #include <sys/sched.h>
52 #include <sys/smp.h>
53 #include <sys/sysctl.h>
54
55 #include <vm/vm.h>
56 #include <vm/vm_param.h>
57 #include <vm/pmap.h>
58 #include <vm/vm_kern.h>
59 #include <vm/vm_extern.h>
60
61 #include <x86/apicreg.h>
62 #include <machine/clock.h>
63 #include <machine/cputypes.h>
64 #include <machine/cpufunc.h>
65 #include <x86/mca.h>
66 #include <machine/md_var.h>
67 #include <machine/pcb.h>
68 #include <machine/psl.h>
69 #include <machine/smp.h>
70 #include <machine/specialreg.h>
71 #include <machine/tss.h>
72 #include <machine/cpu.h>
73 #include <x86/init.h>
74
75 #define WARMBOOT_TARGET         0
76 #define WARMBOOT_OFF            (KERNBASE + 0x0467)
77 #define WARMBOOT_SEG            (KERNBASE + 0x0469)
78
79 #define CMOS_REG                (0x70)
80 #define CMOS_DATA               (0x71)
81 #define BIOS_RESET              (0x0f)
82 #define BIOS_WARM               (0x0a)
83
84 /* lock region used by kernel profiling */
85 int     mcount_lock;
86
87 int     mp_naps;                /* # of Applications processors */
88 int     boot_cpu_id = -1;       /* designated BSP */
89
90 extern  struct pcpu __pcpu[];
91
92 /* AP uses this during bootstrap.  Do not staticize.  */
93 char *bootSTK;
94 int bootAP;
95
96 /* Free these after use */
97 void *bootstacks[MAXCPU];
98
99 /* Temporary variables for init_secondary()  */
100 char *doublefault_stack;
101 char *nmi_stack;
102 void *dpcpu;
103
104 struct pcb stoppcbs[MAXCPU];
105 struct susppcb **susppcbs;
106
107 /* Variables needed for SMP tlb shootdown. */
108 vm_offset_t smp_tlb_addr2;
109 struct invpcid_descr smp_tlb_invpcid;
110 volatile int smp_tlb_wait;
111 uint64_t pcid_cr3;
112 pmap_t smp_tlb_pmap;
113 extern int invpcid_works;
114
115 #ifdef COUNT_IPIS
116 /* Interrupt counts. */
117 static u_long *ipi_preempt_counts[MAXCPU];
118 static u_long *ipi_ast_counts[MAXCPU];
119 u_long *ipi_invltlb_counts[MAXCPU];
120 u_long *ipi_invlrng_counts[MAXCPU];
121 u_long *ipi_invlpg_counts[MAXCPU];
122 u_long *ipi_invlcache_counts[MAXCPU];
123 u_long *ipi_rendezvous_counts[MAXCPU];
124 static u_long *ipi_hardclock_counts[MAXCPU];
125 #endif
126
127 /* Default cpu_ops implementation. */
128 struct cpu_ops cpu_ops;
129
130 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
131
132 extern int pmap_pcid_enabled;
133
134 /*
135  * Local data and functions.
136  */
137
138 static volatile cpuset_t ipi_nmi_pending;
139
140 /* used to hold the AP's until we are ready to release them */
141 struct mtx ap_boot_mtx;
142
143 /* Set to 1 once we're ready to let the APs out of the pen. */
144 static volatile int aps_ready = 0;
145
146 /*
147  * Store data from cpu_add() until later in the boot when we actually setup
148  * the APs.
149  */
150 struct cpu_info {
151         int     cpu_present:1;
152         int     cpu_bsp:1;
153         int     cpu_disabled:1;
154         int     cpu_hyperthread:1;
155 } static cpu_info[MAX_APIC_ID + 1];
156 int cpu_apic_ids[MAXCPU];
157 int apic_cpuids[MAX_APIC_ID + 1];
158
159 /* Holds pending bitmap based IPIs per CPU */
160 volatile u_int cpu_ipi_pending[MAXCPU];
161
162 static u_int boot_address;
163 static int cpu_logical;                 /* logical cpus per core */
164 static int cpu_cores;                   /* cores per package */
165
166 static void     assign_cpu_ids(void);
167 static void     set_interrupt_apic_ids(void);
168 static int      start_ap(int apic_id);
169 static void     release_aps(void *dummy);
170
171 static u_int    hyperthreading_cpus;    /* logical cpus sharing L1 cache */
172 static int      hyperthreading_allowed = 1;
173 static u_int    bootMP_size;
174
175 static void
176 mem_range_AP_init(void)
177 {
178         if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
179                 mem_range_softc.mr_op->initAP(&mem_range_softc);
180 }
181
182 static void
183 topo_probe_amd(void)
184 {
185         int core_id_bits;
186         int id;
187
188         /* AMD processors do not support HTT. */
189         cpu_logical = 1;
190
191         if ((amd_feature2 & AMDID2_CMP) == 0) {
192                 cpu_cores = 1;
193                 return;
194         }
195
196         core_id_bits = (cpu_procinfo2 & AMDID_COREID_SIZE) >>
197             AMDID_COREID_SIZE_SHIFT;
198         if (core_id_bits == 0) {
199                 cpu_cores = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
200                 return;
201         }
202
203         /* Fam 10h and newer should get here. */
204         for (id = 0; id <= MAX_APIC_ID; id++) {
205                 /* Check logical CPU availability. */
206                 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
207                         continue;
208                 /* Check if logical CPU has the same package ID. */
209                 if ((id >> core_id_bits) != (boot_cpu_id >> core_id_bits))
210                         continue;
211                 cpu_cores++;
212         }
213 }
214
215 /*
216  * Round up to the next power of two, if necessary, and then
217  * take log2.
218  * Returns -1 if argument is zero.
219  */
220 static __inline int
221 mask_width(u_int x)
222 {
223
224         return (fls(x << (1 - powerof2(x))) - 1);
225 }
226
227 static void
228 topo_probe_0x4(void)
229 {
230         u_int p[4];
231         int pkg_id_bits;
232         int core_id_bits;
233         int max_cores;
234         int max_logical;
235         int id;
236
237         /* Both zero and one here mean one logical processor per package. */
238         max_logical = (cpu_feature & CPUID_HTT) != 0 ?
239             (cpu_procinfo & CPUID_HTT_CORES) >> 16 : 1;
240         if (max_logical <= 1)
241                 return;
242
243         /*
244          * Because of uniformity assumption we examine only
245          * those logical processors that belong to the same
246          * package as BSP.  Further, we count number of
247          * logical processors that belong to the same core
248          * as BSP thus deducing number of threads per core.
249          */
250         if (cpu_high >= 0x4) {
251                 cpuid_count(0x04, 0, p);
252                 max_cores = ((p[0] >> 26) & 0x3f) + 1;
253         } else
254                 max_cores = 1;
255         core_id_bits = mask_width(max_logical/max_cores);
256         if (core_id_bits < 0)
257                 return;
258         pkg_id_bits = core_id_bits + mask_width(max_cores);
259
260         for (id = 0; id <= MAX_APIC_ID; id++) {
261                 /* Check logical CPU availability. */
262                 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
263                         continue;
264                 /* Check if logical CPU has the same package ID. */
265                 if ((id >> pkg_id_bits) != (boot_cpu_id >> pkg_id_bits))
266                         continue;
267                 cpu_cores++;
268                 /* Check if logical CPU has the same package and core IDs. */
269                 if ((id >> core_id_bits) == (boot_cpu_id >> core_id_bits))
270                         cpu_logical++;
271         }
272
273         KASSERT(cpu_cores >= 1 && cpu_logical >= 1,
274             ("topo_probe_0x4 couldn't find BSP"));
275
276         cpu_cores /= cpu_logical;
277         hyperthreading_cpus = cpu_logical;
278 }
279
280 static void
281 topo_probe_0xb(void)
282 {
283         u_int p[4];
284         int bits;
285         int cnt;
286         int i;
287         int logical;
288         int type;
289         int x;
290
291         /* We only support three levels for now. */
292         for (i = 0; i < 3; i++) {
293                 cpuid_count(0x0b, i, p);
294
295                 /* Fall back if CPU leaf 11 doesn't really exist. */
296                 if (i == 0 && p[1] == 0) {
297                         topo_probe_0x4();
298                         return;
299                 }
300
301                 bits = p[0] & 0x1f;
302                 logical = p[1] &= 0xffff;
303                 type = (p[2] >> 8) & 0xff;
304                 if (type == 0 || logical == 0)
305                         break;
306                 /*
307                  * Because of uniformity assumption we examine only
308                  * those logical processors that belong to the same
309                  * package as BSP.
310                  */
311                 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
312                         if (!cpu_info[x].cpu_present ||
313                             cpu_info[x].cpu_disabled)
314                                 continue;
315                         if (x >> bits == boot_cpu_id >> bits)
316                                 cnt++;
317                 }
318                 if (type == CPUID_TYPE_SMT)
319                         cpu_logical = cnt;
320                 else if (type == CPUID_TYPE_CORE)
321                         cpu_cores = cnt;
322         }
323         if (cpu_logical == 0)
324                 cpu_logical = 1;
325         cpu_cores /= cpu_logical;
326 }
327
328 /*
329  * Both topology discovery code and code that consumes topology
330  * information assume top-down uniformity of the topology.
331  * That is, all physical packages must be identical and each
332  * core in a package must have the same number of threads.
333  * Topology information is queried only on BSP, on which this
334  * code runs and for which it can query CPUID information.
335  * Then topology is extrapolated on all packages using the
336  * uniformity assumption.
337  */
338 static void
339 topo_probe(void)
340 {
341         static int cpu_topo_probed = 0;
342
343         if (cpu_topo_probed)
344                 return;
345
346         CPU_ZERO(&logical_cpus_mask);
347         if (mp_ncpus <= 1)
348                 cpu_cores = cpu_logical = 1;
349         else if (cpu_vendor_id == CPU_VENDOR_AMD)
350                 topo_probe_amd();
351         else if (cpu_vendor_id == CPU_VENDOR_INTEL) {
352                 /*
353                  * See Intel(R) 64 Architecture Processor
354                  * Topology Enumeration article for details.
355                  *
356                  * Note that 0x1 <= cpu_high < 4 case should be
357                  * compatible with topo_probe_0x4() logic when
358                  * CPUID.1:EBX[23:16] > 0 (cpu_cores will be 1)
359                  * or it should trigger the fallback otherwise.
360                  */
361                 if (cpu_high >= 0xb)
362                         topo_probe_0xb();
363                 else if (cpu_high >= 0x1)
364                         topo_probe_0x4();
365         }
366
367         /*
368          * Fallback: assume each logical CPU is in separate
369          * physical package.  That is, no multi-core, no SMT.
370          */
371         if (cpu_cores == 0 || cpu_logical == 0)
372                 cpu_cores = cpu_logical = 1;
373         cpu_topo_probed = 1;
374 }
375
376 struct cpu_group *
377 cpu_topo(void)
378 {
379         int cg_flags;
380
381         /*
382          * Determine whether any threading flags are
383          * necessry.
384          */
385         topo_probe();
386         if (cpu_logical > 1 && hyperthreading_cpus)
387                 cg_flags = CG_FLAG_HTT;
388         else if (cpu_logical > 1)
389                 cg_flags = CG_FLAG_SMT;
390         else
391                 cg_flags = 0;
392         if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
393                 printf("WARNING: Non-uniform processors.\n");
394                 printf("WARNING: Using suboptimal topology.\n");
395                 return (smp_topo_none());
396         }
397         /*
398          * No multi-core or hyper-threaded.
399          */
400         if (cpu_logical * cpu_cores == 1)
401                 return (smp_topo_none());
402         /*
403          * Only HTT no multi-core.
404          */
405         if (cpu_logical > 1 && cpu_cores == 1)
406                 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
407         /*
408          * Only multi-core no HTT.
409          */
410         if (cpu_cores > 1 && cpu_logical == 1)
411                 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
412         /*
413          * Both HTT and multi-core.
414          */
415         return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
416             CG_SHARE_L1, cpu_logical, cg_flags));
417 }
418
419 /*
420  * Calculate usable address in base memory for AP trampoline code.
421  */
422 u_int
423 mp_bootaddress(u_int basemem)
424 {
425
426         bootMP_size = mptramp_end - mptramp_start;
427         boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
428         if (((basemem * 1024) - boot_address) < bootMP_size)
429                 boot_address -= PAGE_SIZE;      /* not enough, lower by 4k */
430         /* 3 levels of page table pages */
431         mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
432
433         return mptramp_pagetables;
434 }
435
436 void
437 cpu_add(u_int apic_id, char boot_cpu)
438 {
439
440         if (apic_id > MAX_APIC_ID) {
441                 panic("SMP: APIC ID %d too high", apic_id);
442                 return;
443         }
444         KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
445             apic_id));
446         cpu_info[apic_id].cpu_present = 1;
447         if (boot_cpu) {
448                 KASSERT(boot_cpu_id == -1,
449                     ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
450                     boot_cpu_id));
451                 boot_cpu_id = apic_id;
452                 cpu_info[apic_id].cpu_bsp = 1;
453         }
454         if (mp_ncpus < MAXCPU) {
455                 mp_ncpus++;
456                 mp_maxid = mp_ncpus - 1;
457         }
458         if (bootverbose)
459                 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
460                     "AP");
461 }
462
463 void
464 cpu_mp_setmaxid(void)
465 {
466
467         /*
468          * mp_maxid should be already set by calls to cpu_add().
469          * Just sanity check its value here.
470          */
471         if (mp_ncpus == 0)
472                 KASSERT(mp_maxid == 0,
473                     ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
474         else if (mp_ncpus == 1)
475                 mp_maxid = 0;
476         else
477                 KASSERT(mp_maxid >= mp_ncpus - 1,
478                     ("%s: counters out of sync: max %d, count %d", __func__,
479                         mp_maxid, mp_ncpus));
480 }
481
482 int
483 cpu_mp_probe(void)
484 {
485
486         /*
487          * Always record BSP in CPU map so that the mbuf init code works
488          * correctly.
489          */
490         CPU_SETOF(0, &all_cpus);
491         if (mp_ncpus == 0) {
492                 /*
493                  * No CPUs were found, so this must be a UP system.  Setup
494                  * the variables to represent a system with a single CPU
495                  * with an id of 0.
496                  */
497                 mp_ncpus = 1;
498                 return (0);
499         }
500
501         /* At least one CPU was found. */
502         if (mp_ncpus == 1) {
503                 /*
504                  * One CPU was found, so this must be a UP system with
505                  * an I/O APIC.
506                  */
507                 mp_maxid = 0;
508                 return (0);
509         }
510
511         /* At least two CPUs were found. */
512         return (1);
513 }
514
515 /*
516  * Initialize the IPI handlers and start up the AP's.
517  */
518 void
519 cpu_mp_start(void)
520 {
521         int i;
522
523         /* Initialize the logical ID to APIC ID table. */
524         for (i = 0; i < MAXCPU; i++) {
525                 cpu_apic_ids[i] = -1;
526                 cpu_ipi_pending[i] = 0;
527         }
528
529         /* Install an inter-CPU IPI for TLB invalidation */
530         if (pmap_pcid_enabled) {
531                 setidt(IPI_INVLTLB, IDTVEC(invltlb_pcid), SDT_SYSIGT,
532                     SEL_KPL, 0);
533                 setidt(IPI_INVLPG, IDTVEC(invlpg_pcid), SDT_SYSIGT,
534                     SEL_KPL, 0);
535         } else {
536                 setidt(IPI_INVLTLB, IDTVEC(invltlb), SDT_SYSIGT, SEL_KPL, 0);
537                 setidt(IPI_INVLPG, IDTVEC(invlpg), SDT_SYSIGT, SEL_KPL, 0);
538         }
539         setidt(IPI_INVLRNG, IDTVEC(invlrng), SDT_SYSIGT, SEL_KPL, 0);
540
541         /* Install an inter-CPU IPI for cache invalidation. */
542         setidt(IPI_INVLCACHE, IDTVEC(invlcache), SDT_SYSIGT, SEL_KPL, 0);
543
544         /* Install an inter-CPU IPI for all-CPU rendezvous */
545         setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
546
547         /* Install generic inter-CPU IPI handler */
548         setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
549                SDT_SYSIGT, SEL_KPL, 0);
550
551         /* Install an inter-CPU IPI for CPU stop/restart */
552         setidt(IPI_STOP, IDTVEC(cpustop), SDT_SYSIGT, SEL_KPL, 0);
553
554         /* Install an inter-CPU IPI for CPU suspend/resume */
555         setidt(IPI_SUSPEND, IDTVEC(cpususpend), SDT_SYSIGT, SEL_KPL, 0);
556
557         /* Set boot_cpu_id if needed. */
558         if (boot_cpu_id == -1) {
559                 boot_cpu_id = PCPU_GET(apic_id);
560                 cpu_info[boot_cpu_id].cpu_bsp = 1;
561         } else
562                 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
563                     ("BSP's APIC ID doesn't match boot_cpu_id"));
564
565         /* Probe logical/physical core configuration. */
566         topo_probe();
567
568         assign_cpu_ids();
569
570         /* Start each Application Processor */
571         init_ops.start_all_aps();
572
573         set_interrupt_apic_ids();
574 }
575
576
577 /*
578  * Print various information about the SMP system hardware and setup.
579  */
580 void
581 cpu_mp_announce(void)
582 {
583         const char *hyperthread;
584         int i;
585
586         printf("FreeBSD/SMP: %d package(s) x %d core(s)",
587             mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
588         if (hyperthreading_cpus > 1)
589             printf(" x %d HTT threads", cpu_logical);
590         else if (cpu_logical > 1)
591             printf(" x %d SMT threads", cpu_logical);
592         printf("\n");
593
594         /* List active CPUs first. */
595         printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
596         for (i = 1; i < mp_ncpus; i++) {
597                 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
598                         hyperthread = "/HT";
599                 else
600                         hyperthread = "";
601                 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
602                     cpu_apic_ids[i]);
603         }
604
605         /* List disabled CPUs last. */
606         for (i = 0; i <= MAX_APIC_ID; i++) {
607                 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
608                         continue;
609                 if (cpu_info[i].cpu_hyperthread)
610                         hyperthread = "/HT";
611                 else
612                         hyperthread = "";
613                 printf("  cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
614                     i);
615         }
616 }
617
618 /*
619  * AP CPU's call this to initialize themselves.
620  */
621 void
622 init_secondary(void)
623 {
624         struct pcpu *pc;
625         struct nmi_pcpu *np;
626         u_int64_t msr, cr0;
627         u_int cpuid;
628         int cpu, gsel_tss, x;
629         struct region_descriptor ap_gdt;
630
631         /* Set by the startup code for us to use */
632         cpu = bootAP;
633
634         /* Init tss */
635         common_tss[cpu] = common_tss[0];
636         common_tss[cpu].tss_rsp0 = 0;   /* not used until after switch */
637         common_tss[cpu].tss_iobase = sizeof(struct amd64tss) +
638             IOPERM_BITMAP_SIZE;
639         common_tss[cpu].tss_ist1 = (long)&doublefault_stack[PAGE_SIZE];
640
641         /* The NMI stack runs on IST2. */
642         np = ((struct nmi_pcpu *) &nmi_stack[PAGE_SIZE]) - 1;
643         common_tss[cpu].tss_ist2 = (long) np;
644
645         /* Prepare private GDT */
646         gdt_segs[GPROC0_SEL].ssd_base = (long) &common_tss[cpu];
647         for (x = 0; x < NGDT; x++) {
648                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1) &&
649                     x != GUSERLDT_SEL && x != (GUSERLDT_SEL + 1))
650                         ssdtosd(&gdt_segs[x], &gdt[NGDT * cpu + x]);
651         }
652         ssdtosyssd(&gdt_segs[GPROC0_SEL],
653             (struct system_segment_descriptor *)&gdt[NGDT * cpu + GPROC0_SEL]);
654         ap_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
655         ap_gdt.rd_base =  (long) &gdt[NGDT * cpu];
656         lgdt(&ap_gdt);                  /* does magic intra-segment return */
657
658         /* Get per-cpu data */
659         pc = &__pcpu[cpu];
660
661         /* prime data page for it to use */
662         pcpu_init(pc, cpu, sizeof(struct pcpu));
663         dpcpu_init(dpcpu, cpu);
664         pc->pc_apic_id = cpu_apic_ids[cpu];
665         pc->pc_prvspace = pc;
666         pc->pc_curthread = 0;
667         pc->pc_tssp = &common_tss[cpu];
668         pc->pc_commontssp = &common_tss[cpu];
669         pc->pc_rsp0 = 0;
670         pc->pc_tss = (struct system_segment_descriptor *)&gdt[NGDT * cpu +
671             GPROC0_SEL];
672         pc->pc_fs32p = &gdt[NGDT * cpu + GUFS32_SEL];
673         pc->pc_gs32p = &gdt[NGDT * cpu + GUGS32_SEL];
674         pc->pc_ldt = (struct system_segment_descriptor *)&gdt[NGDT * cpu +
675             GUSERLDT_SEL];
676
677         /* Save the per-cpu pointer for use by the NMI handler. */
678         np->np_pcpu = (register_t) pc;
679
680         wrmsr(MSR_FSBASE, 0);           /* User value */
681         wrmsr(MSR_GSBASE, (u_int64_t)pc);
682         wrmsr(MSR_KGSBASE, (u_int64_t)pc);      /* XXX User value while we're in the kernel */
683
684         lidt(&r_idt);
685
686         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
687         ltr(gsel_tss);
688
689         /*
690          * Set to a known state:
691          * Set by mpboot.s: CR0_PG, CR0_PE
692          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
693          */
694         cr0 = rcr0();
695         cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
696         load_cr0(cr0);
697
698         /* Set up the fast syscall stuff */
699         msr = rdmsr(MSR_EFER) | EFER_SCE;
700         wrmsr(MSR_EFER, msr);
701         wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
702         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
703         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
704               ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
705         wrmsr(MSR_STAR, msr);
706         wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
707
708         /* signal our startup to the BSP. */
709         mp_naps++;
710
711         /* Spin until the BSP releases the AP's. */
712         while (!aps_ready)
713                 ia32_pause();
714
715         /*
716          * On real hardware, switch to x2apic mode if possible.  Do it
717          * after aps_ready was signalled, to avoid manipulating the
718          * mode while BSP might still want to send some IPI to us
719          * (second startup IPI is ignored on modern hardware etc).
720          */
721         lapic_xapic_mode();
722
723         /* Initialize the PAT MSR. */
724         pmap_init_pat();
725
726         /* set up CPU registers and state */
727         cpu_setregs();
728
729         /* set up SSE/NX */
730         initializecpu();
731
732         /* set up FPU state on the AP */
733         fpuinit();
734
735         if (cpu_ops.cpu_init)
736                 cpu_ops.cpu_init();
737
738         /* A quick check from sanity claus */
739         cpuid = PCPU_GET(cpuid);
740         if (PCPU_GET(apic_id) != lapic_id()) {
741                 printf("SMP: cpuid = %d\n", cpuid);
742                 printf("SMP: actual apic_id = %d\n", lapic_id());
743                 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
744                 panic("cpuid mismatch! boom!!");
745         }
746
747         /* Initialize curthread. */
748         KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
749         PCPU_SET(curthread, PCPU_GET(idlethread));
750
751         mca_init();
752
753         mtx_lock_spin(&ap_boot_mtx);
754
755         /* Init local apic for irq's */
756         lapic_setup(1);
757
758         /* Set memory range attributes for this CPU to match the BSP */
759         mem_range_AP_init();
760
761         smp_cpus++;
762
763         CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", cpuid);
764         printf("SMP: AP CPU #%d Launched!\n", cpuid);
765
766         /* Determine if we are a logical CPU. */
767         /* XXX Calculation depends on cpu_logical being a power of 2, e.g. 2 */
768         if (cpu_logical > 1 && PCPU_GET(apic_id) % cpu_logical != 0)
769                 CPU_SET(cpuid, &logical_cpus_mask);
770
771         if (bootverbose)
772                 lapic_dump("AP");
773
774         if (smp_cpus == mp_ncpus) {
775                 /* enable IPI's, tlb shootdown, freezes etc */
776                 atomic_store_rel_int(&smp_started, 1);
777         }
778
779         /*
780          * Enable global pages TLB extension
781          * This also implicitly flushes the TLB 
782          */
783
784         load_cr4(rcr4() | CR4_PGE);
785         if (pmap_pcid_enabled)
786                 load_cr4(rcr4() | CR4_PCIDE);
787         load_ds(_udatasel);
788         load_es(_udatasel);
789         load_fs(_ufssel);
790         mtx_unlock_spin(&ap_boot_mtx);
791
792         /* Wait until all the AP's are up. */
793         while (smp_started == 0)
794                 ia32_pause();
795
796         /* Start per-CPU event timers. */
797         cpu_initclocks_ap();
798
799         sched_throw(NULL);
800
801         panic("scheduler returned us to %s", __func__);
802         /* NOTREACHED */
803 }
804
805 /*******************************************************************
806  * local functions and data
807  */
808
809 /*
810  * We tell the I/O APIC code about all the CPUs we want to receive
811  * interrupts.  If we don't want certain CPUs to receive IRQs we
812  * can simply not tell the I/O APIC code about them in this function.
813  * We also do not tell it about the BSP since it tells itself about
814  * the BSP internally to work with UP kernels and on UP machines.
815  */
816 static void
817 set_interrupt_apic_ids(void)
818 {
819         u_int i, apic_id;
820
821         for (i = 0; i < MAXCPU; i++) {
822                 apic_id = cpu_apic_ids[i];
823                 if (apic_id == -1)
824                         continue;
825                 if (cpu_info[apic_id].cpu_bsp)
826                         continue;
827                 if (cpu_info[apic_id].cpu_disabled)
828                         continue;
829
830                 /* Don't let hyperthreads service interrupts. */
831                 if (cpu_logical > 1 &&
832                     apic_id % cpu_logical != 0)
833                         continue;
834
835                 intr_add_cpu(i);
836         }
837 }
838
839 /*
840  * Assign logical CPU IDs to local APICs.
841  */
842 static void
843 assign_cpu_ids(void)
844 {
845         u_int i;
846
847         TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
848             &hyperthreading_allowed);
849
850         /* Check for explicitly disabled CPUs. */
851         for (i = 0; i <= MAX_APIC_ID; i++) {
852                 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
853                         continue;
854
855                 if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
856                         cpu_info[i].cpu_hyperthread = 1;
857
858                         /*
859                          * Don't use HT CPU if it has been disabled by a
860                          * tunable.
861                          */
862                         if (hyperthreading_allowed == 0) {
863                                 cpu_info[i].cpu_disabled = 1;
864                                 continue;
865                         }
866                 }
867
868                 /* Don't use this CPU if it has been disabled by a tunable. */
869                 if (resource_disabled("lapic", i)) {
870                         cpu_info[i].cpu_disabled = 1;
871                         continue;
872                 }
873         }
874
875         if (hyperthreading_allowed == 0 && hyperthreading_cpus > 1) {
876                 hyperthreading_cpus = 0;
877                 cpu_logical = 1;
878         }
879
880         /*
881          * Assign CPU IDs to local APIC IDs and disable any CPUs
882          * beyond MAXCPU.  CPU 0 is always assigned to the BSP.
883          *
884          * To minimize confusion for userland, we attempt to number
885          * CPUs such that all threads and cores in a package are
886          * grouped together.  For now we assume that the BSP is always
887          * the first thread in a package and just start adding APs
888          * starting with the BSP's APIC ID.
889          */
890         mp_ncpus = 1;
891         cpu_apic_ids[0] = boot_cpu_id;
892         apic_cpuids[boot_cpu_id] = 0;
893         for (i = boot_cpu_id + 1; i != boot_cpu_id;
894              i == MAX_APIC_ID ? i = 0 : i++) {
895                 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
896                     cpu_info[i].cpu_disabled)
897                         continue;
898
899                 if (mp_ncpus < MAXCPU) {
900                         cpu_apic_ids[mp_ncpus] = i;
901                         apic_cpuids[i] = mp_ncpus;
902                         mp_ncpus++;
903                 } else
904                         cpu_info[i].cpu_disabled = 1;
905         }
906         KASSERT(mp_maxid >= mp_ncpus - 1,
907             ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
908             mp_ncpus));         
909 }
910
911 /*
912  * start each AP in our list
913  */
914 int
915 native_start_all_aps(void)
916 {
917         vm_offset_t va = boot_address + KERNBASE;
918         u_int64_t *pt4, *pt3, *pt2;
919         u_int32_t mpbioswarmvec;
920         int apic_id, cpu, i;
921         u_char mpbiosreason;
922
923         mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
924
925         /* install the AP 1st level boot code */
926         pmap_kenter(va, boot_address);
927         pmap_invalidate_page(kernel_pmap, va);
928         bcopy(mptramp_start, (void *)va, bootMP_size);
929
930         /* Locate the page tables, they'll be below the trampoline */
931         pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
932         pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
933         pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
934
935         /* Create the initial 1GB replicated page tables */
936         for (i = 0; i < 512; i++) {
937                 /* Each slot of the level 4 pages points to the same level 3 page */
938                 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
939                 pt4[i] |= PG_V | PG_RW | PG_U;
940
941                 /* Each slot of the level 3 pages points to the same level 2 page */
942                 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
943                 pt3[i] |= PG_V | PG_RW | PG_U;
944
945                 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
946                 pt2[i] = i * (2 * 1024 * 1024);
947                 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
948         }
949
950         /* save the current value of the warm-start vector */
951         mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
952         outb(CMOS_REG, BIOS_RESET);
953         mpbiosreason = inb(CMOS_DATA);
954
955         /* setup a vector to our boot code */
956         *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
957         *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
958         outb(CMOS_REG, BIOS_RESET);
959         outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
960
961         /* start each AP */
962         for (cpu = 1; cpu < mp_ncpus; cpu++) {
963                 apic_id = cpu_apic_ids[cpu];
964
965                 /* allocate and set up an idle stack data page */
966                 bootstacks[cpu] = (void *)kmem_malloc(kernel_arena,
967                     KSTACK_PAGES * PAGE_SIZE, M_WAITOK | M_ZERO);
968                 doublefault_stack = (char *)kmem_malloc(kernel_arena,
969                     PAGE_SIZE, M_WAITOK | M_ZERO);
970                 nmi_stack = (char *)kmem_malloc(kernel_arena, PAGE_SIZE,
971                     M_WAITOK | M_ZERO);
972                 dpcpu = (void *)kmem_malloc(kernel_arena, DPCPU_SIZE,
973                     M_WAITOK | M_ZERO);
974
975                 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 8;
976                 bootAP = cpu;
977
978                 /* attempt to start the Application Processor */
979                 if (!start_ap(apic_id)) {
980                         /* restore the warmstart vector */
981                         *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
982                         panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
983                 }
984
985                 CPU_SET(cpu, &all_cpus);        /* record AP in CPU map */
986         }
987
988         /* restore the warmstart vector */
989         *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
990
991         outb(CMOS_REG, BIOS_RESET);
992         outb(CMOS_DATA, mpbiosreason);
993
994         /* number of APs actually started */
995         return mp_naps;
996 }
997
998
999 /*
1000  * This function starts the AP (application processor) identified
1001  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
1002  * to accomplish this.  This is necessary because of the nuances
1003  * of the different hardware we might encounter.  It isn't pretty,
1004  * but it seems to work.
1005  */
1006 static int
1007 start_ap(int apic_id)
1008 {
1009         int vector, ms;
1010         int cpus;
1011
1012         /* calculate the vector */
1013         vector = (boot_address >> 12) & 0xff;
1014
1015         /* used as a watchpoint to signal AP startup */
1016         cpus = mp_naps;
1017
1018         ipi_startup(apic_id, vector);
1019
1020         /* Wait up to 5 seconds for it to start. */
1021         for (ms = 0; ms < 5000; ms++) {
1022                 if (mp_naps > cpus)
1023                         return 1;       /* return SUCCESS */
1024                 DELAY(1000);
1025         }
1026         return 0;               /* return FAILURE */
1027 }
1028
1029 #ifdef COUNT_XINVLTLB_HITS
1030 u_int xhits_gbl[MAXCPU];
1031 u_int xhits_pg[MAXCPU];
1032 u_int xhits_rng[MAXCPU];
1033 static SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1034 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1035     sizeof(xhits_gbl), "IU", "");
1036 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1037     sizeof(xhits_pg), "IU", "");
1038 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1039     sizeof(xhits_rng), "IU", "");
1040
1041 u_int ipi_global;
1042 u_int ipi_page;
1043 u_int ipi_range;
1044 u_int ipi_range_size;
1045 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1046 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1047 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1048 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW,
1049     &ipi_range_size, 0, "");
1050
1051 u_int ipi_masked_global;
1052 u_int ipi_masked_page;
1053 u_int ipi_masked_range;
1054 u_int ipi_masked_range_size;
1055 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
1056     &ipi_masked_global, 0, "");
1057 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
1058     &ipi_masked_page, 0, "");
1059 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
1060     &ipi_masked_range, 0, "");
1061 SYSCTL_UINT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
1062     &ipi_masked_range_size, 0, "");
1063 #endif /* COUNT_XINVLTLB_HITS */
1064
1065 /*
1066  * Init and startup IPI.
1067  */
1068 void
1069 ipi_startup(int apic_id, int vector)
1070 {
1071
1072         /*
1073          * This attempts to follow the algorithm described in the
1074          * Intel Multiprocessor Specification v1.4 in section B.4.
1075          * For each IPI, we allow the local APIC ~20us to deliver the
1076          * IPI.  If that times out, we panic.
1077          */
1078
1079         /*
1080          * first we do an INIT IPI: this INIT IPI might be run, resetting
1081          * and running the target CPU. OR this INIT IPI might be latched (P5
1082          * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1083          * ignored.
1084          */
1085         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_LEVEL |
1086             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1087         lapic_ipi_wait(20);
1088
1089         /* Explicitly deassert the INIT IPI. */
1090         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_LEVEL |
1091             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT,
1092             apic_id);
1093
1094         DELAY(10000);           /* wait ~10mS */
1095
1096         /*
1097          * next we do a STARTUP IPI: the previous INIT IPI might still be
1098          * latched, (P5 bug) this 1st STARTUP would then terminate
1099          * immediately, and the previously started INIT IPI would continue. OR
1100          * the previous INIT IPI has already run. and this STARTUP IPI will
1101          * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1102          * will run.
1103          */
1104         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1105             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1106             vector, apic_id);
1107         if (!lapic_ipi_wait(20))
1108                 panic("Failed to deliver first STARTUP IPI to APIC %d",
1109                     apic_id);
1110         DELAY(200);             /* wait ~200uS */
1111
1112         /*
1113          * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1114          * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1115          * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1116          * recognized after hardware RESET or INIT IPI.
1117          */
1118         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1119             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1120             vector, apic_id);
1121         if (!lapic_ipi_wait(20))
1122                 panic("Failed to deliver second STARTUP IPI to APIC %d",
1123                     apic_id);
1124
1125         DELAY(200);             /* wait ~200uS */
1126 }
1127
1128 /*
1129  * Send an IPI to specified CPU handling the bitmap logic.
1130  */
1131 static void
1132 ipi_send_cpu(int cpu, u_int ipi)
1133 {
1134         u_int bitmap, old_pending, new_pending;
1135
1136         KASSERT(cpu_apic_ids[cpu] != -1, ("IPI to non-existent CPU %d", cpu));
1137
1138         if (IPI_IS_BITMAPED(ipi)) {
1139                 bitmap = 1 << ipi;
1140                 ipi = IPI_BITMAP_VECTOR;
1141                 do {
1142                         old_pending = cpu_ipi_pending[cpu];
1143                         new_pending = old_pending | bitmap;
1144                 } while  (!atomic_cmpset_int(&cpu_ipi_pending[cpu],
1145                     old_pending, new_pending)); 
1146                 if (old_pending)
1147                         return;
1148         }
1149         lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1150 }
1151
1152 /*
1153  * Flush the TLB on all other CPU's
1154  */
1155 static void
1156 smp_tlb_shootdown(u_int vector, pmap_t pmap, vm_offset_t addr1,
1157     vm_offset_t addr2)
1158 {
1159         u_int ncpu;
1160
1161         ncpu = mp_ncpus - 1;    /* does not shootdown self */
1162         if (ncpu < 1)
1163                 return;         /* no other cpus */
1164         if (!(read_rflags() & PSL_I))
1165                 panic("%s: interrupts disabled", __func__);
1166         mtx_lock_spin(&smp_ipi_mtx);
1167         smp_tlb_invpcid.addr = addr1;
1168         if (pmap == NULL) {
1169                 smp_tlb_invpcid.pcid = 0;
1170         } else {
1171                 smp_tlb_invpcid.pcid = pmap->pm_pcid;
1172                 pcid_cr3 = pmap->pm_cr3;
1173         }
1174         smp_tlb_addr2 = addr2;
1175         smp_tlb_pmap = pmap;
1176         atomic_store_rel_int(&smp_tlb_wait, 0);
1177         ipi_all_but_self(vector);
1178         while (smp_tlb_wait < ncpu)
1179                 ia32_pause();
1180         mtx_unlock_spin(&smp_ipi_mtx);
1181 }
1182
1183 static void
1184 smp_targeted_tlb_shootdown(cpuset_t mask, u_int vector, pmap_t pmap,
1185     vm_offset_t addr1, vm_offset_t addr2)
1186 {
1187         int cpu, ncpu, othercpus;
1188
1189         othercpus = mp_ncpus - 1;
1190         if (CPU_ISFULLSET(&mask)) {
1191                 if (othercpus < 1)
1192                         return;
1193         } else {
1194                 CPU_CLR(PCPU_GET(cpuid), &mask);
1195                 if (CPU_EMPTY(&mask))
1196                         return;
1197         }
1198         if (!(read_rflags() & PSL_I))
1199                 panic("%s: interrupts disabled", __func__);
1200         mtx_lock_spin(&smp_ipi_mtx);
1201         smp_tlb_invpcid.addr = addr1;
1202         if (pmap == NULL) {
1203                 smp_tlb_invpcid.pcid = 0;
1204         } else {
1205                 smp_tlb_invpcid.pcid = pmap->pm_pcid;
1206                 pcid_cr3 = pmap->pm_cr3;
1207         }
1208         smp_tlb_addr2 = addr2;
1209         smp_tlb_pmap = pmap;
1210         atomic_store_rel_int(&smp_tlb_wait, 0);
1211         if (CPU_ISFULLSET(&mask)) {
1212                 ncpu = othercpus;
1213                 ipi_all_but_self(vector);
1214         } else {
1215                 ncpu = 0;
1216                 while ((cpu = CPU_FFS(&mask)) != 0) {
1217                         cpu--;
1218                         CPU_CLR(cpu, &mask);
1219                         CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__,
1220                             cpu, vector);
1221                         ipi_send_cpu(cpu, vector);
1222                         ncpu++;
1223                 }
1224         }
1225         while (smp_tlb_wait < ncpu)
1226                 ia32_pause();
1227         mtx_unlock_spin(&smp_ipi_mtx);
1228 }
1229
1230 void
1231 smp_cache_flush(void)
1232 {
1233
1234         if (smp_started)
1235                 smp_tlb_shootdown(IPI_INVLCACHE, NULL, 0, 0);
1236 }
1237
1238 void
1239 smp_invltlb(pmap_t pmap)
1240 {
1241
1242         if (smp_started) {
1243                 smp_tlb_shootdown(IPI_INVLTLB, pmap, 0, 0);
1244 #ifdef COUNT_XINVLTLB_HITS
1245                 ipi_global++;
1246 #endif
1247         }
1248 }
1249
1250 void
1251 smp_invlpg(pmap_t pmap, vm_offset_t addr)
1252 {
1253
1254         if (smp_started) {
1255                 smp_tlb_shootdown(IPI_INVLPG, pmap, addr, 0);
1256 #ifdef COUNT_XINVLTLB_HITS
1257                 ipi_page++;
1258 #endif
1259         }
1260 }
1261
1262 void
1263 smp_invlpg_range(pmap_t pmap, vm_offset_t addr1, vm_offset_t addr2)
1264 {
1265
1266         if (smp_started) {
1267                 smp_tlb_shootdown(IPI_INVLRNG, pmap, addr1, addr2);
1268 #ifdef COUNT_XINVLTLB_HITS
1269                 ipi_range++;
1270                 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1271 #endif
1272         }
1273 }
1274
1275 void
1276 smp_masked_invltlb(cpuset_t mask, pmap_t pmap)
1277 {
1278
1279         if (smp_started) {
1280                 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, pmap, 0, 0);
1281 #ifdef COUNT_XINVLTLB_HITS
1282                 ipi_masked_global++;
1283 #endif
1284         }
1285 }
1286
1287 void
1288 smp_masked_invlpg(cpuset_t mask, pmap_t pmap, vm_offset_t addr)
1289 {
1290
1291         if (smp_started) {
1292                 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, pmap, addr, 0);
1293 #ifdef COUNT_XINVLTLB_HITS
1294                 ipi_masked_page++;
1295 #endif
1296         }
1297 }
1298
1299 void
1300 smp_masked_invlpg_range(cpuset_t mask, pmap_t pmap, vm_offset_t addr1,
1301     vm_offset_t addr2)
1302 {
1303
1304         if (smp_started) {
1305                 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, pmap, addr1,
1306                     addr2);
1307 #ifdef COUNT_XINVLTLB_HITS
1308                 ipi_masked_range++;
1309                 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1310 #endif
1311         }
1312 }
1313
1314 void
1315 ipi_bitmap_handler(struct trapframe frame)
1316 {
1317         struct trapframe *oldframe;
1318         struct thread *td;
1319         int cpu = PCPU_GET(cpuid);
1320         u_int ipi_bitmap;
1321
1322         critical_enter();
1323         td = curthread;
1324         td->td_intr_nesting_level++;
1325         oldframe = td->td_intr_frame;
1326         td->td_intr_frame = &frame;
1327         ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1328         if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1329 #ifdef COUNT_IPIS
1330                 (*ipi_preempt_counts[cpu])++;
1331 #endif
1332                 sched_preempt(td);
1333         }
1334         if (ipi_bitmap & (1 << IPI_AST)) {
1335 #ifdef COUNT_IPIS
1336                 (*ipi_ast_counts[cpu])++;
1337 #endif
1338                 /* Nothing to do for AST */
1339         }
1340         if (ipi_bitmap & (1 << IPI_HARDCLOCK)) {
1341 #ifdef COUNT_IPIS
1342                 (*ipi_hardclock_counts[cpu])++;
1343 #endif
1344                 hardclockintr();
1345         }
1346         td->td_intr_frame = oldframe;
1347         td->td_intr_nesting_level--;
1348         critical_exit();
1349 }
1350
1351 /*
1352  * send an IPI to a set of cpus.
1353  */
1354 void
1355 ipi_selected(cpuset_t cpus, u_int ipi)
1356 {
1357         int cpu;
1358
1359         /*
1360          * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1361          * of help in order to understand what is the source.
1362          * Set the mask of receiving CPUs for this purpose.
1363          */
1364         if (ipi == IPI_STOP_HARD)
1365                 CPU_OR_ATOMIC(&ipi_nmi_pending, &cpus);
1366
1367         while ((cpu = CPU_FFS(&cpus)) != 0) {
1368                 cpu--;
1369                 CPU_CLR(cpu, &cpus);
1370                 CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1371                 ipi_send_cpu(cpu, ipi);
1372         }
1373 }
1374
1375 /*
1376  * send an IPI to a specific CPU.
1377  */
1378 void
1379 ipi_cpu(int cpu, u_int ipi)
1380 {
1381
1382         /*
1383          * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1384          * of help in order to understand what is the source.
1385          * Set the mask of receiving CPUs for this purpose.
1386          */
1387         if (ipi == IPI_STOP_HARD)
1388                 CPU_SET_ATOMIC(cpu, &ipi_nmi_pending);
1389
1390         CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1391         ipi_send_cpu(cpu, ipi);
1392 }
1393
1394 /*
1395  * send an IPI to all CPUs EXCEPT myself
1396  */
1397 void
1398 ipi_all_but_self(u_int ipi)
1399 {
1400         cpuset_t other_cpus;
1401
1402         other_cpus = all_cpus;
1403         CPU_CLR(PCPU_GET(cpuid), &other_cpus);
1404
1405         if (IPI_IS_BITMAPED(ipi)) {
1406                 ipi_selected(other_cpus, ipi);
1407                 return;
1408         }
1409
1410         /*
1411          * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1412          * of help in order to understand what is the source.
1413          * Set the mask of receiving CPUs for this purpose.
1414          */
1415         if (ipi == IPI_STOP_HARD)
1416                 CPU_OR_ATOMIC(&ipi_nmi_pending, &other_cpus);
1417
1418         CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1419         lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1420 }
1421
1422 int
1423 ipi_nmi_handler()
1424 {
1425         u_int cpuid;
1426
1427         /*
1428          * As long as there is not a simple way to know about a NMI's
1429          * source, if the bitmask for the current CPU is present in
1430          * the global pending bitword an IPI_STOP_HARD has been issued
1431          * and should be handled.
1432          */
1433         cpuid = PCPU_GET(cpuid);
1434         if (!CPU_ISSET(cpuid, &ipi_nmi_pending))
1435                 return (1);
1436
1437         CPU_CLR_ATOMIC(cpuid, &ipi_nmi_pending);
1438         cpustop_handler();
1439         return (0);
1440 }
1441      
1442 /*
1443  * Handle an IPI_STOP by saving our current context and spinning until we
1444  * are resumed.
1445  */
1446 void
1447 cpustop_handler(void)
1448 {
1449         u_int cpu;
1450
1451         cpu = PCPU_GET(cpuid);
1452
1453         savectx(&stoppcbs[cpu]);
1454
1455         /* Indicate that we are stopped */
1456         CPU_SET_ATOMIC(cpu, &stopped_cpus);
1457
1458         /* Wait for restart */
1459         while (!CPU_ISSET(cpu, &started_cpus))
1460             ia32_pause();
1461
1462         CPU_CLR_ATOMIC(cpu, &started_cpus);
1463         CPU_CLR_ATOMIC(cpu, &stopped_cpus);
1464
1465 #ifdef DDB
1466         amd64_db_resume_dbreg();
1467 #endif
1468
1469         if (cpu == 0 && cpustop_restartfunc != NULL) {
1470                 cpustop_restartfunc();
1471                 cpustop_restartfunc = NULL;
1472         }
1473 }
1474
1475 /*
1476  * Handle an IPI_SUSPEND by saving our current context and spinning until we
1477  * are resumed.
1478  */
1479 void
1480 cpususpend_handler(void)
1481 {
1482         u_int cpu;
1483
1484         mtx_assert(&smp_ipi_mtx, MA_NOTOWNED);
1485
1486         cpu = PCPU_GET(cpuid);
1487         if (savectx(&susppcbs[cpu]->sp_pcb)) {
1488                 fpususpend(susppcbs[cpu]->sp_fpususpend);
1489                 wbinvd();
1490                 CPU_SET_ATOMIC(cpu, &suspended_cpus);
1491         } else {
1492                 fpuresume(susppcbs[cpu]->sp_fpususpend);
1493                 pmap_init_pat();
1494                 initializecpu();
1495                 PCPU_SET(switchtime, 0);
1496                 PCPU_SET(switchticks, ticks);
1497
1498                 /* Indicate that we are resumed */
1499                 CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1500         }
1501
1502         /* Wait for resume */
1503         while (!CPU_ISSET(cpu, &started_cpus))
1504                 ia32_pause();
1505
1506         if (cpu_ops.cpu_resume)
1507                 cpu_ops.cpu_resume();
1508         if (vmm_resume_p)
1509                 vmm_resume_p();
1510
1511         /* Resume MCA and local APIC */
1512         lapic_xapic_mode();
1513         mca_resume();
1514         lapic_setup(0);
1515
1516         CPU_CLR_ATOMIC(cpu, &started_cpus);
1517         /* Indicate that we are resumed */
1518         CPU_CLR_ATOMIC(cpu, &suspended_cpus);
1519 }
1520
1521 /*
1522  * Handlers for TLB related IPIs
1523  */
1524 void
1525 invltlb_handler(void)
1526 {
1527 #ifdef COUNT_XINVLTLB_HITS
1528         xhits_gbl[PCPU_GET(cpuid)]++;
1529 #endif /* COUNT_XINVLTLB_HITS */
1530 #ifdef COUNT_IPIS
1531         (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
1532 #endif /* COUNT_IPIS */
1533
1534         invltlb();
1535         atomic_add_int(&smp_tlb_wait, 1);
1536 }
1537
1538 void
1539 invltlb_pcid_handler(void)
1540 {
1541         uint64_t cr3;
1542         u_int cpuid;
1543 #ifdef COUNT_XINVLTLB_HITS
1544         xhits_gbl[PCPU_GET(cpuid)]++;
1545 #endif /* COUNT_XINVLTLB_HITS */
1546 #ifdef COUNT_IPIS
1547         (*ipi_invltlb_counts[PCPU_GET(cpuid)])++;
1548 #endif /* COUNT_IPIS */
1549
1550         if (smp_tlb_invpcid.pcid != (uint64_t)-1 &&
1551             smp_tlb_invpcid.pcid != 0) {
1552                 if (invpcid_works) {
1553                         invpcid(&smp_tlb_invpcid, INVPCID_CTX);
1554                 } else {
1555                         /* Otherwise reload %cr3 twice. */
1556                         cr3 = rcr3();
1557                         if (cr3 != pcid_cr3) {
1558                                 load_cr3(pcid_cr3);
1559                                 cr3 |= CR3_PCID_SAVE;
1560                         }
1561                         load_cr3(cr3);
1562                 }
1563         } else {
1564                 invltlb_globpcid();
1565         }
1566         if (smp_tlb_pmap != NULL) {
1567                 cpuid = PCPU_GET(cpuid);
1568                 if (!CPU_ISSET(cpuid, &smp_tlb_pmap->pm_active))
1569                         CPU_CLR_ATOMIC(cpuid, &smp_tlb_pmap->pm_save);
1570         }
1571
1572         atomic_add_int(&smp_tlb_wait, 1);
1573 }
1574
1575 void
1576 invlpg_handler(void)
1577 {
1578 #ifdef COUNT_XINVLTLB_HITS
1579         xhits_pg[PCPU_GET(cpuid)]++;
1580 #endif /* COUNT_XINVLTLB_HITS */
1581 #ifdef COUNT_IPIS
1582         (*ipi_invlpg_counts[PCPU_GET(cpuid)])++;
1583 #endif /* COUNT_IPIS */
1584
1585         invlpg(smp_tlb_invpcid.addr);
1586         atomic_add_int(&smp_tlb_wait, 1);
1587 }
1588
1589 void
1590 invlpg_pcid_handler(void)
1591 {
1592         uint64_t cr3;
1593 #ifdef COUNT_XINVLTLB_HITS
1594         xhits_pg[PCPU_GET(cpuid)]++;
1595 #endif /* COUNT_XINVLTLB_HITS */
1596 #ifdef COUNT_IPIS
1597         (*ipi_invlpg_counts[PCPU_GET(cpuid)])++;
1598 #endif /* COUNT_IPIS */
1599
1600         if (smp_tlb_invpcid.pcid == (uint64_t)-1) {
1601                 invltlb_globpcid();
1602         } else if (smp_tlb_invpcid.pcid == 0) {
1603                 invlpg(smp_tlb_invpcid.addr);
1604         } else if (invpcid_works) {
1605                 invpcid(&smp_tlb_invpcid, INVPCID_ADDR);
1606         } else {
1607                 /*
1608                  * PCID supported, but INVPCID is not.
1609                  * Temporarily switch to the target address
1610                  * space and do INVLPG.
1611                  */
1612                 cr3 = rcr3();
1613                 if (cr3 != pcid_cr3)
1614                         load_cr3(pcid_cr3 | CR3_PCID_SAVE);
1615                 invlpg(smp_tlb_invpcid.addr);
1616                 load_cr3(cr3 | CR3_PCID_SAVE);
1617         }
1618
1619         atomic_add_int(&smp_tlb_wait, 1);
1620 }
1621
1622 static inline void
1623 invlpg_range(vm_offset_t start, vm_offset_t end)
1624 {
1625
1626         do {
1627                 invlpg(start);
1628                 start += PAGE_SIZE;
1629         } while (start < end);
1630 }
1631
1632 void
1633 invlrng_handler(void)
1634 {
1635         struct invpcid_descr d;
1636         vm_offset_t addr;
1637         uint64_t cr3;
1638         u_int cpuid;
1639 #ifdef COUNT_XINVLTLB_HITS
1640         xhits_rng[PCPU_GET(cpuid)]++;
1641 #endif /* COUNT_XINVLTLB_HITS */
1642 #ifdef COUNT_IPIS
1643         (*ipi_invlrng_counts[PCPU_GET(cpuid)])++;
1644 #endif /* COUNT_IPIS */
1645
1646         addr = smp_tlb_invpcid.addr;
1647         if (pmap_pcid_enabled) {
1648                 if (smp_tlb_invpcid.pcid == 0) {
1649                         /*
1650                          * kernel pmap - use invlpg to invalidate
1651                          * global mapping.
1652                          */
1653                         invlpg_range(addr, smp_tlb_addr2);
1654                 } else if (smp_tlb_invpcid.pcid == (uint64_t)-1) {
1655                         invltlb_globpcid();
1656                         if (smp_tlb_pmap != NULL) {
1657                                 cpuid = PCPU_GET(cpuid);
1658                                 if (!CPU_ISSET(cpuid, &smp_tlb_pmap->pm_active))
1659                                         CPU_CLR_ATOMIC(cpuid,
1660                                             &smp_tlb_pmap->pm_save);
1661                         }
1662                 } else if (invpcid_works) {
1663                         d = smp_tlb_invpcid;
1664                         do {
1665                                 invpcid(&d, INVPCID_ADDR);
1666                                 d.addr += PAGE_SIZE;
1667                         } while (d.addr <= smp_tlb_addr2);
1668                 } else {
1669                         cr3 = rcr3();
1670                         if (cr3 != pcid_cr3)
1671                                 load_cr3(pcid_cr3 | CR3_PCID_SAVE);
1672                         invlpg_range(addr, smp_tlb_addr2);
1673                         load_cr3(cr3 | CR3_PCID_SAVE);
1674                 }
1675         } else {
1676                 invlpg_range(addr, smp_tlb_addr2);
1677         }
1678
1679         atomic_add_int(&smp_tlb_wait, 1);
1680 }
1681
1682 void
1683 invlcache_handler(void)
1684 {
1685 #ifdef COUNT_IPIS
1686         (*ipi_invlcache_counts[PCPU_GET(cpuid)])++;
1687 #endif /* COUNT_IPIS */
1688
1689         wbinvd();
1690         atomic_add_int(&smp_tlb_wait, 1);
1691 }
1692
1693 /*
1694  * This is called once the rest of the system is up and running and we're
1695  * ready to let the AP's out of the pen.
1696  */
1697 static void
1698 release_aps(void *dummy __unused)
1699 {
1700
1701         if (mp_ncpus == 1) 
1702                 return;
1703         atomic_store_rel_int(&aps_ready, 1);
1704         while (smp_started == 0)
1705                 ia32_pause();
1706 }
1707 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1708
1709 #ifdef COUNT_IPIS
1710 /*
1711  * Setup interrupt counters for IPI handlers.
1712  */
1713 static void
1714 mp_ipi_intrcnt(void *dummy)
1715 {
1716         char buf[64];
1717         int i;
1718
1719         CPU_FOREACH(i) {
1720                 snprintf(buf, sizeof(buf), "cpu%d:invltlb", i);
1721                 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1722                 snprintf(buf, sizeof(buf), "cpu%d:invlrng", i);
1723                 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1724                 snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
1725                 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1726                 snprintf(buf, sizeof(buf), "cpu%d:invlcache", i);
1727                 intrcnt_add(buf, &ipi_invlcache_counts[i]);
1728                 snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
1729                 intrcnt_add(buf, &ipi_preempt_counts[i]);
1730                 snprintf(buf, sizeof(buf), "cpu%d:ast", i);
1731                 intrcnt_add(buf, &ipi_ast_counts[i]);
1732                 snprintf(buf, sizeof(buf), "cpu%d:rendezvous", i);
1733                 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1734                 snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
1735                 intrcnt_add(buf, &ipi_hardclock_counts[i]);
1736         }
1737 }
1738 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);
1739 #endif
1740