]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/i386/i386/mp_machdep.c
Merge gdtoa-20110304.
[FreeBSD/FreeBSD.git] / sys / i386 / i386 / mp_machdep.c
1 /*-
2  * Copyright (c) 1996, by Steve Passe
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. The name of the developer may NOT be used to endorse or promote products
11  *    derived from this software without specific prior written permission.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #include "opt_apic.h"
30 #include "opt_cpu.h"
31 #include "opt_kstack_pages.h"
32 #include "opt_mp_watchdog.h"
33 #include "opt_pmap.h"
34 #include "opt_sched.h"
35 #include "opt_smp.h"
36
37 #if !defined(lint)
38 #if !defined(SMP)
39 #error How did you get here?
40 #endif
41
42 #ifndef DEV_APIC
43 #error The apic device is required for SMP, add "device apic" to your config file.
44 #endif
45 #if defined(CPU_DISABLE_CMPXCHG) && !defined(COMPILING_LINT)
46 #error SMP not supported with CPU_DISABLE_CMPXCHG
47 #endif
48 #endif /* not lint */
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/bus.h>
53 #include <sys/cons.h>   /* cngetc() */
54 #ifdef GPROF 
55 #include <sys/gmon.h>
56 #endif
57 #include <sys/kernel.h>
58 #include <sys/ktr.h>
59 #include <sys/lock.h>
60 #include <sys/malloc.h>
61 #include <sys/memrange.h>
62 #include <sys/mutex.h>
63 #include <sys/pcpu.h>
64 #include <sys/proc.h>
65 #include <sys/sched.h>
66 #include <sys/smp.h>
67 #include <sys/sysctl.h>
68
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_extern.h>
74
75 #include <x86/apicreg.h>
76 #include <machine/clock.h>
77 #include <machine/cputypes.h>
78 #include <x86/mca.h>
79 #include <machine/md_var.h>
80 #include <machine/mp_watchdog.h>
81 #include <machine/pcb.h>
82 #include <machine/psl.h>
83 #include <machine/smp.h>
84 #include <machine/specialreg.h>
85
86 #define WARMBOOT_TARGET         0
87 #define WARMBOOT_OFF            (KERNBASE + 0x0467)
88 #define WARMBOOT_SEG            (KERNBASE + 0x0469)
89
90 #define CMOS_REG                (0x70)
91 #define CMOS_DATA               (0x71)
92 #define BIOS_RESET              (0x0f)
93 #define BIOS_WARM               (0x0a)
94
95 /*
96  * this code MUST be enabled here and in mpboot.s.
97  * it follows the very early stages of AP boot by placing values in CMOS ram.
98  * it NORMALLY will never be needed and thus the primitive method for enabling.
99  *
100 #define CHECK_POINTS
101  */
102
103 #if defined(CHECK_POINTS) && !defined(PC98)
104 #define CHECK_READ(A)    (outb(CMOS_REG, (A)), inb(CMOS_DATA))
105 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
106
107 #define CHECK_INIT(D);                          \
108         CHECK_WRITE(0x34, (D));                 \
109         CHECK_WRITE(0x35, (D));                 \
110         CHECK_WRITE(0x36, (D));                 \
111         CHECK_WRITE(0x37, (D));                 \
112         CHECK_WRITE(0x38, (D));                 \
113         CHECK_WRITE(0x39, (D));
114
115 #define CHECK_PRINT(S);                         \
116         printf("%s: %d, %d, %d, %d, %d, %d\n",  \
117            (S),                                 \
118            CHECK_READ(0x34),                    \
119            CHECK_READ(0x35),                    \
120            CHECK_READ(0x36),                    \
121            CHECK_READ(0x37),                    \
122            CHECK_READ(0x38),                    \
123            CHECK_READ(0x39));
124
125 #else                           /* CHECK_POINTS */
126
127 #define CHECK_INIT(D)
128 #define CHECK_PRINT(S)
129 #define CHECK_WRITE(A, D)
130
131 #endif                          /* CHECK_POINTS */
132
133 /* lock region used by kernel profiling */
134 int     mcount_lock;
135
136 int     mp_naps;                /* # of Applications processors */
137 int     boot_cpu_id = -1;       /* designated BSP */
138
139 extern  struct pcpu __pcpu[];
140
141 /* AP uses this during bootstrap.  Do not staticize.  */
142 char *bootSTK;
143 static int bootAP;
144
145 /* Free these after use */
146 void *bootstacks[MAXCPU];
147 static void *dpcpu;
148
149 /* Hotwire a 0->4MB V==P mapping */
150 extern pt_entry_t *KPTphys;
151
152 struct pcb stoppcbs[MAXCPU];
153
154 /* Variables needed for SMP tlb shootdown. */
155 vm_offset_t smp_tlb_addr1;
156 vm_offset_t smp_tlb_addr2;
157 volatile int smp_tlb_wait;
158
159 #ifdef COUNT_IPIS
160 /* Interrupt counts. */
161 static u_long *ipi_preempt_counts[MAXCPU];
162 static u_long *ipi_ast_counts[MAXCPU];
163 u_long *ipi_invltlb_counts[MAXCPU];
164 u_long *ipi_invlrng_counts[MAXCPU];
165 u_long *ipi_invlpg_counts[MAXCPU];
166 u_long *ipi_invlcache_counts[MAXCPU];
167 u_long *ipi_rendezvous_counts[MAXCPU];
168 u_long *ipi_lazypmap_counts[MAXCPU];
169 static u_long *ipi_hardclock_counts[MAXCPU];
170 #endif
171
172 /*
173  * Local data and functions.
174  */
175
176 static volatile cpumask_t ipi_nmi_pending;
177
178 /* used to hold the AP's until we are ready to release them */
179 static struct mtx ap_boot_mtx;
180
181 /* Set to 1 once we're ready to let the APs out of the pen. */
182 static volatile int aps_ready = 0;
183
184 /*
185  * Store data from cpu_add() until later in the boot when we actually setup
186  * the APs.
187  */
188 struct cpu_info {
189         int     cpu_present:1;
190         int     cpu_bsp:1;
191         int     cpu_disabled:1;
192         int     cpu_hyperthread:1;
193 } static cpu_info[MAX_APIC_ID + 1];
194 int cpu_apic_ids[MAXCPU];
195 int apic_cpuids[MAX_APIC_ID + 1];
196
197 /* Holds pending bitmap based IPIs per CPU */
198 static volatile u_int cpu_ipi_pending[MAXCPU];
199
200 static u_int boot_address;
201 static int cpu_logical;                 /* logical cpus per core */
202 static int cpu_cores;                   /* cores per package */
203
204 static void     assign_cpu_ids(void);
205 static void     install_ap_tramp(void);
206 static void     set_interrupt_apic_ids(void);
207 static int      start_all_aps(void);
208 static int      start_ap(int apic_id);
209 static void     release_aps(void *dummy);
210
211 static int      hlt_logical_cpus;
212 static u_int    hyperthreading_cpus;    /* logical cpus sharing L1 cache */
213 static cpumask_t        hyperthreading_cpus_mask;
214 static int      hyperthreading_allowed = 1;
215 static struct   sysctl_ctx_list logical_cpu_clist;
216
217 static void
218 mem_range_AP_init(void)
219 {
220         if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
221                 mem_range_softc.mr_op->initAP(&mem_range_softc);
222 }
223
224 static void
225 topo_probe_amd(void)
226 {
227
228         /* AMD processors do not support HTT. */
229         cpu_cores = (amd_feature2 & AMDID2_CMP) != 0 ?
230             (cpu_procinfo2 & AMDID_CMP_CORES) + 1 : 1;
231         cpu_logical = 1;
232 }
233
234 /*
235  * Round up to the next power of two, if necessary, and then
236  * take log2.
237  * Returns -1 if argument is zero.
238  */
239 static __inline int
240 mask_width(u_int x)
241 {
242
243         return (fls(x << (1 - powerof2(x))) - 1);
244 }
245
246 static void
247 topo_probe_0x4(void)
248 {
249         u_int p[4];
250         int pkg_id_bits;
251         int core_id_bits;
252         int max_cores;
253         int max_logical;
254         int id;
255
256         /* Both zero and one here mean one logical processor per package. */
257         max_logical = (cpu_feature & CPUID_HTT) != 0 ?
258             (cpu_procinfo & CPUID_HTT_CORES) >> 16 : 1;
259         if (max_logical <= 1)
260                 return;
261
262         /*
263          * Because of uniformity assumption we examine only
264          * those logical processors that belong to the same
265          * package as BSP.  Further, we count number of
266          * logical processors that belong to the same core
267          * as BSP thus deducing number of threads per core.
268          */
269         cpuid_count(0x04, 0, p);
270         max_cores = ((p[0] >> 26) & 0x3f) + 1;
271         core_id_bits = mask_width(max_logical/max_cores);
272         if (core_id_bits < 0)
273                 return;
274         pkg_id_bits = core_id_bits + mask_width(max_cores);
275
276         for (id = 0; id <= MAX_APIC_ID; id++) {
277                 /* Check logical CPU availability. */
278                 if (!cpu_info[id].cpu_present || cpu_info[id].cpu_disabled)
279                         continue;
280                 /* Check if logical CPU has the same package ID. */
281                 if ((id >> pkg_id_bits) != (boot_cpu_id >> pkg_id_bits))
282                         continue;
283                 cpu_cores++;
284                 /* Check if logical CPU has the same package and core IDs. */
285                 if ((id >> core_id_bits) == (boot_cpu_id >> core_id_bits))
286                         cpu_logical++;
287         }
288
289         KASSERT(cpu_cores >= 1 && cpu_logical >= 1,
290             ("topo_probe_0x4 couldn't find BSP"));
291
292         cpu_cores /= cpu_logical;
293         hyperthreading_cpus = cpu_logical;
294 }
295
296 static void
297 topo_probe_0xb(void)
298 {
299         u_int p[4];
300         int bits;
301         int cnt;
302         int i;
303         int logical;
304         int type;
305         int x;
306
307         /* We only support three levels for now. */
308         for (i = 0; i < 3; i++) {
309                 cpuid_count(0x0b, i, p);
310
311                 /* Fall back if CPU leaf 11 doesn't really exist. */
312                 if (i == 0 && p[1] == 0) {
313                         topo_probe_0x4();
314                         return;
315                 }
316
317                 bits = p[0] & 0x1f;
318                 logical = p[1] &= 0xffff;
319                 type = (p[2] >> 8) & 0xff;
320                 if (type == 0 || logical == 0)
321                         break;
322                 /*
323                  * Because of uniformity assumption we examine only
324                  * those logical processors that belong to the same
325                  * package as BSP.
326                  */
327                 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
328                         if (!cpu_info[x].cpu_present ||
329                             cpu_info[x].cpu_disabled)
330                                 continue;
331                         if (x >> bits == boot_cpu_id >> bits)
332                                 cnt++;
333                 }
334                 if (type == CPUID_TYPE_SMT)
335                         cpu_logical = cnt;
336                 else if (type == CPUID_TYPE_CORE)
337                         cpu_cores = cnt;
338         }
339         if (cpu_logical == 0)
340                 cpu_logical = 1;
341         cpu_cores /= cpu_logical;
342 }
343
344 /*
345  * Both topology discovery code and code that consumes topology
346  * information assume top-down uniformity of the topology.
347  * That is, all physical packages must be identical and each
348  * core in a package must have the same number of threads.
349  * Topology information is queried only on BSP, on which this
350  * code runs and for which it can query CPUID information.
351  * Then topology is extrapolated on all packages using the
352  * uniformity assumption.
353  */
354 static void
355 topo_probe(void)
356 {
357         static int cpu_topo_probed = 0;
358
359         if (cpu_topo_probed)
360                 return;
361
362         logical_cpus_mask = 0;
363         if (mp_ncpus <= 1)
364                 cpu_cores = cpu_logical = 1;
365         else if (cpu_vendor_id == CPU_VENDOR_AMD)
366                 topo_probe_amd();
367         else if (cpu_vendor_id == CPU_VENDOR_INTEL) {
368                 /*
369                  * See Intel(R) 64 Architecture Processor
370                  * Topology Enumeration article for details.
371                  *
372                  * Note that 0x1 <= cpu_high < 4 case should be
373                  * compatible with topo_probe_0x4() logic when
374                  * CPUID.1:EBX[23:16] > 0 (cpu_cores will be 1)
375                  * or it should trigger the fallback otherwise.
376                  */
377                 if (cpu_high >= 0xb)
378                         topo_probe_0xb();
379                 else if (cpu_high >= 0x1)
380                         topo_probe_0x4();
381         }
382
383         /*
384          * Fallback: assume each logical CPU is in separate
385          * physical package.  That is, no multi-core, no SMT.
386          */
387         if (cpu_cores == 0 || cpu_logical == 0)
388                 cpu_cores = cpu_logical = 1;
389         cpu_topo_probed = 1;
390 }
391
392 struct cpu_group *
393 cpu_topo(void)
394 {
395         int cg_flags;
396
397         /*
398          * Determine whether any threading flags are
399          * necessry.
400          */
401         topo_probe();
402         if (cpu_logical > 1 && hyperthreading_cpus)
403                 cg_flags = CG_FLAG_HTT;
404         else if (cpu_logical > 1)
405                 cg_flags = CG_FLAG_SMT;
406         else
407                 cg_flags = 0;
408         if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
409                 printf("WARNING: Non-uniform processors.\n");
410                 printf("WARNING: Using suboptimal topology.\n");
411                 return (smp_topo_none());
412         }
413         /*
414          * No multi-core or hyper-threaded.
415          */
416         if (cpu_logical * cpu_cores == 1)
417                 return (smp_topo_none());
418         /*
419          * Only HTT no multi-core.
420          */
421         if (cpu_logical > 1 && cpu_cores == 1)
422                 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
423         /*
424          * Only multi-core no HTT.
425          */
426         if (cpu_cores > 1 && cpu_logical == 1)
427                 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
428         /*
429          * Both HTT and multi-core.
430          */
431         return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
432             CG_SHARE_L1, cpu_logical, cg_flags));
433 }
434
435
436 /*
437  * Calculate usable address in base memory for AP trampoline code.
438  */
439 u_int
440 mp_bootaddress(u_int basemem)
441 {
442
443         boot_address = trunc_page(basemem);     /* round down to 4k boundary */
444         if ((basemem - boot_address) < bootMP_size)
445                 boot_address -= PAGE_SIZE;      /* not enough, lower by 4k */
446
447         return boot_address;
448 }
449
450 void
451 cpu_add(u_int apic_id, char boot_cpu)
452 {
453
454         if (apic_id > MAX_APIC_ID) {
455                 panic("SMP: APIC ID %d too high", apic_id);
456                 return;
457         }
458         KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
459             apic_id));
460         cpu_info[apic_id].cpu_present = 1;
461         if (boot_cpu) {
462                 KASSERT(boot_cpu_id == -1,
463                     ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
464                     boot_cpu_id));
465                 boot_cpu_id = apic_id;
466                 cpu_info[apic_id].cpu_bsp = 1;
467         }
468         if (mp_ncpus < MAXCPU) {
469                 mp_ncpus++;
470                 mp_maxid = mp_ncpus - 1;
471         }
472         if (bootverbose)
473                 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
474                     "AP");
475 }
476
477 void
478 cpu_mp_setmaxid(void)
479 {
480
481         /*
482          * mp_maxid should be already set by calls to cpu_add().
483          * Just sanity check its value here.
484          */
485         if (mp_ncpus == 0)
486                 KASSERT(mp_maxid == 0,
487                     ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
488         else if (mp_ncpus == 1)
489                 mp_maxid = 0;
490         else
491                 KASSERT(mp_maxid >= mp_ncpus - 1,
492                     ("%s: counters out of sync: max %d, count %d", __func__,
493                         mp_maxid, mp_ncpus));
494 }
495
496 int
497 cpu_mp_probe(void)
498 {
499
500         /*
501          * Always record BSP in CPU map so that the mbuf init code works
502          * correctly.
503          */
504         all_cpus = 1;
505         if (mp_ncpus == 0) {
506                 /*
507                  * No CPUs were found, so this must be a UP system.  Setup
508                  * the variables to represent a system with a single CPU
509                  * with an id of 0.
510                  */
511                 mp_ncpus = 1;
512                 return (0);
513         }
514
515         /* At least one CPU was found. */
516         if (mp_ncpus == 1) {
517                 /*
518                  * One CPU was found, so this must be a UP system with
519                  * an I/O APIC.
520                  */
521                 mp_maxid = 0;
522                 return (0);
523         }
524
525         /* At least two CPUs were found. */
526         return (1);
527 }
528
529 /*
530  * Initialize the IPI handlers and start up the AP's.
531  */
532 void
533 cpu_mp_start(void)
534 {
535         int i;
536
537         /* Initialize the logical ID to APIC ID table. */
538         for (i = 0; i < MAXCPU; i++) {
539                 cpu_apic_ids[i] = -1;
540                 cpu_ipi_pending[i] = 0;
541         }
542
543         /* Install an inter-CPU IPI for TLB invalidation */
544         setidt(IPI_INVLTLB, IDTVEC(invltlb),
545                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
546         setidt(IPI_INVLPG, IDTVEC(invlpg),
547                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
548         setidt(IPI_INVLRNG, IDTVEC(invlrng),
549                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
550
551         /* Install an inter-CPU IPI for cache invalidation. */
552         setidt(IPI_INVLCACHE, IDTVEC(invlcache),
553                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
554
555         /* Install an inter-CPU IPI for lazy pmap release */
556         setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
557                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
558
559         /* Install an inter-CPU IPI for all-CPU rendezvous */
560         setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
561                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
562
563         /* Install generic inter-CPU IPI handler */
564         setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
565                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
566
567         /* Install an inter-CPU IPI for CPU stop/restart */
568         setidt(IPI_STOP, IDTVEC(cpustop),
569                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
570
571
572         /* Set boot_cpu_id if needed. */
573         if (boot_cpu_id == -1) {
574                 boot_cpu_id = PCPU_GET(apic_id);
575                 cpu_info[boot_cpu_id].cpu_bsp = 1;
576         } else
577                 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
578                     ("BSP's APIC ID doesn't match boot_cpu_id"));
579
580         /* Probe logical/physical core configuration. */
581         topo_probe();
582
583         assign_cpu_ids();
584
585         /* Start each Application Processor */
586         start_all_aps();
587
588         set_interrupt_apic_ids();
589 }
590
591
592 /*
593  * Print various information about the SMP system hardware and setup.
594  */
595 void
596 cpu_mp_announce(void)
597 {
598         const char *hyperthread;
599         int i;
600
601         printf("FreeBSD/SMP: %d package(s) x %d core(s)",
602             mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
603         if (hyperthreading_cpus > 1)
604             printf(" x %d HTT threads", cpu_logical);
605         else if (cpu_logical > 1)
606             printf(" x %d SMT threads", cpu_logical);
607         printf("\n");
608
609         /* List active CPUs first. */
610         printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
611         for (i = 1; i < mp_ncpus; i++) {
612                 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
613                         hyperthread = "/HT";
614                 else
615                         hyperthread = "";
616                 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
617                     cpu_apic_ids[i]);
618         }
619
620         /* List disabled CPUs last. */
621         for (i = 0; i <= MAX_APIC_ID; i++) {
622                 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
623                         continue;
624                 if (cpu_info[i].cpu_hyperthread)
625                         hyperthread = "/HT";
626                 else
627                         hyperthread = "";
628                 printf("  cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
629                     i);
630         }
631 }
632
633 /*
634  * AP CPU's call this to initialize themselves.
635  */
636 void
637 init_secondary(void)
638 {
639         struct pcpu *pc;
640         vm_offset_t addr;
641         int     gsel_tss;
642         int     x, myid;
643         u_int   cr0;
644
645         /* bootAP is set in start_ap() to our ID. */
646         myid = bootAP;
647
648         /* Get per-cpu data */
649         pc = &__pcpu[myid];
650
651         /* prime data page for it to use */
652         pcpu_init(pc, myid, sizeof(struct pcpu));
653         dpcpu_init(dpcpu, myid);
654         pc->pc_apic_id = cpu_apic_ids[myid];
655         pc->pc_prvspace = pc;
656         pc->pc_curthread = 0;
657
658         gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
659         gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
660
661         for (x = 0; x < NGDT; x++) {
662                 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
663         }
664
665         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
666         r_gdt.rd_base = (int) &gdt[myid * NGDT];
667         lgdt(&r_gdt);                   /* does magic intra-segment return */
668
669         lidt(&r_idt);
670
671         lldt(_default_ldt);
672         PCPU_SET(currentldt, _default_ldt);
673
674         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
675         gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
676         PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
677         PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
678         PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
679         PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
680         PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
681         ltr(gsel_tss);
682
683         PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
684
685         /*
686          * Set to a known state:
687          * Set by mpboot.s: CR0_PG, CR0_PE
688          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
689          */
690         cr0 = rcr0();
691         cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
692         load_cr0(cr0);
693         CHECK_WRITE(0x38, 5);
694         
695         /* Disable local APIC just to be sure. */
696         lapic_disable();
697
698         /* signal our startup to the BSP. */
699         mp_naps++;
700         CHECK_WRITE(0x39, 6);
701
702         /* Spin until the BSP releases the AP's. */
703         while (!aps_ready)
704                 ia32_pause();
705
706         /* BSP may have changed PTD while we were waiting */
707         invltlb();
708         for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
709                 invlpg(addr);
710
711 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
712         lidt(&r_idt);
713 #endif
714
715         /* Initialize the PAT MSR if present. */
716         pmap_init_pat();
717
718         /* set up CPU registers and state */
719         cpu_setregs();
720
721         /* set up FPU state on the AP */
722         npxinit();
723
724         /* set up SSE registers */
725         enable_sse();
726
727 #ifdef PAE
728         /* Enable the PTE no-execute bit. */
729         if ((amd_feature & AMDID_NX) != 0) {
730                 uint64_t msr;
731
732                 msr = rdmsr(MSR_EFER) | EFER_NXE;
733                 wrmsr(MSR_EFER, msr);
734         }
735 #endif
736
737         /* A quick check from sanity claus */
738         if (PCPU_GET(apic_id) != lapic_id()) {
739                 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
740                 printf("SMP: actual apic_id = %d\n", lapic_id());
741                 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
742                 panic("cpuid mismatch! boom!!");
743         }
744
745         /* Initialize curthread. */
746         KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
747         PCPU_SET(curthread, PCPU_GET(idlethread));
748
749         mca_init();
750
751         mtx_lock_spin(&ap_boot_mtx);
752
753         /* Init local apic for irq's */
754         lapic_setup(1);
755
756         /* Set memory range attributes for this CPU to match the BSP */
757         mem_range_AP_init();
758
759         smp_cpus++;
760
761         CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
762         printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
763
764         /* Determine if we are a logical CPU. */
765         /* XXX Calculation depends on cpu_logical being a power of 2, e.g. 2 */
766         if (cpu_logical > 1 && PCPU_GET(apic_id) % cpu_logical != 0)
767                 logical_cpus_mask |= PCPU_GET(cpumask);
768         
769         /* Determine if we are a hyperthread. */
770         if (hyperthreading_cpus > 1 &&
771             PCPU_GET(apic_id) % hyperthreading_cpus != 0)
772                 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
773
774         /* Build our map of 'other' CPUs. */
775         PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
776
777         if (bootverbose)
778                 lapic_dump("AP");
779
780         if (smp_cpus == mp_ncpus) {
781                 /* enable IPI's, tlb shootdown, freezes etc */
782                 atomic_store_rel_int(&smp_started, 1);
783                 smp_active = 1;  /* historic */
784         }
785
786         mtx_unlock_spin(&ap_boot_mtx);
787
788         /* Wait until all the AP's are up. */
789         while (smp_started == 0)
790                 ia32_pause();
791
792         /* Start per-CPU event timers. */
793         cpu_initclocks_ap();
794
795         /* Enter the scheduler. */
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 #if defined(SCHED_ULE)
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 #endif
864                 }
865
866                 /* Don't use this CPU if it has been disabled by a tunable. */
867                 if (resource_disabled("lapic", i)) {
868                         cpu_info[i].cpu_disabled = 1;
869                         continue;
870                 }
871         }
872
873         /*
874          * Assign CPU IDs to local APIC IDs and disable any CPUs
875          * beyond MAXCPU.  CPU 0 is always assigned to the BSP.
876          *
877          * To minimize confusion for userland, we attempt to number
878          * CPUs such that all threads and cores in a package are
879          * grouped together.  For now we assume that the BSP is always
880          * the first thread in a package and just start adding APs
881          * starting with the BSP's APIC ID.
882          */
883         mp_ncpus = 1;
884         cpu_apic_ids[0] = boot_cpu_id;
885         apic_cpuids[boot_cpu_id] = 0;
886         for (i = boot_cpu_id + 1; i != boot_cpu_id;
887              i == MAX_APIC_ID ? i = 0 : i++) {
888                 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
889                     cpu_info[i].cpu_disabled)
890                         continue;
891
892                 if (mp_ncpus < MAXCPU) {
893                         cpu_apic_ids[mp_ncpus] = i;
894                         apic_cpuids[i] = mp_ncpus;
895                         mp_ncpus++;
896                 } else
897                         cpu_info[i].cpu_disabled = 1;
898         }
899         KASSERT(mp_maxid >= mp_ncpus - 1,
900             ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
901             mp_ncpus));         
902 }
903
904 /*
905  * start each AP in our list
906  */
907 /* Lowest 1MB is already mapped: don't touch*/
908 #define TMPMAP_START 1
909 static int
910 start_all_aps(void)
911 {
912 #ifndef PC98
913         u_char mpbiosreason;
914 #endif
915         uintptr_t kptbase;
916         u_int32_t mpbioswarmvec;
917         int apic_id, cpu, i;
918
919         mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
920
921         /* install the AP 1st level boot code */
922         install_ap_tramp();
923
924         /* save the current value of the warm-start vector */
925         mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
926 #ifndef PC98
927         outb(CMOS_REG, BIOS_RESET);
928         mpbiosreason = inb(CMOS_DATA);
929 #endif
930
931         /* set up temporary P==V mapping for AP boot */
932         /* XXX this is a hack, we should boot the AP on its own stack/PTD */
933
934         kptbase = (uintptr_t)(void *)KPTphys;
935         for (i = TMPMAP_START; i < NKPT; i++)
936                 PTD[i] = (pd_entry_t)(PG_V | PG_RW |
937                     ((kptbase + i * PAGE_SIZE) & PG_FRAME));
938         invltlb();
939
940         /* start each AP */
941         for (cpu = 1; cpu < mp_ncpus; cpu++) {
942                 apic_id = cpu_apic_ids[cpu];
943
944                 /* allocate and set up a boot stack data page */
945                 bootstacks[cpu] =
946                     (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
947                 dpcpu = (void *)kmem_alloc(kernel_map, DPCPU_SIZE);
948                 /* setup a vector to our boot code */
949                 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
950                 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
951 #ifndef PC98
952                 outb(CMOS_REG, BIOS_RESET);
953                 outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
954 #endif
955
956                 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 4;
957                 bootAP = cpu;
958
959                 /* attempt to start the Application Processor */
960                 CHECK_INIT(99); /* setup checkpoints */
961                 if (!start_ap(apic_id)) {
962                         printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
963                         CHECK_PRINT("trace");   /* show checkpoints */
964                         /* better panic as the AP may be running loose */
965                         printf("panic y/n? [y] ");
966                         if (cngetc() != 'n')
967                                 panic("bye-bye");
968                 }
969                 CHECK_PRINT("trace");           /* show checkpoints */
970
971                 all_cpus |= (1 << cpu);         /* record AP in CPU map */
972         }
973
974         /* build our map of 'other' CPUs */
975         PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
976
977         /* restore the warmstart vector */
978         *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
979
980 #ifndef PC98
981         outb(CMOS_REG, BIOS_RESET);
982         outb(CMOS_DATA, mpbiosreason);
983 #endif
984
985         /* Undo V==P hack from above */
986         for (i = TMPMAP_START; i < NKPT; i++)
987                 PTD[i] = 0;
988         pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
989
990         /* number of APs actually started */
991         return mp_naps;
992 }
993
994 /*
995  * load the 1st level AP boot code into base memory.
996  */
997
998 /* targets for relocation */
999 extern void bigJump(void);
1000 extern void bootCodeSeg(void);
1001 extern void bootDataSeg(void);
1002 extern void MPentry(void);
1003 extern u_int MP_GDT;
1004 extern u_int mp_gdtbase;
1005
1006 static void
1007 install_ap_tramp(void)
1008 {
1009         int     x;
1010         int     size = *(int *) ((u_long) & bootMP_size);
1011         vm_offset_t va = boot_address + KERNBASE;
1012         u_char *src = (u_char *) ((u_long) bootMP);
1013         u_char *dst = (u_char *) va;
1014         u_int   boot_base = (u_int) bootMP;
1015         u_int8_t *dst8;
1016         u_int16_t *dst16;
1017         u_int32_t *dst32;
1018
1019         KASSERT (size <= PAGE_SIZE,
1020             ("'size' do not fit into PAGE_SIZE, as expected."));
1021         pmap_kenter(va, boot_address);
1022         pmap_invalidate_page (kernel_pmap, va);
1023         for (x = 0; x < size; ++x)
1024                 *dst++ = *src++;
1025
1026         /*
1027          * modify addresses in code we just moved to basemem. unfortunately we
1028          * need fairly detailed info about mpboot.s for this to work.  changes
1029          * to mpboot.s might require changes here.
1030          */
1031
1032         /* boot code is located in KERNEL space */
1033         dst = (u_char *) va;
1034
1035         /* modify the lgdt arg */
1036         dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
1037         *dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
1038
1039         /* modify the ljmp target for MPentry() */
1040         dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
1041         *dst32 = ((u_int) MPentry - KERNBASE);
1042
1043         /* modify the target for boot code segment */
1044         dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
1045         dst8 = (u_int8_t *) (dst16 + 1);
1046         *dst16 = (u_int) boot_address & 0xffff;
1047         *dst8 = ((u_int) boot_address >> 16) & 0xff;
1048
1049         /* modify the target for boot data segment */
1050         dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
1051         dst8 = (u_int8_t *) (dst16 + 1);
1052         *dst16 = (u_int) boot_address & 0xffff;
1053         *dst8 = ((u_int) boot_address >> 16) & 0xff;
1054 }
1055
1056 /*
1057  * This function starts the AP (application processor) identified
1058  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
1059  * to accomplish this.  This is necessary because of the nuances
1060  * of the different hardware we might encounter.  It isn't pretty,
1061  * but it seems to work.
1062  */
1063 static int
1064 start_ap(int apic_id)
1065 {
1066         int vector, ms;
1067         int cpus;
1068
1069         /* calculate the vector */
1070         vector = (boot_address >> 12) & 0xff;
1071
1072         /* used as a watchpoint to signal AP startup */
1073         cpus = mp_naps;
1074
1075         /*
1076          * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
1077          * and running the target CPU. OR this INIT IPI might be latched (P5
1078          * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1079          * ignored.
1080          */
1081
1082         /* do an INIT IPI: assert RESET */
1083         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1084             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1085
1086         /* wait for pending status end */
1087         lapic_ipi_wait(-1);
1088
1089         /* do an INIT IPI: deassert RESET */
1090         lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
1091             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
1092
1093         /* wait for pending status end */
1094         DELAY(10000);           /* wait ~10mS */
1095         lapic_ipi_wait(-1);
1096
1097         /*
1098          * next we do a STARTUP IPI: the previous INIT IPI might still be
1099          * latched, (P5 bug) this 1st STARTUP would then terminate
1100          * immediately, and the previously started INIT IPI would continue. OR
1101          * the previous INIT IPI has already run. and this STARTUP IPI will
1102          * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1103          * will run.
1104          */
1105
1106         /* do a STARTUP IPI */
1107         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1108             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1109             vector, apic_id);
1110         lapic_ipi_wait(-1);
1111         DELAY(200);             /* wait ~200uS */
1112
1113         /*
1114          * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1115          * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1116          * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1117          * recognized after hardware RESET or INIT IPI.
1118          */
1119
1120         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1121             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1122             vector, apic_id);
1123         lapic_ipi_wait(-1);
1124         DELAY(200);             /* wait ~200uS */
1125
1126         /* Wait up to 5 seconds for it to start. */
1127         for (ms = 0; ms < 5000; ms++) {
1128                 if (mp_naps > cpus)
1129                         return 1;       /* return SUCCESS */
1130                 DELAY(1000);
1131         }
1132         return 0;               /* return FAILURE */
1133 }
1134
1135 #ifdef COUNT_XINVLTLB_HITS
1136 u_int xhits_gbl[MAXCPU];
1137 u_int xhits_pg[MAXCPU];
1138 u_int xhits_rng[MAXCPU];
1139 SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1140 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1141     sizeof(xhits_gbl), "IU", "");
1142 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1143     sizeof(xhits_pg), "IU", "");
1144 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1145     sizeof(xhits_rng), "IU", "");
1146
1147 u_int ipi_global;
1148 u_int ipi_page;
1149 u_int ipi_range;
1150 u_int ipi_range_size;
1151 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1152 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1153 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1154 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1155     0, "");
1156
1157 u_int ipi_masked_global;
1158 u_int ipi_masked_page;
1159 u_int ipi_masked_range;
1160 u_int ipi_masked_range_size;
1161 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
1162     &ipi_masked_global, 0, "");
1163 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
1164     &ipi_masked_page, 0, "");
1165 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
1166     &ipi_masked_range, 0, "");
1167 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
1168     &ipi_masked_range_size, 0, "");
1169 #endif /* COUNT_XINVLTLB_HITS */
1170
1171 /*
1172  * Flush the TLB on all other CPU's
1173  */
1174 static void
1175 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1176 {
1177         u_int ncpu;
1178
1179         ncpu = mp_ncpus - 1;    /* does not shootdown self */
1180         if (ncpu < 1)
1181                 return;         /* no other cpus */
1182         if (!(read_eflags() & PSL_I))
1183                 panic("%s: interrupts disabled", __func__);
1184         mtx_lock_spin(&smp_ipi_mtx);
1185         smp_tlb_addr1 = addr1;
1186         smp_tlb_addr2 = addr2;
1187         atomic_store_rel_int(&smp_tlb_wait, 0);
1188         ipi_all_but_self(vector);
1189         while (smp_tlb_wait < ncpu)
1190                 ia32_pause();
1191         mtx_unlock_spin(&smp_ipi_mtx);
1192 }
1193
1194 static void
1195 smp_targeted_tlb_shootdown(cpumask_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1196 {
1197         int ncpu, othercpus;
1198
1199         othercpus = mp_ncpus - 1;
1200         if (mask == (u_int)-1) {
1201                 ncpu = othercpus;
1202                 if (ncpu < 1)
1203                         return;
1204         } else {
1205                 mask &= ~PCPU_GET(cpumask);
1206                 if (mask == 0)
1207                         return;
1208                 ncpu = bitcount32(mask);
1209                 if (ncpu > othercpus) {
1210                         /* XXX this should be a panic offence */
1211                         printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1212                             ncpu, othercpus);
1213                         ncpu = othercpus;
1214                 }
1215                 /* XXX should be a panic, implied by mask == 0 above */
1216                 if (ncpu < 1)
1217                         return;
1218         }
1219         if (!(read_eflags() & PSL_I))
1220                 panic("%s: interrupts disabled", __func__);
1221         mtx_lock_spin(&smp_ipi_mtx);
1222         smp_tlb_addr1 = addr1;
1223         smp_tlb_addr2 = addr2;
1224         atomic_store_rel_int(&smp_tlb_wait, 0);
1225         if (mask == (u_int)-1)
1226                 ipi_all_but_self(vector);
1227         else
1228                 ipi_selected(mask, vector);
1229         while (smp_tlb_wait < ncpu)
1230                 ia32_pause();
1231         mtx_unlock_spin(&smp_ipi_mtx);
1232 }
1233
1234 /*
1235  * Send an IPI to specified CPU handling the bitmap logic.
1236  */
1237 static void
1238 ipi_send_cpu(int cpu, u_int ipi)
1239 {
1240         u_int bitmap, old_pending, new_pending;
1241
1242         KASSERT(cpu_apic_ids[cpu] != -1, ("IPI to non-existent CPU %d", cpu));
1243
1244         if (IPI_IS_BITMAPED(ipi)) {
1245                 bitmap = 1 << ipi;
1246                 ipi = IPI_BITMAP_VECTOR;
1247                 do {
1248                         old_pending = cpu_ipi_pending[cpu];
1249                         new_pending = old_pending | bitmap;
1250                 } while  (!atomic_cmpset_int(&cpu_ipi_pending[cpu],
1251                     old_pending, new_pending)); 
1252                 if (old_pending)
1253                         return;
1254         }
1255         lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1256 }
1257
1258 void
1259 smp_cache_flush(void)
1260 {
1261
1262         if (smp_started)
1263                 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1264 }
1265
1266 void
1267 smp_invltlb(void)
1268 {
1269
1270         if (smp_started) {
1271                 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1272 #ifdef COUNT_XINVLTLB_HITS
1273                 ipi_global++;
1274 #endif
1275         }
1276 }
1277
1278 void
1279 smp_invlpg(vm_offset_t addr)
1280 {
1281
1282         if (smp_started) {
1283                 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1284 #ifdef COUNT_XINVLTLB_HITS
1285                 ipi_page++;
1286 #endif
1287         }
1288 }
1289
1290 void
1291 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1292 {
1293
1294         if (smp_started) {
1295                 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1296 #ifdef COUNT_XINVLTLB_HITS
1297                 ipi_range++;
1298                 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1299 #endif
1300         }
1301 }
1302
1303 void
1304 smp_masked_invltlb(cpumask_t mask)
1305 {
1306
1307         if (smp_started) {
1308                 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1309 #ifdef COUNT_XINVLTLB_HITS
1310                 ipi_masked_global++;
1311 #endif
1312         }
1313 }
1314
1315 void
1316 smp_masked_invlpg(cpumask_t mask, vm_offset_t addr)
1317 {
1318
1319         if (smp_started) {
1320                 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1321 #ifdef COUNT_XINVLTLB_HITS
1322                 ipi_masked_page++;
1323 #endif
1324         }
1325 }
1326
1327 void
1328 smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
1329 {
1330
1331         if (smp_started) {
1332                 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1333 #ifdef COUNT_XINVLTLB_HITS
1334                 ipi_masked_range++;
1335                 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1336 #endif
1337         }
1338 }
1339
1340 void
1341 ipi_bitmap_handler(struct trapframe frame)
1342 {
1343         struct trapframe *oldframe;
1344         struct thread *td;
1345         int cpu = PCPU_GET(cpuid);
1346         u_int ipi_bitmap;
1347
1348         critical_enter();
1349         td = curthread;
1350         td->td_intr_nesting_level++;
1351         oldframe = td->td_intr_frame;
1352         td->td_intr_frame = &frame;
1353         ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1354         if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1355 #ifdef COUNT_IPIS
1356                 (*ipi_preempt_counts[cpu])++;
1357 #endif
1358                 sched_preempt(td);
1359         }
1360         if (ipi_bitmap & (1 << IPI_AST)) {
1361 #ifdef COUNT_IPIS
1362                 (*ipi_ast_counts[cpu])++;
1363 #endif
1364                 /* Nothing to do for AST */
1365         }
1366         if (ipi_bitmap & (1 << IPI_HARDCLOCK)) {
1367 #ifdef COUNT_IPIS
1368                 (*ipi_hardclock_counts[cpu])++;
1369 #endif
1370                 hardclockintr();
1371         }
1372         td->td_intr_frame = oldframe;
1373         td->td_intr_nesting_level--;
1374         critical_exit();
1375 }
1376
1377 /*
1378  * send an IPI to a set of cpus.
1379  */
1380 void
1381 ipi_selected(cpumask_t cpus, u_int ipi)
1382 {
1383         int cpu;
1384
1385         /*
1386          * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1387          * of help in order to understand what is the source.
1388          * Set the mask of receiving CPUs for this purpose.
1389          */
1390         if (ipi == IPI_STOP_HARD)
1391                 atomic_set_int(&ipi_nmi_pending, cpus);
1392
1393         CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1394         while ((cpu = ffs(cpus)) != 0) {
1395                 cpu--;
1396                 cpus &= ~(1 << cpu);
1397                 ipi_send_cpu(cpu, ipi);
1398         }
1399 }
1400
1401 /*
1402  * send an IPI to a specific CPU.
1403  */
1404 void
1405 ipi_cpu(int cpu, u_int ipi)
1406 {
1407
1408         /*
1409          * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1410          * of help in order to understand what is the source.
1411          * Set the mask of receiving CPUs for this purpose.
1412          */
1413         if (ipi == IPI_STOP_HARD)
1414                 atomic_set_int(&ipi_nmi_pending, 1 << cpu);
1415
1416         CTR3(KTR_SMP, "%s: cpu: %d ipi: %x", __func__, cpu, ipi);
1417         ipi_send_cpu(cpu, ipi);
1418 }
1419
1420 /*
1421  * send an IPI to all CPUs EXCEPT myself
1422  */
1423 void
1424 ipi_all_but_self(u_int ipi)
1425 {
1426
1427         if (IPI_IS_BITMAPED(ipi)) {
1428                 ipi_selected(PCPU_GET(other_cpus), ipi);
1429                 return;
1430         }
1431
1432         /*
1433          * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1434          * of help in order to understand what is the source.
1435          * Set the mask of receiving CPUs for this purpose.
1436          */
1437         if (ipi == IPI_STOP_HARD)
1438                 atomic_set_int(&ipi_nmi_pending, PCPU_GET(other_cpus));
1439         CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1440         lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1441 }
1442
1443 int
1444 ipi_nmi_handler()
1445 {
1446         cpumask_t cpumask;
1447
1448         /*
1449          * As long as there is not a simple way to know about a NMI's
1450          * source, if the bitmask for the current CPU is present in
1451          * the global pending bitword an IPI_STOP_HARD has been issued
1452          * and should be handled.
1453          */
1454         cpumask = PCPU_GET(cpumask);
1455         if ((ipi_nmi_pending & cpumask) == 0)
1456                 return (1);
1457
1458         atomic_clear_int(&ipi_nmi_pending, cpumask);
1459         cpustop_handler();
1460         return (0);
1461 }
1462
1463 /*
1464  * Handle an IPI_STOP by saving our current context and spinning until we
1465  * are resumed.
1466  */
1467 void
1468 cpustop_handler(void)
1469 {
1470         cpumask_t cpumask;
1471         u_int cpu;
1472
1473         cpu = PCPU_GET(cpuid);
1474         cpumask = PCPU_GET(cpumask);
1475
1476         savectx(&stoppcbs[cpu]);
1477
1478         /* Indicate that we are stopped */
1479         atomic_set_int(&stopped_cpus, cpumask);
1480
1481         /* Wait for restart */
1482         while (!(started_cpus & cpumask))
1483             ia32_pause();
1484
1485         atomic_clear_int(&started_cpus, cpumask);
1486         atomic_clear_int(&stopped_cpus, cpumask);
1487
1488         if (cpu == 0 && cpustop_restartfunc != NULL) {
1489                 cpustop_restartfunc();
1490                 cpustop_restartfunc = NULL;
1491         }
1492 }
1493
1494 /*
1495  * This is called once the rest of the system is up and running and we're
1496  * ready to let the AP's out of the pen.
1497  */
1498 static void
1499 release_aps(void *dummy __unused)
1500 {
1501
1502         if (mp_ncpus == 1) 
1503                 return;
1504         atomic_store_rel_int(&aps_ready, 1);
1505         while (smp_started == 0)
1506                 ia32_pause();
1507 }
1508 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1509
1510 static int
1511 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1512 {
1513         cpumask_t mask;
1514         int error;
1515
1516         mask = hlt_cpus_mask;
1517         error = sysctl_handle_int(oidp, &mask, 0, req);
1518         if (error || !req->newptr)
1519                 return (error);
1520
1521         if (logical_cpus_mask != 0 &&
1522             (mask & logical_cpus_mask) == logical_cpus_mask)
1523                 hlt_logical_cpus = 1;
1524         else
1525                 hlt_logical_cpus = 0;
1526
1527         if (! hyperthreading_allowed)
1528                 mask |= hyperthreading_cpus_mask;
1529
1530         if ((mask & all_cpus) == all_cpus)
1531                 mask &= ~(1<<0);
1532         hlt_cpus_mask = mask;
1533         return (error);
1534 }
1535 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1536     0, 0, sysctl_hlt_cpus, "IU",
1537     "Bitmap of CPUs to halt.  101 (binary) will halt CPUs 0 and 2.");
1538
1539 static int
1540 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1541 {
1542         int disable, error;
1543
1544         disable = hlt_logical_cpus;
1545         error = sysctl_handle_int(oidp, &disable, 0, req);
1546         if (error || !req->newptr)
1547                 return (error);
1548
1549         if (disable)
1550                 hlt_cpus_mask |= logical_cpus_mask;
1551         else
1552                 hlt_cpus_mask &= ~logical_cpus_mask;
1553
1554         if (! hyperthreading_allowed)
1555                 hlt_cpus_mask |= hyperthreading_cpus_mask;
1556
1557         if ((hlt_cpus_mask & all_cpus) == all_cpus)
1558                 hlt_cpus_mask &= ~(1<<0);
1559
1560         hlt_logical_cpus = disable;
1561         return (error);
1562 }
1563
1564 static int
1565 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1566 {
1567         int allowed, error;
1568
1569         allowed = hyperthreading_allowed;
1570         error = sysctl_handle_int(oidp, &allowed, 0, req);
1571         if (error || !req->newptr)
1572                 return (error);
1573
1574 #ifdef SCHED_ULE
1575         /*
1576          * SCHED_ULE doesn't allow enabling/disabling HT cores at
1577          * run-time.
1578          */
1579         if (allowed != hyperthreading_allowed)
1580                 return (ENOTSUP);
1581         return (error);
1582 #endif
1583
1584         if (allowed)
1585                 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1586         else
1587                 hlt_cpus_mask |= hyperthreading_cpus_mask;
1588
1589         if (logical_cpus_mask != 0 &&
1590             (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1591                 hlt_logical_cpus = 1;
1592         else
1593                 hlt_logical_cpus = 0;
1594
1595         if ((hlt_cpus_mask & all_cpus) == all_cpus)
1596                 hlt_cpus_mask &= ~(1<<0);
1597
1598         hyperthreading_allowed = allowed;
1599         return (error);
1600 }
1601
1602 static void
1603 cpu_hlt_setup(void *dummy __unused)
1604 {
1605
1606         if (logical_cpus_mask != 0) {
1607                 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1608                     &hlt_logical_cpus);
1609                 sysctl_ctx_init(&logical_cpu_clist);
1610                 SYSCTL_ADD_PROC(&logical_cpu_clist,
1611                     SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1612                     "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1613                     sysctl_hlt_logical_cpus, "IU", "");
1614                 SYSCTL_ADD_UINT(&logical_cpu_clist,
1615                     SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1616                     "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1617                     &logical_cpus_mask, 0, "");
1618
1619                 if (hlt_logical_cpus)
1620                         hlt_cpus_mask |= logical_cpus_mask;
1621
1622                 /*
1623                  * If necessary for security purposes, force
1624                  * hyperthreading off, regardless of the value
1625                  * of hlt_logical_cpus.
1626                  */
1627                 if (hyperthreading_cpus_mask) {
1628                         SYSCTL_ADD_PROC(&logical_cpu_clist,
1629                             SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1630                             "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1631                             0, 0, sysctl_hyperthreading_allowed, "IU", "");
1632                         if (! hyperthreading_allowed)
1633                                 hlt_cpus_mask |= hyperthreading_cpus_mask;
1634                 }
1635         }
1636 }
1637 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1638
1639 int
1640 mp_grab_cpu_hlt(void)
1641 {
1642         cpumask_t mask;
1643 #ifdef MP_WATCHDOG
1644         u_int cpuid;
1645 #endif
1646         int retval;
1647
1648         mask = PCPU_GET(cpumask);
1649 #ifdef MP_WATCHDOG
1650         cpuid = PCPU_GET(cpuid);
1651         ap_watchdog(cpuid);
1652 #endif
1653
1654         retval = 0;
1655         while (mask & hlt_cpus_mask) {
1656                 retval = 1;
1657                 __asm __volatile("sti; hlt" : : : "memory");
1658         }
1659         return (retval);
1660 }
1661
1662 #ifdef COUNT_IPIS
1663 /*
1664  * Setup interrupt counters for IPI handlers.
1665  */
1666 static void
1667 mp_ipi_intrcnt(void *dummy)
1668 {
1669         char buf[64];
1670         int i;
1671
1672         CPU_FOREACH(i) {
1673                 snprintf(buf, sizeof(buf), "cpu%d:invltlb", i);
1674                 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1675                 snprintf(buf, sizeof(buf), "cpu%d:invlrng", i);
1676                 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1677                 snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
1678                 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1679                 snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
1680                 intrcnt_add(buf, &ipi_preempt_counts[i]);
1681                 snprintf(buf, sizeof(buf), "cpu%d:ast", i);
1682                 intrcnt_add(buf, &ipi_ast_counts[i]);
1683                 snprintf(buf, sizeof(buf), "cpu%d:rendezvous", i);
1684                 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1685                 snprintf(buf, sizeof(buf), "cpu%d:lazypmap", i);
1686                 intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1687                 snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
1688                 intrcnt_add(buf, &ipi_hardclock_counts[i]);
1689         }               
1690 }
1691 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);
1692 #endif