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