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