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