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