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