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