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