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