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