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