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