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