mptable: Test the usage of default MPTABLE config during mptable_probe()
[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  * $DragonFly: src/sys/platform/pc32/i386/mp_machdep.c,v 1.60 2008/06/07 12:03:52 mneumann Exp $
27  */
28
29 #include "opt_cpu.h"
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/sysctl.h>
35 #include <sys/malloc.h>
36 #include <sys/memrange.h>
37 #include <sys/cons.h>   /* cngetc() */
38 #include <sys/machintr.h>
39
40 #include <vm/vm.h>
41 #include <vm/vm_param.h>
42 #include <vm/pmap.h>
43 #include <vm/vm_kern.h>
44 #include <vm/vm_extern.h>
45 #include <sys/lock.h>
46 #include <vm/vm_map.h>
47 #include <sys/user.h>
48 #ifdef GPROF 
49 #include <sys/gmon.h>
50 #endif
51
52 #include <sys/mplock2.h>
53
54 #include <machine/smp.h>
55 #include <machine_base/apic/apicreg.h>
56 #include <machine/atomic.h>
57 #include <machine/cpufunc.h>
58 #include <machine/cputypes.h>
59 #include <machine_base/apic/mpapic.h>
60 #include <machine/psl.h>
61 #include <machine/segments.h>
62 #include <machine/tss.h>
63 #include <machine/specialreg.h>
64 #include <machine/globaldata.h>
65 #include <machine/pmap_inval.h>
66
67 #include <machine/md_var.h>             /* setidt() */
68 #include <machine_base/icu/icu.h>       /* IPIs */
69 #include <machine/intr_machdep.h>       /* IPIs */
70
71 #define FIXUP_EXTRA_APIC_INTS   8       /* additional entries we may create */
72
73 #define WARMBOOT_TARGET         0
74 #define WARMBOOT_OFF            (KERNBASE + 0x0467)
75 #define WARMBOOT_SEG            (KERNBASE + 0x0469)
76
77 #define BIOS_BASE               (0xf0000)
78 #define BIOS_BASE2              (0xe0000)
79 #define BIOS_SIZE               (0x10000)
80 #define BIOS_COUNT              (BIOS_SIZE/4)
81
82 #define CMOS_REG                (0x70)
83 #define CMOS_DATA               (0x71)
84 #define BIOS_RESET              (0x0f)
85 #define BIOS_WARM               (0x0a)
86
87 #define PROCENTRY_FLAG_EN       0x01
88 #define PROCENTRY_FLAG_BP       0x02
89 #define IOAPICENTRY_FLAG_EN     0x01
90
91
92 /* MP Floating Pointer Structure */
93 typedef struct MPFPS {
94         char    signature[4];
95         u_int32_t pap;
96         u_char  length;
97         u_char  spec_rev;
98         u_char  checksum;
99         u_char  mpfb1;
100         u_char  mpfb2;
101         u_char  mpfb3;
102         u_char  mpfb4;
103         u_char  mpfb5;
104 }      *mpfps_t;
105
106 /* MP Configuration Table Header */
107 typedef struct MPCTH {
108         char    signature[4];
109         u_short base_table_length;
110         u_char  spec_rev;
111         u_char  checksum;
112         u_char  oem_id[8];
113         u_char  product_id[12];
114         void   *oem_table_pointer;
115         u_short oem_table_size;
116         u_short entry_count;
117         void   *apic_address;
118         u_short extended_table_length;
119         u_char  extended_table_checksum;
120         u_char  reserved;
121 }      *mpcth_t;
122
123
124 typedef struct PROCENTRY {
125         u_char  type;
126         u_char  apic_id;
127         u_char  apic_version;
128         u_char  cpu_flags;
129         u_long  cpu_signature;
130         u_long  feature_flags;
131         u_long  reserved1;
132         u_long  reserved2;
133 }      *proc_entry_ptr;
134
135 typedef struct BUSENTRY {
136         u_char  type;
137         u_char  bus_id;
138         char    bus_type[6];
139 }      *bus_entry_ptr;
140
141 typedef struct IOAPICENTRY {
142         u_char  type;
143         u_char  apic_id;
144         u_char  apic_version;
145         u_char  apic_flags;
146         void   *apic_address;
147 }      *io_apic_entry_ptr;
148
149 typedef struct INTENTRY {
150         u_char  type;
151         u_char  int_type;
152         u_short int_flags;
153         u_char  src_bus_id;
154         u_char  src_bus_irq;
155         u_char  dst_apic_id;
156         u_char  dst_apic_int;
157 }      *int_entry_ptr;
158
159 /* descriptions of MP basetable entries */
160 typedef struct BASETABLE_ENTRY {
161         u_char  type;
162         u_char  length;
163         char    name[16];
164 }       basetable_entry;
165
166 struct mptable_pos {
167         mpfps_t         mp_fps;
168         mpcth_t         mp_cth;
169         vm_size_t       mp_cth_mapsz;
170 };
171
172 #define MPTABLE_POS_USE_DEFAULT(mpt) \
173         ((mpt)->mp_fps->mpfb1 != 0 || (mpt)->mp_cth == NULL)
174
175 typedef int     (*mptable_iter_func)(void *, const void *, int);
176
177 /*
178  * this code MUST be enabled here and in mpboot.s.
179  * it follows the very early stages of AP boot by placing values in CMOS ram.
180  * it NORMALLY will never be needed and thus the primitive method for enabling.
181  *
182  */
183 #if defined(CHECK_POINTS)
184 #define CHECK_READ(A)    (outb(CMOS_REG, (A)), inb(CMOS_DATA))
185 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
186
187 #define CHECK_INIT(D);                          \
188         CHECK_WRITE(0x34, (D));                 \
189         CHECK_WRITE(0x35, (D));                 \
190         CHECK_WRITE(0x36, (D));                 \
191         CHECK_WRITE(0x37, (D));                 \
192         CHECK_WRITE(0x38, (D));                 \
193         CHECK_WRITE(0x39, (D));
194
195 #define CHECK_PRINT(S);                         \
196         kprintf("%s: %d, %d, %d, %d, %d, %d\n", \
197            (S),                                 \
198            CHECK_READ(0x34),                    \
199            CHECK_READ(0x35),                    \
200            CHECK_READ(0x36),                    \
201            CHECK_READ(0x37),                    \
202            CHECK_READ(0x38),                    \
203            CHECK_READ(0x39));
204
205 #else                           /* CHECK_POINTS */
206
207 #define CHECK_INIT(D)
208 #define CHECK_PRINT(S)
209
210 #endif                          /* CHECK_POINTS */
211
212 /*
213  * Values to send to the POST hardware.
214  */
215 #define MP_BOOTADDRESS_POST     0x10
216 #define MP_PROBE_POST           0x11
217 #define MPTABLE_PASS1_POST      0x12
218
219 #define MP_START_POST           0x13
220 #define MP_ENABLE_POST          0x14
221 #define MPTABLE_PASS2_POST      0x15
222
223 #define START_ALL_APS_POST      0x16
224 #define INSTALL_AP_TRAMP_POST   0x17
225 #define START_AP_POST           0x18
226
227 #define MP_ANNOUNCE_POST        0x19
228
229 /** XXX FIXME: where does this really belong, isa.h/isa.c perhaps? */
230 int     current_postcode;
231
232 /** XXX FIXME: what system files declare these??? */
233 extern struct region_descriptor r_gdt, r_idt;
234
235 int     mp_naps;                /* # of Applications processors */
236 #ifdef SMP /* APIC-IO */
237 static int      mp_nbusses;     /* # of busses */
238 int     mp_napics;              /* # of IO APICs */
239 vm_offset_t io_apic_address[NAPICID];   /* NAPICID is more than enough */
240 u_int32_t *io_apic_versions;
241 #endif
242 extern  int nkpt;
243
244 u_int32_t cpu_apic_versions[MAXCPU];
245 int64_t tsc0_offset;
246 extern int64_t tsc_offsets[];
247
248 extern u_long ebda_addr;
249
250 #ifdef SMP /* APIC-IO */
251 struct apic_intmapinfo  int_to_apicintpin[APIC_INTMAPSIZE];
252 #endif
253
254 /*
255  * APIC ID logical/physical mapping structures.
256  * We oversize these to simplify boot-time config.
257  */
258 int     cpu_num_to_apic_id[NAPICID];
259 #ifdef SMP /* APIC-IO */
260 int     io_num_to_apic_id[NAPICID];
261 #endif
262 int     apic_id_to_logical[NAPICID];
263
264 /* AP uses this during bootstrap.  Do not staticize.  */
265 char *bootSTK;
266 static int bootAP;
267
268 /* Hotwire a 0->4MB V==P mapping */
269 extern pt_entry_t *KPTphys;
270
271 /*
272  * SMP page table page.  Setup by locore to point to a page table
273  * page from which we allocate per-cpu privatespace areas io_apics,
274  * and so forth.
275  */
276
277 #define IO_MAPPING_START_INDEX  \
278                 (SMP_MAXCPU * sizeof(struct privatespace) / PAGE_SIZE)
279
280 extern pt_entry_t *SMPpt;
281 static int SMPpt_alloc_index = IO_MAPPING_START_INDEX;
282
283 struct pcb stoppcbs[MAXCPU];
284
285 static basetable_entry basetable_entry_types[] =
286 {
287         {0, 20, "Processor"},
288         {1, 8, "Bus"},
289         {2, 8, "I/O APIC"},
290         {3, 8, "I/O INT"},
291         {4, 8, "Local INT"}
292 };
293
294 /*
295  * Local data and functions.
296  */
297
298 static u_int    boot_address;
299 static u_int    base_memory;
300 static int      mp_finish;
301
302 static void     mp_enable(u_int boot_addr);
303
304 static int      mptable_iterate_entries(const mpcth_t,
305                     mptable_iter_func, void *);
306 static int      mptable_search(void);
307 static int      mptable_search_sig(u_int32_t target, int count);
308 static int      mptable_hyperthread_fixup(cpumask_t, int);
309 #ifdef SMP /* APIC-IO */
310 static void     mptable_pass1(struct mptable_pos *);
311 static void     mptable_pass2(struct mptable_pos *);
312 static void     mptable_default(int type);
313 static void     mptable_fix(void);
314 #endif
315 static int      mptable_map(struct mptable_pos *);
316 static void     mptable_unmap(struct mptable_pos *);
317 static void     mptable_imcr(struct mptable_pos *);
318
319 static int      mptable_lapic_probe(struct lapic_enumerator *);
320 static void     mptable_lapic_enumerate(struct lapic_enumerator *);
321 static void     mptable_lapic_default(void);
322
323 #ifdef SMP /* APIC-IO */
324 static void     setup_apic_irq_mapping(void);
325 static int      apic_int_is_bus_type(int intr, int bus_type);
326 #endif
327 static int      start_all_aps(u_int boot_addr);
328 static void     install_ap_tramp(u_int boot_addr);
329 static int      start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest);
330 static int      smitest(void);
331
332 static cpumask_t smp_startup_mask = 1;  /* which cpus have been started */
333 cpumask_t smp_active_mask = 1;  /* which cpus are ready for IPIs etc? */
334 SYSCTL_INT(_machdep, OID_AUTO, smp_active, CTLFLAG_RD, &smp_active_mask, 0, "");
335
336 static vm_paddr_t       mptable_fps_phyaddr;
337 static int              mptable_use_default;
338
339 /*
340  * Calculate usable address in base memory for AP trampoline code.
341  */
342 u_int
343 mp_bootaddress(u_int basemem)
344 {
345         POSTCODE(MP_BOOTADDRESS_POST);
346
347         base_memory = basemem;
348
349         boot_address = base_memory & ~0xfff;    /* round down to 4k boundary */
350         if ((base_memory - boot_address) < bootMP_size)
351                 boot_address -= 4096;   /* not enough, lower by 4k */
352
353         return boot_address;
354 }
355
356
357 static void
358 mptable_probe(void)
359 {
360         struct mptable_pos mpt;
361         int error;
362
363         KKASSERT(mptable_fps_phyaddr == 0);
364
365         mptable_fps_phyaddr = mptable_search();
366         if (mptable_fps_phyaddr == 0)
367                 return;
368
369         error = mptable_map(&mpt);
370         if (error) {
371                 mptable_fps_phyaddr = 0;
372                 return;
373         }
374
375         if (MPTABLE_POS_USE_DEFAULT(&mpt)) {
376                 kprintf("MPTABLE: use default configuration\n");
377                 mptable_use_default = 1;
378         }
379
380         mptable_unmap(&mpt);
381 }
382 SYSINIT(mptable_probe, SI_BOOT2_PRESMP, SI_ORDER_FIRST, mptable_probe, 0);
383
384 /*
385  * Look for an Intel MP spec table (ie, SMP capable hardware).
386  */
387 static int
388 mptable_search(void)
389 {
390         int     x;
391         u_int32_t target;
392  
393         /*
394          * Make sure our SMPpt[] page table is big enough to hold all the
395          * mappings we need.
396          */
397         KKASSERT(IO_MAPPING_START_INDEX < NPTEPG - 2);
398
399         POSTCODE(MP_PROBE_POST);
400
401         /* see if EBDA exists */
402         if (ebda_addr != 0) {
403                 /* search first 1K of EBDA */
404                 target = (u_int32_t)ebda_addr;
405                 if ((x = mptable_search_sig(target, 1024 / 4)) > 0)
406                         return x;
407         } else {
408                 /* last 1K of base memory, effective 'top of base' passed in */
409                 target = (u_int32_t)(base_memory - 0x400);
410                 if ((x = mptable_search_sig(target, 1024 / 4)) > 0)
411                         return x;
412         }
413
414         /* search the BIOS */
415         target = (u_int32_t)BIOS_BASE;
416         if ((x = mptable_search_sig(target, BIOS_COUNT)) > 0)
417                 return x;
418
419         /* search the extended BIOS */
420         target = (u_int32_t)BIOS_BASE2;
421         if ((x = mptable_search_sig(target, BIOS_COUNT)) > 0)
422                 return x;
423
424         /* nothing found */
425         return 0;
426 }
427
428 static int
429 mptable_iterate_entries(const mpcth_t cth, mptable_iter_func func, void *arg)
430 {
431         int count, total_size;
432         const void *position;
433
434         KKASSERT(cth->base_table_length >= sizeof(struct MPCTH));
435         total_size = cth->base_table_length - sizeof(struct MPCTH);
436         position = (const uint8_t *)cth + sizeof(struct MPCTH);
437         count = cth->entry_count;
438
439         while (count--) {
440                 int type, error;
441
442                 KKASSERT(total_size >= 0);
443                 if (total_size == 0) {
444                         kprintf("invalid base MP table, "
445                                 "entry count and length mismatch\n");
446                         return EINVAL;
447                 }
448
449                 type = *(const uint8_t *)position;
450                 switch (type) {
451                 case 0: /* processor_entry */
452                 case 1: /* bus_entry */
453                 case 2: /* io_apic_entry */
454                 case 3: /* int_entry */
455                 case 4: /* int_entry */
456                         break;
457                 default:
458                         kprintf("unknown base MP table entry type %d\n", type);
459                         return EINVAL;
460                 }
461
462                 if (total_size < basetable_entry_types[type].length) {
463                         kprintf("invalid base MP table length, "
464                                 "does not contain all entries\n");
465                         return EINVAL;
466                 }
467                 total_size -= basetable_entry_types[type].length;
468
469                 error = func(arg, position, type);
470                 if (error)
471                         return error;
472
473                 position = (const uint8_t *)position +
474                     basetable_entry_types[type].length;
475         }
476         return 0;
477 }
478
479
480 /*
481  * Startup the SMP processors.
482  */
483 void
484 mp_start(void)
485 {
486         POSTCODE(MP_START_POST);
487         mp_enable(boot_address);
488 }
489
490
491 /*
492  * Print various information about the SMP system hardware and setup.
493  */
494 void
495 mp_announce(void)
496 {
497         int     x;
498
499         POSTCODE(MP_ANNOUNCE_POST);
500
501         kprintf("DragonFly/MP: Multiprocessor motherboard\n");
502         kprintf(" cpu0 (BSP): apic id: %2d", CPU_TO_ID(0));
503         kprintf(", version: 0x%08x\n", cpu_apic_versions[0]);
504         for (x = 1; x <= mp_naps; ++x) {
505                 kprintf(" cpu%d (AP):  apic id: %2d", x, CPU_TO_ID(x));
506                 kprintf(", version: 0x%08x\n", cpu_apic_versions[x]);
507         }
508
509 if (apic_io_enable) {
510         for (x = 0; x < mp_napics; ++x) {
511                 kprintf(" io%d (APIC): apic id: %2d", x, IO_TO_ID(x));
512                 kprintf(", version: 0x%08x", io_apic_versions[x]);
513                 kprintf(", at 0x%08lx\n", io_apic_address[x]);
514         }
515 } else {
516         kprintf(" Warning: APIC I/O disabled\n");
517 }
518 }
519
520 /*
521  * AP cpu's call this to sync up protected mode.
522  *
523  * WARNING!  We must ensure that the cpu is sufficiently initialized to
524  * be able to use to the FP for our optimized bzero/bcopy code before
525  * we enter more mainstream C code.
526  *
527  * WARNING! %fs is not set up on entry.  This routine sets up %fs.
528  */
529 void
530 init_secondary(void)
531 {
532         int     gsel_tss;
533         int     x, myid = bootAP;
534         u_int   cr0;
535         struct mdglobaldata *md;
536         struct privatespace *ps;
537
538         ps = &CPU_prvspace[myid];
539
540         gdt_segs[GPRIV_SEL].ssd_base = (int)ps;
541         gdt_segs[GPROC0_SEL].ssd_base =
542                 (int) &ps->mdglobaldata.gd_common_tss;
543         ps->mdglobaldata.mi.gd_prvspace = ps;
544
545         for (x = 0; x < NGDT; x++) {
546                 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
547         }
548
549         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
550         r_gdt.rd_base = (int) &gdt[myid * NGDT];
551         lgdt(&r_gdt);                   /* does magic intra-segment return */
552
553         lidt(&r_idt);
554
555         lldt(_default_ldt);
556         mdcpu->gd_currentldt = _default_ldt;
557
558         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
559         gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
560
561         md = mdcpu;     /* loaded through %fs:0 (mdglobaldata.mi.gd_prvspace)*/
562
563         md->gd_common_tss.tss_esp0 = 0; /* not used until after switch */
564         md->gd_common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
565         md->gd_common_tss.tss_ioopt = (sizeof md->gd_common_tss) << 16;
566         md->gd_tss_gdt = &gdt[myid * NGDT + GPROC0_SEL].sd;
567         md->gd_common_tssd = *md->gd_tss_gdt;
568         ltr(gsel_tss);
569
570         /*
571          * Set to a known state:
572          * Set by mpboot.s: CR0_PG, CR0_PE
573          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
574          */
575         cr0 = rcr0();
576         cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
577         load_cr0(cr0);
578         pmap_set_opt();         /* PSE/4MB pages, etc */
579
580         /* set up CPU registers and state */
581         cpu_setregs();
582
583         /* set up FPU state on the AP */
584         npxinit(__INITIAL_NPXCW__);
585
586         /* set up SSE registers */
587         enable_sse();
588 }
589
590 /*******************************************************************
591  * local functions and data
592  */
593
594 /*
595  * start the SMP system
596  */
597 static void
598 mp_enable(u_int boot_addr)
599 {
600         int     apic;
601         u_int   ux;
602         struct mptable_pos mpt;
603
604         POSTCODE(MP_ENABLE_POST);
605
606         lapic_config();
607
608         if (apic_io_enable)
609                 ioapic_config();
610
611         if (mptable_fps_phyaddr) {
612                 mptable_map(&mpt);
613                 mptable_imcr(&mpt);
614                 mptable_unmap(&mpt);
615         }
616 if (apic_io_enable) {
617
618         if (!mptable_fps_phyaddr)
619                 panic("no MP table, disable APIC_IO! (set hw.apic_io_enable=0)\n");
620
621         mptable_map(&mpt);
622
623         /*
624          * Examine the MP table for needed info
625          */
626         mptable_pass1(&mpt);
627         mptable_pass2(&mpt);
628
629         mptable_unmap(&mpt);
630
631         /* Post scan cleanup */
632         mptable_fix();
633
634         setup_apic_irq_mapping();
635
636         /* fill the LOGICAL io_apic_versions table */
637         for (apic = 0; apic < mp_napics; ++apic) {
638                 ux = ioapic_read(ioapic[apic], IOAPIC_VER);
639                 io_apic_versions[apic] = ux;
640                 io_apic_set_id(apic, IO_TO_ID(apic));
641         }
642
643         /* program each IO APIC in the system */
644         for (apic = 0; apic < mp_napics; ++apic)
645                 if (io_apic_setup(apic) < 0)
646                         panic("IO APIC setup failure");
647
648 }
649
650         /*
651          * These are required for SMP operation
652          */
653
654         /* install a 'Spurious INTerrupt' vector */
655         setidt(XSPURIOUSINT_OFFSET, Xspuriousint,
656                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
657
658         /* install an inter-CPU IPI for TLB invalidation */
659         setidt(XINVLTLB_OFFSET, Xinvltlb,
660                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
661
662         /* install an inter-CPU IPI for IPIQ messaging */
663         setidt(XIPIQ_OFFSET, Xipiq,
664                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
665
666         /* install a timer vector */
667         setidt(XTIMER_OFFSET, Xtimer,
668                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
669         
670         /* install an inter-CPU IPI for CPU stop/restart */
671         setidt(XCPUSTOP_OFFSET, Xcpustop,
672                SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
673
674         /* start each Application Processor */
675         start_all_aps(boot_addr);
676 }
677
678
679 /*
680  * look for the MP spec signature
681  */
682
683 /* string defined by the Intel MP Spec as identifying the MP table */
684 #define MP_SIG          0x5f504d5f      /* _MP_ */
685 #define NEXT(X)         ((X) += 4)
686 static int
687 mptable_search_sig(u_int32_t target, int count)
688 {
689         vm_size_t map_size;
690         u_int32_t *addr;
691         int x, ret;
692
693         KKASSERT(target != 0);
694
695         map_size = count * sizeof(u_int32_t);
696         addr = pmap_mapdev((vm_paddr_t)target, map_size);
697
698         ret = 0;
699         for (x = 0; x < count; NEXT(x)) {
700                 if (addr[x] == MP_SIG) {
701                         /* make array index a byte index */
702                         ret = target + (x * sizeof(u_int32_t));
703                         break;
704                 }
705         }
706
707         pmap_unmapdev((vm_offset_t)addr, map_size);
708         return ret;
709 }
710
711
712 typedef struct BUSDATA {
713         u_char  bus_id;
714         enum busTypes bus_type;
715 }       bus_datum;
716
717 typedef struct INTDATA {
718         u_char  int_type;
719         u_short int_flags;
720         u_char  src_bus_id;
721         u_char  src_bus_irq;
722         u_char  dst_apic_id;
723         u_char  dst_apic_int;
724         u_char  int_vector;
725 }       io_int, local_int;
726
727 typedef struct BUSTYPENAME {
728         u_char  type;
729         char    name[7];
730 }       bus_type_name;
731
732 static bus_type_name bus_type_table[] =
733 {
734         {CBUS, "CBUS"},
735         {CBUSII, "CBUSII"},
736         {EISA, "EISA"},
737         {MCA, "MCA"},
738         {UNKNOWN_BUSTYPE, "---"},
739         {ISA, "ISA"},
740         {MCA, "MCA"},
741         {UNKNOWN_BUSTYPE, "---"},
742         {UNKNOWN_BUSTYPE, "---"},
743         {UNKNOWN_BUSTYPE, "---"},
744         {UNKNOWN_BUSTYPE, "---"},
745         {UNKNOWN_BUSTYPE, "---"},
746         {PCI, "PCI"},
747         {UNKNOWN_BUSTYPE, "---"},
748         {UNKNOWN_BUSTYPE, "---"},
749         {UNKNOWN_BUSTYPE, "---"},
750         {UNKNOWN_BUSTYPE, "---"},
751         {XPRESS, "XPRESS"},
752         {UNKNOWN_BUSTYPE, "---"}
753 };
754 /* from MP spec v1.4, table 5-1 */
755 static int default_data[7][5] =
756 {
757 /*   nbus, id0, type0, id1, type1 */
758         {1, 0, ISA, 255, 255},
759         {1, 0, EISA, 255, 255},
760         {1, 0, EISA, 255, 255},
761         {1, 0, MCA, 255, 255},
762         {2, 0, ISA, 1, PCI},
763         {2, 0, EISA, 1, PCI},
764         {2, 0, MCA, 1, PCI}
765 };
766
767
768 /* the bus data */
769 static bus_datum *bus_data;
770
771 /* the IO INT data, one entry per possible APIC INTerrupt */
772 static io_int  *io_apic_ints;
773 static int nintrs;
774
775 static int processor_entry      (const struct PROCENTRY *entry, int cpu);
776 static int bus_entry            (const struct BUSENTRY *entry, int bus);
777 static int io_apic_entry        (const struct IOAPICENTRY *entry, int apic);
778 static int int_entry            (const struct INTENTRY *entry, int intr);
779 static int lookup_bus_type      (char *name);
780
781 static int
782 mptable_ioapic_pass1_callback(void *xarg, const void *pos, int type)
783 {
784         const struct IOAPICENTRY *ioapic_ent;
785
786         switch (type) {
787         case 1: /* bus_entry */
788                 ++mp_nbusses;
789                 break;
790
791         case 2: /* io_apic_entry */
792                 ioapic_ent = pos;
793                 if (ioapic_ent->apic_flags & IOAPICENTRY_FLAG_EN) {
794                         io_apic_address[mp_napics++] =
795                             (vm_offset_t)ioapic_ent->apic_address;
796                 }
797                 break;
798
799         case 3: /* int_entry */
800                 ++nintrs;
801                 break;
802         }
803         return 0;
804 }
805
806 /*
807  * 1st pass on motherboard's Intel MP specification table.
808  *
809  * determines:
810  *      io_apic_address[N]
811  *      mp_nbusses
812  *      mp_napics
813  *      nintrs
814  */
815 static void
816 mptable_pass1(struct mptable_pos *mpt)
817 {
818         mpfps_t fps;
819         int x;
820
821         POSTCODE(MPTABLE_PASS1_POST);
822
823         fps = mpt->mp_fps;
824         KKASSERT(fps != NULL);
825
826         /* clear various tables */
827         for (x = 0; x < NAPICID; ++x)
828                 io_apic_address[x] = ~0;        /* IO APIC address table */
829
830         mp_nbusses = 0;
831         mp_napics = 0;
832         nintrs = 0;
833
834         /* check for use of 'default' configuration */
835         if (fps->mpfb1 != 0) {
836                 io_apic_address[0] = DEFAULT_IO_APIC_BASE;
837                 mp_nbusses = default_data[fps->mpfb1 - 1][0];
838                 mp_napics = 1;
839                 nintrs = 16;
840         } else {
841                 int error;
842
843                 error = mptable_iterate_entries(mpt->mp_cth,
844                             mptable_ioapic_pass1_callback, NULL);
845                 if (error)
846                         panic("mptable_iterate_entries(ioapic_pass1) failed\n");
847         }
848 }
849
850 struct mptable_ioapic2_cbarg {
851         int     bus;
852         int     apic;
853         int     intr;
854 };
855
856 static int
857 mptable_ioapic_pass2_callback(void *xarg, const void *pos, int type)
858 {
859         struct mptable_ioapic2_cbarg *arg = xarg;
860
861         switch (type) {
862         case 1:
863                 if (bus_entry(pos, arg->bus))
864                         ++arg->bus;
865                 break;
866
867         case 2:
868                 if (io_apic_entry(pos, arg->apic))
869                         ++arg->apic;
870                 break;
871
872         case 3:
873                 if (int_entry(pos, arg->intr))
874                         ++arg->intr;
875                 break;
876         }
877         return 0;
878 }
879
880 /*
881  * 2nd pass on motherboard's Intel MP specification table.
882  *
883  * sets:
884  *      ID_TO_IO(N), phy APIC ID to log CPU/IO table
885  *      IO_TO_ID(N), logical IO to APIC ID table
886  *      bus_data[N]
887  *      io_apic_ints[N]
888  */
889 static void
890 mptable_pass2(struct mptable_pos *mpt)
891 {
892         struct mptable_ioapic2_cbarg arg;
893         mpfps_t fps;
894         int error, x;
895
896         POSTCODE(MPTABLE_PASS2_POST);
897
898         fps = mpt->mp_fps;
899         KKASSERT(fps != NULL);
900
901         MALLOC(io_apic_versions, u_int32_t *, sizeof(u_int32_t) * mp_napics,
902             M_DEVBUF, M_WAITOK);
903         MALLOC(ioapic, volatile ioapic_t **, sizeof(ioapic_t *) * mp_napics,
904             M_DEVBUF, M_WAITOK | M_ZERO);
905         MALLOC(io_apic_ints, io_int *, sizeof(io_int) * (nintrs + FIXUP_EXTRA_APIC_INTS),
906             M_DEVBUF, M_WAITOK);
907         MALLOC(bus_data, bus_datum *, sizeof(bus_datum) * mp_nbusses,
908             M_DEVBUF, M_WAITOK);
909
910         for (x = 0; x < mp_napics; x++)
911                 ioapic[x] = permanent_io_mapping(io_apic_address[x]);
912
913         /* clear various tables */
914         for (x = 0; x < NAPICID; ++x) {
915                 ID_TO_IO(x) = -1;       /* phy APIC ID to log CPU/IO table */
916                 IO_TO_ID(x) = -1;       /* logical IO to APIC ID table */
917         }
918
919         /* clear bus data table */
920         for (x = 0; x < mp_nbusses; ++x)
921                 bus_data[x].bus_id = 0xff;
922
923         /* clear IO APIC INT table */
924         for (x = 0; x < nintrs + FIXUP_EXTRA_APIC_INTS; ++x) {
925                 io_apic_ints[x].int_type = 0xff;
926                 io_apic_ints[x].int_vector = 0xff;
927         }
928
929         /* check for use of 'default' configuration */
930         if (fps->mpfb1 != 0) {
931                 mptable_default(fps->mpfb1);
932                 return;
933         }
934
935         bzero(&arg, sizeof(arg));
936         error = mptable_iterate_entries(mpt->mp_cth,
937                     mptable_ioapic_pass2_callback, &arg);
938         if (error)
939                 panic("mptable_iterate_entries(ioapic_pass2) failed\n");
940 }
941
942 /*
943  * Check if we should perform a hyperthreading "fix-up" to
944  * enumerate any logical CPU's that aren't already listed
945  * in the table.
946  *
947  * XXX: We assume that all of the physical CPUs in the
948  * system have the same number of logical CPUs.
949  *
950  * XXX: We assume that APIC ID's are allocated such that
951  * the APIC ID's for a physical processor are aligned
952  * with the number of logical CPU's in the processor.
953  */
954 static int
955 mptable_hyperthread_fixup(cpumask_t id_mask, int cpu_count)
956 {
957         int i, id, lcpus_max, logical_cpus;
958
959         if ((cpu_feature & CPUID_HTT) == 0)
960                 return 0;
961
962         lcpus_max = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
963         if (lcpus_max <= 1)
964                 return 0;
965
966         if (cpu_vendor_id == CPU_VENDOR_INTEL) {
967                 /*
968                  * INSTRUCTION SET REFERENCE, A-M (#253666)
969                  * Page 3-181, Table 3-20
970                  * "The nearest power-of-2 integer that is not smaller
971                  *  than EBX[23:16] is the number of unique initial APIC
972                  *  IDs reserved for addressing different logical
973                  *  processors in a physical package."
974                  */
975                 for (i = 0; ; ++i) {
976                         if ((1 << i) >= lcpus_max) {
977                                 lcpus_max = 1 << i;
978                                 break;
979                         }
980                 }
981         }
982
983         KKASSERT(cpu_count != 0);
984         if (cpu_count == lcpus_max) {
985                 /* We have nothing to fix */
986                 return 0;
987         } else if (cpu_count == 1) {
988                 /* XXX this may be incorrect */
989                 logical_cpus = lcpus_max;
990         } else {
991                 int cur, prev, dist;
992
993                 /*
994                  * Calculate the distances between two nearest
995                  * APIC IDs.  If all such distances are same,
996                  * then it is the number of missing cpus that
997                  * we are going to fill later.
998                  */
999                 dist = cur = prev = -1;
1000                 for (id = 0; id < MAXCPU; ++id) {
1001                         if ((id_mask & CPUMASK(id)) == 0)
1002                                 continue;
1003
1004                         cur = id;
1005                         if (prev >= 0) {
1006                                 int new_dist = cur - prev;
1007
1008                                 if (dist < 0)
1009                                         dist = new_dist;
1010
1011                                 /*
1012                                  * Make sure that all distances
1013                                  * between two nearest APIC IDs
1014                                  * are same.
1015                                  */
1016                                 if (dist != new_dist)
1017                                         return 0;
1018                         }
1019                         prev = cur;
1020                 }
1021                 if (dist == 1)
1022                         return 0;
1023
1024                 /* Must be power of 2 */
1025                 if (dist & (dist - 1))
1026                         return 0;
1027
1028                 /* Can't exceed CPU package capacity */
1029                 if (dist > lcpus_max)
1030                         logical_cpus = lcpus_max;
1031                 else
1032                         logical_cpus = dist;
1033         }
1034
1035         /*
1036          * For each APIC ID of a CPU that is set in the mask,
1037          * scan the other candidate APIC ID's for this
1038          * physical processor.  If any of those ID's are
1039          * already in the table, then kill the fixup.
1040          */
1041         for (id = 0; id < MAXCPU; id++) {
1042                 if ((id_mask & CPUMASK(id)) == 0)
1043                         continue;
1044                 /* First, make sure we are on a logical_cpus boundary. */
1045                 if (id % logical_cpus != 0)
1046                         return 0;
1047                 for (i = id + 1; i < id + logical_cpus; i++)
1048                         if ((id_mask & CPUMASK(i)) != 0)
1049                                 return 0;
1050         }
1051         return logical_cpus;
1052 }
1053
1054 static int
1055 mptable_map(struct mptable_pos *mpt)
1056 {
1057         mpfps_t fps = NULL;
1058         mpcth_t cth = NULL;
1059         vm_size_t cth_mapsz = 0;
1060
1061         KKASSERT(mptable_fps_phyaddr != 0);
1062
1063         bzero(mpt, sizeof(*mpt));
1064
1065         fps = pmap_mapdev(mptable_fps_phyaddr, sizeof(*fps));
1066         if (fps->pap != 0) {
1067                 /*
1068                  * Map configuration table header to get
1069                  * the base table size
1070                  */
1071                 cth = pmap_mapdev(fps->pap, sizeof(*cth));
1072                 cth_mapsz = cth->base_table_length;
1073                 pmap_unmapdev((vm_offset_t)cth, sizeof(*cth));
1074
1075                 if (cth_mapsz < sizeof(*cth)) {
1076                         kprintf("invalid base MP table length %d\n",
1077                                 (int)cth_mapsz);
1078                         pmap_unmapdev((vm_offset_t)fps, sizeof(*fps));
1079                         return EINVAL;
1080                 }
1081
1082                 /*
1083                  * Map the base table
1084                  */
1085                 cth = pmap_mapdev(fps->pap, cth_mapsz);
1086         }
1087
1088         mpt->mp_fps = fps;
1089         mpt->mp_cth = cth;
1090         mpt->mp_cth_mapsz = cth_mapsz;
1091
1092         return 0;
1093 }
1094
1095 static void
1096 mptable_unmap(struct mptable_pos *mpt)
1097 {
1098         if (mpt->mp_cth != NULL) {
1099                 pmap_unmapdev((vm_offset_t)mpt->mp_cth, mpt->mp_cth_mapsz);
1100                 mpt->mp_cth = NULL;
1101                 mpt->mp_cth_mapsz = 0;
1102         }
1103         if (mpt->mp_fps != NULL) {
1104                 pmap_unmapdev((vm_offset_t)mpt->mp_fps, sizeof(*mpt->mp_fps));
1105                 mpt->mp_fps = NULL;
1106         }
1107 }
1108
1109 void
1110 assign_apic_irq(int apic, int intpin, int irq)
1111 {
1112         int x;
1113         
1114         if (int_to_apicintpin[irq].ioapic != -1)
1115                 panic("assign_apic_irq: inconsistent table");
1116         
1117         int_to_apicintpin[irq].ioapic = apic;
1118         int_to_apicintpin[irq].int_pin = intpin;
1119         int_to_apicintpin[irq].apic_address = ioapic[apic];
1120         int_to_apicintpin[irq].redirindex = IOAPIC_REDTBL + 2 * intpin;
1121         
1122         for (x = 0; x < nintrs; x++) {
1123                 if ((io_apic_ints[x].int_type == 0 || 
1124                      io_apic_ints[x].int_type == 3) &&
1125                     io_apic_ints[x].int_vector == 0xff &&
1126                     io_apic_ints[x].dst_apic_id == IO_TO_ID(apic) &&
1127                     io_apic_ints[x].dst_apic_int == intpin)
1128                         io_apic_ints[x].int_vector = irq;
1129         }
1130 }
1131
1132 void
1133 revoke_apic_irq(int irq)
1134 {
1135         int x;
1136         int oldapic;
1137         int oldintpin;
1138         
1139         if (int_to_apicintpin[irq].ioapic == -1)
1140                 panic("revoke_apic_irq: inconsistent table");
1141         
1142         oldapic = int_to_apicintpin[irq].ioapic;
1143         oldintpin = int_to_apicintpin[irq].int_pin;
1144
1145         int_to_apicintpin[irq].ioapic = -1;
1146         int_to_apicintpin[irq].int_pin = 0;
1147         int_to_apicintpin[irq].apic_address = NULL;
1148         int_to_apicintpin[irq].redirindex = 0;
1149         
1150         for (x = 0; x < nintrs; x++) {
1151                 if ((io_apic_ints[x].int_type == 0 || 
1152                      io_apic_ints[x].int_type == 3) &&
1153                     io_apic_ints[x].int_vector != 0xff &&
1154                     io_apic_ints[x].dst_apic_id == IO_TO_ID(oldapic) &&
1155                     io_apic_ints[x].dst_apic_int == oldintpin)
1156                         io_apic_ints[x].int_vector = 0xff;
1157         }
1158 }
1159
1160 /*
1161  * Allocate an IRQ 
1162  */
1163 static void
1164 allocate_apic_irq(int intr)
1165 {
1166         int apic;
1167         int intpin;
1168         int irq;
1169         
1170         if (io_apic_ints[intr].int_vector != 0xff)
1171                 return;         /* Interrupt handler already assigned */
1172         
1173         if (io_apic_ints[intr].int_type != 0 &&
1174             (io_apic_ints[intr].int_type != 3 ||
1175              (io_apic_ints[intr].dst_apic_id == IO_TO_ID(0) &&
1176               io_apic_ints[intr].dst_apic_int == 0)))
1177                 return;         /* Not INT or ExtInt on != (0, 0) */
1178         
1179         irq = 0;
1180         while (irq < APIC_INTMAPSIZE &&
1181                int_to_apicintpin[irq].ioapic != -1)
1182                 irq++;
1183         
1184         if (irq >= APIC_INTMAPSIZE)
1185                 return;         /* No free interrupt handlers */
1186         
1187         apic = ID_TO_IO(io_apic_ints[intr].dst_apic_id);
1188         intpin = io_apic_ints[intr].dst_apic_int;
1189         
1190         assign_apic_irq(apic, intpin, irq);
1191 }
1192
1193
1194 static void
1195 swap_apic_id(int apic, int oldid, int newid)
1196 {
1197         int x;
1198         int oapic;
1199         
1200
1201         if (oldid == newid)
1202                 return;                 /* Nothing to do */
1203         
1204         kprintf("Changing APIC ID for IO APIC #%d from %d to %d in MP table\n",
1205                apic, oldid, newid);
1206         
1207         /* Swap physical APIC IDs in interrupt entries */
1208         for (x = 0; x < nintrs; x++) {
1209                 if (io_apic_ints[x].dst_apic_id == oldid)
1210                         io_apic_ints[x].dst_apic_id = newid;
1211                 else if (io_apic_ints[x].dst_apic_id == newid)
1212                         io_apic_ints[x].dst_apic_id = oldid;
1213         }
1214         
1215         /* Swap physical APIC IDs in IO_TO_ID mappings */
1216         for (oapic = 0; oapic < mp_napics; oapic++)
1217                 if (IO_TO_ID(oapic) == newid)
1218                         break;
1219         
1220         if (oapic < mp_napics) {
1221                 kprintf("Changing APIC ID for IO APIC #%d from "
1222                        "%d to %d in MP table\n",
1223                        oapic, newid, oldid);
1224                 IO_TO_ID(oapic) = oldid;
1225         }
1226         IO_TO_ID(apic) = newid;
1227 }
1228
1229
1230 static void
1231 fix_id_to_io_mapping(void)
1232 {
1233         int x;
1234
1235         for (x = 0; x < NAPICID; x++)
1236                 ID_TO_IO(x) = -1;
1237         
1238         for (x = 0; x <= mp_naps; x++)
1239                 if (CPU_TO_ID(x) < NAPICID)
1240                         ID_TO_IO(CPU_TO_ID(x)) = x;
1241         
1242         for (x = 0; x < mp_napics; x++)
1243                 if (IO_TO_ID(x) < NAPICID)
1244                         ID_TO_IO(IO_TO_ID(x)) = x;
1245 }
1246
1247
1248 static int
1249 first_free_apic_id(void)
1250 {
1251         int freeid, x;
1252         
1253         for (freeid = 0; freeid < NAPICID; freeid++) {
1254                 for (x = 0; x <= mp_naps; x++)
1255                         if (CPU_TO_ID(x) == freeid)
1256                                 break;
1257                 if (x <= mp_naps)
1258                         continue;
1259                 for (x = 0; x < mp_napics; x++)
1260                         if (IO_TO_ID(x) == freeid)
1261                                 break;
1262                 if (x < mp_napics)
1263                         continue;
1264                 return freeid;
1265         }
1266         return freeid;
1267 }
1268
1269
1270 static int
1271 io_apic_id_acceptable(int apic, int id)
1272 {
1273         int cpu;                /* Logical CPU number */
1274         int oapic;              /* Logical IO APIC number for other IO APIC */
1275
1276         if (id >= NAPICID)
1277                 return 0;       /* Out of range */
1278         
1279         for (cpu = 0; cpu <= mp_naps; cpu++)
1280                 if (CPU_TO_ID(cpu) == id)
1281                         return 0;       /* Conflict with CPU */
1282         
1283         for (oapic = 0; oapic < mp_napics && oapic < apic; oapic++)
1284                 if (IO_TO_ID(oapic) == id)
1285                         return 0;       /* Conflict with other APIC */
1286         
1287         return 1;               /* ID is acceptable for IO APIC */
1288 }
1289
1290 static
1291 io_int *
1292 io_apic_find_int_entry(int apic, int pin)
1293 {
1294         int     x;
1295
1296         /* search each of the possible INTerrupt sources */
1297         for (x = 0; x < nintrs; ++x) {
1298                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1299                     (pin == io_apic_ints[x].dst_apic_int))
1300                         return (&io_apic_ints[x]);
1301         }
1302         return NULL;
1303 }
1304
1305 /*
1306  * parse an Intel MP specification table
1307  */
1308 static void
1309 mptable_fix(void)
1310 {
1311         int     x;
1312         int     id;
1313         int     apic;           /* IO APIC unit number */
1314         int     freeid;         /* Free physical APIC ID */
1315         int     physid;         /* Current physical IO APIC ID */
1316         io_int *io14;
1317         int     bus_0 = 0;      /* Stop GCC warning */
1318         int     bus_pci = 0;    /* Stop GCC warning */
1319         int     num_pci_bus;
1320
1321         /*
1322          * Fix mis-numbering of the PCI bus and its INT entries if the BIOS
1323          * did it wrong.  The MP spec says that when more than 1 PCI bus
1324          * exists the BIOS must begin with bus entries for the PCI bus and use
1325          * actual PCI bus numbering.  This implies that when only 1 PCI bus
1326          * exists the BIOS can choose to ignore this ordering, and indeed many
1327          * MP motherboards do ignore it.  This causes a problem when the PCI
1328          * sub-system makes requests of the MP sub-system based on PCI bus
1329          * numbers.     So here we look for the situation and renumber the
1330          * busses and associated INTs in an effort to "make it right".
1331          */
1332
1333         /* find bus 0, PCI bus, count the number of PCI busses */
1334         for (num_pci_bus = 0, x = 0; x < mp_nbusses; ++x) {
1335                 if (bus_data[x].bus_id == 0) {
1336                         bus_0 = x;
1337                 }
1338                 if (bus_data[x].bus_type == PCI) {
1339                         ++num_pci_bus;
1340                         bus_pci = x;
1341                 }
1342         }
1343         /*
1344          * bus_0 == slot of bus with ID of 0
1345          * bus_pci == slot of last PCI bus encountered
1346          */
1347
1348         /* check the 1 PCI bus case for sanity */
1349         /* if it is number 0 all is well */
1350         if (num_pci_bus == 1 &&
1351             bus_data[bus_pci].bus_id != 0) {
1352                 
1353                 /* mis-numbered, swap with whichever bus uses slot 0 */
1354
1355                 /* swap the bus entry types */
1356                 bus_data[bus_pci].bus_type = bus_data[bus_0].bus_type;
1357                 bus_data[bus_0].bus_type = PCI;
1358
1359                 /* swap each relavant INTerrupt entry */
1360                 id = bus_data[bus_pci].bus_id;
1361                 for (x = 0; x < nintrs; ++x) {
1362                         if (io_apic_ints[x].src_bus_id == id) {
1363                                 io_apic_ints[x].src_bus_id = 0;
1364                         }
1365                         else if (io_apic_ints[x].src_bus_id == 0) {
1366                                 io_apic_ints[x].src_bus_id = id;
1367                         }
1368                 }
1369         }
1370
1371         /* Assign IO APIC IDs.
1372          * 
1373          * First try the existing ID. If a conflict is detected, try
1374          * the ID in the MP table.  If a conflict is still detected, find
1375          * a free id.
1376          *
1377          * We cannot use the ID_TO_IO table before all conflicts has been
1378          * resolved and the table has been corrected.
1379          */
1380         for (apic = 0; apic < mp_napics; ++apic) { /* For all IO APICs */
1381                 
1382                 /* First try to use the value set by the BIOS */
1383                 physid = io_apic_get_id(apic);
1384                 if (io_apic_id_acceptable(apic, physid)) {
1385                         if (IO_TO_ID(apic) != physid)
1386                                 swap_apic_id(apic, IO_TO_ID(apic), physid);
1387                         continue;
1388                 }
1389
1390                 /* Then check if the value in the MP table is acceptable */
1391                 if (io_apic_id_acceptable(apic, IO_TO_ID(apic)))
1392                         continue;
1393
1394                 /* Last resort, find a free APIC ID and use it */
1395                 freeid = first_free_apic_id();
1396                 if (freeid >= NAPICID)
1397                         panic("No free physical APIC IDs found");
1398                 
1399                 if (io_apic_id_acceptable(apic, freeid)) {
1400                         swap_apic_id(apic, IO_TO_ID(apic), freeid);
1401                         continue;
1402                 }
1403                 panic("Free physical APIC ID not usable");
1404         }
1405         fix_id_to_io_mapping();
1406
1407         /* detect and fix broken Compaq MP table */
1408         if (apic_int_type(0, 0) == -1) {
1409                 kprintf("APIC_IO: MP table broken: 8259->APIC entry missing!\n");
1410                 io_apic_ints[nintrs].int_type = 3;      /* ExtInt */
1411                 io_apic_ints[nintrs].int_vector = 0xff; /* Unassigned */
1412                 /* XXX fixme, set src bus id etc, but it doesn't seem to hurt */
1413                 io_apic_ints[nintrs].dst_apic_id = IO_TO_ID(0);
1414                 io_apic_ints[nintrs].dst_apic_int = 0;  /* Pin 0 */
1415                 nintrs++;
1416         } else if (apic_int_type(0, 0) == 0) {
1417                 kprintf("APIC_IO: MP table broken: ExtINT entry corrupt!\n");
1418                 for (x = 0; x < nintrs; ++x)
1419                         if ((0 == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1420                             (0 == io_apic_ints[x].dst_apic_int)) {
1421                                 io_apic_ints[x].int_type = 3;
1422                                 io_apic_ints[x].int_vector = 0xff;
1423                                 break;
1424                         }
1425         }
1426
1427         /*
1428          * Fix missing IRQ 15 when IRQ 14 is an ISA interrupt.  IDE
1429          * controllers universally come in pairs.  If IRQ 14 is specified
1430          * as an ISA interrupt, then IRQ 15 had better be too.
1431          *
1432          * [ Shuttle XPC / AMD Athlon X2 ]
1433          *      The MPTable is missing an entry for IRQ 15.  Note that the
1434          *      ACPI table has an entry for both 14 and 15.
1435          */
1436         if (apic_int_type(0, 14) == 0 && apic_int_type(0, 15) == -1) {
1437                 kprintf("APIC_IO: MP table broken: IRQ 15 not ISA when IRQ 14 is!\n");
1438                 io14 = io_apic_find_int_entry(0, 14);
1439                 io_apic_ints[nintrs] = *io14;
1440                 io_apic_ints[nintrs].src_bus_irq = 15;
1441                 io_apic_ints[nintrs].dst_apic_int = 15;
1442                 nintrs++;
1443         }
1444 }
1445
1446 /* Assign low level interrupt handlers */
1447 static void
1448 setup_apic_irq_mapping(void)
1449 {
1450         int     x;
1451         int     int_vector;
1452
1453         /* Clear array */
1454         for (x = 0; x < APIC_INTMAPSIZE; x++) {
1455                 int_to_apicintpin[x].ioapic = -1;
1456                 int_to_apicintpin[x].int_pin = 0;
1457                 int_to_apicintpin[x].apic_address = NULL;
1458                 int_to_apicintpin[x].redirindex = 0;
1459
1460                 /* Default to masked */
1461                 int_to_apicintpin[x].flags = IOAPIC_IM_FLAG_MASKED;
1462         }
1463
1464         /* First assign ISA/EISA interrupts */
1465         for (x = 0; x < nintrs; x++) {
1466                 int_vector = io_apic_ints[x].src_bus_irq;
1467                 if (int_vector < APIC_INTMAPSIZE &&
1468                     io_apic_ints[x].int_vector == 0xff && 
1469                     int_to_apicintpin[int_vector].ioapic == -1 &&
1470                     (apic_int_is_bus_type(x, ISA) ||
1471                      apic_int_is_bus_type(x, EISA)) &&
1472                     io_apic_ints[x].int_type == 0) {
1473                         assign_apic_irq(ID_TO_IO(io_apic_ints[x].dst_apic_id), 
1474                                         io_apic_ints[x].dst_apic_int,
1475                                         int_vector);
1476                 }
1477         }
1478
1479         /* Assign ExtInt entry if no ISA/EISA interrupt 0 entry */
1480         for (x = 0; x < nintrs; x++) {
1481                 if (io_apic_ints[x].dst_apic_int == 0 &&
1482                     io_apic_ints[x].dst_apic_id == IO_TO_ID(0) &&
1483                     io_apic_ints[x].int_vector == 0xff && 
1484                     int_to_apicintpin[0].ioapic == -1 &&
1485                     io_apic_ints[x].int_type == 3) {
1486                         assign_apic_irq(0, 0, 0);
1487                         break;
1488                 }
1489         }
1490
1491         /* Assign PCI interrupts */
1492         for (x = 0; x < nintrs; ++x) {
1493                 if (io_apic_ints[x].int_type == 0 &&
1494                     io_apic_ints[x].int_vector == 0xff && 
1495                     apic_int_is_bus_type(x, PCI))
1496                         allocate_apic_irq(x);
1497         }
1498 }
1499
1500 void
1501 mp_set_cpuids(int cpu_id, int apic_id)
1502 {
1503         CPU_TO_ID(cpu_id) = apic_id;
1504         ID_TO_CPU(apic_id) = cpu_id;
1505 }
1506
1507 static int
1508 processor_entry(const struct PROCENTRY *entry, int cpu)
1509 {
1510         KKASSERT(cpu > 0);
1511
1512         /* check for usability */
1513         if (!(entry->cpu_flags & PROCENTRY_FLAG_EN))
1514                 return 0;
1515
1516         /* check for BSP flag */
1517         if (entry->cpu_flags & PROCENTRY_FLAG_BP) {
1518                 mp_set_cpuids(0, entry->apic_id);
1519                 return 0;       /* its already been counted */
1520         }
1521
1522         /* add another AP to list, if less than max number of CPUs */
1523         else if (cpu < MAXCPU) {
1524                 mp_set_cpuids(cpu, entry->apic_id);
1525                 return 1;
1526         }
1527
1528         return 0;
1529 }
1530
1531 static int
1532 bus_entry(const struct BUSENTRY *entry, int bus)
1533 {
1534         int     x;
1535         char    c, name[8];
1536
1537         /* encode the name into an index */
1538         for (x = 0; x < 6; ++x) {
1539                 if ((c = entry->bus_type[x]) == ' ')
1540                         break;
1541                 name[x] = c;
1542         }
1543         name[x] = '\0';
1544
1545         if ((x = lookup_bus_type(name)) == UNKNOWN_BUSTYPE)
1546                 panic("unknown bus type: '%s'", name);
1547
1548         bus_data[bus].bus_id = entry->bus_id;
1549         bus_data[bus].bus_type = x;
1550
1551         return 1;
1552 }
1553
1554 static int
1555 io_apic_entry(const struct IOAPICENTRY *entry, int apic)
1556 {
1557         if (!(entry->apic_flags & IOAPICENTRY_FLAG_EN))
1558                 return 0;
1559
1560         IO_TO_ID(apic) = entry->apic_id;
1561         ID_TO_IO(entry->apic_id) = apic;
1562
1563         return 1;
1564 }
1565
1566 static int
1567 lookup_bus_type(char *name)
1568 {
1569         int     x;
1570
1571         for (x = 0; x < MAX_BUSTYPE; ++x)
1572                 if (strcmp(bus_type_table[x].name, name) == 0)
1573                         return bus_type_table[x].type;
1574
1575         return UNKNOWN_BUSTYPE;
1576 }
1577
1578 static int
1579 int_entry(const struct INTENTRY *entry, int intr)
1580 {
1581         int apic;
1582
1583         io_apic_ints[intr].int_type = entry->int_type;
1584         io_apic_ints[intr].int_flags = entry->int_flags;
1585         io_apic_ints[intr].src_bus_id = entry->src_bus_id;
1586         io_apic_ints[intr].src_bus_irq = entry->src_bus_irq;
1587         if (entry->dst_apic_id == 255) {
1588                 /* This signal goes to all IO APICS.  Select an IO APIC
1589                    with sufficient number of interrupt pins */
1590                 for (apic = 0; apic < mp_napics; apic++)
1591                         if (((ioapic_read(ioapic[apic], IOAPIC_VER) & 
1592                               IOART_VER_MAXREDIR) >> MAXREDIRSHIFT) >= 
1593                             entry->dst_apic_int)
1594                                 break;
1595                 if (apic < mp_napics)
1596                         io_apic_ints[intr].dst_apic_id = IO_TO_ID(apic);
1597                 else
1598                         io_apic_ints[intr].dst_apic_id = entry->dst_apic_id;
1599         } else
1600                 io_apic_ints[intr].dst_apic_id = entry->dst_apic_id;
1601         io_apic_ints[intr].dst_apic_int = entry->dst_apic_int;
1602
1603         return 1;
1604 }
1605
1606 static int
1607 apic_int_is_bus_type(int intr, int bus_type)
1608 {
1609         int     bus;
1610
1611         for (bus = 0; bus < mp_nbusses; ++bus)
1612                 if ((bus_data[bus].bus_id == io_apic_ints[intr].src_bus_id)
1613                     && ((int) bus_data[bus].bus_type == bus_type))
1614                         return 1;
1615
1616         return 0;
1617 }
1618
1619 /*
1620  * Given a traditional ISA INT mask, return an APIC mask.
1621  */
1622 u_int
1623 isa_apic_mask(u_int isa_mask)
1624 {
1625         int isa_irq;
1626         int apic_pin;
1627
1628 #if defined(SKIP_IRQ15_REDIRECT)
1629         if (isa_mask == (1 << 15)) {
1630                 kprintf("skipping ISA IRQ15 redirect\n");
1631                 return isa_mask;
1632         }
1633 #endif  /* SKIP_IRQ15_REDIRECT */
1634
1635         isa_irq = ffs(isa_mask);                /* find its bit position */
1636         if (isa_irq == 0)                       /* doesn't exist */
1637                 return 0;
1638         --isa_irq;                              /* make it zero based */
1639
1640         apic_pin = isa_apic_irq(isa_irq);       /* look for APIC connection */
1641         if (apic_pin == -1)
1642                 return 0;
1643
1644         return (1 << apic_pin);                 /* convert pin# to a mask */
1645 }
1646
1647 /*
1648  * Determine which APIC pin an ISA/EISA INT is attached to.
1649  */
1650 #define INTTYPE(I)      (io_apic_ints[(I)].int_type)
1651 #define INTPIN(I)       (io_apic_ints[(I)].dst_apic_int)
1652 #define INTIRQ(I)       (io_apic_ints[(I)].int_vector)
1653 #define INTAPIC(I)      (ID_TO_IO(io_apic_ints[(I)].dst_apic_id))
1654
1655 #define SRCBUSIRQ(I)    (io_apic_ints[(I)].src_bus_irq)
1656 int
1657 isa_apic_irq(int isa_irq)
1658 {
1659         int     intr;
1660
1661         for (intr = 0; intr < nintrs; ++intr) {         /* check each record */
1662                 if (INTTYPE(intr) == 0) {               /* standard INT */
1663                         if (SRCBUSIRQ(intr) == isa_irq) {
1664                                 if (apic_int_is_bus_type(intr, ISA) ||
1665                                     apic_int_is_bus_type(intr, EISA)) {
1666                                         if (INTIRQ(intr) == 0xff)
1667                                                 return -1; /* unassigned */
1668                                         return INTIRQ(intr);    /* found */
1669                                 }
1670                         }
1671                 }
1672         }
1673         return -1;                                      /* NOT found */
1674 }
1675
1676
1677 /*
1678  * Determine which APIC pin a PCI INT is attached to.
1679  */
1680 #define SRCBUSID(I)     (io_apic_ints[(I)].src_bus_id)
1681 #define SRCBUSDEVICE(I) ((io_apic_ints[(I)].src_bus_irq >> 2) & 0x1f)
1682 #define SRCBUSLINE(I)   (io_apic_ints[(I)].src_bus_irq & 0x03)
1683 int
1684 pci_apic_irq(int pciBus, int pciDevice, int pciInt)
1685 {
1686         int     intr;
1687
1688         --pciInt;                                       /* zero based */
1689
1690         for (intr = 0; intr < nintrs; ++intr) {         /* check each record */
1691                 if ((INTTYPE(intr) == 0)                /* standard INT */
1692                     && (SRCBUSID(intr) == pciBus)
1693                     && (SRCBUSDEVICE(intr) == pciDevice)
1694                     && (SRCBUSLINE(intr) == pciInt)) {  /* a candidate IRQ */
1695                         if (apic_int_is_bus_type(intr, PCI)) {
1696                                 if (INTIRQ(intr) == 0xff) {
1697                                         kprintf("IOAPIC: pci_apic_irq() "
1698                                                 "failed\n");
1699                                         return -1;      /* unassigned */
1700                                 }
1701                                 return INTIRQ(intr);    /* exact match */
1702                         }
1703                 }
1704         }
1705
1706         return -1;                                      /* NOT found */
1707 }
1708
1709 int
1710 next_apic_irq(int irq) 
1711 {
1712         int intr, ointr;
1713         int bus, bustype;
1714
1715         bus = 0;
1716         bustype = 0;
1717         for (intr = 0; intr < nintrs; intr++) {
1718                 if (INTIRQ(intr) != irq || INTTYPE(intr) != 0)
1719                         continue;
1720                 bus = SRCBUSID(intr);
1721                 bustype = apic_bus_type(bus);
1722                 if (bustype != ISA &&
1723                     bustype != EISA &&
1724                     bustype != PCI)
1725                         continue;
1726                 break;
1727         }
1728         if (intr >= nintrs) {
1729                 return -1;
1730         }
1731         for (ointr = intr + 1; ointr < nintrs; ointr++) {
1732                 if (INTTYPE(ointr) != 0)
1733                         continue;
1734                 if (bus != SRCBUSID(ointr))
1735                         continue;
1736                 if (bustype == PCI) {
1737                         if (SRCBUSDEVICE(intr) != SRCBUSDEVICE(ointr))
1738                                 continue;
1739                         if (SRCBUSLINE(intr) != SRCBUSLINE(ointr))
1740                                 continue;
1741                 }
1742                 if (bustype == ISA || bustype == EISA) {
1743                         if (SRCBUSIRQ(intr) != SRCBUSIRQ(ointr))
1744                                 continue;
1745                 }
1746                 if (INTPIN(intr) == INTPIN(ointr))
1747                         continue;
1748                 break;
1749         }
1750         if (ointr >= nintrs) {
1751                 return -1;
1752         }
1753         return INTIRQ(ointr);
1754 }
1755 #undef SRCBUSLINE
1756 #undef SRCBUSDEVICE
1757 #undef SRCBUSID
1758 #undef SRCBUSIRQ
1759
1760 #undef INTPIN
1761 #undef INTIRQ
1762 #undef INTAPIC
1763 #undef INTTYPE
1764
1765 /*
1766  * Reprogram the MB chipset to NOT redirect an ISA INTerrupt.
1767  *
1768  * XXX FIXME:
1769  *  Exactly what this means is unclear at this point.  It is a solution
1770  *  for motherboards that redirect the MBIRQ0 pin.  Generically a motherboard
1771  *  could route any of the ISA INTs to upper (>15) IRQ values.  But most would
1772  *  NOT be redirected via MBIRQ0, thus "undirect()ing" them would NOT be an
1773  *  option.
1774  */
1775 int
1776 undirect_isa_irq(int rirq)
1777 {
1778 #if defined(READY)
1779         if (bootverbose)
1780             kprintf("Freeing redirected ISA irq %d.\n", rirq);
1781         /** FIXME: tickle the MB redirector chip */
1782         return /* XXX */;
1783 #else
1784         if (bootverbose)
1785             kprintf("Freeing (NOT implemented) redirected ISA irq %d.\n", rirq);
1786         return 0;
1787 #endif  /* READY */
1788 }
1789
1790
1791 /*
1792  * Reprogram the MB chipset to NOT redirect a PCI INTerrupt
1793  */
1794 int
1795 undirect_pci_irq(int rirq)
1796 {
1797 #if defined(READY)
1798         if (bootverbose)
1799                 kprintf("Freeing redirected PCI irq %d.\n", rirq);
1800
1801         /** FIXME: tickle the MB redirector chip */
1802         return /* XXX */;
1803 #else
1804         if (bootverbose)
1805                 kprintf("Freeing (NOT implemented) redirected PCI irq %d.\n",
1806                        rirq);
1807         return 0;
1808 #endif  /* READY */
1809 }
1810
1811
1812 /*
1813  * given a bus ID, return:
1814  *  the bus type if found
1815  *  -1 if NOT found
1816  */
1817 int
1818 apic_bus_type(int id)
1819 {
1820         int     x;
1821
1822         for (x = 0; x < mp_nbusses; ++x)
1823                 if (bus_data[x].bus_id == id)
1824                         return bus_data[x].bus_type;
1825
1826         return -1;
1827 }
1828
1829 /*
1830  * given a LOGICAL APIC# and pin#, return:
1831  *  the associated src bus ID if found
1832  *  -1 if NOT found
1833  */
1834 int
1835 apic_src_bus_id(int apic, int pin)
1836 {
1837         int     x;
1838
1839         /* search each of the possible INTerrupt sources */
1840         for (x = 0; x < nintrs; ++x)
1841                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1842                     (pin == io_apic_ints[x].dst_apic_int))
1843                         return (io_apic_ints[x].src_bus_id);
1844
1845         return -1;              /* NOT found */
1846 }
1847
1848 /*
1849  * given a LOGICAL APIC# and pin#, return:
1850  *  the associated src bus IRQ if found
1851  *  -1 if NOT found
1852  */
1853 int
1854 apic_src_bus_irq(int apic, int pin)
1855 {
1856         int     x;
1857
1858         for (x = 0; x < nintrs; x++)
1859                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1860                     (pin == io_apic_ints[x].dst_apic_int))
1861                         return (io_apic_ints[x].src_bus_irq);
1862
1863         return -1;              /* NOT found */
1864 }
1865
1866
1867 /*
1868  * given a LOGICAL APIC# and pin#, return:
1869  *  the associated INTerrupt type if found
1870  *  -1 if NOT found
1871  */
1872 int
1873 apic_int_type(int apic, int pin)
1874 {
1875         int     x;
1876
1877         /* search each of the possible INTerrupt sources */
1878         for (x = 0; x < nintrs; ++x) {
1879                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1880                     (pin == io_apic_ints[x].dst_apic_int))
1881                         return (io_apic_ints[x].int_type);
1882         }
1883         return -1;              /* NOT found */
1884 }
1885
1886 /*
1887  * Return the IRQ associated with an APIC pin
1888  */
1889 int 
1890 apic_irq(int apic, int pin)
1891 {
1892         int x;
1893         int res;
1894
1895         for (x = 0; x < nintrs; ++x) {
1896                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1897                     (pin == io_apic_ints[x].dst_apic_int)) {
1898                         res = io_apic_ints[x].int_vector;
1899                         if (res == 0xff)
1900                                 return -1;
1901                         if (apic != int_to_apicintpin[res].ioapic)
1902                                 panic("apic_irq: inconsistent table %d/%d", apic, int_to_apicintpin[res].ioapic);
1903                         if (pin != int_to_apicintpin[res].int_pin)
1904                                 panic("apic_irq inconsistent table (2)");
1905                         return res;
1906                 }
1907         }
1908         return -1;
1909 }
1910
1911
1912 /*
1913  * given a LOGICAL APIC# and pin#, return:
1914  *  the associated trigger mode if found
1915  *  -1 if NOT found
1916  */
1917 int
1918 apic_trigger(int apic, int pin)
1919 {
1920         int     x;
1921
1922         /* search each of the possible INTerrupt sources */
1923         for (x = 0; x < nintrs; ++x)
1924                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1925                     (pin == io_apic_ints[x].dst_apic_int))
1926                         return ((io_apic_ints[x].int_flags >> 2) & 0x03);
1927
1928         return -1;              /* NOT found */
1929 }
1930
1931
1932 /*
1933  * given a LOGICAL APIC# and pin#, return:
1934  *  the associated 'active' level if found
1935  *  -1 if NOT found
1936  */
1937 int
1938 apic_polarity(int apic, int pin)
1939 {
1940         int     x;
1941
1942         /* search each of the possible INTerrupt sources */
1943         for (x = 0; x < nintrs; ++x)
1944                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1945                     (pin == io_apic_ints[x].dst_apic_int))
1946                         return (io_apic_ints[x].int_flags & 0x03);
1947
1948         return -1;              /* NOT found */
1949 }
1950
1951 /*
1952  * set data according to MP defaults
1953  * FIXME: probably not complete yet...
1954  */
1955 static void
1956 mptable_default(int type)
1957 {
1958         int     io_apic_id;
1959         int     pin;
1960
1961 #if 0
1962         kprintf("  MP default config type: %d\n", type);
1963         switch (type) {
1964         case 1:
1965                 kprintf("   bus: ISA, APIC: 82489DX\n");
1966                 break;
1967         case 2:
1968                 kprintf("   bus: EISA, APIC: 82489DX\n");
1969                 break;
1970         case 3:
1971                 kprintf("   bus: EISA, APIC: 82489DX\n");
1972                 break;
1973         case 4:
1974                 kprintf("   bus: MCA, APIC: 82489DX\n");
1975                 break;
1976         case 5:
1977                 kprintf("   bus: ISA+PCI, APIC: Integrated\n");
1978                 break;
1979         case 6:
1980                 kprintf("   bus: EISA+PCI, APIC: Integrated\n");
1981                 break;
1982         case 7:
1983                 kprintf("   bus: MCA+PCI, APIC: Integrated\n");
1984                 break;
1985         default:
1986                 kprintf("   future type\n");
1987                 break;
1988                 /* NOTREACHED */
1989         }
1990 #endif  /* 0 */
1991
1992         /* one and only IO APIC */
1993         io_apic_id = (ioapic_read(ioapic[0], IOAPIC_ID) & APIC_ID_MASK) >> 24;
1994
1995         /*
1996          * sanity check, refer to MP spec section 3.6.6, last paragraph
1997          * necessary as some hardware isn't properly setting up the IO APIC
1998          */
1999 #if defined(REALLY_ANAL_IOAPICID_VALUE)
2000         if (io_apic_id != 2) {
2001 #else
2002         if ((io_apic_id == 0) || (io_apic_id == 1) || (io_apic_id == 15)) {
2003 #endif  /* REALLY_ANAL_IOAPICID_VALUE */
2004                 io_apic_set_id(0, 2);
2005                 io_apic_id = 2;
2006         }
2007         IO_TO_ID(0) = io_apic_id;
2008         ID_TO_IO(io_apic_id) = 0;
2009
2010         /* fill out bus entries */
2011         switch (type) {
2012         case 1:
2013         case 2:
2014         case 3:
2015         case 4:
2016         case 5:
2017         case 6:
2018         case 7:
2019                 bus_data[0].bus_id = default_data[type - 1][1];
2020                 bus_data[0].bus_type = default_data[type - 1][2];
2021                 bus_data[1].bus_id = default_data[type - 1][3];
2022                 bus_data[1].bus_type = default_data[type - 1][4];
2023                 break;
2024
2025         /* case 4: case 7:                 MCA NOT supported */
2026         default:                /* illegal/reserved */
2027                 panic("BAD default MP config: %d", type);
2028                 /* NOTREACHED */
2029         }
2030
2031         /* general cases from MP v1.4, table 5-2 */
2032         for (pin = 0; pin < 16; ++pin) {
2033                 io_apic_ints[pin].int_type = 0;
2034                 io_apic_ints[pin].int_flags = 0x05;     /* edge/active-hi */
2035                 io_apic_ints[pin].src_bus_id = 0;
2036                 io_apic_ints[pin].src_bus_irq = pin;    /* IRQ2 caught below */
2037                 io_apic_ints[pin].dst_apic_id = io_apic_id;
2038                 io_apic_ints[pin].dst_apic_int = pin;   /* 1-to-1 */
2039         }
2040
2041         /* special cases from MP v1.4, table 5-2 */
2042         if (type == 2) {
2043                 io_apic_ints[2].int_type = 0xff;        /* N/C */
2044                 io_apic_ints[13].int_type = 0xff;       /* N/C */
2045 #if !defined(APIC_MIXED_MODE)
2046                 /** FIXME: ??? */
2047                 panic("sorry, can't support type 2 default yet");
2048 #endif  /* APIC_MIXED_MODE */
2049         }
2050         else
2051                 io_apic_ints[2].src_bus_irq = 0;        /* ISA IRQ0 is on APIC INT 2 */
2052
2053         if (type == 7)
2054                 io_apic_ints[0].int_type = 0xff;        /* N/C */
2055         else
2056                 io_apic_ints[0].int_type = 3;   /* vectored 8259 */
2057 }
2058
2059 /*
2060  * Map a physical memory address representing I/O into KVA.  The I/O
2061  * block is assumed not to cross a page boundary.
2062  */
2063 void *
2064 permanent_io_mapping(vm_paddr_t pa)
2065 {
2066         vm_offset_t vaddr;
2067         int pgeflag;
2068         int i;
2069
2070         KKASSERT(pa < 0x100000000LL);
2071
2072         pgeflag = 0;    /* not used for SMP yet */
2073
2074         /*
2075          * If the requested physical address has already been incidently
2076          * mapped, just use the existing mapping.  Otherwise create a new
2077          * mapping.
2078          */
2079         for (i = IO_MAPPING_START_INDEX; i < SMPpt_alloc_index; ++i) {
2080                 if (((vm_offset_t)SMPpt[i] & PG_FRAME) ==
2081                     ((vm_offset_t)pa & PG_FRAME)) {
2082                         break;
2083                 }
2084         }
2085         if (i == SMPpt_alloc_index) {
2086                 if (i == NPTEPG - 2) {
2087                         panic("permanent_io_mapping: We ran out of space"
2088                               " in SMPpt[]!");
2089                 }
2090                 SMPpt[i] = (pt_entry_t)(PG_V | PG_RW | PG_N | pgeflag |
2091                            ((vm_offset_t)pa & PG_FRAME));
2092                 ++SMPpt_alloc_index;
2093         }
2094         vaddr = (vm_offset_t)CPU_prvspace + (i * PAGE_SIZE) +
2095                 ((vm_offset_t)pa & PAGE_MASK);
2096         return ((void *)vaddr);
2097 }
2098
2099 /*
2100  * start each AP in our list
2101  */
2102 static int
2103 start_all_aps(u_int boot_addr)
2104 {
2105         int     x, i, pg;
2106         int     shift;
2107         int     smicount;
2108         int     smibest;
2109         int     smilast;
2110         u_char  mpbiosreason;
2111         u_long  mpbioswarmvec;
2112         struct mdglobaldata *gd;
2113         struct privatespace *ps;
2114         char *stack;
2115         uintptr_t kptbase;
2116
2117         POSTCODE(START_ALL_APS_POST);
2118
2119         /* Initialize BSP's local APIC */
2120         apic_initialize(TRUE);
2121
2122         /* Finalize PIC */
2123         MachIntrABI.finalize();
2124
2125         /* install the AP 1st level boot code */
2126         install_ap_tramp(boot_addr);
2127
2128
2129         /* save the current value of the warm-start vector */
2130         mpbioswarmvec = *((u_long *) WARMBOOT_OFF);
2131         outb(CMOS_REG, BIOS_RESET);
2132         mpbiosreason = inb(CMOS_DATA);
2133
2134         /* setup a vector to our boot code */
2135         *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
2136         *((volatile u_short *) WARMBOOT_SEG) = (boot_addr >> 4);
2137         outb(CMOS_REG, BIOS_RESET);
2138         outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
2139
2140         /*
2141          * If we have a TSC we can figure out the SMI interrupt rate.
2142          * The SMI does not necessarily use a constant rate.  Spend
2143          * up to 250ms trying to figure it out.
2144          */
2145         smibest = 0;
2146         if (cpu_feature & CPUID_TSC) {
2147                 set_apic_timer(275000);
2148                 smilast = read_apic_timer();
2149                 for (x = 0; x < 20 && read_apic_timer(); ++x) {
2150                         smicount = smitest();
2151                         if (smibest == 0 || smilast - smicount < smibest)
2152                                 smibest = smilast - smicount;
2153                         smilast = smicount;
2154                 }
2155                 if (smibest > 250000)
2156                         smibest = 0;
2157                 if (smibest) {
2158                         smibest = smibest * (int64_t)1000000 /
2159                                   get_apic_timer_frequency();
2160                 }
2161         }
2162         if (smibest)
2163                 kprintf("SMI Frequency (worst case): %d Hz (%d us)\n",
2164                         1000000 / smibest, smibest);
2165
2166
2167         /* set up temporary P==V mapping for AP boot */
2168         /* XXX this is a hack, we should boot the AP on its own stack/PTD */
2169         kptbase = (uintptr_t)(void *)KPTphys;
2170         for (x = 0; x < NKPT; x++) {
2171                 PTD[x] = (pd_entry_t)(PG_V | PG_RW |
2172                     ((kptbase + x * PAGE_SIZE) & PG_FRAME));
2173         }
2174         cpu_invltlb();
2175
2176         /* start each AP */
2177         for (x = 1; x <= mp_naps; ++x) {
2178
2179                 /* This is a bit verbose, it will go away soon.  */
2180
2181                 /* first page of AP's private space */
2182                 pg = x * i386_btop(sizeof(struct privatespace));
2183
2184                 /* allocate new private data page(s) */
2185                 gd = (struct mdglobaldata *)kmem_alloc(&kernel_map, 
2186                                 MDGLOBALDATA_BASEALLOC_SIZE);
2187                 /* wire it into the private page table page */
2188                 for (i = 0; i < MDGLOBALDATA_BASEALLOC_SIZE; i += PAGE_SIZE) {
2189                         SMPpt[pg + i / PAGE_SIZE] = (pt_entry_t)
2190                             (PG_V | PG_RW | vtophys_pte((char *)gd + i));
2191                 }
2192                 pg += MDGLOBALDATA_BASEALLOC_PAGES;
2193
2194                 SMPpt[pg + 0] = 0;              /* *gd_CMAP1 */
2195                 SMPpt[pg + 1] = 0;              /* *gd_CMAP2 */
2196                 SMPpt[pg + 2] = 0;              /* *gd_CMAP3 */
2197                 SMPpt[pg + 3] = 0;              /* *gd_PMAP1 */
2198
2199                 /* allocate and set up an idle stack data page */
2200                 stack = (char *)kmem_alloc(&kernel_map, UPAGES*PAGE_SIZE);
2201                 for (i = 0; i < UPAGES; i++) {
2202                         SMPpt[pg + 4 + i] = (pt_entry_t)
2203                             (PG_V | PG_RW | vtophys_pte(PAGE_SIZE * i + stack));
2204                 }
2205
2206                 gd = &CPU_prvspace[x].mdglobaldata;     /* official location */
2207                 bzero(gd, sizeof(*gd));
2208                 gd->mi.gd_prvspace = ps = &CPU_prvspace[x];
2209
2210                 /* prime data page for it to use */
2211                 mi_gdinit(&gd->mi, x);
2212                 cpu_gdinit(gd, x);
2213                 gd->gd_CMAP1 = &SMPpt[pg + 0];
2214                 gd->gd_CMAP2 = &SMPpt[pg + 1];
2215                 gd->gd_CMAP3 = &SMPpt[pg + 2];
2216                 gd->gd_PMAP1 = &SMPpt[pg + 3];
2217                 gd->gd_CADDR1 = ps->CPAGE1;
2218                 gd->gd_CADDR2 = ps->CPAGE2;
2219                 gd->gd_CADDR3 = ps->CPAGE3;
2220                 gd->gd_PADDR1 = (unsigned *)ps->PPAGE1;
2221
2222                 /*
2223                  * Per-cpu pmap for get_ptbase().
2224                  */
2225                 gd->gd_GDADDR1= (unsigned *)
2226                         kmem_alloc_nofault(&kernel_map, SEG_SIZE, SEG_SIZE);
2227                 gd->gd_GDMAP1 = &PTD[(vm_offset_t)gd->gd_GDADDR1 >> PDRSHIFT];
2228
2229                 gd->mi.gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * (mp_naps + 1));
2230                 bzero(gd->mi.gd_ipiq, sizeof(lwkt_ipiq) * (mp_naps + 1));
2231
2232                 /*
2233                  * Setup the AP boot stack
2234                  */
2235                 bootSTK = &ps->idlestack[UPAGES*PAGE_SIZE/2];
2236                 bootAP = x;
2237
2238                 /* attempt to start the Application Processor */
2239                 CHECK_INIT(99); /* setup checkpoints */
2240                 if (!start_ap(gd, boot_addr, smibest)) {
2241                         kprintf("AP #%d (PHY# %d) failed!\n", x, CPU_TO_ID(x));
2242                         CHECK_PRINT("trace");   /* show checkpoints */
2243                         /* better panic as the AP may be running loose */
2244                         kprintf("panic y/n? [y] ");
2245                         if (cngetc() != 'n')
2246                                 panic("bye-bye");
2247                 }
2248                 CHECK_PRINT("trace");           /* show checkpoints */
2249
2250                 /* record its version info */
2251                 cpu_apic_versions[x] = cpu_apic_versions[0];
2252         }
2253
2254         /* set ncpus to 1 + highest logical cpu.  Not all may have come up */
2255         ncpus = x;
2256
2257         /* ncpus2 -- ncpus rounded down to the nearest power of 2 */
2258         for (shift = 0; (1 << shift) <= ncpus; ++shift)
2259                 ;
2260         --shift;
2261         ncpus2_shift = shift;
2262         ncpus2 = 1 << shift;
2263         ncpus2_mask = ncpus2 - 1;
2264
2265         /* ncpus_fit -- ncpus rounded up to the nearest power of 2 */
2266         if ((1 << shift) < ncpus)
2267                 ++shift;
2268         ncpus_fit = 1 << shift;
2269         ncpus_fit_mask = ncpus_fit - 1;
2270
2271         /* build our map of 'other' CPUs */
2272         mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
2273         mycpu->gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * ncpus);
2274         bzero(mycpu->gd_ipiq, sizeof(lwkt_ipiq) * ncpus);
2275
2276         /* fill in our (BSP) APIC version */
2277         cpu_apic_versions[0] = lapic.version;
2278
2279         /* restore the warmstart vector */
2280         *(u_long *) WARMBOOT_OFF = mpbioswarmvec;
2281         outb(CMOS_REG, BIOS_RESET);
2282         outb(CMOS_DATA, mpbiosreason);
2283
2284         /*
2285          * NOTE!  The idlestack for the BSP was setup by locore.  Finish
2286          * up, clean out the P==V mapping we did earlier.
2287          */
2288         for (x = 0; x < NKPT; x++)
2289                 PTD[x] = 0;
2290         pmap_set_opt();
2291
2292         /* number of APs actually started */
2293         return ncpus - 1;
2294 }
2295
2296 /*
2297  * load the 1st level AP boot code into base memory.
2298  */
2299
2300 /* targets for relocation */
2301 extern void bigJump(void);
2302 extern void bootCodeSeg(void);
2303 extern void bootDataSeg(void);
2304 extern void MPentry(void);
2305 extern u_int MP_GDT;
2306 extern u_int mp_gdtbase;
2307
2308 static void
2309 install_ap_tramp(u_int boot_addr)
2310 {
2311         int     x;
2312         int     size = *(int *) ((u_long) & bootMP_size);
2313         u_char *src = (u_char *) ((u_long) bootMP);
2314         u_char *dst = (u_char *) boot_addr + KERNBASE;
2315         u_int   boot_base = (u_int) bootMP;
2316         u_int8_t *dst8;
2317         u_int16_t *dst16;
2318         u_int32_t *dst32;
2319
2320         POSTCODE(INSTALL_AP_TRAMP_POST);
2321
2322         for (x = 0; x < size; ++x)
2323                 *dst++ = *src++;
2324
2325         /*
2326          * modify addresses in code we just moved to basemem. unfortunately we
2327          * need fairly detailed info about mpboot.s for this to work.  changes
2328          * to mpboot.s might require changes here.
2329          */
2330
2331         /* boot code is located in KERNEL space */
2332         dst = (u_char *) boot_addr + KERNBASE;
2333
2334         /* modify the lgdt arg */
2335         dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
2336         *dst32 = boot_addr + ((u_int) & MP_GDT - boot_base);
2337
2338         /* modify the ljmp target for MPentry() */
2339         dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
2340         *dst32 = ((u_int) MPentry - KERNBASE);
2341
2342         /* modify the target for boot code segment */
2343         dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
2344         dst8 = (u_int8_t *) (dst16 + 1);
2345         *dst16 = (u_int) boot_addr & 0xffff;
2346         *dst8 = ((u_int) boot_addr >> 16) & 0xff;
2347
2348         /* modify the target for boot data segment */
2349         dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
2350         dst8 = (u_int8_t *) (dst16 + 1);
2351         *dst16 = (u_int) boot_addr & 0xffff;
2352         *dst8 = ((u_int) boot_addr >> 16) & 0xff;
2353 }
2354
2355
2356 /*
2357  * This function starts the AP (application processor) identified
2358  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
2359  * to accomplish this.  This is necessary because of the nuances
2360  * of the different hardware we might encounter.  It ain't pretty,
2361  * but it seems to work.
2362  *
2363  * NOTE: eventually an AP gets to ap_init(), which is called just 
2364  * before the AP goes into the LWKT scheduler's idle loop.
2365  */
2366 static int
2367 start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest)
2368 {
2369         int     physical_cpu;
2370         int     vector;
2371         u_long  icr_lo, icr_hi;
2372
2373         POSTCODE(START_AP_POST);
2374
2375         /* get the PHYSICAL APIC ID# */
2376         physical_cpu = CPU_TO_ID(gd->mi.gd_cpuid);
2377
2378         /* calculate the vector */
2379         vector = (boot_addr >> 12) & 0xff;
2380
2381         /* We don't want anything interfering */
2382         cpu_disable_intr();
2383
2384         /* Make sure the target cpu sees everything */
2385         wbinvd();
2386
2387         /*
2388          * Try to detect when a SMI has occurred, wait up to 200ms.
2389          *
2390          * If a SMI occurs during an AP reset but before we issue
2391          * the STARTUP command, the AP may brick.  To work around
2392          * this problem we hold off doing the AP startup until
2393          * after we have detected the SMI.  Hopefully another SMI
2394          * will not occur before we finish the AP startup.
2395          *
2396          * Retries don't seem to help.  SMIs have a window of opportunity
2397          * and if USB->legacy keyboard emulation is enabled in the BIOS
2398          * the interrupt rate can be quite high.
2399          *
2400          * NOTE: Don't worry about the L1 cache load, it might bloat
2401          *       ldelta a little but ndelta will be so huge when the SMI
2402          *       occurs the detection logic will still work fine.
2403          */
2404         if (smibest) {
2405                 set_apic_timer(200000);
2406                 smitest();
2407         }
2408
2409         /*
2410          * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
2411          * and running the target CPU. OR this INIT IPI might be latched (P5
2412          * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
2413          * ignored.
2414          *
2415          * see apic/apicreg.h for icr bit definitions.
2416          *
2417          * TIME CRITICAL CODE, DO NOT DO ANY KPRINTFS IN THE HOT PATH.
2418          */
2419
2420         /*
2421          * Setup the address for the target AP.  We can setup
2422          * icr_hi once and then just trigger operations with
2423          * icr_lo.
2424          */
2425         icr_hi = lapic.icr_hi & ~APIC_ID_MASK;
2426         icr_hi |= (physical_cpu << 24);
2427         icr_lo = lapic.icr_lo & 0xfff00000;
2428         lapic.icr_hi = icr_hi;
2429
2430         /*
2431          * Do an INIT IPI: assert RESET
2432          *
2433          * Use edge triggered mode to assert INIT
2434          */
2435         lapic.icr_lo = icr_lo | 0x0000c500;
2436         while (lapic.icr_lo & APIC_DELSTAT_MASK)
2437                  /* spin */ ;
2438
2439         /*
2440          * The spec calls for a 10ms delay but we may have to use a
2441          * MUCH lower delay to avoid bricking an AP due to a fast SMI
2442          * interrupt.  We have other loops here too and dividing by 2
2443          * doesn't seem to be enough even after subtracting 350us,
2444          * so we divide by 4.
2445          *
2446          * Our minimum delay is 150uS, maximum is 10ms.  If no SMI
2447          * interrupt was detected we use the full 10ms.
2448          */
2449         if (smibest == 0)
2450                 u_sleep(10000);
2451         else if (smibest < 150 * 4 + 350)
2452                 u_sleep(150);
2453         else if ((smibest - 350) / 4 < 10000)
2454                 u_sleep((smibest - 350) / 4);
2455         else
2456                 u_sleep(10000);
2457
2458         /*
2459          * Do an INIT IPI: deassert RESET
2460          *
2461          * Use level triggered mode to deassert.  It is unclear
2462          * why we need to do this.
2463          */
2464         lapic.icr_lo = icr_lo | 0x00008500;
2465         while (lapic.icr_lo & APIC_DELSTAT_MASK)
2466                  /* spin */ ;
2467         u_sleep(150);                           /* wait 150us */
2468
2469         /*
2470          * Next we do a STARTUP IPI: the previous INIT IPI might still be
2471          * latched, (P5 bug) this 1st STARTUP would then terminate
2472          * immediately, and the previously started INIT IPI would continue. OR
2473          * the previous INIT IPI has already run. and this STARTUP IPI will
2474          * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
2475          * will run.
2476          */
2477         lapic.icr_lo = icr_lo | 0x00000600 | vector;
2478         while (lapic.icr_lo & APIC_DELSTAT_MASK)
2479                  /* spin */ ;
2480         u_sleep(200);           /* wait ~200uS */
2481
2482         /*
2483          * Finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
2484          * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
2485          * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
2486          * recognized after hardware RESET or INIT IPI.
2487          */
2488         lapic.icr_lo = icr_lo | 0x00000600 | vector;
2489         while (lapic.icr_lo & APIC_DELSTAT_MASK)
2490                  /* spin */ ;
2491
2492         /* Resume normal operation */
2493         cpu_enable_intr();
2494
2495         /* wait for it to start, see ap_init() */
2496         set_apic_timer(5000000);/* == 5 seconds */
2497         while (read_apic_timer()) {
2498                 if (smp_startup_mask & CPUMASK(gd->mi.gd_cpuid))
2499                         return 1;       /* return SUCCESS */
2500         }
2501
2502         return 0;               /* return FAILURE */
2503 }
2504
2505 static
2506 int
2507 smitest(void)
2508 {
2509         int64_t ltsc;
2510         int64_t ntsc;
2511         int64_t ldelta;
2512         int64_t ndelta;
2513         int count;
2514
2515         ldelta = 0;
2516         ndelta = 0;
2517         while (read_apic_timer()) {
2518                 ltsc = rdtsc();
2519                 for (count = 0; count < 100; ++count)
2520                         ntsc = rdtsc(); /* force loop to occur */
2521                 if (ldelta) {
2522                         ndelta = ntsc - ltsc;
2523                         if (ldelta > ndelta)
2524                                 ldelta = ndelta;
2525                         if (ndelta > ldelta * 2)
2526                                 break;
2527                 } else {
2528                         ldelta = ntsc - ltsc;
2529                 }
2530         }
2531         return(read_apic_timer());
2532 }
2533
2534 /*
2535  * Lazy flush the TLB on all other CPU's.  DEPRECATED.
2536  *
2537  * If for some reason we were unable to start all cpus we cannot safely
2538  * use broadcast IPIs.
2539  */
2540
2541 static cpumask_t smp_invltlb_req;
2542 #define SMP_INVLTLB_DEBUG
2543
2544 void
2545 smp_invltlb(void)
2546 {
2547 #ifdef SMP
2548         struct mdglobaldata *md = mdcpu;
2549 #ifdef SMP_INVLTLB_DEBUG
2550         long count = 0;
2551         long xcount = 0;
2552 #endif
2553
2554         crit_enter_gd(&md->mi);
2555         md->gd_invltlb_ret = 0;
2556         ++md->mi.gd_cnt.v_smpinvltlb;
2557         atomic_set_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
2558 #ifdef SMP_INVLTLB_DEBUG
2559 again:
2560 #endif
2561         if (smp_startup_mask == smp_active_mask) {
2562                 all_but_self_ipi(XINVLTLB_OFFSET);
2563         } else {
2564                 selected_apic_ipi(smp_active_mask & ~md->mi.gd_cpumask,
2565                                   XINVLTLB_OFFSET, APIC_DELMODE_FIXED);
2566         }
2567
2568 #ifdef SMP_INVLTLB_DEBUG
2569         if (xcount)
2570                 kprintf("smp_invltlb: ipi sent\n");
2571 #endif
2572         while ((md->gd_invltlb_ret & smp_active_mask & ~md->mi.gd_cpumask) !=
2573                (smp_active_mask & ~md->mi.gd_cpumask)) {
2574                 cpu_mfence();
2575                 cpu_pause();
2576 #ifdef SMP_INVLTLB_DEBUG
2577                 /* DEBUGGING */
2578                 if (++count == 400000000) {
2579                         print_backtrace(-1);
2580                         kprintf("smp_invltlb: endless loop %08lx %08lx, "
2581                                 "rflags %016lx retry",
2582                                 (long)md->gd_invltlb_ret,
2583                                 (long)smp_invltlb_req,
2584                                 (long)read_eflags());
2585                         __asm __volatile ("sti");
2586                         ++xcount;
2587                         if (xcount > 2)
2588                                 lwkt_process_ipiq();
2589                         if (xcount > 3) {
2590                                 int bcpu = BSFCPUMASK(~md->gd_invltlb_ret &
2591                                                       ~md->mi.gd_cpumask &
2592                                                       smp_active_mask);
2593                                 globaldata_t xgd;
2594                                 kprintf("bcpu %d\n", bcpu);
2595                                 xgd = globaldata_find(bcpu);
2596                                 kprintf("thread %p %s\n", xgd->gd_curthread, xgd->gd_curthread->td_comm);
2597                         }
2598                         if (xcount > 5)
2599                                 panic("giving up");
2600                         count = 0;
2601                         goto again;
2602                 }
2603 #endif
2604         }
2605         atomic_clear_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
2606         crit_exit_gd(&md->mi);
2607 #endif
2608 }
2609
2610 #ifdef SMP
2611
2612 /*
2613  * Called from Xinvltlb assembly with interrupts disabled.  We didn't
2614  * bother to bump the critical section count or nested interrupt count
2615  * so only do very low level operations here.
2616  */
2617 void
2618 smp_invltlb_intr(void)
2619 {
2620         struct mdglobaldata *md = mdcpu;
2621         struct mdglobaldata *omd;
2622         cpumask_t mask;
2623         int cpu;
2624
2625         mask = smp_invltlb_req;
2626         cpu_mfence();
2627         cpu_invltlb();
2628         while (mask) {
2629                 cpu = BSFCPUMASK(mask);
2630                 mask &= ~CPUMASK(cpu);
2631                 omd = (struct mdglobaldata *)globaldata_find(cpu);
2632                 atomic_set_cpumask(&omd->gd_invltlb_ret, md->mi.gd_cpumask);
2633         }
2634 }
2635
2636 #endif
2637
2638 /*
2639  * When called the executing CPU will send an IPI to all other CPUs
2640  *  requesting that they halt execution.
2641  *
2642  * Usually (but not necessarily) called with 'other_cpus' as its arg.
2643  *
2644  *  - Signals all CPUs in map to stop.
2645  *  - Waits for each to stop.
2646  *
2647  * Returns:
2648  *  -1: error
2649  *   0: NA
2650  *   1: ok
2651  *
2652  * XXX FIXME: this is not MP-safe, needs a lock to prevent multiple CPUs
2653  *            from executing at same time.
2654  */
2655 int
2656 stop_cpus(cpumask_t map)
2657 {
2658         map &= smp_active_mask;
2659
2660         /* send the Xcpustop IPI to all CPUs in map */
2661         selected_apic_ipi(map, XCPUSTOP_OFFSET, APIC_DELMODE_FIXED);
2662         
2663         while ((stopped_cpus & map) != map)
2664                 /* spin */ ;
2665
2666         return 1;
2667 }
2668
2669
2670 /*
2671  * Called by a CPU to restart stopped CPUs. 
2672  *
2673  * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
2674  *
2675  *  - Signals all CPUs in map to restart.
2676  *  - Waits for each to restart.
2677  *
2678  * Returns:
2679  *  -1: error
2680  *   0: NA
2681  *   1: ok
2682  */
2683 int
2684 restart_cpus(cpumask_t map)
2685 {
2686         /* signal other cpus to restart */
2687         started_cpus = map & smp_active_mask;
2688
2689         while ((stopped_cpus & map) != 0) /* wait for each to clear its bit */
2690                 /* spin */ ;
2691
2692         return 1;
2693 }
2694
2695 /*
2696  * This is called once the mpboot code has gotten us properly relocated
2697  * and the MMU turned on, etc.   ap_init() is actually the idle thread,
2698  * and when it returns the scheduler will call the real cpu_idle() main
2699  * loop for the idlethread.  Interrupts are disabled on entry and should
2700  * remain disabled at return.
2701  */
2702 void
2703 ap_init(void)
2704 {
2705         u_int   apic_id;
2706
2707         /*
2708          * Adjust smp_startup_mask to signal the BSP that we have started
2709          * up successfully.  Note that we do not yet hold the BGL.  The BSP
2710          * is waiting for our signal.
2711          *
2712          * We can't set our bit in smp_active_mask yet because we are holding
2713          * interrupts physically disabled and remote cpus could deadlock
2714          * trying to send us an IPI.
2715          */
2716         smp_startup_mask |= CPUMASK(mycpu->gd_cpuid);
2717         cpu_mfence();
2718
2719         /*
2720          * Interlock for finalization.  Wait until mp_finish is non-zero,
2721          * then get the MP lock.
2722          *
2723          * Note: We are in a critical section.
2724          *
2725          * Note: we are the idle thread, we can only spin.
2726          *
2727          * Note: The load fence is memory volatile and prevents the compiler
2728          * from improperly caching mp_finish, and the cpu from improperly
2729          * caching it.
2730          */
2731         while (mp_finish == 0)
2732                 cpu_lfence();
2733         while (try_mplock() == 0)
2734                 ;
2735
2736         if (cpu_feature & CPUID_TSC) {
2737                 /*
2738                  * The BSP is constantly updating tsc0_offset, figure out
2739                  * the relative difference to synchronize ktrdump.
2740                  */
2741                 tsc_offsets[mycpu->gd_cpuid] = rdtsc() - tsc0_offset;
2742         }
2743
2744         /* BSP may have changed PTD while we're waiting for the lock */
2745         cpu_invltlb();
2746
2747 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
2748         lidt(&r_idt);
2749 #endif
2750
2751         /* Build our map of 'other' CPUs. */
2752         mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
2753
2754         kprintf("SMP: AP CPU #%d Launched!\n", mycpu->gd_cpuid);
2755
2756         /* A quick check from sanity claus */
2757         apic_id = (apic_id_to_logical[(lapic.id & 0xff000000) >> 24]);
2758         if (mycpu->gd_cpuid != apic_id) {
2759                 kprintf("SMP: cpuid = %d\n", mycpu->gd_cpuid);
2760                 kprintf("SMP: apic_id = %d\n", apic_id);
2761                 kprintf("PTD[MPPTDI] = %p\n", (void *)PTD[MPPTDI]);
2762                 panic("cpuid mismatch! boom!!");
2763         }
2764
2765         /* Initialize AP's local APIC for irq's */
2766         apic_initialize(FALSE);
2767
2768         /* Set memory range attributes for this CPU to match the BSP */
2769         mem_range_AP_init();
2770
2771         /*
2772          * Once we go active we must process any IPIQ messages that may
2773          * have been queued, because no actual IPI will occur until we
2774          * set our bit in the smp_active_mask.  If we don't the IPI
2775          * message interlock could be left set which would also prevent
2776          * further IPIs.
2777          *
2778          * The idle loop doesn't expect the BGL to be held and while
2779          * lwkt_switch() normally cleans things up this is a special case
2780          * because we returning almost directly into the idle loop.
2781          *
2782          * The idle thread is never placed on the runq, make sure
2783          * nothing we've done put it there.
2784          */
2785         KKASSERT(get_mplock_count(curthread) == 1);
2786         smp_active_mask |= CPUMASK(mycpu->gd_cpuid);
2787
2788         /*
2789          * Enable interrupts here.  idle_restore will also do it, but
2790          * doing it here lets us clean up any strays that got posted to
2791          * the CPU during the AP boot while we are still in a critical
2792          * section.
2793          */
2794         __asm __volatile("sti; pause; pause"::);
2795         bzero(mdcpu->gd_ipending, sizeof(mdcpu->gd_ipending));
2796
2797         initclocks_pcpu();      /* clock interrupts (via IPIs) */
2798         lwkt_process_ipiq();
2799
2800         /*
2801          * Releasing the mp lock lets the BSP finish up the SMP init
2802          */
2803         rel_mplock();
2804         KKASSERT((curthread->td_flags & TDF_RUNQ) == 0);
2805 }
2806
2807 /*
2808  * Get SMP fully working before we start initializing devices.
2809  */
2810 static
2811 void
2812 ap_finish(void)
2813 {
2814         mp_finish = 1;
2815         if (bootverbose)
2816                 kprintf("Finish MP startup\n");
2817         if (cpu_feature & CPUID_TSC)
2818                 tsc0_offset = rdtsc();
2819         tsc_offsets[0] = 0;
2820         rel_mplock();
2821         while (smp_active_mask != smp_startup_mask) {
2822                 cpu_lfence();
2823                 if (cpu_feature & CPUID_TSC)
2824                         tsc0_offset = rdtsc();
2825         }
2826         while (try_mplock() == 0)
2827                 ;
2828         if (bootverbose)
2829                 kprintf("Active CPU Mask: %08x\n", smp_active_mask);
2830 }
2831
2832 SYSINIT(finishsmp, SI_BOOT2_FINISH_SMP, SI_ORDER_FIRST, ap_finish, NULL)
2833
2834 void
2835 cpu_send_ipiq(int dcpu)
2836 {
2837         if (CPUMASK(dcpu) & smp_active_mask)
2838                 single_apic_ipi(dcpu, XIPIQ_OFFSET, APIC_DELMODE_FIXED);
2839 }
2840
2841 #if 0   /* single_apic_ipi_passive() not working yet */
2842 /*
2843  * Returns 0 on failure, 1 on success
2844  */
2845 int
2846 cpu_send_ipiq_passive(int dcpu)
2847 {
2848         int r = 0;
2849         if (CPUMASK(dcpu) & smp_active_mask) {
2850                 r = single_apic_ipi_passive(dcpu, XIPIQ_OFFSET,
2851                                         APIC_DELMODE_FIXED);
2852         }
2853         return(r);
2854 }
2855 #endif
2856
2857 struct mptable_lapic_cbarg1 {
2858         int     cpu_count;
2859         int     ht_fixup;
2860         u_int   ht_apicid_mask;
2861 };
2862
2863 static int
2864 mptable_lapic_pass1_callback(void *xarg, const void *pos, int type)
2865 {
2866         const struct PROCENTRY *ent;
2867         struct mptable_lapic_cbarg1 *arg = xarg;
2868
2869         if (type != 0)
2870                 return 0;
2871         ent = pos;
2872
2873         if ((ent->cpu_flags & PROCENTRY_FLAG_EN) == 0)
2874                 return 0;
2875
2876         arg->cpu_count++;
2877         if (ent->apic_id < 32) {
2878                 arg->ht_apicid_mask |= 1 << ent->apic_id;
2879         } else if (arg->ht_fixup) {
2880                 kprintf("MPTABLE: lapic id > 32, disable HTT fixup\n");
2881                 arg->ht_fixup = 0;
2882         }
2883         return 0;
2884 }
2885
2886 struct mptable_lapic_cbarg2 {
2887         int     cpu;
2888         int     logical_cpus;
2889         int     found_bsp;
2890 };
2891
2892 static int
2893 mptable_lapic_pass2_callback(void *xarg, const void *pos, int type)
2894 {
2895         const struct PROCENTRY *ent;
2896         struct mptable_lapic_cbarg2 *arg = xarg;
2897
2898         if (type != 0)
2899                 return 0;
2900         ent = pos;
2901
2902         if (ent->cpu_flags & PROCENTRY_FLAG_BP) {
2903                 KKASSERT(!arg->found_bsp);
2904                 arg->found_bsp = 1;
2905         }
2906
2907         if (processor_entry(ent, arg->cpu))
2908                 arg->cpu++;
2909
2910         if (arg->logical_cpus) {
2911                 struct PROCENTRY proc;
2912                 int i;
2913
2914                 /*
2915                  * Create fake mptable processor entries
2916                  * and feed them to processor_entry() to
2917                  * enumerate the logical CPUs.
2918                  */
2919                 bzero(&proc, sizeof(proc));
2920                 proc.type = 0;
2921                 proc.cpu_flags = PROCENTRY_FLAG_EN;
2922                 proc.apic_id = ent->apic_id;
2923
2924                 for (i = 1; i < arg->logical_cpus; i++) {
2925                         proc.apic_id++;
2926                         processor_entry(&proc, arg->cpu);
2927                         arg->cpu++;
2928                 }
2929         }
2930         return 0;
2931 }
2932
2933 static void
2934 mptable_imcr(struct mptable_pos *mpt)
2935 {
2936         /* record whether PIC or virtual-wire mode */
2937         machintr_setvar_simple(MACHINTR_VAR_IMCR_PRESENT,
2938                                mpt->mp_fps->mpfb2 & 0x80);
2939 }
2940
2941 static void
2942 mptable_lapic_default(void)
2943 {
2944         int ap_apicid, bsp_apicid;
2945
2946         mp_naps = 1; /* exclude BSP */
2947
2948         /* Map local apic before the id field is accessed */
2949         lapic_map(DEFAULT_APIC_BASE);
2950
2951         bsp_apicid = APIC_ID(lapic.id);
2952         ap_apicid = (bsp_apicid == 0) ? 1 : 0;
2953
2954         /* BSP */
2955         mp_set_cpuids(0, bsp_apicid);
2956         /* one and only AP */
2957         mp_set_cpuids(1, ap_apicid);
2958 }
2959
2960 /*
2961  * Configure:
2962  *     mp_naps
2963  *     ID_TO_CPU(N), APIC ID to logical CPU table
2964  *     CPU_TO_ID(N), logical CPU to APIC ID table
2965  */
2966 static void
2967 mptable_lapic_enumerate(struct lapic_enumerator *e)
2968 {
2969         struct mptable_pos mpt;
2970         struct mptable_lapic_cbarg1 arg1;
2971         struct mptable_lapic_cbarg2 arg2;
2972         mpcth_t cth;
2973         int error, logical_cpus = 0;
2974         vm_offset_t lapic_addr;
2975
2976         if (mptable_use_default) {
2977                 mptable_lapic_default();
2978                 return;
2979         }
2980
2981         error = mptable_map(&mpt);
2982         if (error)
2983                 panic("mptable_lapic_enumerate mptable_map failed\n");
2984         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
2985
2986         cth = mpt.mp_cth;
2987
2988         /* Save local apic address */
2989         lapic_addr = (vm_offset_t)cth->apic_address;
2990         KKASSERT(lapic_addr != 0);
2991
2992         /*
2993          * Find out how many CPUs do we have
2994          */
2995         bzero(&arg1, sizeof(arg1));
2996         arg1.ht_fixup = 1; /* Apply ht fixup by default */
2997
2998         error = mptable_iterate_entries(cth,
2999                     mptable_lapic_pass1_callback, &arg1);
3000         if (error)
3001                 panic("mptable_iterate_entries(lapic_pass1) failed\n");
3002         KKASSERT(arg1.cpu_count != 0);
3003
3004         /* See if we need to fixup HT logical CPUs. */
3005         if (arg1.ht_fixup) {
3006                 logical_cpus = mptable_hyperthread_fixup(arg1.ht_apicid_mask,
3007                                                          arg1.cpu_count);
3008                 if (logical_cpus != 0)
3009                         arg1.cpu_count *= logical_cpus;
3010         }
3011         mp_naps = arg1.cpu_count;
3012
3013         /* Qualify the numbers again, after possible HT fixup */
3014         if (mp_naps > MAXCPU) {
3015                 kprintf("Warning: only using %d of %d available CPUs!\n",
3016                         MAXCPU, mp_naps);
3017                 mp_naps = MAXCPU;
3018         }
3019
3020         --mp_naps;      /* subtract the BSP */
3021
3022         /*
3023          * Link logical CPU id to local apic id
3024          */
3025         bzero(&arg2, sizeof(arg2));
3026         arg2.cpu = 1;
3027         arg2.logical_cpus = logical_cpus;
3028
3029         error = mptable_iterate_entries(cth,
3030                     mptable_lapic_pass2_callback, &arg2);
3031         if (error)
3032                 panic("mptable_iterate_entries(lapic_pass2) failed\n");
3033         KKASSERT(arg2.found_bsp);
3034
3035         /* Map local apic */
3036         lapic_map(lapic_addr);
3037
3038         mptable_unmap(&mpt);
3039 }
3040
3041 struct mptable_lapic_probe_cbarg {
3042         int     cpu_count;
3043         int     found_bsp;
3044 };
3045
3046 static int
3047 mptable_lapic_probe_callback(void *xarg, const void *pos, int type)
3048 {
3049         const struct PROCENTRY *ent;
3050         struct mptable_lapic_probe_cbarg *arg = xarg;
3051
3052         if (type != 0)
3053                 return 0;
3054         ent = pos;
3055
3056         if ((ent->cpu_flags & PROCENTRY_FLAG_EN) == 0)
3057                 return 0;
3058         arg->cpu_count++;
3059
3060         if (ent->cpu_flags & PROCENTRY_FLAG_BP) {
3061                 if (arg->found_bsp) {
3062                         kprintf("more than one BSP in base MP table\n");
3063                         return EINVAL;
3064                 }
3065                 arg->found_bsp = 1;
3066         }
3067         return 0;
3068 }
3069
3070 static int
3071 mptable_lapic_probe(struct lapic_enumerator *e)
3072 {
3073         struct mptable_pos mpt;
3074         struct mptable_lapic_probe_cbarg arg;
3075         mpcth_t cth;
3076         int error;
3077
3078         if (mptable_fps_phyaddr == 0)
3079                 return ENXIO;
3080
3081         if (mptable_use_default)
3082                 return 0;
3083
3084         error = mptable_map(&mpt);
3085         if (error)
3086                 return error;
3087         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
3088
3089         error = EINVAL;
3090         cth = mpt.mp_cth;
3091
3092         if (cth->apic_address == 0)
3093                 goto done;
3094
3095         bzero(&arg, sizeof(arg));
3096         error = mptable_iterate_entries(cth,
3097                     mptable_lapic_probe_callback, &arg);
3098         if (!error) {
3099                 if (arg.cpu_count == 0) {
3100                         kprintf("MP table contains no processor entries\n");
3101                         error = EINVAL;
3102                 } else if (!arg.found_bsp) {
3103                         kprintf("MP table does not contains BSP entry\n");
3104                         error = EINVAL;
3105                 }
3106         }
3107 done:
3108         mptable_unmap(&mpt);
3109         return error;
3110 }
3111
3112 static struct lapic_enumerator  mptable_lapic_enumerator = {
3113         .lapic_prio = LAPIC_ENUM_PRIO_MPTABLE,
3114         .lapic_probe = mptable_lapic_probe,
3115         .lapic_enumerate = mptable_lapic_enumerate
3116 };
3117
3118 static void
3119 mptable_lapic_enum_register(void)
3120 {
3121         lapic_enumerator_register(&mptable_lapic_enumerator);
3122 }
3123 SYSINIT(mptable_lapic, SI_BOOT2_PRESMP, SI_ORDER_ANY,
3124         mptable_lapic_enum_register, 0);