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