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