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