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