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