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