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