Merge branch 'vendor/LDNS'
[dragonfly.git] / sys / platform / pc32 / 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  * $FreeBSD: src/sys/i386/i386/mp_machdep.c,v 1.115.2.15 2003/03/14 21:22:35 jhb Exp $
26  */
27
28 #include "opt_cpu.h"
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/sysctl.h>
34 #include <sys/malloc.h>
35 #include <sys/memrange.h>
36 #include <sys/cons.h>   /* cngetc() */
37 #include <sys/machintr.h>
38
39 #include <vm/vm.h>
40 #include <vm/vm_param.h>
41 #include <vm/pmap.h>
42 #include <vm/vm_kern.h>
43 #include <vm/vm_extern.h>
44 #include <sys/lock.h>
45 #include <vm/vm_map.h>
46 #include <sys/user.h>
47 #ifdef GPROF 
48 #include <sys/gmon.h>
49 #endif
50
51 #include <sys/mplock2.h>
52
53 #include <machine/smp.h>
54 #include <machine_base/apic/apicreg.h>
55 #include <machine/atomic.h>
56 #include <machine/cpufunc.h>
57 #include <machine/cputypes.h>
58 #include <machine_base/icu/icu_var.h>
59 #include <machine_base/apic/ioapic_abi.h>
60 #include <machine_base/apic/lapic.h>
61 #include <machine_base/apic/ioapic.h>
62 #include <machine/psl.h>
63 #include <machine/segments.h>
64 #include <machine/tss.h>
65 #include <machine/specialreg.h>
66 #include <machine/globaldata.h>
67 #include <machine/pmap_inval.h>
68
69 #include <machine/md_var.h>             /* setidt() */
70 #include <machine_base/icu/icu.h>       /* IPIs */
71 #include <machine/intr_machdep.h>       /* IPIs */
72
73 #define WARMBOOT_TARGET         0
74 #define WARMBOOT_OFF            (KERNBASE + 0x0467)
75 #define WARMBOOT_SEG            (KERNBASE + 0x0469)
76
77 #define CMOS_REG                (0x70)
78 #define CMOS_DATA               (0x71)
79 #define BIOS_RESET              (0x0f)
80 #define BIOS_WARM               (0x0a)
81
82 /*
83  * this code MUST be enabled here and in mpboot.s.
84  * it follows the very early stages of AP boot by placing values in CMOS ram.
85  * it NORMALLY will never be needed and thus the primitive method for enabling.
86  *
87  */
88 #if defined(CHECK_POINTS)
89 #define CHECK_READ(A)    (outb(CMOS_REG, (A)), inb(CMOS_DATA))
90 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
91
92 #define CHECK_INIT(D);                          \
93         CHECK_WRITE(0x34, (D));                 \
94         CHECK_WRITE(0x35, (D));                 \
95         CHECK_WRITE(0x36, (D));                 \
96         CHECK_WRITE(0x37, (D));                 \
97         CHECK_WRITE(0x38, (D));                 \
98         CHECK_WRITE(0x39, (D));
99
100 #define CHECK_PRINT(S);                         \
101         kprintf("%s: %d, %d, %d, %d, %d, %d\n", \
102            (S),                                 \
103            CHECK_READ(0x34),                    \
104            CHECK_READ(0x35),                    \
105            CHECK_READ(0x36),                    \
106            CHECK_READ(0x37),                    \
107            CHECK_READ(0x38),                    \
108            CHECK_READ(0x39));
109
110 #else                           /* CHECK_POINTS */
111
112 #define CHECK_INIT(D)
113 #define CHECK_PRINT(S)
114
115 #endif                          /* CHECK_POINTS */
116
117 /*
118  * Values to send to the POST hardware.
119  */
120 #define MP_BOOTADDRESS_POST     0x10
121 #define MP_PROBE_POST           0x11
122 #define MPTABLE_PASS1_POST      0x12
123
124 #define MP_START_POST           0x13
125 #define MP_ENABLE_POST          0x14
126 #define MPTABLE_PASS2_POST      0x15
127
128 #define START_ALL_APS_POST      0x16
129 #define INSTALL_AP_TRAMP_POST   0x17
130 #define START_AP_POST           0x18
131
132 #define MP_ANNOUNCE_POST        0x19
133
134 /** XXX FIXME: where does this really belong, isa.h/isa.c perhaps? */
135 int     current_postcode;
136
137 /** XXX FIXME: what system files declare these??? */
138 extern struct region_descriptor r_gdt, r_idt;
139
140 extern int nkpt;
141 extern int naps;
142
143 int64_t tsc0_offset;
144 extern int64_t tsc_offsets[];
145
146 /* AP uses this during bootstrap.  Do not staticize.  */
147 char *bootSTK;
148 static int bootAP;
149
150 /* Hotwire a 0->4MB V==P mapping */
151 extern pt_entry_t *KPTphys;
152
153 /*
154  * SMP page table page.  Setup by locore to point to a page table
155  * page from which we allocate per-cpu privatespace areas io_apics,
156  * and so forth.
157  */
158 extern pt_entry_t *SMPpt;
159
160 struct pcb stoppcbs[MAXCPU];
161
162 /*
163  * Local data and functions.
164  */
165
166 static u_int    boot_address;
167 static int      mp_finish;
168 static int      mp_finish_lapic;
169
170 static int      start_all_aps(u_int boot_addr);
171 static void     install_ap_tramp(u_int boot_addr);
172 static int      start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest);
173 static int      smitest(void);
174 static void     mp_bsp_simple_setup(void);
175
176 static cpumask_t smp_startup_mask = 1;  /* which cpus have been started */
177 static cpumask_t smp_lapic_mask = 1;    /* which cpus have lapic been inited */
178 cpumask_t smp_active_mask = 1;  /* which cpus are ready for IPIs etc? */
179 SYSCTL_INT(_machdep, OID_AUTO, smp_active, CTLFLAG_RD, &smp_active_mask, 0, "");
180
181 /* Local data for detecting CPU TOPOLOGY */
182 static int core_bits = 0;
183 static int logical_CPU_bits = 0;
184
185
186 /*
187  * Calculate usable address in base memory for AP trampoline code.
188  */
189 u_int
190 mp_bootaddress(u_int basemem)
191 {
192         POSTCODE(MP_BOOTADDRESS_POST);
193
194         boot_address = basemem & ~0xfff;        /* round down to 4k boundary */
195         if ((basemem - boot_address) < bootMP_size)
196                 boot_address -= 4096;   /* not enough, lower by 4k */
197
198         return boot_address;
199 }
200
201 /*
202  * Print various information about the SMP system hardware and setup.
203  */
204 void
205 mp_announce(void)
206 {
207         int     x;
208
209         POSTCODE(MP_ANNOUNCE_POST);
210
211         kprintf("DragonFly/MP: Multiprocessor motherboard\n");
212         kprintf(" cpu0 (BSP): apic id: %2d\n", CPUID_TO_APICID(0));
213         for (x = 1; x <= naps; ++x)
214                 kprintf(" cpu%d (AP):  apic id: %2d\n", x, CPUID_TO_APICID(x));
215
216         if (!ioapic_enable)
217                 kprintf(" Warning: APIC I/O disabled\n");
218 }
219
220 /*
221  * AP cpu's call this to sync up protected mode.
222  *
223  * WARNING!  We must ensure that the cpu is sufficiently initialized to
224  * be able to use to the FP for our optimized bzero/bcopy code before
225  * we enter more mainstream C code.
226  *
227  * WARNING! %fs is not set up on entry.  This routine sets up %fs.
228  */
229 void
230 init_secondary(void)
231 {
232         int     gsel_tss;
233         int     x, myid = bootAP;
234         u_int   cr0;
235         struct mdglobaldata *md;
236         struct privatespace *ps;
237
238         ps = &CPU_prvspace[myid];
239
240         gdt_segs[GPRIV_SEL].ssd_base = (int)ps;
241         gdt_segs[GPROC0_SEL].ssd_base =
242                 (int) &ps->mdglobaldata.gd_common_tss;
243         ps->mdglobaldata.mi.gd_prvspace = ps;
244
245         for (x = 0; x < NGDT; x++) {
246                 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
247         }
248
249         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
250         r_gdt.rd_base = (int) &gdt[myid * NGDT];
251         lgdt(&r_gdt);                   /* does magic intra-segment return */
252
253         lidt(&r_idt);
254
255         lldt(_default_ldt);
256         mdcpu->gd_currentldt = _default_ldt;
257
258         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
259         gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
260
261         md = mdcpu;     /* loaded through %fs:0 (mdglobaldata.mi.gd_prvspace)*/
262
263         md->gd_common_tss.tss_esp0 = 0; /* not used until after switch */
264         md->gd_common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
265         md->gd_common_tss.tss_ioopt = (sizeof md->gd_common_tss) << 16;
266         md->gd_tss_gdt = &gdt[myid * NGDT + GPROC0_SEL].sd;
267         md->gd_common_tssd = *md->gd_tss_gdt;
268         ltr(gsel_tss);
269
270         /*
271          * Set to a known state:
272          * Set by mpboot.s: CR0_PG, CR0_PE
273          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
274          */
275         cr0 = rcr0();
276         cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
277         load_cr0(cr0);
278         pmap_set_opt();         /* PSE/4MB pages, etc */
279
280         pmap_init_pat();        /* Page Attribute Table */
281
282         /* set up CPU registers and state */
283         cpu_setregs();
284
285         /* set up FPU state on the AP */
286         npxinit(__INITIAL_NPXCW__);
287
288         /* set up SSE registers */
289         enable_sse();
290 }
291
292 /*******************************************************************
293  * local functions and data
294  */
295
296 /*
297  * Start the SMP system
298  */
299 static void
300 mp_start_aps(void *dummy __unused)
301 {
302         if (lapic_enable) {
303                 /* start each Application Processor */
304                 start_all_aps(boot_address);
305         } else {
306                 mp_bsp_simple_setup();
307         }
308 }
309 SYSINIT(startaps, SI_BOOT2_START_APS, SI_ORDER_FIRST, mp_start_aps, NULL)
310
311 /*
312  * start each AP in our list
313  */
314 static int
315 start_all_aps(u_int boot_addr)
316 {
317         int     x, i, pg;
318         int     shift;
319         int     smicount;
320         int     smibest;
321         int     smilast;
322         u_char  mpbiosreason;
323         u_long  mpbioswarmvec;
324         struct mdglobaldata *gd;
325         struct privatespace *ps;
326         char *stack;
327         uintptr_t kptbase;
328
329         POSTCODE(START_ALL_APS_POST);
330
331         /* install the AP 1st level boot code */
332         install_ap_tramp(boot_addr);
333
334
335         /* save the current value of the warm-start vector */
336         mpbioswarmvec = *((u_long *) WARMBOOT_OFF);
337         outb(CMOS_REG, BIOS_RESET);
338         mpbiosreason = inb(CMOS_DATA);
339
340         /* setup a vector to our boot code */
341         *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
342         *((volatile u_short *) WARMBOOT_SEG) = (boot_addr >> 4);
343         outb(CMOS_REG, BIOS_RESET);
344         outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
345
346         /*
347          * If we have a TSC we can figure out the SMI interrupt rate.
348          * The SMI does not necessarily use a constant rate.  Spend
349          * up to 250ms trying to figure it out.
350          */
351         smibest = 0;
352         if (cpu_feature & CPUID_TSC) {
353                 set_apic_timer(275000);
354                 smilast = read_apic_timer();
355                 for (x = 0; x < 20 && read_apic_timer(); ++x) {
356                         smicount = smitest();
357                         if (smibest == 0 || smilast - smicount < smibest)
358                                 smibest = smilast - smicount;
359                         smilast = smicount;
360                 }
361                 if (smibest > 250000)
362                         smibest = 0;
363                 if (smibest) {
364                         smibest = smibest * (int64_t)1000000 /
365                                   get_apic_timer_frequency();
366                 }
367         }
368         if (smibest)
369                 kprintf("SMI Frequency (worst case): %d Hz (%d us)\n",
370                         1000000 / smibest, smibest);
371
372
373         /* set up temporary P==V mapping for AP boot */
374         /* XXX this is a hack, we should boot the AP on its own stack/PTD */
375         kptbase = (uintptr_t)(void *)KPTphys;
376         for (x = 0; x < NKPT; x++) {
377                 PTD[x] = (pd_entry_t)(PG_V | PG_RW |
378                     ((kptbase + x * PAGE_SIZE) & PG_FRAME));
379         }
380         cpu_invltlb();
381
382         /* start each AP */
383         for (x = 1; x <= naps; ++x) {
384
385                 /* This is a bit verbose, it will go away soon.  */
386
387                 /* first page of AP's private space */
388                 pg = x * i386_btop(sizeof(struct privatespace));
389
390                 /* allocate new private data page(s) */
391                 gd = (struct mdglobaldata *)kmem_alloc(&kernel_map, 
392                                 MDGLOBALDATA_BASEALLOC_SIZE);
393                 /* wire it into the private page table page */
394                 for (i = 0; i < MDGLOBALDATA_BASEALLOC_SIZE; i += PAGE_SIZE) {
395                         SMPpt[pg + i / PAGE_SIZE] = (pt_entry_t)
396                             (PG_V | PG_RW | vtophys_pte((char *)gd + i));
397                 }
398                 pg += MDGLOBALDATA_BASEALLOC_PAGES;
399
400                 SMPpt[pg + 0] = 0;              /* *gd_CMAP1 */
401                 SMPpt[pg + 1] = 0;              /* *gd_CMAP2 */
402                 SMPpt[pg + 2] = 0;              /* *gd_CMAP3 */
403                 SMPpt[pg + 3] = 0;              /* *gd_PMAP1 */
404
405                 /* allocate and set up an idle stack data page */
406                 stack = (char *)kmem_alloc(&kernel_map, UPAGES*PAGE_SIZE);
407                 for (i = 0; i < UPAGES; i++) {
408                         SMPpt[pg + 4 + i] = (pt_entry_t)
409                             (PG_V | PG_RW | vtophys_pte(PAGE_SIZE * i + stack));
410                 }
411
412                 gd = &CPU_prvspace[x].mdglobaldata;     /* official location */
413                 bzero(gd, sizeof(*gd));
414                 gd->mi.gd_prvspace = ps = &CPU_prvspace[x];
415
416                 /* prime data page for it to use */
417                 mi_gdinit(&gd->mi, x);
418                 cpu_gdinit(gd, x);
419                 gd->gd_CMAP1 = &SMPpt[pg + 0];
420                 gd->gd_CMAP2 = &SMPpt[pg + 1];
421                 gd->gd_CMAP3 = &SMPpt[pg + 2];
422                 gd->gd_PMAP1 = &SMPpt[pg + 3];
423                 gd->gd_CADDR1 = ps->CPAGE1;
424                 gd->gd_CADDR2 = ps->CPAGE2;
425                 gd->gd_CADDR3 = ps->CPAGE3;
426                 gd->gd_PADDR1 = (unsigned *)ps->PPAGE1;
427
428                 /*
429                  * Per-cpu pmap for get_ptbase().
430                  */
431                 gd->gd_GDADDR1= (unsigned *)
432                         kmem_alloc_nofault(&kernel_map, SEG_SIZE, SEG_SIZE);
433                 gd->gd_GDMAP1 = &PTD[(vm_offset_t)gd->gd_GDADDR1 >> PDRSHIFT];
434
435                 gd->mi.gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * (naps + 1));
436                 bzero(gd->mi.gd_ipiq, sizeof(lwkt_ipiq) * (naps + 1));
437
438                 /*
439                  * Setup the AP boot stack
440                  */
441                 bootSTK = &ps->idlestack[UPAGES*PAGE_SIZE/2];
442                 bootAP = x;
443
444                 /* attempt to start the Application Processor */
445                 CHECK_INIT(99); /* setup checkpoints */
446                 if (!start_ap(gd, boot_addr, smibest)) {
447                         kprintf("AP #%d (PHY# %d) failed!\n", x,
448                             CPUID_TO_APICID(x));
449                         CHECK_PRINT("trace");   /* show checkpoints */
450                         /* better panic as the AP may be running loose */
451                         kprintf("panic y/n? [y] ");
452                         if (cngetc() != 'n')
453                                 panic("bye-bye");
454                 }
455                 CHECK_PRINT("trace");           /* show checkpoints */
456         }
457
458         /* set ncpus to 1 + highest logical cpu.  Not all may have come up */
459         ncpus = x;
460
461         /* ncpus2 -- ncpus rounded down to the nearest power of 2 */
462         for (shift = 0; (1 << shift) <= ncpus; ++shift)
463                 ;
464         --shift;
465         ncpus2_shift = shift;
466         ncpus2 = 1 << shift;
467         ncpus2_mask = ncpus2 - 1;
468
469         /* ncpus_fit -- ncpus rounded up to the nearest power of 2 */
470         if ((1 << shift) < ncpus)
471                 ++shift;
472         ncpus_fit = 1 << shift;
473         ncpus_fit_mask = ncpus_fit - 1;
474
475         /* build our map of 'other' CPUs */
476         mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
477         mycpu->gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * ncpus);
478         bzero(mycpu->gd_ipiq, sizeof(lwkt_ipiq) * ncpus);
479
480         /* restore the warmstart vector */
481         *(u_long *) WARMBOOT_OFF = mpbioswarmvec;
482         outb(CMOS_REG, BIOS_RESET);
483         outb(CMOS_DATA, mpbiosreason);
484
485         /*
486          * NOTE!  The idlestack for the BSP was setup by locore.  Finish
487          * up, clean out the P==V mapping we did earlier.
488          */
489         for (x = 0; x < NKPT; x++)
490                 PTD[x] = 0;
491         pmap_set_opt();
492
493         /*
494          * Wait all APs to finish initializing LAPIC
495          */
496         mp_finish_lapic = 1;
497         if (bootverbose)
498                 kprintf("SMP: Waiting APs LAPIC initialization\n");
499         if (cpu_feature & CPUID_TSC)
500                 tsc0_offset = rdtsc();
501         tsc_offsets[0] = 0;
502         rel_mplock();
503         while (smp_lapic_mask != smp_startup_mask) {
504                 cpu_lfence();
505                 if (cpu_feature & CPUID_TSC)
506                         tsc0_offset = rdtsc();
507         }
508         while (try_mplock() == 0)
509                 ;
510
511         /* number of APs actually started */
512         return ncpus - 1;
513 }
514
515 /*
516  * load the 1st level AP boot code into base memory.
517  */
518
519 /* targets for relocation */
520 extern void bigJump(void);
521 extern void bootCodeSeg(void);
522 extern void bootDataSeg(void);
523 extern void MPentry(void);
524 extern u_int MP_GDT;
525 extern u_int mp_gdtbase;
526
527 static void
528 install_ap_tramp(u_int boot_addr)
529 {
530         int     x;
531         int     size = *(int *) ((u_long) & bootMP_size);
532         u_char *src = (u_char *) ((u_long) bootMP);
533         u_char *dst = (u_char *) boot_addr + KERNBASE;
534         u_int   boot_base = (u_int) bootMP;
535         u_int8_t *dst8;
536         u_int16_t *dst16;
537         u_int32_t *dst32;
538
539         POSTCODE(INSTALL_AP_TRAMP_POST);
540
541         for (x = 0; x < size; ++x)
542                 *dst++ = *src++;
543
544         /*
545          * modify addresses in code we just moved to basemem. unfortunately we
546          * need fairly detailed info about mpboot.s for this to work.  changes
547          * to mpboot.s might require changes here.
548          */
549
550         /* boot code is located in KERNEL space */
551         dst = (u_char *) boot_addr + KERNBASE;
552
553         /* modify the lgdt arg */
554         dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
555         *dst32 = boot_addr + ((u_int) & MP_GDT - boot_base);
556
557         /* modify the ljmp target for MPentry() */
558         dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
559         *dst32 = ((u_int) MPentry - KERNBASE);
560
561         /* modify the target for boot code segment */
562         dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
563         dst8 = (u_int8_t *) (dst16 + 1);
564         *dst16 = boot_addr & 0xffff;
565         *dst8 = (boot_addr >> 16) & 0xff;
566
567         /* modify the target for boot data segment */
568         dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
569         dst8 = (u_int8_t *) (dst16 + 1);
570         *dst16 = boot_addr & 0xffff;
571         *dst8 = (boot_addr >> 16) & 0xff;
572 }
573
574
575 /*
576  * This function starts the AP (application processor) identified
577  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
578  * to accomplish this.  This is necessary because of the nuances
579  * of the different hardware we might encounter.  It ain't pretty,
580  * but it seems to work.
581  *
582  * NOTE: eventually an AP gets to ap_init(), which is called just 
583  * before the AP goes into the LWKT scheduler's idle loop.
584  */
585 static int
586 start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest)
587 {
588         int     physical_cpu;
589         int     vector;
590         u_long  icr_lo, icr_hi;
591
592         POSTCODE(START_AP_POST);
593
594         /* get the PHYSICAL APIC ID# */
595         physical_cpu = CPUID_TO_APICID(gd->mi.gd_cpuid);
596
597         /* calculate the vector */
598         vector = (boot_addr >> 12) & 0xff;
599
600         /* We don't want anything interfering */
601         cpu_disable_intr();
602
603         /* Make sure the target cpu sees everything */
604         wbinvd();
605
606         /*
607          * Try to detect when a SMI has occurred, wait up to 200ms.
608          *
609          * If a SMI occurs during an AP reset but before we issue
610          * the STARTUP command, the AP may brick.  To work around
611          * this problem we hold off doing the AP startup until
612          * after we have detected the SMI.  Hopefully another SMI
613          * will not occur before we finish the AP startup.
614          *
615          * Retries don't seem to help.  SMIs have a window of opportunity
616          * and if USB->legacy keyboard emulation is enabled in the BIOS
617          * the interrupt rate can be quite high.
618          *
619          * NOTE: Don't worry about the L1 cache load, it might bloat
620          *       ldelta a little but ndelta will be so huge when the SMI
621          *       occurs the detection logic will still work fine.
622          */
623         if (smibest) {
624                 set_apic_timer(200000);
625                 smitest();
626         }
627
628         /*
629          * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
630          * and running the target CPU. OR this INIT IPI might be latched (P5
631          * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
632          * ignored.
633          *
634          * see apic/apicreg.h for icr bit definitions.
635          *
636          * TIME CRITICAL CODE, DO NOT DO ANY KPRINTFS IN THE HOT PATH.
637          */
638
639         /*
640          * Setup the address for the target AP.  We can setup
641          * icr_hi once and then just trigger operations with
642          * icr_lo.
643          */
644         icr_hi = lapic->icr_hi & ~APIC_ID_MASK;
645         icr_hi |= (physical_cpu << 24);
646         icr_lo = lapic->icr_lo & 0xfff00000;
647         lapic->icr_hi = icr_hi;
648
649         /*
650          * Do an INIT IPI: assert RESET
651          *
652          * Use edge triggered mode to assert INIT
653          */
654         lapic->icr_lo = icr_lo | 0x0000c500;
655         while (lapic->icr_lo & APIC_DELSTAT_MASK)
656                  /* spin */ ;
657
658         /*
659          * The spec calls for a 10ms delay but we may have to use a
660          * MUCH lower delay to avoid bricking an AP due to a fast SMI
661          * interrupt.  We have other loops here too and dividing by 2
662          * doesn't seem to be enough even after subtracting 350us,
663          * so we divide by 4.
664          *
665          * Our minimum delay is 150uS, maximum is 10ms.  If no SMI
666          * interrupt was detected we use the full 10ms.
667          */
668         if (smibest == 0)
669                 u_sleep(10000);
670         else if (smibest < 150 * 4 + 350)
671                 u_sleep(150);
672         else if ((smibest - 350) / 4 < 10000)
673                 u_sleep((smibest - 350) / 4);
674         else
675                 u_sleep(10000);
676
677         /*
678          * Do an INIT IPI: deassert RESET
679          *
680          * Use level triggered mode to deassert.  It is unclear
681          * why we need to do this.
682          */
683         lapic->icr_lo = icr_lo | 0x00008500;
684         while (lapic->icr_lo & APIC_DELSTAT_MASK)
685                  /* spin */ ;
686         u_sleep(150);                           /* wait 150us */
687
688         /*
689          * Next we do a STARTUP IPI: the previous INIT IPI might still be
690          * latched, (P5 bug) this 1st STARTUP would then terminate
691          * immediately, and the previously started INIT IPI would continue. OR
692          * the previous INIT IPI has already run. and this STARTUP IPI will
693          * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
694          * will run.
695          */
696         lapic->icr_lo = icr_lo | 0x00000600 | vector;
697         while (lapic->icr_lo & APIC_DELSTAT_MASK)
698                  /* spin */ ;
699         u_sleep(200);           /* wait ~200uS */
700
701         /*
702          * Finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
703          * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
704          * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
705          * recognized after hardware RESET or INIT IPI.
706          */
707         lapic->icr_lo = icr_lo | 0x00000600 | vector;
708         while (lapic->icr_lo & APIC_DELSTAT_MASK)
709                  /* spin */ ;
710
711         /* Resume normal operation */
712         cpu_enable_intr();
713
714         /* wait for it to start, see ap_init() */
715         set_apic_timer(5000000);/* == 5 seconds */
716         while (read_apic_timer()) {
717                 if (smp_startup_mask & CPUMASK(gd->mi.gd_cpuid))
718                         return 1;       /* return SUCCESS */
719         }
720
721         return 0;               /* return FAILURE */
722 }
723
724 static
725 int
726 smitest(void)
727 {
728         int64_t ltsc;
729         int64_t ntsc;
730         int64_t ldelta;
731         int64_t ndelta;
732         int count;
733
734         ldelta = 0;
735         ndelta = 0;
736         while (read_apic_timer()) {
737                 ltsc = rdtsc();
738                 for (count = 0; count < 100; ++count)
739                         ntsc = rdtsc(); /* force loop to occur */
740                 if (ldelta) {
741                         ndelta = ntsc - ltsc;
742                         if (ldelta > ndelta)
743                                 ldelta = ndelta;
744                         if (ndelta > ldelta * 2)
745                                 break;
746                 } else {
747                         ldelta = ntsc - ltsc;
748                 }
749         }
750         return(read_apic_timer());
751 }
752
753 /*
754  * Lazy flush the TLB on all other CPU's.  DEPRECATED.
755  *
756  * If for some reason we were unable to start all cpus we cannot safely
757  * use broadcast IPIs.
758  */
759
760 static cpumask_t smp_invltlb_req;
761 #define SMP_INVLTLB_DEBUG
762
763 void
764 smp_invltlb(void)
765 {
766         struct mdglobaldata *md = mdcpu;
767 #ifdef SMP_INVLTLB_DEBUG
768         long count = 0;
769         long xcount = 0;
770 #endif
771
772         crit_enter_gd(&md->mi);
773         md->gd_invltlb_ret = 0;
774         ++md->mi.gd_cnt.v_smpinvltlb;
775         atomic_set_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
776 #ifdef SMP_INVLTLB_DEBUG
777 again:
778 #endif
779         if (smp_startup_mask == smp_active_mask) {
780                 all_but_self_ipi(XINVLTLB_OFFSET);
781         } else {
782                 selected_apic_ipi(smp_active_mask & ~md->mi.gd_cpumask,
783                                   XINVLTLB_OFFSET, APIC_DELMODE_FIXED);
784         }
785
786 #ifdef SMP_INVLTLB_DEBUG
787         if (xcount)
788                 kprintf("smp_invltlb: ipi sent\n");
789 #endif
790         while ((md->gd_invltlb_ret & smp_active_mask & ~md->mi.gd_cpumask) !=
791                (smp_active_mask & ~md->mi.gd_cpumask)) {
792                 cpu_mfence();
793                 cpu_pause();
794 #ifdef SMP_INVLTLB_DEBUG
795                 /* DEBUGGING */
796                 if (++count == 400000000) {
797                         print_backtrace(-1);
798                         kprintf("smp_invltlb: endless loop %08lx %08lx, "
799                                 "eflags %016lx retry",
800                                 (long)md->gd_invltlb_ret,
801                                 (long)smp_invltlb_req,
802                                 (long)read_eflags());
803                         __asm __volatile ("sti");
804                         ++xcount;
805                         if (xcount > 2)
806                                 lwkt_process_ipiq();
807                         if (xcount > 3) {
808                                 int bcpu = BSFCPUMASK(~md->gd_invltlb_ret &
809                                                       ~md->mi.gd_cpumask &
810                                                       smp_active_mask);
811                                 globaldata_t xgd;
812                                 kprintf("bcpu %d\n", bcpu);
813                                 xgd = globaldata_find(bcpu);
814                                 kprintf("thread %p %s\n", xgd->gd_curthread, xgd->gd_curthread->td_comm);
815                         }
816                         if (xcount > 5)
817                                 panic("giving up");
818                         count = 0;
819                         goto again;
820                 }
821 #endif
822         }
823         atomic_clear_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
824         crit_exit_gd(&md->mi);
825 }
826
827 /*
828  * Called from Xinvltlb assembly with interrupts disabled.  We didn't
829  * bother to bump the critical section count or nested interrupt count
830  * so only do very low level operations here.
831  */
832 void
833 smp_invltlb_intr(void)
834 {
835         struct mdglobaldata *md = mdcpu;
836         struct mdglobaldata *omd;
837         cpumask_t mask;
838         int cpu;
839
840         mask = smp_invltlb_req;
841         cpu_mfence();
842         cpu_invltlb();
843         while (mask) {
844                 cpu = BSFCPUMASK(mask);
845                 mask &= ~CPUMASK(cpu);
846                 omd = (struct mdglobaldata *)globaldata_find(cpu);
847                 atomic_set_cpumask(&omd->gd_invltlb_ret, md->mi.gd_cpumask);
848         }
849 }
850
851 void
852 cpu_wbinvd_on_all_cpus_callback(void *arg)
853 {
854     wbinvd();
855 }
856
857 /*
858  * When called the executing CPU will send an IPI to all other CPUs
859  *  requesting that they halt execution.
860  *
861  * Usually (but not necessarily) called with 'other_cpus' as its arg.
862  *
863  *  - Signals all CPUs in map to stop.
864  *  - Waits for each to stop.
865  *
866  * Returns:
867  *  -1: error
868  *   0: NA
869  *   1: ok
870  *
871  * XXX FIXME: this is not MP-safe, needs a lock to prevent multiple CPUs
872  *            from executing at same time.
873  */
874 int
875 stop_cpus(cpumask_t map)
876 {
877         map &= smp_active_mask;
878
879         /* send the Xcpustop IPI to all CPUs in map */
880         selected_apic_ipi(map, XCPUSTOP_OFFSET, APIC_DELMODE_FIXED);
881         
882         while ((stopped_cpus & map) != map)
883                 /* spin */ ;
884
885         return 1;
886 }
887
888
889 /*
890  * Called by a CPU to restart stopped CPUs. 
891  *
892  * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
893  *
894  *  - Signals all CPUs in map to restart.
895  *  - Waits for each to restart.
896  *
897  * Returns:
898  *  -1: error
899  *   0: NA
900  *   1: ok
901  */
902 int
903 restart_cpus(cpumask_t map)
904 {
905         /* signal other cpus to restart */
906         started_cpus = map & smp_active_mask;
907
908         while ((stopped_cpus & map) != 0) /* wait for each to clear its bit */
909                 /* spin */ ;
910
911         return 1;
912 }
913
914 /*
915  * This is called once the mpboot code has gotten us properly relocated
916  * and the MMU turned on, etc.   ap_init() is actually the idle thread,
917  * and when it returns the scheduler will call the real cpu_idle() main
918  * loop for the idlethread.  Interrupts are disabled on entry and should
919  * remain disabled at return.
920  */
921 void
922 ap_init(void)
923 {
924         int     cpu_id;
925
926         /*
927          * Adjust smp_startup_mask to signal the BSP that we have started
928          * up successfully.  Note that we do not yet hold the BGL.  The BSP
929          * is waiting for our signal.
930          *
931          * We can't set our bit in smp_active_mask yet because we are holding
932          * interrupts physically disabled and remote cpus could deadlock
933          * trying to send us an IPI.
934          */
935         smp_startup_mask |= CPUMASK(mycpu->gd_cpuid);
936         cpu_mfence();
937
938         /*
939          * Interlock for LAPIC initialization.  Wait until mp_finish_lapic is
940          * non-zero, then get the MP lock.
941          *
942          * Note: We are in a critical section.
943          *
944          * Note: we are the idle thread, we can only spin.
945          *
946          * Note: The load fence is memory volatile and prevents the compiler
947          * from improperly caching mp_finish_lapic, and the cpu from improperly
948          * caching it.
949          */
950         while (mp_finish_lapic == 0)
951                 cpu_lfence();
952         while (try_mplock() == 0)
953                 ;
954
955         if (cpu_feature & CPUID_TSC) {
956                 /*
957                  * The BSP is constantly updating tsc0_offset, figure out
958                  * the relative difference to synchronize ktrdump.
959                  */
960                 tsc_offsets[mycpu->gd_cpuid] = rdtsc() - tsc0_offset;
961         }
962
963         /* BSP may have changed PTD while we're waiting for the lock */
964         cpu_invltlb();
965
966 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
967         lidt(&r_idt);
968 #endif
969
970         /* Build our map of 'other' CPUs. */
971         mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
972
973         /* A quick check from sanity claus */
974         cpu_id = APICID_TO_CPUID((lapic->id & 0xff000000) >> 24);
975         if (mycpu->gd_cpuid != cpu_id) {
976                 kprintf("SMP: assigned cpuid = %d\n", mycpu->gd_cpuid);
977                 kprintf("SMP: actual cpuid = %d\n", cpu_id);
978                 kprintf("PTD[MPPTDI] = %p\n", (void *)PTD[MPPTDI]);
979                 panic("cpuid mismatch! boom!!");
980         }
981
982         /* Initialize AP's local APIC for irq's */
983         lapic_init(FALSE);
984
985         /* LAPIC initialization is done */
986         smp_lapic_mask |= CPUMASK(mycpu->gd_cpuid);
987         cpu_mfence();
988
989         /* Let BSP move onto the next initialization stage */
990         rel_mplock();
991
992         /*
993          * Interlock for finalization.  Wait until mp_finish is non-zero,
994          * then get the MP lock.
995          *
996          * Note: We are in a critical section.
997          *
998          * Note: we are the idle thread, we can only spin.
999          *
1000          * Note: The load fence is memory volatile and prevents the compiler
1001          * from improperly caching mp_finish, and the cpu from improperly
1002          * caching it.
1003          */
1004         while (mp_finish == 0)
1005                 cpu_lfence();
1006         while (try_mplock() == 0)
1007                 ;
1008
1009         /* BSP may have changed PTD while we're waiting for the lock */
1010         cpu_invltlb();
1011
1012         /* Set memory range attributes for this CPU to match the BSP */
1013         mem_range_AP_init();
1014
1015         /*
1016          * Once we go active we must process any IPIQ messages that may
1017          * have been queued, because no actual IPI will occur until we
1018          * set our bit in the smp_active_mask.  If we don't the IPI
1019          * message interlock could be left set which would also prevent
1020          * further IPIs.
1021          *
1022          * The idle loop doesn't expect the BGL to be held and while
1023          * lwkt_switch() normally cleans things up this is a special case
1024          * because we returning almost directly into the idle loop.
1025          *
1026          * The idle thread is never placed on the runq, make sure
1027          * nothing we've done put it there.
1028          */
1029         KKASSERT(get_mplock_count(curthread) == 1);
1030         smp_active_mask |= CPUMASK(mycpu->gd_cpuid);
1031
1032         /*
1033          * Enable interrupts here.  idle_restore will also do it, but
1034          * doing it here lets us clean up any strays that got posted to
1035          * the CPU during the AP boot while we are still in a critical
1036          * section.
1037          */
1038         __asm __volatile("sti; pause; pause"::);
1039         bzero(mdcpu->gd_ipending, sizeof(mdcpu->gd_ipending));
1040
1041         initclocks_pcpu();      /* clock interrupts (via IPIs) */
1042         lwkt_process_ipiq();
1043
1044         /*
1045          * Releasing the mp lock lets the BSP finish up the SMP init
1046          */
1047         rel_mplock();
1048         KKASSERT((curthread->td_flags & TDF_RUNQ) == 0);
1049 }
1050
1051 /*
1052  * Get SMP fully working before we start initializing devices.
1053  */
1054 static
1055 void
1056 ap_finish(void)
1057 {
1058         mp_finish = 1;
1059         if (bootverbose)
1060                 kprintf("Finish MP startup\n");
1061         rel_mplock();
1062         while (smp_active_mask != smp_startup_mask)
1063                 cpu_lfence();
1064         while (try_mplock() == 0)
1065                 ;
1066         if (bootverbose)
1067                 kprintf("Active CPU Mask: %08x\n", smp_active_mask);
1068 }
1069
1070 SYSINIT(finishsmp, SI_BOOT2_FINISH_SMP, SI_ORDER_FIRST, ap_finish, NULL)
1071
1072 void
1073 cpu_send_ipiq(int dcpu)
1074 {
1075         if (CPUMASK(dcpu) & smp_active_mask)
1076                 single_apic_ipi(dcpu, XIPIQ_OFFSET, APIC_DELMODE_FIXED);
1077 }
1078
1079 #if 0   /* single_apic_ipi_passive() not working yet */
1080 /*
1081  * Returns 0 on failure, 1 on success
1082  */
1083 int
1084 cpu_send_ipiq_passive(int dcpu)
1085 {
1086         int r = 0;
1087         if (CPUMASK(dcpu) & smp_active_mask) {
1088                 r = single_apic_ipi_passive(dcpu, XIPIQ_OFFSET,
1089                                         APIC_DELMODE_FIXED);
1090         }
1091         return(r);
1092 }
1093 #endif
1094
1095 static void
1096 mp_bsp_simple_setup(void)
1097 {
1098         /* build our map of 'other' CPUs */
1099         mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
1100         mycpu->gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * ncpus);
1101         bzero(mycpu->gd_ipiq, sizeof(lwkt_ipiq) * ncpus);
1102
1103         pmap_set_opt();
1104
1105         if (cpu_feature & CPUID_TSC)
1106                 tsc0_offset = rdtsc();
1107 }
1108
1109
1110 /*
1111  * CPU TOPOLOGY DETECTION FUNCTIONS
1112  */
1113
1114 /* Detect intel topology using CPUID 
1115  * Ref: http://www.intel.com/Assets/PDF/appnote/241618.pdf, pg 41
1116  */
1117 static void
1118 detect_intel_topology(int count_htt_cores)
1119 {
1120         int shift = 0;
1121         int ecx_index = 0;
1122         int core_plus_logical_bits = 0;
1123         int cores_per_package;
1124         int logical_per_package;
1125         int logical_per_core;
1126         unsigned int p[4];
1127
1128         if (cpu_high >= 0xb) {
1129                 goto FUNC_B;
1130
1131         } else if (cpu_high >= 0x4) {
1132                 goto FUNC_4;
1133
1134         } else {
1135                 core_bits = 0;
1136                 for (shift = 0; (1 << shift) < count_htt_cores; ++shift)
1137                         ;
1138                 logical_CPU_bits = 1 << shift;
1139                 return;
1140         }
1141
1142 FUNC_B:
1143         cpuid_count(0xb, FUNC_B_THREAD_LEVEL, p);
1144
1145         /* if 0xb not supported - fallback to 0x4 */
1146         if (p[1] == 0 || (FUNC_B_TYPE(p[2]) != FUNC_B_THREAD_TYPE)) {
1147                 goto FUNC_4;
1148         }
1149
1150         logical_CPU_bits = FUNC_B_BITS_SHIFT_NEXT_LEVEL(p[0]);
1151
1152         ecx_index = FUNC_B_THREAD_LEVEL + 1;
1153         do {
1154                 cpuid_count(0xb, ecx_index, p);
1155                 /* Check for the Core type in the implemented sub leaves. */
1156                 if (FUNC_B_TYPE(p[2]) == FUNC_B_CORE_TYPE) {
1157                         core_plus_logical_bits = FUNC_B_BITS_SHIFT_NEXT_LEVEL(p[0]);
1158                         break;
1159                 }
1160                 ecx_index++;
1161         } while (FUNC_B_TYPE(p[2]) != FUNC_B_INVALID_TYPE);
1162
1163         core_bits = core_plus_logical_bits - logical_CPU_bits;
1164
1165         return;
1166
1167 FUNC_4:
1168         cpuid_count(0x4, 0, p);
1169         cores_per_package = FUNC_4_MAX_CORE_NO(p[0]) + 1;
1170         
1171         logical_per_package = count_htt_cores;
1172         logical_per_core = logical_per_package / cores_per_package;
1173         
1174         for (shift = 0; (1 << shift) < logical_per_core; ++shift)
1175                 ;
1176         logical_CPU_bits = shift;
1177
1178         for (shift = 0; (1 << shift) < cores_per_package; ++shift)
1179                 ;
1180         core_bits = shift;
1181
1182         return;
1183 }
1184
1185 /* Detect AMD topology using CPUID 
1186  * Ref: http://support.amd.com/us/Embedded_TechDocs/25481.pdf, last page
1187  */
1188 static void
1189 detect_amd_topology(int count_htt_cores)
1190 {
1191         int shift = 0;
1192
1193         if ((cpu_feature & CPUID_HTT)
1194             && (amd_feature2 & AMDID2_CMP)) {
1195
1196                 if (cpu_procinfo2 & AMDID_COREID_SIZE) {
1197                         core_bits = (cpu_procinfo2 & AMDID_COREID_SIZE)
1198                                 >> AMDID_COREID_SIZE_SHIFT;
1199                 } else {
1200                         core_bits = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
1201                         for (shift = 0; (1 << shift) < core_bits; ++shift);
1202                         core_bits = shift;
1203                 }
1204
1205                 logical_CPU_bits = count_htt_cores >> core_bits;
1206                 for (shift = 0; (1 << shift) < logical_CPU_bits; ++shift)
1207                         ;
1208                 logical_CPU_bits = shift;
1209         } else {
1210                 for (shift = 0; (1 << shift) < count_htt_cores; ++shift)
1211                         ;
1212                 core_bits = shift;
1213                 logical_CPU_bits = 0;
1214         }
1215 }
1216
1217 /* Calculate
1218  * - logical_CPU_bits
1219  * - core_bits
1220  * With the values above (for AMD or INTEL) we are able to generally
1221  * detect the CPU topology (number of cores for each level):
1222  * Ref: http://wiki.osdev.org/Detecting_CPU_Topology_(80x86)
1223  * Ref: http://www.multicoreinfo.com/research/papers/whitepapers/Intel-detect-topology.pdf
1224  */
1225 void
1226 detect_cpu_topology(void)
1227 {
1228         static int topology_detected = 0;
1229         int count = 0;
1230         
1231         if (topology_detected) {
1232                 goto OUT;
1233         }
1234
1235         if ((cpu_feature & CPUID_HTT) == 0) {
1236                 core_bits = 0;
1237                 logical_CPU_bits = 0;
1238                 goto OUT;
1239         } else {
1240                 count = (cpu_procinfo & CPUID_HTT_CORES)
1241                     >> CPUID_HTT_CORE_SHIFT;
1242         }       
1243
1244         if (cpu_vendor_id == CPU_VENDOR_INTEL) {
1245                 detect_intel_topology(count);   
1246         } else if (cpu_vendor_id == CPU_VENDOR_AMD) {
1247                 detect_amd_topology(count);
1248         }
1249
1250 OUT:
1251         if (bootverbose)
1252                 kprintf("Bits within APICID: logical_CPU_bits: %d; core_bits: %d\n",
1253                     logical_CPU_bits, core_bits);
1254
1255         topology_detected = 1;
1256 }
1257
1258 /* Interface functions to calculate chip_ID,
1259  * core_number and logical_number
1260  * Ref: http://wiki.osdev.org/Detecting_CPU_Topology_(80x86)
1261  */
1262 int
1263 get_chip_ID(int cpuid)
1264 {
1265         return get_apicid_from_cpuid(cpuid) >>
1266             (logical_CPU_bits + core_bits);
1267 }
1268
1269 int
1270 get_core_number_within_chip(int cpuid)
1271 {
1272         return (get_apicid_from_cpuid(cpuid) >> logical_CPU_bits) &
1273             ( (1 << core_bits) -1);
1274 }
1275
1276 int
1277 get_logical_CPU_number_within_core(int cpuid)
1278 {
1279         return get_apicid_from_cpuid(cpuid) &
1280             ( (1 << logical_CPU_bits) -1);
1281 }