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