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