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