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