xref: /freebsd/sys/kern/subr_smp.c (revision 9a3b3e8bce8e8c8bbec663229e16bebb3cfc5d53)
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.45 1997/08/25 21:28:08 bde Exp $
26  */
27 
28 #include "opt_smp.h"
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/proc.h>
34 #include <sys/sysctl.h>
35 
36 #include <vm/vm.h>
37 #include <vm/vm_param.h>
38 #include <vm/pmap.h>
39 #include <vm/vm_kern.h>
40 #include <vm/vm_extern.h>
41 
42 #include <machine/smp.h>
43 #include <machine/apic.h>
44 #include <machine/mpapic.h>
45 #include <machine/segments.h>
46 #include <machine/smptests.h>	/** TEST_DEFAULT_CONFIG, TEST_TEST1 */
47 #include <machine/tss.h>
48 #include <machine/specialreg.h>
49 
50 #include <i386/i386/cons.h>	/* cngetc() */
51 
52 #if defined(APIC_IO)
53 #include <machine/md_var.h>		/* setidt() */
54 #include <i386/isa/icu.h>		/* IPIs */
55 #include <i386/isa/intr_machdep.h>	/* IPIs */
56 #endif	/* APIC_IO */
57 
58 #if defined(TEST_DEFAULT_CONFIG)
59 #define MPFPS_MPFB1	TEST_DEFAULT_CONFIG
60 #else
61 #define MPFPS_MPFB1	mpfps->mpfb1
62 #endif  /* TEST_DEFAULT_CONFIG */
63 
64 #define WARMBOOT_TARGET		0
65 #define WARMBOOT_OFF		(KERNBASE + 0x0467)
66 #define WARMBOOT_SEG		(KERNBASE + 0x0469)
67 
68 #define BIOS_BASE		(0xf0000)
69 #define BIOS_SIZE		(0x10000)
70 #define BIOS_COUNT		(BIOS_SIZE/4)
71 
72 #define CMOS_REG		(0x70)
73 #define CMOS_DATA		(0x71)
74 #define BIOS_RESET		(0x0f)
75 #define BIOS_WARM		(0x0a)
76 
77 #define PROCENTRY_FLAG_EN	0x01
78 #define PROCENTRY_FLAG_BP	0x02
79 #define IOAPICENTRY_FLAG_EN	0x01
80 
81 
82 /* MP Floating Pointer Structure */
83 typedef struct MPFPS {
84 	char    signature[4];
85 	void   *pap;
86 	u_char  length;
87 	u_char  spec_rev;
88 	u_char  checksum;
89 	u_char  mpfb1;
90 	u_char  mpfb2;
91 	u_char  mpfb3;
92 	u_char  mpfb4;
93 	u_char  mpfb5;
94 }      *mpfps_t;
95 
96 /* MP Configuration Table Header */
97 typedef struct MPCTH {
98 	char    signature[4];
99 	u_short base_table_length;
100 	u_char  spec_rev;
101 	u_char  checksum;
102 	u_char  oem_id[8];
103 	u_char  product_id[12];
104 	void   *oem_table_pointer;
105 	u_short oem_table_size;
106 	u_short entry_count;
107 	void   *apic_address;
108 	u_short extended_table_length;
109 	u_char  extended_table_checksum;
110 	u_char  reserved;
111 }      *mpcth_t;
112 
113 
114 typedef struct PROCENTRY {
115 	u_char  type;
116 	u_char  apic_id;
117 	u_char  apic_version;
118 	u_char  cpu_flags;
119 	u_long  cpu_signature;
120 	u_long  feature_flags;
121 	u_long  reserved1;
122 	u_long  reserved2;
123 }      *proc_entry_ptr;
124 
125 typedef struct BUSENTRY {
126 	u_char  type;
127 	u_char  bus_id;
128 	char    bus_type[6];
129 }      *bus_entry_ptr;
130 
131 typedef struct IOAPICENTRY {
132 	u_char  type;
133 	u_char  apic_id;
134 	u_char  apic_version;
135 	u_char  apic_flags;
136 	void   *apic_address;
137 }      *io_apic_entry_ptr;
138 
139 typedef struct INTENTRY {
140 	u_char  type;
141 	u_char  int_type;
142 	u_short int_flags;
143 	u_char  src_bus_id;
144 	u_char  src_bus_irq;
145 	u_char  dst_apic_id;
146 	u_char  dst_apic_int;
147 }      *int_entry_ptr;
148 
149 /* descriptions of MP basetable entries */
150 typedef struct BASETABLE_ENTRY {
151 	u_char  type;
152 	u_char  length;
153 	char    name[16];
154 }       basetable_entry;
155 
156 /*
157  * this code MUST be enabled here and in mpboot.s.
158  * it follows the very early stages of AP boot by placing values in CMOS ram.
159  * it NORMALLY will never be needed and thus the primitive method for enabling.
160  *
161 #define CHECK_POINTS
162  */
163 
164 #if defined(CHECK_POINTS)
165 #define CHECK_READ(A)	 (outb(CMOS_REG, (A)), inb(CMOS_DATA))
166 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
167 
168 #define CHECK_INIT(D);				\
169 	CHECK_WRITE(0x34, (D));			\
170 	CHECK_WRITE(0x35, (D));			\
171 	CHECK_WRITE(0x36, (D));			\
172 	CHECK_WRITE(0x37, (D));			\
173 	CHECK_WRITE(0x38, (D));			\
174 	CHECK_WRITE(0x39, (D));
175 
176 #define CHECK_PRINT(S);				\
177 	printf("%s: %d, %d, %d, %d, %d, %d\n",	\
178 	   (S),					\
179 	   CHECK_READ(0x34),			\
180 	   CHECK_READ(0x35),			\
181 	   CHECK_READ(0x36),			\
182 	   CHECK_READ(0x37),			\
183 	   CHECK_READ(0x38),			\
184 	   CHECK_READ(0x39));
185 
186 #else				/* CHECK_POINTS */
187 
188 #define CHECK_INIT(D)
189 #define CHECK_PRINT(S)
190 
191 #endif				/* CHECK_POINTS */
192 
193 /*
194  * Values to send to the POST hardware.
195  */
196 #define MP_BOOTADDRESS_POST	0x10
197 #define MP_PROBE_POST		0x11
198 #define MP_START_POST		0x12
199 #define MP_ANNOUNCE_POST	0x13
200 #define MPTABLE_PASS1_POST	0x14
201 #define MPTABLE_PASS2_POST	0x15
202 #define MP_ENABLE_POST		0x16
203 #define START_ALL_APS_POST	0x17
204 #define INSTALL_AP_TRAMP_POST	0x18
205 #define START_AP_POST		0x19
206 
207 /** XXX FIXME: where does this really belong, isa.h/isa.c perhaps? */
208 int	current_postcode;
209 
210 /** XXX FIXME: what system files declare these??? */
211 extern struct region_descriptor r_gdt, r_idt;
212 
213 int	bsp_apic_ready = 0;	/* flags useability of BSP apic */
214 int	mp_ncpus;		/* # of CPUs, including BSP */
215 int	mp_naps;		/* # of Applications processors */
216 int	mp_nbusses;		/* # of busses */
217 int	mp_napics;		/* # of IO APICs */
218 int	boot_cpu_id;		/* designated BSP */
219 vm_offset_t cpu_apic_address;
220 vm_offset_t io_apic_address[NAPICID];	/* NAPICID is more than enough */
221 
222 u_int32_t cpu_apic_versions[NCPU];
223 u_int32_t io_apic_versions[NAPIC];
224 
225 /*
226  * APIC ID logical/physical mapping structures.
227  * We oversize these to simplify boot-time config.
228  */
229 int     cpu_num_to_apic_id[NAPICID];
230 int     io_num_to_apic_id[NAPICID];
231 int     apic_id_to_logical[NAPICID];
232 
233 /* Bitmap of all available CPUs */
234 u_int	all_cpus;
235 
236 /* AP uses this PTD during bootstrap */
237 pd_entry_t *bootPTD;
238 
239 /* Hotwire a 0->4MB V==P mapping */
240 extern pt_entry_t *KPTphys;
241 
242 /* Virtual address of per-cpu common_tss */
243 extern struct i386tss common_tss;
244 
245 /* IdlePTD per cpu */
246 pd_entry_t *IdlePTDS[NCPU];
247 
248 /* "my" private page table page, for BSP init */
249 extern pt_entry_t SMP_prvpt[];
250 
251 /* Private page pointer to curcpu's PTD, used during BSP init */
252 extern pd_entry_t *my_idlePTD;
253 
254 /*
255  * Local data and functions.
256  */
257 
258 static int	mp_capable;
259 static u_int	boot_address;
260 static u_int	base_memory;
261 
262 static int	picmode;		/* 0: virtual wire mode, 1: PIC mode */
263 static mpfps_t	mpfps;
264 static int	search_for_sig(u_int32_t target, int count);
265 static void	mp_enable(u_int boot_addr);
266 
267 static int	mptable_pass1(void);
268 static int	mptable_pass2(void);
269 static void	default_mp_table(int type);
270 static void	fix_mp_table(void);
271 static void	init_locks(void);
272 static int	start_all_aps(u_int boot_addr);
273 static void	install_ap_tramp(u_int boot_addr);
274 static int	start_ap(int logicalCpu, u_int boot_addr);
275 
276 
277 /*
278  * Calculate usable address in base memory for AP trampoline code.
279  */
280 u_int
281 mp_bootaddress(u_int basemem)
282 {
283 	POSTCODE(MP_BOOTADDRESS_POST);
284 
285 	base_memory = basemem * 1024;	/* convert to bytes */
286 
287 	boot_address = base_memory & ~0xfff;	/* round down to 4k boundary */
288 	if ((base_memory - boot_address) < bootMP_size)
289 		boot_address -= 4096;	/* not enough, lower by 4k */
290 
291 	return boot_address;
292 }
293 
294 
295 /*
296  * Look for an Intel MP spec table (ie, SMP capable hardware).
297  */
298 int
299 mp_probe(void)
300 {
301 	int     x;
302 	u_long  segment;
303 	u_int32_t target;
304 
305 	POSTCODE(MP_PROBE_POST);
306 
307 	/* see if EBDA exists */
308 	if (segment = (u_long) * (u_short *) (KERNBASE + 0x40e)) {
309 		/* search first 1K of EBDA */
310 		target = (u_int32_t) (segment << 4);
311 		if ((x = search_for_sig(target, 1024 / 4)) >= 0)
312 			goto found;
313 	} else {
314 		/* last 1K of base memory, effective 'top of base' passed in */
315 		target = (u_int32_t) (base_memory - 0x400);
316 		if ((x = search_for_sig(target, 1024 / 4)) >= 0)
317 			goto found;
318 	}
319 
320 	/* search the BIOS */
321 	target = (u_int32_t) BIOS_BASE;
322 	if ((x = search_for_sig(target, BIOS_COUNT)) >= 0)
323 		goto found;
324 
325 	/* nothing found */
326 	mpfps = (mpfps_t)0;
327 	mp_capable = 0;
328 	return 0;
329 
330 found:
331 	/* calculate needed resources */
332 	mpfps = (mpfps_t)x;
333 	if (mptable_pass1())
334 		panic("you must reconfigure your kernel");
335 
336 	/* flag fact that we are running multiple processors */
337 	mp_capable = 1;
338 	return 1;
339 }
340 
341 
342 /*
343  * Startup the SMP processors.
344  */
345 void
346 mp_start(void)
347 {
348 	POSTCODE(MP_START_POST);
349 
350 	/* look for MP capable motherboard */
351 	if (mp_capable)
352 		mp_enable(boot_address);
353 	else
354 		panic("MP hardware not found!");
355 }
356 
357 
358 /*
359  * Print various information about the SMP system hardware and setup.
360  */
361 void
362 mp_announce(void)
363 {
364 	int     x;
365 
366 	POSTCODE(MP_ANNOUNCE_POST);
367 
368 	printf("FreeBSD/SMP: Multiprocessor motherboard\n");
369 	printf(" cpu0 (BSP): apic id: %2d", CPU_TO_ID(0));
370 	printf(", version: 0x%08x", cpu_apic_versions[0]);
371 	printf(", at 0x%08x\n", cpu_apic_address);
372 	for (x = 1; x <= mp_naps; ++x) {
373 		printf(" cpu%d (AP):  apic id: %2d", x, CPU_TO_ID(x));
374 		printf(", version: 0x%08x", cpu_apic_versions[x]);
375 		printf(", at 0x%08x\n", cpu_apic_address);
376 	}
377 
378 #if defined(APIC_IO)
379 	for (x = 0; x < mp_napics; ++x) {
380 		printf(" io%d (APIC): apic id: %2d", x, IO_TO_ID(x));
381 		printf(", version: 0x%08x", io_apic_versions[x]);
382 		printf(", at 0x%08x\n", io_apic_address[x]);
383 	}
384 #else
385 	printf(" Warning: APIC I/O disabled\n");
386 #endif	/* APIC_IO */
387 }
388 
389 /*
390  * AP cpu's call this to sync up protected mode.
391  */
392 void
393 init_secondary(void)
394 {
395 	int     gsel_tss, slot;
396 
397 	r_gdt.rd_limit = sizeof(gdt[0]) * (NGDT + NCPU) - 1;
398 	r_gdt.rd_base = (int) gdt;
399 	lgdt(&r_gdt);			/* does magic intra-segment return */
400 	lidt(&r_idt);
401 	lldt(_default_ldt);
402 
403 	slot = NGDT + cpuid;
404 	gsel_tss = GSEL(slot, SEL_KPL);
405 	gdt[slot].sd.sd_type = SDT_SYS386TSS;
406 	common_tss.tss_esp0 = 0;	/* not used until after switch */
407 	common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
408 	common_tss.tss_ioopt = (sizeof common_tss) << 16;
409 	ltr(gsel_tss);
410 
411 	load_cr0(0x8005003b);		/* XXX! */
412 
413 	PTD[0] = 0;
414 	pmap_set_opt((unsigned *)PTD);
415 
416 	invltlb();
417 }
418 
419 
420 #if defined(APIC_IO)
421 /*
422  * Final configuration of the BSP's local APIC:
423  *  - disable 'pic mode'.
424  *  - disable 'virtual wire mode'.
425  *  - enable NMI.
426  */
427 void
428 bsp_apic_configure(void)
429 {
430 	u_char		byte;
431 	u_int32_t	temp;
432 
433 	/* leave 'pic mode' if necessary */
434 	if (picmode) {
435 		outb(0x22, 0x70);	/* select IMCR */
436 		byte = inb(0x23);	/* current contents */
437 		byte |= 0x01;		/* mask external INTR */
438 		outb(0x23, byte);	/* disconnect 8259s/NMI */
439 	}
440 
441 	/* mask lint0 (the 8259 'virtual wire' connection) */
442 	temp = lapic.lvt_lint0;
443 	temp |= APIC_LVT_M;		/* set the mask */
444 	lapic.lvt_lint0 = temp;
445 
446         /* setup lint1 to handle NMI */
447         temp = lapic.lvt_lint1;
448         temp &= ~APIC_LVT_M;		/* clear the mask */
449         lapic.lvt_lint1 = temp;
450 
451 	if (bootverbose)
452 		apic_dump("bsp_apic_configure()");
453 }
454 #endif  /* APIC_IO */
455 
456 
457 /*******************************************************************
458  * local functions and data
459  */
460 
461 /*
462  * start the SMP system
463  */
464 static void
465 mp_enable(u_int boot_addr)
466 {
467 	int     x;
468 #if defined(APIC_IO)
469 	int     apic;
470 	u_int   ux;
471 #endif	/* APIC_IO */
472 
473 	POSTCODE(MP_ENABLE_POST);
474 
475 	/* turn on 4MB of V == P addressing so we can get to MP table */
476 	*(int *)PTD = PG_V | PG_RW | ((u_long)KPTphys & PG_FRAME);
477 	invltlb();
478 
479 	/* examine the MP table for needed info, uses physical addresses */
480 	x = mptable_pass2();
481 
482 	*(int *)PTD = 0;
483 	invltlb();
484 
485 	/* can't process default configs till the CPU APIC is pmapped */
486 	if (x)
487 		default_mp_table(x);
488 
489 	/* post scan cleanup */
490 	fix_mp_table();
491 
492 #if defined(APIC_IO)
493 
494 	/* fill the LOGICAL io_apic_versions table */
495 	for (apic = 0; apic < mp_napics; ++apic) {
496 		ux = io_apic_read(apic, IOAPIC_VER);
497 		io_apic_versions[apic] = ux;
498 	}
499 
500 	/* program each IO APIC in the system */
501 	for (apic = 0; apic < mp_napics; ++apic)
502 		if (io_apic_setup(apic) < 0)
503 			panic("IO APIC setup failure");
504 
505 	/* install a 'Spurious INTerrupt' vector */
506 	setidt(XSPURIOUSINT_OFFSET, Xspuriousint,
507 	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
508 
509 	/* install an inter-CPU IPI for TLB invalidation */
510 	setidt(XINVLTLB_OFFSET, Xinvltlb,
511 	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
512 
513 	/* install an inter-CPU IPI for CPU stop/restart */
514 	setidt(XCPUSTOP_OFFSET, Xcpustop,
515 	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
516 
517 #if defined(TEST_TEST1)
518 	/* install a "fake hardware INTerrupt" vector */
519 	setidt(XTEST1_OFFSET, Xtest1,
520 	       SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
521 #endif  /** TEST_TEST1 */
522 
523 #endif	/* APIC_IO */
524 
525 	/* initialize all SMP locks */
526 	init_locks();
527 
528 	/* start each Application Processor */
529 	start_all_aps(boot_addr);
530 
531 	/*
532 	 * The init process might be started on a different CPU now,
533 	 * and the boot CPU might not call prepare_usermode to get
534 	 * cr0 correctly configured. Thus we initialize cr0 here.
535 	 */
536 	load_cr0(rcr0() | CR0_WP | CR0_AM);
537 }
538 
539 
540 /*
541  * look for the MP spec signature
542  */
543 
544 /* string defined by the Intel MP Spec as identifying the MP table */
545 #define MP_SIG		0x5f504d5f	/* _MP_ */
546 #define NEXT(X)		((X) += 4)
547 static int
548 search_for_sig(u_int32_t target, int count)
549 {
550 	int     x;
551 	u_int32_t *addr = (u_int32_t *) (KERNBASE + target);
552 
553 	for (x = 0; x < count; NEXT(x))
554 		if (addr[x] == MP_SIG)
555 			/* make array index a byte index */
556 			return (target + (x * sizeof(u_int32_t)));
557 
558 	return -1;
559 }
560 
561 
562 static basetable_entry basetable_entry_types[] =
563 {
564 	{0, 20, "Processor"},
565 	{1, 8, "Bus"},
566 	{2, 8, "I/O APIC"},
567 	{3, 8, "I/O INT"},
568 	{4, 8, "Local INT"}
569 };
570 
571 typedef struct BUSDATA {
572 	u_char  bus_id;
573 	enum busTypes bus_type;
574 }       bus_datum;
575 
576 typedef struct INTDATA {
577 	u_char  int_type;
578 	u_short int_flags;
579 	u_char  src_bus_id;
580 	u_char  src_bus_irq;
581 	u_char  dst_apic_id;
582 	u_char  dst_apic_int;
583 }       io_int, local_int;
584 
585 typedef struct BUSTYPENAME {
586 	u_char  type;
587 	char    name[7];
588 }       bus_type_name;
589 
590 static bus_type_name bus_type_table[] =
591 {
592 	{CBUS, "CBUS"},
593 	{CBUSII, "CBUSII"},
594 	{EISA, "EISA"},
595 	{UNKNOWN_BUSTYPE, "---"},
596 	{UNKNOWN_BUSTYPE, "---"},
597 	{ISA, "ISA"},
598 	{UNKNOWN_BUSTYPE, "---"},
599 	{UNKNOWN_BUSTYPE, "---"},
600 	{UNKNOWN_BUSTYPE, "---"},
601 	{UNKNOWN_BUSTYPE, "---"},
602 	{UNKNOWN_BUSTYPE, "---"},
603 	{UNKNOWN_BUSTYPE, "---"},
604 	{PCI, "PCI"},
605 	{UNKNOWN_BUSTYPE, "---"},
606 	{UNKNOWN_BUSTYPE, "---"},
607 	{UNKNOWN_BUSTYPE, "---"},
608 	{UNKNOWN_BUSTYPE, "---"},
609 	{XPRESS, "XPRESS"},
610 	{UNKNOWN_BUSTYPE, "---"}
611 };
612 /* from MP spec v1.4, table 5-1 */
613 static int default_data[7][5] =
614 {
615 /*   nbus, id0, type0, id1, type1 */
616 	{1, 0, ISA, 255, 255},
617 	{1, 0, EISA, 255, 255},
618 	{1, 0, EISA, 255, 255},
619 	{0, 255, 255, 255, 255},/* MCA not supported */
620 	{2, 0, ISA, 1, PCI},
621 	{2, 0, EISA, 1, PCI},
622 	{0, 255, 255, 255, 255}	/* MCA not supported */
623 };
624 
625 
626 /* the bus data */
627 bus_datum bus_data[NBUS];
628 
629 /* the IO INT data, one entry per possible APIC INTerrupt */
630 io_int  io_apic_ints[NINTR];
631 
632 static int nintrs;
633 
634 static int processor_entry	__P((proc_entry_ptr entry, int cpu));
635 static int bus_entry		__P((bus_entry_ptr entry, int bus));
636 static int io_apic_entry	__P((io_apic_entry_ptr entry, int apic));
637 static int int_entry		__P((int_entry_ptr entry, int intr));
638 static int lookup_bus_type	__P((char *name));
639 
640 
641 /*
642  * 1st pass on motherboard's Intel MP specification table.
643  *
644  * initializes:
645  *	mp_ncpus = 1
646  *
647  * determines:
648  *	cpu_apic_address (common to all CPUs)
649  *	io_apic_address[N]
650  *	mp_naps
651  *	mp_nbusses
652  *	mp_napics
653  *	nintrs
654  */
655 static int
656 mptable_pass1(void)
657 {
658 	int	x;
659 	mpcth_t	cth;
660 	int	totalSize;
661 	void*	position;
662 	int	count;
663 	int	type;
664 	int	mustpanic;
665 
666 	POSTCODE(MPTABLE_PASS1_POST);
667 
668 	mustpanic = 0;
669 
670 	/* clear various tables */
671 	for (x = 0; x < NAPICID; ++x) {
672 		io_apic_address[x] = ~0;	/* IO APIC address table */
673 	}
674 
675 	/* init everything to empty */
676 	mp_naps = 0;
677 	mp_nbusses = 0;
678 	mp_napics = 0;
679 	nintrs = 0;
680 
681 	/* check for use of 'default' configuration */
682 	if (MPFPS_MPFB1 != 0) {
683 		/* use default addresses */
684 		cpu_apic_address = DEFAULT_APIC_BASE;
685 		io_apic_address[0] = DEFAULT_IO_APIC_BASE;
686 
687 		/* fill in with defaults */
688 		mp_naps = 2;		/* includes BSP */
689 		mp_nbusses = default_data[MPFPS_MPFB1 - 1][0];
690 #if defined(APIC_IO)
691 		mp_napics = 1;
692 		nintrs = 16;
693 #endif	/* APIC_IO */
694 	}
695 	else {
696 		if ((cth = mpfps->pap) == 0)
697 			panic("MP Configuration Table Header MISSING!");
698 
699 		cpu_apic_address = (vm_offset_t) cth->apic_address;
700 
701 		/* walk the table, recording info of interest */
702 		totalSize = cth->base_table_length - sizeof(struct MPCTH);
703 		position = (u_char *) cth + sizeof(struct MPCTH);
704 		count = cth->entry_count;
705 
706 		while (count--) {
707 			switch (type = *(u_char *) position) {
708 			case 0: /* processor_entry */
709 				if (((proc_entry_ptr)position)->cpu_flags
710 					& PROCENTRY_FLAG_EN)
711 					++mp_naps;
712 				break;
713 			case 1: /* bus_entry */
714 				++mp_nbusses;
715 				break;
716 			case 2: /* io_apic_entry */
717 				if (((io_apic_entry_ptr)position)->apic_flags
718 					& IOAPICENTRY_FLAG_EN)
719 					io_apic_address[mp_napics++] =
720 					    (vm_offset_t)((io_apic_entry_ptr)
721 						position)->apic_address;
722 				break;
723 			case 3: /* int_entry */
724 				++nintrs;
725 				break;
726 			case 4:	/* int_entry */
727 				break;
728 			default:
729 				panic("mpfps Base Table HOSED!");
730 				/* NOTREACHED */
731 			}
732 
733 			totalSize -= basetable_entry_types[type].length;
734 			(u_char*)position += basetable_entry_types[type].length;
735 		}
736 	}
737 
738 	/* qualify the numbers */
739 	if (mp_naps > NCPU)
740 #if 0 /* XXX FIXME: kern/4255 */
741 		printf("Warning: only using %d of %d available CPUs!\n",
742 			NCPU, mp_naps);
743 #else
744 	{
745 		printf("NCPU cannot be different than actual CPU count.\n");
746 		printf(" add 'options NCPU=%d' to your kernel config file,\n",
747 			mp_naps);
748 		printf(" then rerun config & rebuild your SMP kernel\n");
749 		mustpanic = 1;
750 	}
751 #endif /* XXX FIXME: kern/4255 */
752 	if (mp_nbusses > NBUS) {
753 		printf("found %d busses, increase NBUS\n", mp_nbusses);
754 		mustpanic = 1;
755 	}
756 	if (mp_napics > NAPIC) {
757 		printf("found %d apics, increase NAPIC\n", mp_napics);
758 		mustpanic = 1;
759 	}
760 	if (nintrs > NINTR) {
761 		printf("found %d intrs, increase NINTR\n", nintrs);
762 		mustpanic = 1;
763 	}
764 
765 	/*
766 	 * Count the BSP.
767 	 * This is also used as a counter while starting the APs.
768 	 */
769 	mp_ncpus = 1;
770 
771 	--mp_naps;	/* subtract the BSP */
772 
773 	return mustpanic;
774 }
775 
776 
777 /*
778  * 2nd pass on motherboard's Intel MP specification table.
779  *
780  * sets:
781  *	boot_cpu_id
782  *	ID_TO_IO(N), phy APIC ID to log CPU/IO table
783  *	CPU_TO_ID(N), logical CPU to APIC ID table
784  *	IO_TO_ID(N), logical IO to APIC ID table
785  *	bus_data[N]
786  *	io_apic_ints[N]
787  */
788 static int
789 mptable_pass2(void)
790 {
791 	int     x;
792 	mpcth_t cth;
793 	int     totalSize;
794 	void*   position;
795 	int     count;
796 	int     type;
797 	int     apic, bus, cpu, intr;
798 
799 	POSTCODE(MPTABLE_PASS2_POST);
800 
801 	/* clear various tables */
802 	for (x = 0; x < NAPICID; ++x) {
803 		ID_TO_IO(x) = -1;	/* phy APIC ID to log CPU/IO table */
804 		CPU_TO_ID(x) = -1;	/* logical CPU to APIC ID table */
805 		IO_TO_ID(x) = -1;	/* logical IO to APIC ID table */
806 	}
807 
808 	/* clear bus data table */
809 	for (x = 0; x < NBUS; ++x)
810 		bus_data[x].bus_id = 0xff;
811 
812 	/* clear IO APIC INT table */
813 	for (x = 0; x < NINTR; ++x)
814 		io_apic_ints[x].int_type = 0xff;
815 
816 	/* setup the cpu/apic mapping arrays */
817 	boot_cpu_id = -1;
818 
819 	/* record whether PIC or virtual-wire mode */
820 	picmode = (mpfps->mpfb2 & 0x80) ? 1 : 0;
821 
822 	/* check for use of 'default' configuration */
823 	if (MPFPS_MPFB1 != 0)
824 		return MPFPS_MPFB1;	/* return default configuration type */
825 
826 	if ((cth = mpfps->pap) == 0)
827 		panic("MP Configuration Table Header MISSING!");
828 
829 	/* walk the table, recording info of interest */
830 	totalSize = cth->base_table_length - sizeof(struct MPCTH);
831 	position = (u_char *) cth + sizeof(struct MPCTH);
832 	count = cth->entry_count;
833 	apic = bus = intr = 0;
834 	cpu = 1;				/* pre-count the BSP */
835 
836 	while (count--) {
837 		switch (type = *(u_char *) position) {
838 		case 0:
839 			if (processor_entry(position, cpu))
840 				++cpu;
841 			break;
842 		case 1:
843 			if (bus_entry(position, bus))
844 				++bus;
845 			break;
846 		case 2:
847 			if (io_apic_entry(position, apic))
848 				++apic;
849 			break;
850 		case 3:
851 			if (int_entry(position, intr))
852 				++intr;
853 			break;
854 		case 4:
855 			/* int_entry(position); */
856 			break;
857 		default:
858 			panic("mpfps Base Table HOSED!");
859 			/* NOTREACHED */
860 		}
861 
862 		totalSize -= basetable_entry_types[type].length;
863 		(u_char *) position += basetable_entry_types[type].length;
864 	}
865 
866 	if (boot_cpu_id == -1)
867 		panic("NO BSP found!");
868 
869 	/* report fact that its NOT a default configuration */
870 	return 0;
871 }
872 
873 
874 /*
875  * parse an Intel MP specification table
876  */
877 static void
878 fix_mp_table(void)
879 {
880 	int	x;
881 	int	id;
882 	int	bus_0;
883 	int	bus_pci;
884 	int	num_pci_bus;
885 
886 	/*
887 	 * Fix mis-numbering of the PCI bus and its INT entries if the BIOS
888 	 * did it wrong.  The MP spec says that when more than 1 PCI bus
889 	 * exists the BIOS must begin with bus entries for the PCI bus and use
890 	 * actual PCI bus numbering.  This implies that when only 1 PCI bus
891 	 * exists the BIOS can choose to ignore this ordering, and indeed many
892 	 * MP motherboards do ignore it.  This causes a problem when the PCI
893 	 * sub-system makes requests of the MP sub-system based on PCI bus
894 	 * numbers.	So here we look for the situation and renumber the
895 	 * busses and associated INTs in an effort to "make it right".
896 	 */
897 
898 	/* find bus 0, PCI bus, count the number of PCI busses */
899 	for (num_pci_bus = 0, x = 0; x < mp_nbusses; ++x) {
900 		if (bus_data[x].bus_id == 0) {
901 			bus_0 = x;
902 		}
903 		if (bus_data[x].bus_type == PCI) {
904 			++num_pci_bus;
905 			bus_pci = x;
906 		}
907 	}
908 	/*
909 	 * bus_0 == slot of bus with ID of 0
910 	 * bus_pci == slot of last PCI bus encountered
911 	 */
912 
913 	/* check the 1 PCI bus case for sanity */
914 	if (num_pci_bus == 1) {
915 
916 		/* if it is number 0 all is well */
917 		if (bus_data[bus_pci].bus_id == 0)
918 			return;
919 
920 		/* mis-numbered, swap with whichever bus uses slot 0 */
921 
922 		/* swap the bus entry types */
923 		bus_data[bus_pci].bus_type = bus_data[bus_0].bus_type;
924 		bus_data[bus_0].bus_type = PCI;
925 
926 		/* swap each relavant INTerrupt entry */
927 		id = bus_data[bus_pci].bus_id;
928 		for (x = 0; x < nintrs; ++x) {
929 			if (io_apic_ints[x].src_bus_id == id) {
930 				io_apic_ints[x].src_bus_id = 0;
931 			}
932 			else if (io_apic_ints[x].src_bus_id == 0) {
933 				io_apic_ints[x].src_bus_id = id;
934 			}
935 		}
936 	}
937 	/* sanity check if more than 1 PCI bus */
938 	else if (num_pci_bus > 1) {
939 		for (x = 0; x < mp_nbusses; ++x) {
940 			if (bus_data[x].bus_type != PCI)
941 				continue;
942 			if (bus_data[x].bus_id >= num_pci_bus)
943 				panic("bad PCI bus numbering");
944 		}
945 	}
946 }
947 
948 
949 static int
950 processor_entry(proc_entry_ptr entry, int cpu)
951 {
952 	/* check for usability */
953 	if ((cpu >= NCPU) || !(entry->cpu_flags & PROCENTRY_FLAG_EN))
954 		return 0;
955 
956 	/* check for BSP flag */
957 	if (entry->cpu_flags & PROCENTRY_FLAG_BP) {
958 		boot_cpu_id = entry->apic_id;
959 		CPU_TO_ID(0) = entry->apic_id;
960 		ID_TO_CPU(entry->apic_id) = 0;
961 		return 0;	/* its already been counted */
962 	}
963 
964 	/* add another AP to list, if less than max number of CPUs */
965 	else {
966 		CPU_TO_ID(cpu) = entry->apic_id;
967 		ID_TO_CPU(entry->apic_id) = cpu;
968 		return 1;
969 	}
970 }
971 
972 
973 static int
974 bus_entry(bus_entry_ptr entry, int bus)
975 {
976 	int     x;
977 	char    c, name[8];
978 
979 	/* encode the name into an index */
980 	for (x = 0; x < 6; ++x) {
981 		if ((c = entry->bus_type[x]) == ' ')
982 			break;
983 		name[x] = c;
984 	}
985 	name[x] = '\0';
986 
987 	if ((x = lookup_bus_type(name)) == UNKNOWN_BUSTYPE)
988 		panic("unknown bus type: '%s'", name);
989 
990 	bus_data[bus].bus_id = entry->bus_id;
991 	bus_data[bus].bus_type = x;
992 
993 	return 1;
994 }
995 
996 
997 static int
998 io_apic_entry(io_apic_entry_ptr entry, int apic)
999 {
1000 	if (!(entry->apic_flags & IOAPICENTRY_FLAG_EN))
1001 		return 0;
1002 
1003 	IO_TO_ID(apic) = entry->apic_id;
1004 	ID_TO_IO(entry->apic_id) = apic;
1005 
1006 	return 1;
1007 }
1008 
1009 
1010 static int
1011 lookup_bus_type(char *name)
1012 {
1013 	int     x;
1014 
1015 	for (x = 0; x < MAX_BUSTYPE; ++x)
1016 		if (strcmp(bus_type_table[x].name, name) == 0)
1017 			return bus_type_table[x].type;
1018 
1019 	return UNKNOWN_BUSTYPE;
1020 }
1021 
1022 
1023 static int
1024 int_entry(int_entry_ptr entry, int intr)
1025 {
1026 	io_apic_ints[intr].int_type = entry->int_type;
1027 	io_apic_ints[intr].int_flags = entry->int_flags;
1028 	io_apic_ints[intr].src_bus_id = entry->src_bus_id;
1029 	io_apic_ints[intr].src_bus_irq = entry->src_bus_irq;
1030 	io_apic_ints[intr].dst_apic_id = entry->dst_apic_id;
1031 	io_apic_ints[intr].dst_apic_int = entry->dst_apic_int;
1032 
1033 	return 1;
1034 }
1035 
1036 
1037 static int
1038 apic_int_is_bus_type(int intr, int bus_type)
1039 {
1040 	int     bus;
1041 
1042 	for (bus = 0; bus < mp_nbusses; ++bus)
1043 		if ((bus_data[bus].bus_id == io_apic_ints[intr].src_bus_id)
1044 		    && ((int) bus_data[bus].bus_type == bus_type))
1045 			return 1;
1046 
1047 	return 0;
1048 }
1049 
1050 
1051 /*
1052  * Given a traditional ISA INT mask, return an APIC mask.
1053  */
1054 u_int
1055 isa_apic_mask(u_int isa_mask)
1056 {
1057 	int isa_irq;
1058 	int apic_pin;
1059 
1060 #if defined(SKIP_IRQ15_REDIRECT)
1061 	if (isa_mask == (1 << 15)) {
1062 		printf("skipping ISA IRQ15 redirect\n");
1063 		return isa_mask;
1064 	}
1065 #endif  /* SKIP_IRQ15_REDIRECT */
1066 
1067 	isa_irq = ffs(isa_mask);		/* find its bit position */
1068 	if (isa_irq == 0)			/* doesn't exist */
1069 		return 0;
1070 	--isa_irq;				/* make it zero based */
1071 
1072 	apic_pin = isa_apic_pin(isa_irq);	/* look for APIC connection */
1073 	if (apic_pin == -1)
1074 		return 0;
1075 
1076 	return (1 << apic_pin);			/* convert pin# to a mask */
1077 }
1078 
1079 
1080 /*
1081  * Determine which APIC pin an ISA/EISA INT is attached to.
1082  */
1083 #define INTTYPE(I)	(io_apic_ints[(I)].int_type)
1084 #define INTPIN(I)	(io_apic_ints[(I)].dst_apic_int)
1085 
1086 #define SRCBUSIRQ(I)	(io_apic_ints[(I)].src_bus_irq)
1087 int
1088 isa_apic_pin(int isa_irq)
1089 {
1090 	int     intr;
1091 
1092 	for (intr = 0; intr < nintrs; ++intr) {		/* check each record */
1093 		if (INTTYPE(intr) == 0) {		/* standard INT */
1094 			if (SRCBUSIRQ(intr) == isa_irq) {
1095 				if (apic_int_is_bus_type(intr, ISA) ||
1096 			            apic_int_is_bus_type(intr, EISA))
1097 					return INTPIN(intr);	/* found */
1098 			}
1099 		}
1100 	}
1101 	return -1;					/* NOT found */
1102 }
1103 #undef SRCBUSIRQ
1104 
1105 
1106 /*
1107  * Determine which APIC pin a PCI INT is attached to.
1108  */
1109 #define SRCBUSID(I)	(io_apic_ints[(I)].src_bus_id)
1110 #define SRCBUSDEVICE(I)	((io_apic_ints[(I)].src_bus_irq >> 2) & 0x1f)
1111 #define SRCBUSLINE(I)	(io_apic_ints[(I)].src_bus_irq & 0x03)
1112 int
1113 pci_apic_pin(int pciBus, int pciDevice, int pciInt)
1114 {
1115 	int     intr;
1116 
1117 	--pciInt;					/* zero based */
1118 
1119 	for (intr = 0; intr < nintrs; ++intr)		/* check each record */
1120 		if ((INTTYPE(intr) == 0)		/* standard INT */
1121 		    && (SRCBUSID(intr) == pciBus)
1122 		    && (SRCBUSDEVICE(intr) == pciDevice)
1123 		    && (SRCBUSLINE(intr) == pciInt))	/* a candidate IRQ */
1124 			if (apic_int_is_bus_type(intr, PCI))
1125 				return INTPIN(intr);	/* exact match */
1126 
1127 	return -1;					/* NOT found */
1128 }
1129 #undef SRCBUSLINE
1130 #undef SRCBUSDEVICE
1131 #undef SRCBUSID
1132 
1133 #undef INTPIN
1134 #undef INTTYPE
1135 
1136 
1137 /*
1138  * Reprogram the MB chipset to NOT redirect an ISA INTerrupt.
1139  *
1140  * XXX FIXME:
1141  *  Exactly what this means is unclear at this point.  It is a solution
1142  *  for motherboards that redirect the MBIRQ0 pin.  Generically a motherboard
1143  *  could route any of the ISA INTs to upper (>15) IRQ values.  But most would
1144  *  NOT be redirected via MBIRQ0, thus "undirect()ing" them would NOT be an
1145  *  option.
1146  */
1147 int
1148 undirect_isa_irq(int rirq)
1149 {
1150 #if defined(READY)
1151 	printf("Freeing redirected ISA irq %d.\n", rirq);
1152 	/** FIXME: tickle the MB redirector chip */
1153 	return ???;
1154 #else
1155 	printf("Freeing (NOT implemented) redirected ISA irq %d.\n", rirq);
1156 	return 0;
1157 #endif  /* READY */
1158 }
1159 
1160 
1161 /*
1162  * Reprogram the MB chipset to NOT redirect a PCI INTerrupt
1163  */
1164 int
1165 undirect_pci_irq(int rirq)
1166 {
1167 #if defined(READY)
1168 	if (bootverbose)
1169 		printf("Freeing redirected PCI irq %d.\n", rirq);
1170 
1171 	/** FIXME: tickle the MB redirector chip */
1172 	return ???;
1173 #else
1174 	if (bootverbose)
1175 		printf("Freeing (NOT implemented) redirected PCI irq %d.\n",
1176 		       rirq);
1177 	return 0;
1178 #endif  /* READY */
1179 }
1180 
1181 
1182 /*
1183  * given a bus ID, return:
1184  *  the bus type if found
1185  *  -1 if NOT found
1186  */
1187 int
1188 apic_bus_type(int id)
1189 {
1190 	int     x;
1191 
1192 	for (x = 0; x < mp_nbusses; ++x)
1193 		if (bus_data[x].bus_id == id)
1194 			return bus_data[x].bus_type;
1195 
1196 	return -1;
1197 }
1198 
1199 
1200 /*
1201  * given a LOGICAL APIC# and pin#, return:
1202  *  the associated src bus ID if found
1203  *  -1 if NOT found
1204  */
1205 int
1206 apic_src_bus_id(int apic, int pin)
1207 {
1208 	int     x;
1209 
1210 	/* search each of the possible INTerrupt sources */
1211 	for (x = 0; x < nintrs; ++x)
1212 		if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1213 		    (pin == io_apic_ints[x].dst_apic_int))
1214 			return (io_apic_ints[x].src_bus_id);
1215 
1216 	return -1;		/* NOT found */
1217 }
1218 
1219 
1220 /*
1221  * given a LOGICAL APIC# and pin#, return:
1222  *  the associated src bus IRQ if found
1223  *  -1 if NOT found
1224  */
1225 int
1226 apic_src_bus_irq(int apic, int pin)
1227 {
1228 	int     x;
1229 
1230 	for (x = 0; x < nintrs; x++)
1231 		if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1232 		    (pin == io_apic_ints[x].dst_apic_int))
1233 			return (io_apic_ints[x].src_bus_irq);
1234 
1235 	return -1;		/* NOT found */
1236 }
1237 
1238 
1239 /*
1240  * given a LOGICAL APIC# and pin#, return:
1241  *  the associated INTerrupt type if found
1242  *  -1 if NOT found
1243  */
1244 int
1245 apic_int_type(int apic, int pin)
1246 {
1247 	int     x;
1248 
1249 	/* search each of the possible INTerrupt sources */
1250 	for (x = 0; x < nintrs; ++x)
1251 		if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1252 		    (pin == io_apic_ints[x].dst_apic_int))
1253 			return (io_apic_ints[x].int_type);
1254 
1255 	return -1;		/* NOT found */
1256 }
1257 
1258 
1259 /*
1260  * given a LOGICAL APIC# and pin#, return:
1261  *  the associated trigger mode if found
1262  *  -1 if NOT found
1263  */
1264 int
1265 apic_trigger(int apic, int pin)
1266 {
1267 	int     x;
1268 
1269 	/* search each of the possible INTerrupt sources */
1270 	for (x = 0; x < nintrs; ++x)
1271 		if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1272 		    (pin == io_apic_ints[x].dst_apic_int))
1273 			return ((io_apic_ints[x].int_flags >> 2) & 0x03);
1274 
1275 	return -1;		/* NOT found */
1276 }
1277 
1278 
1279 /*
1280  * given a LOGICAL APIC# and pin#, return:
1281  *  the associated 'active' level if found
1282  *  -1 if NOT found
1283  */
1284 int
1285 apic_polarity(int apic, int pin)
1286 {
1287 	int     x;
1288 
1289 	/* search each of the possible INTerrupt sources */
1290 	for (x = 0; x < nintrs; ++x)
1291 		if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1292 		    (pin == io_apic_ints[x].dst_apic_int))
1293 			return (io_apic_ints[x].int_flags & 0x03);
1294 
1295 	return -1;		/* NOT found */
1296 }
1297 
1298 
1299 /*
1300  * set data according to MP defaults
1301  * FIXME: probably not complete yet...
1302  */
1303 static void
1304 default_mp_table(int type)
1305 {
1306 	int     ap_cpu_id;
1307 #if defined(APIC_IO)
1308 	u_int32_t ux;
1309 	int     io_apic_id;
1310 	int     pin;
1311 #endif	/* APIC_IO */
1312 
1313 #if 0
1314 	printf("  MP default config type: %d\n", type);
1315 	switch (type) {
1316 	case 1:
1317 		printf("   bus: ISA, APIC: 82489DX\n");
1318 		break;
1319 	case 2:
1320 		printf("   bus: EISA, APIC: 82489DX\n");
1321 		break;
1322 	case 3:
1323 		printf("   bus: EISA, APIC: 82489DX\n");
1324 		break;
1325 	case 4:
1326 		printf("   bus: MCA, APIC: 82489DX\n");
1327 		break;
1328 	case 5:
1329 		printf("   bus: ISA+PCI, APIC: Integrated\n");
1330 		break;
1331 	case 6:
1332 		printf("   bus: EISA+PCI, APIC: Integrated\n");
1333 		break;
1334 	case 7:
1335 		printf("   bus: MCA+PCI, APIC: Integrated\n");
1336 		break;
1337 	default:
1338 		printf("   future type\n");
1339 		break;
1340 		/* NOTREACHED */
1341 	}
1342 #endif	/* 0 */
1343 
1344 	boot_cpu_id = (lapic.id & APIC_ID_MASK) >> 24;
1345 	ap_cpu_id = (boot_cpu_id == 0) ? 1 : 0;
1346 
1347 	/* BSP */
1348 	CPU_TO_ID(0) = boot_cpu_id;
1349 	ID_TO_CPU(boot_cpu_id) = 0;
1350 
1351 	/* one and only AP */
1352 	CPU_TO_ID(1) = ap_cpu_id;
1353 	ID_TO_CPU(ap_cpu_id) = 1;
1354 
1355 #if defined(APIC_IO)
1356 	/* one and only IO APIC */
1357 	io_apic_id = (io_apic_read(0, IOAPIC_ID) & APIC_ID_MASK) >> 24;
1358 
1359 	/*
1360 	 * sanity check, refer to MP spec section 3.6.6, last paragraph
1361 	 * necessary as some hardware isn't properly setting up the IO APIC
1362 	 */
1363 #if defined(REALLY_ANAL_IOAPICID_VALUE)
1364 	if (io_apic_id != 2) {
1365 #else
1366 	if ((io_apic_id == 0) || (io_apic_id == 1) || (io_apic_id == 15)) {
1367 #endif	/* REALLY_ANAL_IOAPICID_VALUE */
1368 		ux = io_apic_read(0, IOAPIC_ID);	/* get current contents */
1369 		ux &= ~APIC_ID_MASK;	/* clear the ID field */
1370 		ux |= 0x02000000;	/* set it to '2' */
1371 		io_apic_write(0, IOAPIC_ID, ux);	/* write new value */
1372 		ux = io_apic_read(0, IOAPIC_ID);	/* re-read && test */
1373 		if ((ux & APIC_ID_MASK) != 0x02000000)
1374 			panic("can't control IO APIC ID, reg: 0x%08x", ux);
1375 		io_apic_id = 2;
1376 	}
1377 	IO_TO_ID(0) = io_apic_id;
1378 	ID_TO_IO(io_apic_id) = 0;
1379 #endif	/* APIC_IO */
1380 
1381 	/* fill out bus entries */
1382 	switch (type) {
1383 	case 1:
1384 	case 2:
1385 	case 3:
1386 	case 5:
1387 	case 6:
1388 		bus_data[0].bus_id = default_data[type - 1][1];
1389 		bus_data[0].bus_type = default_data[type - 1][2];
1390 		bus_data[1].bus_id = default_data[type - 1][3];
1391 		bus_data[1].bus_type = default_data[type - 1][4];
1392 		break;
1393 
1394 	/* case 4: case 7:		   MCA NOT supported */
1395 	default:		/* illegal/reserved */
1396 		panic("BAD default MP config: %d", type);
1397 		/* NOTREACHED */
1398 	}
1399 
1400 #if defined(APIC_IO)
1401 	/* general cases from MP v1.4, table 5-2 */
1402 	for (pin = 0; pin < 16; ++pin) {
1403 		io_apic_ints[pin].int_type = 0;
1404 		io_apic_ints[pin].int_flags = 0x05;	/* edge/active-hi */
1405 		io_apic_ints[pin].src_bus_id = 0;
1406 		io_apic_ints[pin].src_bus_irq = pin;	/* IRQ2 caught below */
1407 		io_apic_ints[pin].dst_apic_id = io_apic_id;
1408 		io_apic_ints[pin].dst_apic_int = pin;	/* 1-to-1 */
1409 	}
1410 
1411 	/* special cases from MP v1.4, table 5-2 */
1412 	if (type == 2) {
1413 		io_apic_ints[2].int_type = 0xff;	/* N/C */
1414 		io_apic_ints[13].int_type = 0xff;	/* N/C */
1415 #if !defined(APIC_MIXED_MODE)
1416 		/** FIXME: ??? */
1417 		panic("sorry, can't support type 2 default yet");
1418 #endif	/* APIC_MIXED_MODE */
1419 	}
1420 	else
1421 		io_apic_ints[2].src_bus_irq = 0;	/* ISA IRQ0 is on APIC INT 2 */
1422 
1423 	if (type == 7)
1424 		io_apic_ints[0].int_type = 0xff;	/* N/C */
1425 	else
1426 		io_apic_ints[0].int_type = 3;	/* vectored 8259 */
1427 #endif	/* APIC_IO */
1428 }
1429 
1430 
1431 /*
1432  * initialize all the SMP locks
1433  */
1434 
1435 /* critical region around IO APIC, apic_imen */
1436 struct simplelock	imen_lock;
1437 
1438 /* critical region around splxx(), cpl, cil, ipending */
1439 struct simplelock	cpl_lock;
1440 
1441 /* Make FAST_INTR() routines sequential */
1442 struct simplelock	fast_intr_lock;
1443 
1444 /* critical region around INTR() routines */
1445 struct simplelock	intr_lock;
1446 
1447 /* lock the com (tty) data structures */
1448 struct simplelock	com_lock;
1449 
1450 static void
1451 init_locks(void)
1452 {
1453 	/*
1454 	 * Get the initial mp_lock with a count of 1 for the BSP.
1455 	 * This uses a LOGICAL cpu ID, ie BSP == 0.
1456 	 */
1457 	mp_lock = 0x00000001;
1458 
1459 	/* ISR uses its own "giant lock" */
1460 	isr_lock = 0x00000000;
1461 
1462 	/* serializes FAST_INTR() accesses */
1463 	s_lock_init((struct simplelock*)&fast_intr_lock);
1464 
1465 	/* serializes INTR() accesses */
1466 	s_lock_init((struct simplelock*)&intr_lock);
1467 
1468 	/* locks the IO APIC and apic_imen accesses */
1469 	s_lock_init((struct simplelock*)&imen_lock);
1470 
1471 	/* locks cpl accesses */
1472 	s_lock_init((struct simplelock*)&cpl_lock);
1473 
1474 	/* locks com (tty) data/hardware accesses: a FASTINTR() */
1475 	s_lock_init((struct simplelock*)&com_lock);
1476 }
1477 
1478 
1479 /*
1480  * start each AP in our list
1481  */
1482 static int
1483 start_all_aps(u_int boot_addr)
1484 {
1485 	int     x, i;
1486 	u_char  mpbiosreason;
1487 	u_long  mpbioswarmvec;
1488 	pd_entry_t *newptd;
1489 	pt_entry_t *newpt;
1490 	int *newpp, *stack;
1491 
1492 	POSTCODE(START_ALL_APS_POST);
1493 
1494 	/* initialize BSP's local APIC */
1495 	apic_initialize();
1496 	bsp_apic_ready = 1;
1497 
1498 	/* install the AP 1st level boot code */
1499 	install_ap_tramp(boot_addr);
1500 
1501 
1502 	/* save the current value of the warm-start vector */
1503 	mpbioswarmvec = *((u_long *) WARMBOOT_OFF);
1504 	outb(CMOS_REG, BIOS_RESET);
1505 	mpbiosreason = inb(CMOS_DATA);
1506 
1507 	/* record BSP in CPU map */
1508 	all_cpus = 1;
1509 
1510 	/* start each AP */
1511 	for (x = 1; x <= mp_naps; ++x) {
1512 
1513 		/* This is a bit verbose, it will go away soon.  */
1514 
1515 		/* alloc new page table directory */
1516 		newptd = (pd_entry_t *)(kmem_alloc(kernel_map, PAGE_SIZE));
1517 
1518 		/* Store the virtual PTD address for this CPU */
1519 		IdlePTDS[x] = newptd;
1520 
1521 		/* clone currently active one (ie: IdlePTD) */
1522 		bcopy(PTD, newptd, PAGE_SIZE);	/* inc prv page pde */
1523 
1524 		/* set up 0 -> 4MB P==V mapping for AP boot */
1525 		newptd[0] = (pd_entry_t) (PG_V | PG_RW |
1526 						((u_long)KPTphys & PG_FRAME));
1527 
1528 		/* store PTD for this AP's boot sequence */
1529 		bootPTD = (pd_entry_t *)vtophys(newptd);
1530 
1531 		/* alloc new page table page */
1532 		newpt = (pt_entry_t *)(kmem_alloc(kernel_map, PAGE_SIZE));
1533 
1534 		/* set the new PTD's private page to point there */
1535 		newptd[MPPTDI] = (pt_entry_t)(PG_V | PG_RW | vtophys(newpt));
1536 
1537 		/* install self referential entry */
1538 		newptd[PTDPTDI] = (pd_entry_t)(PG_V | PG_RW | vtophys(newptd));
1539 
1540 		/* allocate a new private data page */
1541 		newpp = (int *)kmem_alloc(kernel_map, PAGE_SIZE);
1542 
1543 		/* wire it into the private page table page */
1544 		newpt[0] = (pt_entry_t)(PG_V | PG_RW | vtophys(newpp));
1545 
1546 		/* wire the ptp into itself for access */
1547 		newpt[1] = (pt_entry_t)(PG_V | PG_RW | vtophys(newpt));
1548 
1549 		/* copy in the pointer to the local apic */
1550 		newpt[2] = SMP_prvpt[2];
1551 
1552 		/* and the IO apic mapping[s] */
1553 		for (i = 16; i < 32; i++)
1554 			newpt[i] = SMP_prvpt[i];
1555 
1556 		/* allocate and set up an idle stack data page */
1557 		stack = (int *)kmem_alloc(kernel_map, PAGE_SIZE);
1558 		newpt[3] = (pt_entry_t)(PG_V | PG_RW | vtophys(stack));
1559 
1560 		newpt[4] = 0;			/* *prv_CMAP1 */
1561 		newpt[5] = 0;			/* *prv_CMAP2 */
1562 		newpt[6] = 0;			/* *prv_CMAP3 */
1563 
1564 		/* prime data page for it to use */
1565 		newpp[0] = x;			/* cpuid */
1566 		newpp[1] = 0;			/* curproc */
1567 		newpp[2] = 0;			/* curpcb */
1568 		newpp[3] = 0;			/* npxproc */
1569 		newpp[4] = 0;			/* runtime.tv_sec */
1570 		newpp[5] = 0;			/* runtime.tv_usec */
1571 		newpp[6] = x << 24;		/* cpu_lockid */
1572 		newpp[7] = 0;			/* other_cpus */
1573 		newpp[8] = (int)bootPTD;	/* my_idlePTD */
1574 		newpp[9] = 0;			/* ss_tpr */
1575 		newpp[10] = (int)&newpt[4];	/* prv_CMAP1 */
1576 		newpp[11] = (int)&newpt[5];	/* prv_CMAP2 */
1577 		newpp[12] = (int)&newpt[6];	/* prv_CMAP3 */
1578 
1579 		/* setup a vector to our boot code */
1580 		*((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
1581 		*((volatile u_short *) WARMBOOT_SEG) = (boot_addr >> 4);
1582 		outb(CMOS_REG, BIOS_RESET);
1583 		outb(CMOS_DATA, BIOS_WARM);	/* 'warm-start' */
1584 
1585 		/* attempt to start the Application Processor */
1586 		CHECK_INIT(99);	/* setup checkpoints */
1587 		if (!start_ap(x, boot_addr)) {
1588 			printf("AP #%d (PHY# %d) failed!\n", x, CPU_TO_ID(x));
1589 			CHECK_PRINT("trace");	/* show checkpoints */
1590 			/* better panic as the AP may be running loose */
1591 			printf("panic y/n? [y] ");
1592 			if (cngetc() != 'n')
1593 				panic("bye-bye");
1594 		}
1595 		CHECK_PRINT("trace");		/* show checkpoints */
1596 
1597 		/* record its version info */
1598 		cpu_apic_versions[x] = cpu_apic_versions[0];
1599 
1600 		all_cpus |= (1 << x);		/* record AP in CPU map */
1601 	}
1602 
1603 	/* build our map of 'other' CPUs */
1604 	other_cpus = all_cpus & ~(1 << cpuid);
1605 
1606 	/* fill in our (BSP) APIC version */
1607 	cpu_apic_versions[0] = lapic.version;
1608 
1609 	/* restore the warmstart vector */
1610 	*(u_long *) WARMBOOT_OFF = mpbioswarmvec;
1611 	outb(CMOS_REG, BIOS_RESET);
1612 	outb(CMOS_DATA, mpbiosreason);
1613 
1614 	/*
1615 	 * Set up the idle context for the BSP.  Similar to above except
1616 	 * that some was done by locore, some by pmap.c and some is implicit
1617 	 * because the BSP is cpu#0 and the page is initially zero, and also
1618 	 * because we can refer to variables by name on the BSP..
1619 	 */
1620 	newptd = (pd_entry_t *)(kmem_alloc(kernel_map, PAGE_SIZE));
1621 
1622 	bcopy(PTD, newptd, PAGE_SIZE);	/* inc prv page pde */
1623 	IdlePTDS[0] = newptd;
1624 
1625 	/* Point PTD[] to this page instead of IdlePTD's physical page */
1626 	newptd[PTDPTDI] = (pd_entry_t)(PG_V | PG_RW | vtophys(newptd));
1627 
1628 	my_idlePTD = (pd_entry_t *)vtophys(newptd);
1629 
1630 	/* Allocate and setup BSP idle stack */
1631 	stack = (int *)kmem_alloc(kernel_map, PAGE_SIZE);
1632 	SMP_prvpt[3] = (pt_entry_t)(PG_V | PG_RW | vtophys(stack));
1633 
1634 	pmap_set_opt_bsp();
1635 
1636 	/* number of APs actually started */
1637 	return mp_ncpus - 1;
1638 }
1639 
1640 
1641 /*
1642  * load the 1st level AP boot code into base memory.
1643  */
1644 
1645 /* targets for relocation */
1646 extern void bigJump(void);
1647 extern void bootCodeSeg(void);
1648 extern void bootDataSeg(void);
1649 extern void MPentry(void);
1650 extern u_int MP_GDT;
1651 extern u_int mp_gdtbase;
1652 
1653 static void
1654 install_ap_tramp(u_int boot_addr)
1655 {
1656 	int     x;
1657 	int     size = *(int *) ((u_long) & bootMP_size);
1658 	u_char *src = (u_char *) ((u_long) bootMP);
1659 	u_char *dst = (u_char *) boot_addr + KERNBASE;
1660 	u_int   boot_base = (u_int) bootMP;
1661 	u_int8_t *dst8;
1662 	u_int16_t *dst16;
1663 	u_int32_t *dst32;
1664 
1665 	POSTCODE(INSTALL_AP_TRAMP_POST);
1666 
1667 	for (x = 0; x < size; ++x)
1668 		*dst++ = *src++;
1669 
1670 	/*
1671 	 * modify addresses in code we just moved to basemem. unfortunately we
1672 	 * need fairly detailed info about mpboot.s for this to work.  changes
1673 	 * to mpboot.s might require changes here.
1674 	 */
1675 
1676 	/* boot code is located in KERNEL space */
1677 	dst = (u_char *) boot_addr + KERNBASE;
1678 
1679 	/* modify the lgdt arg */
1680 	dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
1681 	*dst32 = boot_addr + ((u_int) & MP_GDT - boot_base);
1682 
1683 	/* modify the ljmp target for MPentry() */
1684 	dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
1685 	*dst32 = ((u_int) MPentry - KERNBASE);
1686 
1687 	/* modify the target for boot code segment */
1688 	dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
1689 	dst8 = (u_int8_t *) (dst16 + 1);
1690 	*dst16 = (u_int) boot_addr & 0xffff;
1691 	*dst8 = ((u_int) boot_addr >> 16) & 0xff;
1692 
1693 	/* modify the target for boot data segment */
1694 	dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
1695 	dst8 = (u_int8_t *) (dst16 + 1);
1696 	*dst16 = (u_int) boot_addr & 0xffff;
1697 	*dst8 = ((u_int) boot_addr >> 16) & 0xff;
1698 }
1699 
1700 
1701 /*
1702  * this function starts the AP (application processor) identified
1703  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
1704  * to accomplish this.  This is necessary because of the nuances
1705  * of the different hardware we might encounter.  It ain't pretty,
1706  * but it seems to work.
1707  */
1708 static int
1709 start_ap(int logical_cpu, u_int boot_addr)
1710 {
1711 	int     physical_cpu;
1712 	int     vector;
1713 	int     cpus;
1714 	u_long  icr_lo, icr_hi;
1715 
1716 	POSTCODE(START_AP_POST);
1717 
1718 	/* get the PHYSICAL APIC ID# */
1719 	physical_cpu = CPU_TO_ID(logical_cpu);
1720 
1721 	/* calculate the vector */
1722 	vector = (boot_addr >> 12) & 0xff;
1723 
1724 	/* used as a watchpoint to signal AP startup */
1725 	cpus = mp_ncpus;
1726 
1727 	/*
1728 	 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
1729 	 * and running the target CPU. OR this INIT IPI might be latched (P5
1730 	 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1731 	 * ignored.
1732 	 */
1733 
1734 	/* setup the address for the target AP */
1735 	icr_hi = lapic.icr_hi & ~APIC_ID_MASK;
1736 	icr_hi |= (physical_cpu << 24);
1737 	lapic.icr_hi = icr_hi;
1738 
1739 	/* do an INIT IPI: assert RESET */
1740 	icr_lo = lapic.icr_lo & 0xfff00000;
1741 	lapic.icr_lo = icr_lo | 0x0000c500;
1742 
1743 	/* wait for pending status end */
1744 	while (lapic.icr_lo & APIC_DELSTAT_MASK)
1745 		 /* spin */ ;
1746 
1747 	/* do an INIT IPI: deassert RESET */
1748 	lapic.icr_lo = icr_lo | 0x00008500;
1749 
1750 	/* wait for pending status end */
1751 	u_sleep(10000);		/* wait ~10mS */
1752 	while (lapic.icr_lo & APIC_DELSTAT_MASK)
1753 		 /* spin */ ;
1754 
1755 	/*
1756 	 * next we do a STARTUP IPI: the previous INIT IPI might still be
1757 	 * latched, (P5 bug) this 1st STARTUP would then terminate
1758 	 * immediately, and the previously started INIT IPI would continue. OR
1759 	 * the previous INIT IPI has already run. and this STARTUP IPI will
1760 	 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1761 	 * will run.
1762 	 */
1763 
1764 	/* do a STARTUP IPI */
1765 	lapic.icr_lo = icr_lo | 0x00000600 | vector;
1766 	while (lapic.icr_lo & APIC_DELSTAT_MASK)
1767 		 /* spin */ ;
1768 	u_sleep(200);		/* wait ~200uS */
1769 
1770 	/*
1771 	 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1772 	 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1773 	 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1774 	 * recognized after hardware RESET or INIT IPI.
1775 	 */
1776 
1777 	lapic.icr_lo = icr_lo | 0x00000600 | vector;
1778 	while (lapic.icr_lo & APIC_DELSTAT_MASK)
1779 		 /* spin */ ;
1780 	u_sleep(200);		/* wait ~200uS */
1781 
1782 	/* wait for it to start */
1783 	set_apic_timer(5000000);/* == 5 seconds */
1784 	while (read_apic_timer())
1785 		if (mp_ncpus > cpus)
1786 			return 1;	/* return SUCCESS */
1787 
1788 	return 0;		/* return FAILURE */
1789 }
1790 
1791 
1792 /*
1793  * Flush the TLB on all other CPU's
1794  *
1795  * XXX: Needs to handshake and wait for completion before proceding.
1796  */
1797 void
1798 smp_invltlb(void)
1799 {
1800 #if defined(APIC_IO)
1801 	if (smp_active && invltlb_ok)
1802 		all_but_self_ipi(XINVLTLB_OFFSET);
1803 #endif  /* APIC_IO */
1804 }
1805 
1806 void
1807 invlpg(u_int addr)
1808 {
1809 	__asm   __volatile("invlpg (%0)"::"r"(addr):"memory");
1810 
1811 	/* send a message to the other CPUs */
1812 	smp_invltlb();
1813 }
1814 
1815 void
1816 invltlb(void)
1817 {
1818 	u_long  temp;
1819 
1820 	/*
1821 	 * This should be implemented as load_cr3(rcr3()) when load_cr3() is
1822 	 * inlined.
1823 	 */
1824 	__asm __volatile("movl %%cr3, %0; movl %0, %%cr3":"=r"(temp) :: "memory");
1825 
1826 	/* send a message to the other CPUs */
1827 	smp_invltlb();
1828 }
1829 
1830 
1831 /*
1832  * When called the executing CPU will send an IPI to all other CPUs
1833  *  requesting that they halt execution.
1834  *
1835  * Usually (but not necessarily) called with 'other_cpus' as its arg.
1836  *
1837  *  - Signals all CPUs in map to stop.
1838  *  - Waits for each to stop.
1839  *
1840  * Returns:
1841  *  -1: error
1842  *   0: NA
1843  *   1: ok
1844  *
1845  * XXX FIXME: this is not MP-safe, needs a lock to prevent multiple CPUs
1846  *            from executing at same time.
1847  */
1848 int
1849 stop_cpus(u_int map)
1850 {
1851 	if (!smp_active)
1852 		return 0;
1853 
1854 	/* send IPI to all CPUs in map */
1855 	stopped_cpus = 0;
1856 
1857 	/* send the Xcpustop IPI to all CPUs in map */
1858 	selected_apic_ipi(map, XCPUSTOP_OFFSET, APIC_DELMODE_FIXED);
1859 
1860 	while (stopped_cpus != map)
1861 		/* spin */ ;
1862 
1863 	return 1;
1864 }
1865 
1866 
1867 /*
1868  * Called by a CPU to restart stopped CPUs.
1869  *
1870  * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
1871  *
1872  *  - Signals all CPUs in map to restart.
1873  *  - Waits for each to restart.
1874  *
1875  * Returns:
1876  *  -1: error
1877  *   0: NA
1878  *   1: ok
1879  */
1880 int
1881 restart_cpus(u_int map)
1882 {
1883 	if (!smp_active)
1884 		return 0;
1885 
1886 	started_cpus = map;		/* signal other cpus to restart */
1887 
1888 	while (started_cpus)		/* wait for each to clear its bit */
1889 		/* spin */ ;
1890 
1891 	return 1;
1892 }
1893 
1894 int smp_active = 0;	/* are the APs allowed to run? */
1895 SYSCTL_INT(_machdep, OID_AUTO, smp_active, CTLFLAG_RW, &smp_active, 0, "");
1896 
1897 /* XXX maybe should be hw.ncpu */
1898 int smp_cpus = 1;	/* how many cpu's running */
1899 SYSCTL_INT(_machdep, OID_AUTO, smp_cpus, CTLFLAG_RD, &smp_cpus, 0, "");
1900 
1901 int invltlb_ok = 0;	/* throttle smp_invltlb() till safe */
1902 SYSCTL_INT(_machdep, OID_AUTO, invltlb_ok, CTLFLAG_RW, &invltlb_ok, 0, "");
1903 
1904 int do_page_zero_idle = 0; /* bzero pages for fun and profit in idleloop */
1905 SYSCTL_INT(_machdep, OID_AUTO, do_page_zero_idle, CTLFLAG_RW,
1906 	   &do_page_zero_idle, 0, "");
1907 
1908 
1909 /*
1910  * This is called once the rest of the system is up and running and we're
1911  * ready to let the AP's out of the pen.
1912  */
1913 void ap_init(void);
1914 
1915 void
1916 ap_init()
1917 {
1918 	u_int   temp;
1919 	u_int	apic_id;
1920 
1921 	smp_cpus++;
1922 
1923 	/* Build our map of 'other' CPUs. */
1924 	other_cpus = all_cpus & ~(1 << cpuid);
1925 
1926 	printf("SMP: AP CPU #%d Launched!\n", cpuid);
1927 
1928 	/* XXX FIXME: i386 specific, and redundant: Setup the FPU. */
1929 	load_cr0((rcr0() & ~CR0_EM) | CR0_MP | CR0_NE | CR0_TS);
1930 
1931 	/* A quick check from sanity claus */
1932 	apic_id = (apic_id_to_logical[(lapic.id & 0x0f000000) >> 24]);
1933 	if (cpuid != apic_id) {
1934 		printf("SMP: cpuid = %d\n", cpuid);
1935 		printf("SMP: apic_id = %d\n", apic_id);
1936 		printf("PTD[MPPTDI] = %08x\n", PTD[MPPTDI]);
1937 		panic("cpuid mismatch! boom!!");
1938 	}
1939 
1940 	/* Init local apic for irq's */
1941 	apic_initialize();
1942 
1943 	/*
1944 	 * Activate smp_invltlb, although strictly speaking, this isn't
1945 	 * quite correct yet.  We should have a bitfield for cpus willing
1946 	 * to accept TLB flush IPI's or something and sync them.
1947 	 */
1948 	invltlb_ok = 1;
1949 	smp_active = 1;		/* historic */
1950 
1951 	curproc = NULL;		/* make sure */
1952 }
1953