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