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