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