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