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