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