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