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