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