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