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