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