]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/mp_machdep.c
This commit was generated by cvs2svn to compensate for changes in r151513,
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / mp_machdep.c
1 /*-
2  * Copyright (c) 1996, by Steve Passe
3  * Copyright (c) 2003, by Peter Wemm
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. The name of the developer may NOT be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_cpu.h"
31 #include "opt_kdb.h"
32 #include "opt_kstack_pages.h"
33 #include "opt_mp_watchdog.h"
34 #include "opt_sched.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/bus.h>
39 #ifdef GPROF 
40 #include <sys/gmon.h>
41 #endif
42 #include <sys/kernel.h>
43 #include <sys/ktr.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/memrange.h>
47 #include <sys/mutex.h>
48 #include <sys/pcpu.h>
49 #include <sys/proc.h>
50 #include <sys/smp.h>
51 #include <sys/sysctl.h>
52
53 #include <vm/vm.h>
54 #include <vm/vm_param.h>
55 #include <vm/pmap.h>
56 #include <vm/vm_kern.h>
57 #include <vm/vm_extern.h>
58
59 #include <machine/apicreg.h>
60 #include <machine/clock.h>
61 #include <machine/md_var.h>
62 #include <machine/mp_watchdog.h>
63 #include <machine/pcb.h>
64 #include <machine/psl.h>
65 #include <machine/smp.h>
66 #include <machine/specialreg.h>
67 #include <machine/tss.h>
68
69 #define WARMBOOT_TARGET         0
70 #define WARMBOOT_OFF            (KERNBASE + 0x0467)
71 #define WARMBOOT_SEG            (KERNBASE + 0x0469)
72
73 #define CMOS_REG                (0x70)
74 #define CMOS_DATA               (0x71)
75 #define BIOS_RESET              (0x0f)
76 #define BIOS_WARM               (0x0a)
77
78 /* lock region used by kernel profiling */
79 int     mcount_lock;
80
81 int     mp_naps;                /* # of Applications processors */
82 int     boot_cpu_id = -1;       /* designated BSP */
83 extern  int nkpt;
84
85 /*
86  * CPU topology map datastructures for HTT.
87  */
88 static struct cpu_group mp_groups[MAXCPU];
89 static struct cpu_top mp_top;
90
91 /* AP uses this during bootstrap.  Do not staticize.  */
92 char *bootSTK;
93 static int bootAP;
94
95 /* Free these after use */
96 void *bootstacks[MAXCPU];
97
98 /* Temporary holder for double fault stack */
99 char *doublefault_stack;
100
101 /* Hotwire a 0->4MB V==P mapping */
102 extern pt_entry_t *KPTphys;
103
104 /* SMP page table page */
105 extern pt_entry_t *SMPpt;
106
107 struct pcb stoppcbs[MAXCPU];
108
109 /* Variables needed for SMP tlb shootdown. */
110 vm_offset_t smp_tlb_addr1;
111 vm_offset_t smp_tlb_addr2;
112 volatile int smp_tlb_wait;
113
114 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
115
116 /*
117  * Local data and functions.
118  */
119
120 static u_int logical_cpus;
121
122 /* used to hold the AP's until we are ready to release them */
123 static struct mtx ap_boot_mtx;
124
125 /* Set to 1 once we're ready to let the APs out of the pen. */
126 static volatile int aps_ready = 0;
127
128 /*
129  * Store data from cpu_add() until later in the boot when we actually setup
130  * the APs.
131  */
132 struct cpu_info {
133         int     cpu_present:1;
134         int     cpu_bsp:1;
135         int     cpu_disabled:1;
136 } static cpu_info[MAXCPU];
137 static int cpu_apic_ids[MAXCPU];
138
139 /* Holds pending bitmap based IPIs per CPU */
140 static volatile u_int cpu_ipi_pending[MAXCPU];
141
142 static u_int boot_address;
143
144 static void     set_logical_apic_ids(void);
145 static int      start_all_aps(void);
146 static int      start_ap(int apic_id);
147 static void     release_aps(void *dummy);
148
149 static int      hlt_logical_cpus;
150 static u_int    hyperthreading_cpus;
151 static cpumask_t        hyperthreading_cpus_mask;
152 static int      hyperthreading_allowed = 1;
153 static struct   sysctl_ctx_list logical_cpu_clist;
154 static u_int    bootMP_size;
155
156 static void
157 mem_range_AP_init(void)
158 {
159         if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
160                 mem_range_softc.mr_op->initAP(&mem_range_softc);
161 }
162
163 void
164 mp_topology(void)
165 {
166         struct cpu_group *group;
167         int logical_cpus;
168         int apic_id;
169         int groups;
170         int cpu;
171
172         /* Build the smp_topology map. */
173         /* Nothing to do if there is no HTT support. */
174         if ((cpu_feature & CPUID_HTT) == 0)
175                 return;
176         logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
177         if (logical_cpus <= 1)
178                 return;
179         group = &mp_groups[0];
180         groups = 1;
181         for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
182                 if (!cpu_info[apic_id].cpu_present)
183                         continue;
184                 /*
185                  * If the current group has members and we're not a logical
186                  * cpu, create a new group.
187                  */
188                 if (group->cg_count != 0 && (apic_id % logical_cpus) == 0) {
189                         group++;
190                         groups++;
191                 }
192                 group->cg_count++;
193                 group->cg_mask |= 1 << cpu;
194                 cpu++;
195         }
196
197         mp_top.ct_count = groups;
198         mp_top.ct_group = mp_groups;
199         smp_topology = &mp_top;
200 }
201
202
203 #ifdef KDB_STOP_NMI
204 volatile cpumask_t ipi_nmi_pending;
205 #endif 
206
207 /*
208  * Calculate usable address in base memory for AP trampoline code.
209  */
210 u_int
211 mp_bootaddress(u_int basemem)
212 {
213
214         bootMP_size = mptramp_end - mptramp_start;
215         boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
216         if (((basemem * 1024) - boot_address) < bootMP_size)
217                 boot_address -= PAGE_SIZE;      /* not enough, lower by 4k */
218         /* 3 levels of page table pages */
219         mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
220
221         return mptramp_pagetables;
222 }
223
224 void
225 cpu_add(u_int apic_id, char boot_cpu)
226 {
227
228         if (apic_id >= MAXCPU) {
229                 printf("SMP: CPU %d exceeds maximum CPU %d, ignoring\n",
230                     apic_id, MAXCPU - 1);
231                 return;
232         }
233         KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
234             apic_id));
235         cpu_info[apic_id].cpu_present = 1;
236         if (boot_cpu) {
237                 KASSERT(boot_cpu_id == -1,
238                     ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
239                     boot_cpu_id));
240                 boot_cpu_id = apic_id;
241                 cpu_info[apic_id].cpu_bsp = 1;
242         }
243         mp_ncpus++;
244         if (apic_id > mp_maxid)
245                 mp_maxid = apic_id;
246         if (bootverbose)
247                 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
248                     "AP");
249         
250 }
251
252 void
253 cpu_mp_setmaxid(void)
254 {
255
256         /*
257          * mp_maxid should be already set by calls to cpu_add().
258          * Just sanity check its value here.
259          */
260         if (mp_ncpus == 0)
261                 KASSERT(mp_maxid == 0,
262                     ("%s: mp_ncpus is zero, but mp_maxid is not", __func__));
263         else if (mp_ncpus == 1)
264                 mp_maxid = 0;
265         else
266                 KASSERT(mp_maxid >= mp_ncpus - 1,
267                     ("%s: counters out of sync: max %d, count %d", __func__,
268                         mp_maxid, mp_ncpus));
269                 
270 }
271
272 int
273 cpu_mp_probe(void)
274 {
275
276         /*
277          * Always record BSP in CPU map so that the mbuf init code works
278          * correctly.
279          */
280         all_cpus = 1;
281         if (mp_ncpus == 0) {
282                 /*
283                  * No CPUs were found, so this must be a UP system.  Setup
284                  * the variables to represent a system with a single CPU
285                  * with an id of 0.
286                  */
287                 mp_ncpus = 1;
288                 return (0);
289         }
290
291         /* At least one CPU was found. */
292         if (mp_ncpus == 1) {
293                 /*
294                  * One CPU was found, so this must be a UP system with
295                  * an I/O APIC.
296                  */
297                 mp_maxid = 0;
298                 return (0);
299         }
300
301         /* At least two CPUs were found. */
302         return (1);
303 }
304
305 /*
306  * Initialize the IPI handlers and start up the AP's.
307  */
308 void
309 cpu_mp_start(void)
310 {
311         int i;
312         u_int threads_per_cache, p[4];
313
314         /* Initialize the logical ID to APIC ID table. */
315         for (i = 0; i < MAXCPU; i++) {
316                 cpu_apic_ids[i] = -1;
317                 cpu_ipi_pending[i] = 0;
318         }
319
320         /* Install an inter-CPU IPI for TLB invalidation */
321         setidt(IPI_INVLTLB, IDTVEC(invltlb), SDT_SYSIGT, SEL_KPL, 0);
322         setidt(IPI_INVLPG, IDTVEC(invlpg), SDT_SYSIGT, SEL_KPL, 0);
323         setidt(IPI_INVLRNG, IDTVEC(invlrng), SDT_SYSIGT, SEL_KPL, 0);
324         
325         /* Install an inter-CPU IPI for all-CPU rendezvous */
326         setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous), SDT_SYSIGT, SEL_KPL, 0);
327
328         /* Install generic inter-CPU IPI handler */
329         setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
330                SDT_SYSIGT, SEL_KPL, 0);
331
332         /* Install an inter-CPU IPI for CPU stop/restart */
333         setidt(IPI_STOP, IDTVEC(cpustop), SDT_SYSIGT, SEL_KPL, 0);
334
335         /* Set boot_cpu_id if needed. */
336         if (boot_cpu_id == -1) {
337                 boot_cpu_id = PCPU_GET(apic_id);
338                 cpu_info[boot_cpu_id].cpu_bsp = 1;
339         } else
340                 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
341                     ("BSP's APIC ID doesn't match boot_cpu_id"));
342         cpu_apic_ids[0] = boot_cpu_id;
343
344         /* Start each Application Processor */
345         start_all_aps();
346
347         /* Setup the initial logical CPUs info. */
348         logical_cpus = logical_cpus_mask = 0;
349         if (cpu_feature & CPUID_HTT)
350                 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
351
352         /*
353          * Work out if hyperthreading is *really* enabled.  This
354          * is made really ugly by the fact that processors lie: Dual
355          * core processors claim to be hyperthreaded even when they're
356          * not, presumably because they want to be treated the same
357          * way as HTT with respect to per-cpu software licensing.
358          * At the time of writing (May 12, 2005) the only hyperthreaded
359          * cpus are from Intel, and Intel's dual-core processors can be
360          * identified via the "deterministic cache parameters" cpuid
361          * calls.
362          */
363         /*
364          * First determine if this is an Intel processor which claims
365          * to have hyperthreading support.
366          */
367         if ((cpu_feature & CPUID_HTT) &&
368             (strcmp(cpu_vendor, "GenuineIntel") == 0)) {
369                 /*
370                  * If the "deterministic cache parameters" cpuid calls
371                  * are available, use them.
372                  */
373                 if (cpu_high >= 4) {
374                         /* Ask the processor about up to 32 caches. */
375                         for (i = 0; i < 32; i++) {
376                                 cpuid_count(4, i, p);
377                                 threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
378                                 if (hyperthreading_cpus < threads_per_cache)
379                                         hyperthreading_cpus = threads_per_cache;
380                                 if ((p[0] & 0x1f) == 0)
381                                         break;
382                         }
383                 }
384
385                 /*
386                  * If the deterministic cache parameters are not
387                  * available, or if no caches were reported to exist,
388                  * just accept what the HTT flag indicated.
389                  */
390                 if (hyperthreading_cpus == 0)
391                         hyperthreading_cpus = logical_cpus;
392         }
393
394         set_logical_apic_ids();
395 }
396
397
398 /*
399  * Print various information about the SMP system hardware and setup.
400  */
401 void
402 cpu_mp_announce(void)
403 {
404         int i, x;
405
406         /* List CPUs */
407         printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
408         for (i = 1, x = 0; x < MAXCPU; x++) {
409                 if (!cpu_info[x].cpu_present || cpu_info[x].cpu_bsp)
410                         continue;
411                 if (cpu_info[x].cpu_disabled)
412                         printf("  cpu (AP): APIC ID: %2d (disabled)\n", x);
413                 else {
414                         KASSERT(i < mp_ncpus,
415                             ("mp_ncpus and actual cpus are out of whack"));
416                         printf(" cpu%d (AP): APIC ID: %2d\n", i++, x);
417                 }
418         }
419 }
420
421 /*
422  * AP CPU's call this to initialize themselves.
423  */
424 void
425 init_secondary(void)
426 {
427         struct pcpu *pc;
428         u_int64_t msr, cr0;
429         int cpu, gsel_tss;
430
431         /* Set by the startup code for us to use */
432         cpu = bootAP;
433
434         /* Init tss */
435         common_tss[cpu] = common_tss[0];
436         common_tss[cpu].tss_rsp0 = 0;   /* not used until after switch */
437         common_tss[cpu].tss_iobase = sizeof(struct amd64tss);
438         common_tss[cpu].tss_ist1 = (long)&doublefault_stack[PAGE_SIZE];
439
440         gdt_segs[GPROC0_SEL].ssd_base = (long) &common_tss[cpu];
441         ssdtosyssd(&gdt_segs[GPROC0_SEL],
442            (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
443
444         lgdt(&r_gdt);                   /* does magic intra-segment return */
445
446         /* Get per-cpu data */
447         pc = &__pcpu[cpu];
448
449         /* prime data page for it to use */
450         pcpu_init(pc, cpu, sizeof(struct pcpu));
451         pc->pc_apic_id = cpu_apic_ids[cpu];
452         pc->pc_prvspace = pc;
453         pc->pc_curthread = 0;
454         pc->pc_tssp = &common_tss[cpu];
455         pc->pc_rsp0 = 0;
456
457         wrmsr(MSR_FSBASE, 0);           /* User value */
458         wrmsr(MSR_GSBASE, (u_int64_t)pc);
459         wrmsr(MSR_KGSBASE, (u_int64_t)pc);      /* XXX User value while we're in the kernel */
460
461         lidt(&r_idt);
462
463         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
464         ltr(gsel_tss);
465
466         /*
467          * Set to a known state:
468          * Set by mpboot.s: CR0_PG, CR0_PE
469          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
470          */
471         cr0 = rcr0();
472         cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
473         load_cr0(cr0);
474
475         /* Set up the fast syscall stuff */
476         msr = rdmsr(MSR_EFER) | EFER_SCE;
477         wrmsr(MSR_EFER, msr);
478         wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
479         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
480         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
481               ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
482         wrmsr(MSR_STAR, msr);
483         wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
484
485         /* Disable local APIC just to be sure. */
486         lapic_disable();
487
488         /* signal our startup to the BSP. */
489         mp_naps++;
490
491         /* Spin until the BSP releases the AP's. */
492         while (!aps_ready)
493                 ia32_pause();
494
495         /* set up CPU registers and state */
496         cpu_setregs();
497
498         /* set up SSE/NX registers */
499         initializecpu();
500
501         /* set up FPU state on the AP */
502         fpuinit();
503
504         /* A quick check from sanity claus */
505         if (PCPU_GET(apic_id) != lapic_id()) {
506                 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
507                 printf("SMP: actual apic_id = %d\n", lapic_id());
508                 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
509                 panic("cpuid mismatch! boom!!");
510         }
511
512         /* Initialize curthread. */
513         KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
514         PCPU_SET(curthread, PCPU_GET(idlethread));
515
516         mtx_lock_spin(&ap_boot_mtx);
517
518         /* Init local apic for irq's */
519         lapic_setup();
520
521         /* Set memory range attributes for this CPU to match the BSP */
522         mem_range_AP_init();
523
524         smp_cpus++;
525
526         CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
527         printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
528
529         /* Determine if we are a logical CPU. */
530         if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
531                 logical_cpus_mask |= PCPU_GET(cpumask);
532         
533         /* Determine if we are a hyperthread. */
534         if (hyperthreading_cpus > 1 &&
535             PCPU_GET(apic_id) % hyperthreading_cpus != 0)
536                 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
537
538         /* Build our map of 'other' CPUs. */
539         PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
540
541         if (bootverbose)
542                 lapic_dump("AP");
543
544         if (smp_cpus == mp_ncpus) {
545                 /* enable IPI's, tlb shootdown, freezes etc */
546                 atomic_store_rel_int(&smp_started, 1);
547                 smp_active = 1;  /* historic */
548         }
549
550         mtx_unlock_spin(&ap_boot_mtx);
551
552         /* wait until all the AP's are up */
553         while (smp_started == 0)
554                 ia32_pause();
555
556         /* ok, now grab sched_lock and enter the scheduler */
557         mtx_lock_spin(&sched_lock);
558
559         /*
560          * Correct spinlock nesting.  The idle thread context that we are
561          * borrowing was created so that it would start out with a single
562          * spin lock (sched_lock) held in fork_trampoline().  Since we've
563          * explicitly acquired locks in this function, the nesting count
564          * is now 2 rather than 1.  Since we are nested, calling
565          * spinlock_exit() will simply adjust the counts without allowing
566          * spin lock using code to interrupt us.
567          */
568         spinlock_exit();
569         KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
570
571         binuptime(PCPU_PTR(switchtime));
572         PCPU_SET(switchticks, ticks);
573
574         cpu_throw(NULL, choosethread());        /* doesn't return */
575
576         panic("scheduler returned us to %s", __func__);
577         /* NOTREACHED */
578 }
579
580 /*******************************************************************
581  * local functions and data
582  */
583
584 /*
585  * Set the APIC logical IDs.
586  *
587  * We want to cluster logical CPU's within the same APIC ID cluster.
588  * Since logical CPU's are aligned simply filling in the clusters in
589  * APIC ID order works fine.  Note that this does not try to balance
590  * the number of CPU's in each cluster. (XXX?)
591  */
592 static void
593 set_logical_apic_ids(void)
594 {
595         u_int apic_id, cluster, cluster_id;
596
597         /* Force us to allocate cluster 0 at the start. */
598         cluster = -1;
599         cluster_id = APIC_MAX_INTRACLUSTER_ID;
600         for (apic_id = 0; apic_id < MAXCPU; apic_id++) {
601                 if (!cpu_info[apic_id].cpu_present)
602                         continue;
603                 if (cluster_id == APIC_MAX_INTRACLUSTER_ID) {
604                         cluster = ioapic_next_logical_cluster();
605                         cluster_id = 0;
606                 } else
607                         cluster_id++;
608                 if (bootverbose)
609                         printf("APIC ID: physical %u, logical %u:%u\n",
610                             apic_id, cluster, cluster_id);
611                 lapic_set_logical_id(apic_id, cluster, cluster_id);
612         }
613 }
614
615 /*
616  * start each AP in our list
617  */
618 static int
619 start_all_aps(void)
620 {
621         vm_offset_t va = boot_address + KERNBASE;
622         u_int64_t *pt4, *pt3, *pt2;
623         u_int32_t mpbioswarmvec;
624         int apic_id, cpu, i;
625         u_char mpbiosreason;
626
627         mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
628
629         /* install the AP 1st level boot code */
630         pmap_kenter(va, boot_address);
631         pmap_invalidate_page(kernel_pmap, va);
632         bcopy(mptramp_start, (void *)va, bootMP_size);
633
634         /* Locate the page tables, they'll be below the trampoline */
635         pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
636         pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
637         pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
638
639         /* Create the initial 1GB replicated page tables */
640         for (i = 0; i < 512; i++) {
641                 /* Each slot of the level 4 pages points to the same level 3 page */
642                 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
643                 pt4[i] |= PG_V | PG_RW | PG_U;
644
645                 /* Each slot of the level 3 pages points to the same level 2 page */
646                 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
647                 pt3[i] |= PG_V | PG_RW | PG_U;
648
649                 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
650                 pt2[i] = i * (2 * 1024 * 1024);
651                 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
652         }
653
654         /* save the current value of the warm-start vector */
655         mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
656         outb(CMOS_REG, BIOS_RESET);
657         mpbiosreason = inb(CMOS_DATA);
658
659         /* setup a vector to our boot code */
660         *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
661         *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
662         outb(CMOS_REG, BIOS_RESET);
663         outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
664
665         /* start each AP */
666         for (cpu = 0, apic_id = 0; apic_id < MAXCPU; apic_id++) {
667
668                 /* Ignore non-existent CPUs and the BSP. */
669                 if (!cpu_info[apic_id].cpu_present ||
670                     cpu_info[apic_id].cpu_bsp)
671                         continue;
672
673                 /* Don't use this CPU if it has been disabled by a tunable. */
674                 if (resource_disabled("lapic", apic_id)) {
675                         cpu_info[apic_id].cpu_disabled = 1;
676                         mp_ncpus--;
677                         continue;
678                 }
679
680                 cpu++;
681
682                 /* save APIC ID for this logical ID */
683                 cpu_apic_ids[cpu] = apic_id;
684
685                 /* allocate and set up an idle stack data page */
686                 bootstacks[cpu] = (void *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
687                 doublefault_stack = (char *)kmem_alloc(kernel_map, PAGE_SIZE);
688
689                 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 8;
690                 bootAP = cpu;
691
692                 /* attempt to start the Application Processor */
693                 if (!start_ap(apic_id)) {
694                         /* restore the warmstart vector */
695                         *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
696                         panic("AP #%d (PHY# %d) failed!", cpu, apic_id);
697                 }
698
699                 all_cpus |= (1 << cpu);         /* record AP in CPU map */
700         }
701
702         /* build our map of 'other' CPUs */
703         PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
704
705         /* restore the warmstart vector */
706         *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
707
708         outb(CMOS_REG, BIOS_RESET);
709         outb(CMOS_DATA, mpbiosreason);
710
711         /* number of APs actually started */
712         return mp_naps;
713 }
714
715
716 /*
717  * This function starts the AP (application processor) identified
718  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
719  * to accomplish this.  This is necessary because of the nuances
720  * of the different hardware we might encounter.  It isn't pretty,
721  * but it seems to work.
722  */
723 static int
724 start_ap(int apic_id)
725 {
726         int vector, ms;
727         int cpus;
728
729         /* calculate the vector */
730         vector = (boot_address >> 12) & 0xff;
731
732         /* used as a watchpoint to signal AP startup */
733         cpus = mp_naps;
734
735         /*
736          * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
737          * and running the target CPU. OR this INIT IPI might be latched (P5
738          * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
739          * ignored.
740          */
741
742         /* do an INIT IPI: assert RESET */
743         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
744             APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
745
746         /* wait for pending status end */
747         lapic_ipi_wait(-1);
748
749         /* do an INIT IPI: deassert RESET */
750         lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
751             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
752
753         /* wait for pending status end */
754         DELAY(10000);           /* wait ~10mS */
755         lapic_ipi_wait(-1);
756
757         /*
758          * next we do a STARTUP IPI: the previous INIT IPI might still be
759          * latched, (P5 bug) this 1st STARTUP would then terminate
760          * immediately, and the previously started INIT IPI would continue. OR
761          * the previous INIT IPI has already run. and this STARTUP IPI will
762          * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
763          * will run.
764          */
765
766         /* do a STARTUP IPI */
767         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
768             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
769             vector, apic_id);
770         lapic_ipi_wait(-1);
771         DELAY(200);             /* wait ~200uS */
772
773         /*
774          * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
775          * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
776          * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
777          * recognized after hardware RESET or INIT IPI.
778          */
779
780         lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
781             APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
782             vector, apic_id);
783         lapic_ipi_wait(-1);
784         DELAY(200);             /* wait ~200uS */
785
786         /* Wait up to 5 seconds for it to start. */
787         for (ms = 0; ms < 5000; ms++) {
788                 if (mp_naps > cpus)
789                         return 1;       /* return SUCCESS */
790                 DELAY(1000);
791         }
792         return 0;               /* return FAILURE */
793 }
794
795 /*
796  * Flush the TLB on all other CPU's
797  */
798 static void
799 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
800 {
801         u_int ncpu;
802
803         ncpu = mp_ncpus - 1;    /* does not shootdown self */
804         if (ncpu < 1)
805                 return;         /* no other cpus */
806         mtx_assert(&smp_ipi_mtx, MA_OWNED);
807         smp_tlb_addr1 = addr1;
808         smp_tlb_addr2 = addr2;
809         atomic_store_rel_int(&smp_tlb_wait, 0);
810         ipi_all_but_self(vector);
811         while (smp_tlb_wait < ncpu)
812                 ia32_pause();
813 }
814
815 static void
816 smp_targeted_tlb_shootdown(u_int mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
817 {
818         int ncpu, othercpus;
819
820         othercpus = mp_ncpus - 1;
821         if (mask == (u_int)-1) {
822                 ncpu = othercpus;
823                 if (ncpu < 1)
824                         return;
825         } else {
826                 mask &= ~PCPU_GET(cpumask);
827                 if (mask == 0)
828                         return;
829                 ncpu = bitcount32(mask);
830                 if (ncpu > othercpus) {
831                         /* XXX this should be a panic offence */
832                         printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
833                             ncpu, othercpus);
834                         ncpu = othercpus;
835                 }
836                 /* XXX should be a panic, implied by mask == 0 above */
837                 if (ncpu < 1)
838                         return;
839         }
840         mtx_assert(&smp_ipi_mtx, MA_OWNED);
841         smp_tlb_addr1 = addr1;
842         smp_tlb_addr2 = addr2;
843         atomic_store_rel_int(&smp_tlb_wait, 0);
844         if (mask == (u_int)-1)
845                 ipi_all_but_self(vector);
846         else
847                 ipi_selected(mask, vector);
848         while (smp_tlb_wait < ncpu)
849                 ia32_pause();
850 }
851
852 void
853 smp_invltlb(void)
854 {
855
856         if (smp_started) {
857                 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
858         }
859 }
860
861 void
862 smp_invlpg(vm_offset_t addr)
863 {
864
865         if (smp_started)
866                 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
867 }
868
869 void
870 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
871 {
872
873         if (smp_started) {
874                 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
875         }
876 }
877
878 void
879 smp_masked_invltlb(u_int mask)
880 {
881
882         if (smp_started) {
883                 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
884         }
885 }
886
887 void
888 smp_masked_invlpg(u_int mask, vm_offset_t addr)
889 {
890
891         if (smp_started) {
892                 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
893         }
894 }
895
896 void
897 smp_masked_invlpg_range(u_int mask, vm_offset_t addr1, vm_offset_t addr2)
898 {
899
900         if (smp_started) {
901                 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
902         }
903 }
904
905
906 void
907 ipi_bitmap_handler(struct clockframe frame)
908 {
909         int cpu = PCPU_GET(cpuid);
910         u_int ipi_bitmap;
911
912         ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
913
914 #ifdef IPI_PREEMPTION
915         if (ipi_bitmap & IPI_PREEMPT) {
916                 mtx_lock_spin(&sched_lock);
917                 /* Don't preempt the idle thread */
918                 if (curthread->td_priority <  PRI_MIN_IDLE) {
919                         struct thread *running_thread = curthread;
920                         if (running_thread->td_critnest > 1) 
921                                 running_thread->td_owepreempt = 1;
922                         else            
923                                 mi_switch(SW_INVOL | SW_PREEMPT, NULL);
924                 }
925                 mtx_unlock_spin(&sched_lock);
926         }
927 #endif
928
929         /* Nothing to do for AST */
930 }
931
932 /*
933  * send an IPI to a set of cpus.
934  */
935 void
936 ipi_selected(u_int32_t cpus, u_int ipi)
937 {
938         int cpu;
939         u_int bitmap = 0;
940         u_int old_pending;
941         u_int new_pending;
942
943         if (IPI_IS_BITMAPED(ipi)) { 
944                 bitmap = 1 << ipi;
945                 ipi = IPI_BITMAP_VECTOR;
946         }
947
948         CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
949         while ((cpu = ffs(cpus)) != 0) {
950                 cpu--;
951                 cpus &= ~(1 << cpu);
952
953                 KASSERT(cpu_apic_ids[cpu] != -1,
954                     ("IPI to non-existent CPU %d", cpu));
955
956                 if (bitmap) {
957                         do {
958                                 old_pending = cpu_ipi_pending[cpu];
959                                 new_pending = old_pending | bitmap;
960                         } while  (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));  
961
962                         if (old_pending)
963                                 continue;
964                 }
965
966                 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
967         }
968
969 }
970
971 /*
972  * send an IPI INTerrupt containing 'vector' to all CPUs, including myself
973  */
974 void
975 ipi_all(u_int ipi)
976 {
977
978         CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
979         lapic_ipi_vectored(ipi, APIC_IPI_DEST_ALL);
980 }
981
982 /*
983  * send an IPI to all CPUs EXCEPT myself
984  */
985 void
986 ipi_all_but_self(u_int ipi)
987 {
988
989         CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
990         lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
991 }
992
993 /*
994  * send an IPI to myself
995  */
996 void
997 ipi_self(u_int ipi)
998 {
999
1000         CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1001         lapic_ipi_vectored(ipi, APIC_IPI_DEST_SELF);
1002 }
1003
1004 #ifdef KDB_STOP_NMI
1005 /*
1006  * send NMI IPI to selected CPUs
1007  */
1008
1009 #define BEFORE_SPIN     1000000
1010
1011 void
1012 ipi_nmi_selected(u_int32_t cpus)
1013 {
1014
1015         int cpu;
1016         register_t icrlo;
1017
1018         icrlo = APIC_DELMODE_NMI | APIC_DESTMODE_PHY | APIC_LEVEL_ASSERT 
1019                 | APIC_TRIGMOD_EDGE; 
1020         
1021         CTR2(KTR_SMP, "%s: cpus: %x nmi", __func__, cpus);
1022
1023
1024         atomic_set_int(&ipi_nmi_pending, cpus);
1025
1026
1027         while ((cpu = ffs(cpus)) != 0) {
1028                 cpu--;
1029                 cpus &= ~(1 << cpu);
1030
1031                 KASSERT(cpu_apic_ids[cpu] != -1,
1032                     ("IPI NMI to non-existent CPU %d", cpu));
1033                 
1034                 /* Wait for an earlier IPI to finish. */
1035                 if (!lapic_ipi_wait(BEFORE_SPIN))
1036                         panic("ipi_nmi_selected: previous IPI has not cleared");
1037
1038                 lapic_ipi_raw(icrlo,cpu_apic_ids[cpu]);
1039         }
1040 }
1041
1042
1043 int
1044 ipi_nmi_handler()
1045 {
1046         int cpu  = PCPU_GET(cpuid);
1047
1048         if(!(atomic_load_acq_int(&ipi_nmi_pending) & (1 << cpu)))
1049                 return 1;
1050
1051         atomic_clear_int(&ipi_nmi_pending,1 << cpu);
1052
1053         savectx(&stoppcbs[cpu]);
1054
1055         /* Indicate that we are stopped */
1056         atomic_set_int(&stopped_cpus,1 << cpu);
1057
1058
1059         /* Wait for restart */
1060         while(!(atomic_load_acq_int(&started_cpus) & (1 << cpu)))
1061             ia32_pause();
1062
1063         atomic_clear_int(&started_cpus,1 << cpu);
1064         atomic_clear_int(&stopped_cpus,1 << cpu);
1065
1066         if(cpu == 0 && cpustop_restartfunc != NULL)
1067                 cpustop_restartfunc();
1068
1069         return 0;
1070 }
1071      
1072 #endif /* KDB_STOP_NMI */
1073
1074 /*
1075  * This is called once the rest of the system is up and running and we're
1076  * ready to let the AP's out of the pen.
1077  */
1078 static void
1079 release_aps(void *dummy __unused)
1080 {
1081
1082         if (mp_ncpus == 1) 
1083                 return;
1084         mtx_lock_spin(&sched_lock);
1085         atomic_store_rel_int(&aps_ready, 1);
1086         while (smp_started == 0)
1087                 ia32_pause();
1088         mtx_unlock_spin(&sched_lock);
1089 }
1090 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1091
1092 static int
1093 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1094 {
1095         u_int mask;
1096         int error;
1097
1098         mask = hlt_cpus_mask;
1099         error = sysctl_handle_int(oidp, &mask, 0, req);
1100         if (error || !req->newptr)
1101                 return (error);
1102
1103         if (logical_cpus_mask != 0 &&
1104             (mask & logical_cpus_mask) == logical_cpus_mask)
1105                 hlt_logical_cpus = 1;
1106         else
1107                 hlt_logical_cpus = 0;
1108
1109         if (! hyperthreading_allowed)
1110                 mask |= hyperthreading_cpus_mask;
1111
1112         if ((mask & all_cpus) == all_cpus)
1113                 mask &= ~(1<<0);
1114         hlt_cpus_mask = mask;
1115         return (error);
1116 }
1117 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1118     0, 0, sysctl_hlt_cpus, "IU",
1119     "Bitmap of CPUs to halt.  101 (binary) will halt CPUs 0 and 2.");
1120
1121 static int
1122 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1123 {
1124         int disable, error;
1125
1126         disable = hlt_logical_cpus;
1127         error = sysctl_handle_int(oidp, &disable, 0, req);
1128         if (error || !req->newptr)
1129                 return (error);
1130
1131         if (disable)
1132                 hlt_cpus_mask |= logical_cpus_mask;
1133         else
1134                 hlt_cpus_mask &= ~logical_cpus_mask;
1135
1136         if (! hyperthreading_allowed)
1137                 hlt_cpus_mask |= hyperthreading_cpus_mask;
1138
1139         if ((hlt_cpus_mask & all_cpus) == all_cpus)
1140                 hlt_cpus_mask &= ~(1<<0);
1141
1142         hlt_logical_cpus = disable;
1143         return (error);
1144 }
1145
1146 static int
1147 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1148 {
1149         int allowed, error;
1150
1151         allowed = hyperthreading_allowed;
1152         error = sysctl_handle_int(oidp, &allowed, 0, req);
1153         if (error || !req->newptr)
1154                 return (error);
1155
1156         if (allowed)
1157                 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1158         else
1159                 hlt_cpus_mask |= hyperthreading_cpus_mask;
1160
1161         if (logical_cpus_mask != 0 &&
1162             (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1163                 hlt_logical_cpus = 1;
1164         else
1165                 hlt_logical_cpus = 0;
1166
1167         if ((hlt_cpus_mask & all_cpus) == all_cpus)
1168                 hlt_cpus_mask &= ~(1<<0);
1169
1170         hyperthreading_allowed = allowed;
1171         return (error);
1172 }
1173
1174 static void
1175 cpu_hlt_setup(void *dummy __unused)
1176 {
1177
1178         if (logical_cpus_mask != 0) {
1179                 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1180                     &hlt_logical_cpus);
1181                 sysctl_ctx_init(&logical_cpu_clist);
1182                 SYSCTL_ADD_PROC(&logical_cpu_clist,
1183                     SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1184                     "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1185                     sysctl_hlt_logical_cpus, "IU", "");
1186                 SYSCTL_ADD_UINT(&logical_cpu_clist,
1187                     SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1188                     "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1189                     &logical_cpus_mask, 0, "");
1190
1191                 if (hlt_logical_cpus)
1192                         hlt_cpus_mask |= logical_cpus_mask;
1193
1194                 /*
1195                  * If necessary for security purposes, force
1196                  * hyperthreading off, regardless of the value
1197                  * of hlt_logical_cpus.
1198                  */
1199                 if (hyperthreading_cpus_mask) {
1200                         TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
1201                             &hyperthreading_allowed);
1202                         SYSCTL_ADD_PROC(&logical_cpu_clist,
1203                             SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1204                             "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1205                             0, 0, sysctl_hyperthreading_allowed, "IU", "");
1206                         if (! hyperthreading_allowed)
1207                                 hlt_cpus_mask |= hyperthreading_cpus_mask;
1208                 }
1209         }
1210 }
1211 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1212
1213 int
1214 mp_grab_cpu_hlt(void)
1215 {
1216         u_int mask = PCPU_GET(cpumask);
1217 #ifdef MP_WATCHDOG
1218         u_int cpuid = PCPU_GET(cpuid);
1219 #endif
1220         int retval;
1221
1222 #ifdef MP_WATCHDOG
1223         ap_watchdog(cpuid);
1224 #endif
1225
1226         retval = mask & hlt_cpus_mask;
1227         while (mask & hlt_cpus_mask)
1228                 __asm __volatile("sti; hlt" : : : "memory");
1229         return (retval);
1230 }