xref: /illumos-gate/usr/src/uts/i86pc/io/mp_platform_common.c (revision 6523a3aa7f325d64841382707603be7a86e68147)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2016 Nexenta Systems, Inc.
24  * Copyright (c) 2017 by Delphix. All rights reserved.
25  * Copyright (c) 2019, Joyent, Inc.
26  * Copyright 2020 RackTop Systems, Inc.
27  */
28 /*
29  * Copyright (c) 2010, Intel Corporation.
30  * All rights reserved.
31  */
32 
33 /*
34  * PSMI 1.1 extensions are supported only in 2.6 and later versions.
35  * PSMI 1.2 extensions are supported only in 2.7 and later versions.
36  * PSMI 1.3 and 1.4 extensions are supported in Solaris 10.
37  * PSMI 1.5 extensions are supported in Solaris Nevada.
38  * PSMI 1.6 extensions are supported in Solaris Nevada.
39  * PSMI 1.7 extensions are supported in Solaris Nevada.
40  */
41 #define	PSMI_1_7
42 
43 #include <sys/processor.h>
44 #include <sys/time.h>
45 #include <sys/psm.h>
46 #include <sys/smp_impldefs.h>
47 #include <sys/cram.h>
48 #include <sys/acpi/acpi.h>
49 #include <sys/acpica.h>
50 #include <sys/psm_common.h>
51 #include <sys/apic.h>
52 #include <sys/apic_timer.h>
53 #include <sys/pit.h>
54 #include <sys/ddi.h>
55 #include <sys/sunddi.h>
56 #include <sys/ddi_impldefs.h>
57 #include <sys/pci.h>
58 #include <sys/promif.h>
59 #include <sys/x86_archext.h>
60 #include <sys/cpc_impl.h>
61 #include <sys/uadmin.h>
62 #include <sys/panic.h>
63 #include <sys/debug.h>
64 #include <sys/archsystm.h>
65 #include <sys/trap.h>
66 #include <sys/machsystm.h>
67 #include <sys/cpuvar.h>
68 #include <sys/rm_platter.h>
69 #include <sys/privregs.h>
70 #include <sys/cyclic.h>
71 #include <sys/note.h>
72 #include <sys/pci_intr_lib.h>
73 #include <sys/sunndi.h>
74 #if !defined(__xpv)
75 #include <sys/hpet.h>
76 #include <sys/clock.h>
77 #endif
78 
79 /*
80  *	Local Function Prototypes
81  */
82 static int apic_handle_defconf(void);
83 static int apic_parse_mpct(caddr_t mpct, int bypass);
84 static struct apic_mpfps_hdr *apic_find_fps_sig(caddr_t fptr, int size);
85 static int apic_checksum(caddr_t bptr, int len);
86 static int apic_find_bus_type(char *bus);
87 static int apic_find_bus(int busid);
88 static struct apic_io_intr *apic_find_io_intr(int irqno);
89 static int apic_find_free_irq(int start, int end);
90 struct apic_io_intr *apic_find_io_intr_w_busid(int irqno, int busid);
91 static void apic_set_pwroff_method_from_mpcnfhdr(struct apic_mp_cnf_hdr *hdrp);
92 static void apic_free_apic_cpus(void);
93 static boolean_t apic_is_ioapic_AMD_813x(uint32_t physaddr);
94 static int apic_acpi_enter_apicmode(void);
95 
96 int apic_handle_pci_pci_bridge(dev_info_t *idip, int child_devno,
97     int child_ipin, struct apic_io_intr **intrp);
98 int apic_find_bus_id(int bustype);
99 int apic_find_intin(uchar_t ioapic, uchar_t intin);
100 void apic_record_rdt_entry(apic_irq_t *irqptr, int irq);
101 
102 int apic_debug_mps_id = 0;	/* 1 - print MPS ID strings */
103 
104 /* ACPI SCI interrupt configuration; -1 if SCI not used */
105 int apic_sci_vect = -1;
106 iflag_t apic_sci_flags;
107 
108 #if !defined(__xpv)
109 /* ACPI HPET interrupt configuration; -1 if HPET not used */
110 int apic_hpet_vect = -1;
111 iflag_t apic_hpet_flags;
112 #endif
113 
114 /*
115  * psm name pointer
116  */
117 char *psm_name;
118 
119 /* ACPI support routines */
120 static int acpi_probe(char *);
121 static int apic_acpi_irq_configure(acpi_psm_lnk_t *acpipsmlnkp, dev_info_t *dip,
122     int *pci_irqp, iflag_t *intr_flagp);
123 
124 int apic_acpi_translate_pci_irq(dev_info_t *dip, int busid, int devid,
125     int ipin, int *pci_irqp, iflag_t *intr_flagp);
126 uchar_t acpi_find_ioapic(int irq);
127 static int acpi_intr_compatible(iflag_t iflag1, iflag_t iflag2);
128 
129 /* Max wait time (in repetitions) for flags to clear in an RDT entry. */
130 int apic_max_reps_clear_pending = 1000;
131 
132 int	apic_intr_policy = INTR_ROUND_ROBIN;
133 
134 int	apic_next_bind_cpu = 1; /* For round robin assignment */
135 				/* start with cpu 1 */
136 
137 /*
138  * If enabled, the distribution works as follows:
139  * On every interrupt entry, the current ipl for the CPU is set in cpu_info
140  * and the irq corresponding to the ipl is also set in the aci_current array.
141  * interrupt exit and setspl (due to soft interrupts) will cause the current
142  * ipl to be be changed. This is cache friendly as these frequently used
143  * paths write into a per cpu structure.
144  *
145  * Sampling is done by checking the structures for all CPUs and incrementing
146  * the busy field of the irq (if any) executing on each CPU and the busy field
147  * of the corresponding CPU.
148  * In periodic mode this is done on every clock interrupt.
149  * In one-shot mode, this is done thru a cyclic with an interval of
150  * apic_redistribute_sample_interval (default 10 milli sec).
151  *
152  * Every apic_sample_factor_redistribution times we sample, we do computations
153  * to decide which interrupt needs to be migrated (see comments
154  * before apic_intr_redistribute().
155  */
156 
157 /*
158  * Following 3 variables start as % and can be patched or set using an
159  * API to be defined in future. They will be scaled to
160  * sample_factor_redistribution which is in turn set to hertz+1 (in periodic
161  * mode), or 101 in one-shot mode to stagger it away from one sec processing
162  */
163 
164 int	apic_int_busy_mark = 60;
165 int	apic_int_free_mark = 20;
166 int	apic_diff_for_redistribution = 10;
167 
168 /* sampling interval for interrupt redistribution for dynamic migration */
169 int	apic_redistribute_sample_interval = NANOSEC / 100; /* 10 millisec */
170 
171 /*
172  * number of times we sample before deciding to redistribute interrupts
173  * for dynamic migration
174  */
175 int	apic_sample_factor_redistribution = 101;
176 
177 int	apic_redist_cpu_skip = 0;
178 int	apic_num_imbalance = 0;
179 int	apic_num_rebind = 0;
180 
181 /*
182  * Maximum number of APIC CPUs in the system, -1 indicates that dynamic
183  * allocation of CPU ids is disabled.
184  */
185 int	apic_max_nproc = -1;
186 int	apic_nproc = 0;
187 size_t	apic_cpus_size = 0;
188 int	apic_defconf = 0;
189 int	apic_irq_translate = 0;
190 int	apic_spec_rev = 0;
191 int	apic_imcrp = 0;
192 
193 int	apic_use_acpi = 1;	/* 1 = use ACPI, 0 = don't use ACPI */
194 int	apic_use_acpi_madt_only = 0;	/* 1=ONLY use MADT from ACPI */
195 
196 /*
197  * For interrupt link devices, if apic_unconditional_srs is set, an irq resource
198  * will be assigned (via _SRS). If it is not set, use the current
199  * irq setting (via _CRS), but only if that irq is in the set of possible
200  * irqs (returned by _PRS) for the device.
201  */
202 int	apic_unconditional_srs = 1;
203 
204 /*
205  * For interrupt link devices, if apic_prefer_crs is set when we are
206  * assigning an IRQ resource to a device, prefer the current IRQ setting
207  * over other possible irq settings under same conditions.
208  */
209 
210 int	apic_prefer_crs = 1;
211 
212 uchar_t apic_io_id[MAX_IO_APIC];
213 volatile uint32_t *apicioadr[MAX_IO_APIC];
214 uchar_t	apic_io_ver[MAX_IO_APIC];
215 uchar_t	apic_io_vectbase[MAX_IO_APIC];
216 uchar_t	apic_io_vectend[MAX_IO_APIC];
217 uchar_t apic_reserved_irqlist[MAX_ISA_IRQ + 1];
218 uint32_t apic_physaddr[MAX_IO_APIC];
219 
220 boolean_t ioapic_mask_workaround[MAX_IO_APIC];
221 
222 /*
223  * First available slot to be used as IRQ index into the apic_irq_table
224  * for those interrupts (like MSI/X) that don't have a physical IRQ.
225  */
226 int apic_first_avail_irq  = APIC_FIRST_FREE_IRQ;
227 
228 /*
229  * apic_ioapic_lock protects the ioapics (reg select), the status, temp_bound
230  * and bound elements of cpus_info and the temp_cpu element of irq_struct
231  */
232 lock_t	apic_ioapic_lock;
233 
234 int	apic_io_max = 0;	/* no. of i/o apics enabled */
235 
236 struct apic_io_intr *apic_io_intrp = NULL;
237 static	struct apic_bus	*apic_busp;
238 
239 uchar_t	apic_resv_vector[MAXIPL+1];
240 
241 char	apic_level_intr[APIC_MAX_VECTOR+1];
242 
243 uint32_t	eisa_level_intr_mask = 0;
244 	/* At least MSB will be set if EISA bus */
245 
246 int	apic_pci_bus_total = 0;
247 uchar_t	apic_single_pci_busid = 0;
248 
249 /*
250  * airq_mutex protects additions to the apic_irq_table - the first
251  * pointer and any airq_nexts off of that one. It also protects
252  * apic_max_device_irq & apic_min_device_irq. It also guarantees
253  * that share_id is unique as new ids are generated only when new
254  * irq_t structs are linked in. Once linked in the structs are never
255  * deleted. temp_cpu & mps_intr_index field indicate if it is programmed
256  * or allocated. Note that there is a slight gap between allocating in
257  * apic_introp_xlate and programming in addspl.
258  */
259 kmutex_t	airq_mutex;
260 apic_irq_t	*apic_irq_table[APIC_MAX_VECTOR+1];
261 int		apic_max_device_irq = 0;
262 int		apic_min_device_irq = APIC_MAX_VECTOR;
263 
264 typedef struct prs_irq_list_ent {
265 	int			list_prio;
266 	int32_t			irq;
267 	iflag_t			intrflags;
268 	acpi_prs_private_t	prsprv;
269 	struct prs_irq_list_ent	*next;
270 } prs_irq_list_t;
271 
272 
273 /*
274  * ACPI variables
275  */
276 /* 1 = acpi is enabled & working, 0 = acpi is not enabled or not there */
277 int apic_enable_acpi = 0;
278 
279 /* ACPI Multiple APIC Description Table ptr */
280 static	ACPI_TABLE_MADT *acpi_mapic_dtp = NULL;
281 
282 /* ACPI Interrupt Source Override Structure ptr */
283 ACPI_MADT_INTERRUPT_OVERRIDE *acpi_isop = NULL;
284 int acpi_iso_cnt = 0;
285 
286 /* ACPI Non-maskable Interrupt Sources ptr */
287 static	ACPI_MADT_NMI_SOURCE *acpi_nmi_sp = NULL;
288 static	int acpi_nmi_scnt = 0;
289 static	ACPI_MADT_LOCAL_APIC_NMI *acpi_nmi_cp = NULL;
290 static	int acpi_nmi_ccnt = 0;
291 
292 static	boolean_t acpi_found_smp_config = B_FALSE;
293 
294 /*
295  * The following added to identify a software poweroff method if available.
296  */
297 
298 static struct {
299 	int	poweroff_method;
300 	char	oem_id[APIC_MPS_OEM_ID_LEN + 1];	/* MAX + 1 for NULL */
301 	char	prod_id[APIC_MPS_PROD_ID_LEN + 1];	/* MAX + 1 for NULL */
302 } apic_mps_ids[] = {
303 	{ APIC_POWEROFF_VIA_RTC,	"INTEL",	"ALDER" },   /* 4300 */
304 	{ APIC_POWEROFF_VIA_RTC,	"NCR",		"AMC" },    /* 4300 */
305 	{ APIC_POWEROFF_VIA_ASPEN_BMC,	"INTEL",	"A450NX" },  /* 4400? */
306 	{ APIC_POWEROFF_VIA_ASPEN_BMC,	"INTEL",	"AD450NX" }, /* 4400 */
307 	{ APIC_POWEROFF_VIA_ASPEN_BMC,	"INTEL",	"AC450NX" }, /* 4400R */
308 	{ APIC_POWEROFF_VIA_SITKA_BMC,	"INTEL",	"S450NX" },  /* S50  */
309 	{ APIC_POWEROFF_VIA_SITKA_BMC,	"INTEL",	"SC450NX" }  /* S50? */
310 };
311 
312 int	apic_poweroff_method = APIC_POWEROFF_NONE;
313 
314 /*
315  * Auto-configuration routines
316  */
317 
318 /*
319  * Look at MPSpec 1.4 (Intel Order # 242016-005) for details of what we do here
320  * May work with 1.1 - but not guaranteed.
321  * According to the MP Spec, the MP floating pointer structure
322  * will be searched in the order described below:
323  * 1. In the first kilobyte of Extended BIOS Data Area (EBDA)
324  * 2. Within the last kilobyte of system base memory
325  * 3. In the BIOS ROM address space between 0F0000h and 0FFFFh
326  * Once we find the right signature with proper checksum, we call
327  * either handle_defconf or parse_mpct to get all info necessary for
328  * subsequent operations.
329  */
330 int
331 apic_probe_common(char *modname)
332 {
333 	uint32_t mpct_addr, ebda_start = 0, base_mem_end;
334 	caddr_t	biosdatap;
335 	caddr_t	mpct = NULL;
336 	caddr_t	fptr;
337 	int	i, mpct_size = 0, mapsize, retval = PSM_FAILURE;
338 	ushort_t	ebda_seg, base_mem_size;
339 	struct	apic_mpfps_hdr	*fpsp;
340 	struct	apic_mp_cnf_hdr	*hdrp;
341 	int bypass_cpu_and_ioapics_in_mptables;
342 	int acpi_user_options;
343 
344 	if (apic_forceload < 0)
345 		return (retval);
346 
347 	/*
348 	 * Remember who we are
349 	 */
350 	psm_name = modname;
351 
352 	/* Allow override for MADT-only mode */
353 	acpi_user_options = ddi_prop_get_int(DDI_DEV_T_ANY, ddi_root_node(), 0,
354 	    "acpi-user-options", 0);
355 	apic_use_acpi_madt_only = ((acpi_user_options & ACPI_OUSER_MADT) != 0);
356 
357 	/* Allow apic_use_acpi to override MADT-only mode */
358 	if (!apic_use_acpi)
359 		apic_use_acpi_madt_only = 0;
360 
361 	retval = acpi_probe(modname);
362 
363 	/* in UEFI system, there is no BIOS data */
364 	if (ddi_prop_exists(DDI_DEV_T_ANY, ddi_root_node(), 0, "efi-systab"))
365 		goto apic_ret;
366 
367 	/*
368 	 * mapin the bios data area 40:0
369 	 * 40:13h - two-byte location reports the base memory size
370 	 * 40:0Eh - two-byte location for the exact starting address of
371 	 *	    the EBDA segment for EISA
372 	 */
373 	biosdatap = psm_map_phys(0x400, 0x20, PROT_READ);
374 	if (!biosdatap)
375 		goto apic_ret;
376 	fpsp = (struct apic_mpfps_hdr *)NULL;
377 	mapsize = MPFPS_RAM_WIN_LEN;
378 	/*LINTED: pointer cast may result in improper alignment */
379 	ebda_seg = *((ushort_t *)(biosdatap+0xe));
380 	/* check the 1k of EBDA */
381 	if (ebda_seg) {
382 		ebda_start = ((uint32_t)ebda_seg) << 4;
383 		fptr = psm_map_phys(ebda_start, MPFPS_RAM_WIN_LEN, PROT_READ);
384 		if (fptr) {
385 			if (!(fpsp =
386 			    apic_find_fps_sig(fptr, MPFPS_RAM_WIN_LEN)))
387 				psm_unmap_phys(fptr, MPFPS_RAM_WIN_LEN);
388 		}
389 	}
390 	/* If not in EBDA, check the last k of system base memory */
391 	if (!fpsp) {
392 		/*LINTED: pointer cast may result in improper alignment */
393 		base_mem_size = *((ushort_t *)(biosdatap + 0x13));
394 
395 		if (base_mem_size > 512)
396 			base_mem_end = 639 * 1024;
397 		else
398 			base_mem_end = 511 * 1024;
399 		/* if ebda == last k of base mem, skip to check BIOS ROM */
400 		if (base_mem_end != ebda_start) {
401 
402 			fptr = psm_map_phys(base_mem_end, MPFPS_RAM_WIN_LEN,
403 			    PROT_READ);
404 
405 			if (fptr) {
406 				if (!(fpsp = apic_find_fps_sig(fptr,
407 				    MPFPS_RAM_WIN_LEN)))
408 					psm_unmap_phys(fptr, MPFPS_RAM_WIN_LEN);
409 			}
410 		}
411 	}
412 	psm_unmap_phys(biosdatap, 0x20);
413 
414 	/* If still cannot find it, check the BIOS ROM space */
415 	if (!fpsp) {
416 		mapsize = MPFPS_ROM_WIN_LEN;
417 		fptr = psm_map_phys(MPFPS_ROM_WIN_START,
418 		    MPFPS_ROM_WIN_LEN, PROT_READ);
419 		if (fptr) {
420 			if (!(fpsp =
421 			    apic_find_fps_sig(fptr, MPFPS_ROM_WIN_LEN))) {
422 				psm_unmap_phys(fptr, MPFPS_ROM_WIN_LEN);
423 				goto apic_ret;
424 			}
425 		}
426 	}
427 
428 	if (apic_checksum((caddr_t)fpsp, fpsp->mpfps_length * 16) != 0) {
429 		psm_unmap_phys(fptr, MPFPS_ROM_WIN_LEN);
430 		goto apic_ret;
431 	}
432 
433 	apic_spec_rev = fpsp->mpfps_spec_rev;
434 	if ((apic_spec_rev != 04) && (apic_spec_rev != 01)) {
435 		psm_unmap_phys(fptr, MPFPS_ROM_WIN_LEN);
436 		goto apic_ret;
437 	}
438 
439 	/* check IMCR is present or not */
440 	apic_imcrp = fpsp->mpfps_featinfo2 & MPFPS_FEATINFO2_IMCRP;
441 
442 	/* check default configuration (dual CPUs) */
443 	if ((apic_defconf = fpsp->mpfps_featinfo1) != 0) {
444 		psm_unmap_phys(fptr, mapsize);
445 		if ((retval = apic_handle_defconf()) != PSM_SUCCESS)
446 			return (retval);
447 
448 		goto apic_ret;
449 	}
450 
451 	/* MP Configuration Table */
452 	mpct_addr = (uint32_t)(fpsp->mpfps_mpct_paddr);
453 
454 	psm_unmap_phys(fptr, mapsize); /* unmap floating ptr struct */
455 
456 	/*
457 	 * Map in enough memory for the MP Configuration Table Header.
458 	 * Use this table to read the total length of the BIOS data and
459 	 * map in all the info
460 	 */
461 	/*LINTED: pointer cast may result in improper alignment */
462 	hdrp = (struct apic_mp_cnf_hdr *)psm_map_phys(mpct_addr,
463 	    sizeof (struct apic_mp_cnf_hdr), PROT_READ);
464 	if (!hdrp)
465 		goto apic_ret;
466 
467 	/* check mp configuration table signature PCMP */
468 	if (hdrp->mpcnf_sig != 0x504d4350) {
469 		psm_unmap_phys((caddr_t)hdrp, sizeof (struct apic_mp_cnf_hdr));
470 		goto apic_ret;
471 	}
472 	mpct_size = (int)hdrp->mpcnf_tbl_length;
473 
474 	apic_set_pwroff_method_from_mpcnfhdr(hdrp);
475 
476 	psm_unmap_phys((caddr_t)hdrp, sizeof (struct apic_mp_cnf_hdr));
477 
478 	if ((retval == PSM_SUCCESS) && !apic_use_acpi_madt_only) {
479 		/* This is an ACPI machine No need for further checks */
480 		goto apic_ret;
481 	}
482 
483 	/*
484 	 * Map in the entries for this machine, ie. Processor
485 	 * Entry Tables, Bus Entry Tables, etc.
486 	 * They are in fixed order following one another
487 	 */
488 	mpct = psm_map_phys(mpct_addr, mpct_size, PROT_READ);
489 	if (!mpct)
490 		goto apic_ret;
491 
492 	if (apic_checksum(mpct, mpct_size) != 0)
493 		goto apic_fail1;
494 
495 	/*LINTED: pointer cast may result in improper alignment */
496 	hdrp = (struct apic_mp_cnf_hdr *)mpct;
497 	apicadr = (uint32_t *)mapin_apic((uint32_t)hdrp->mpcnf_local_apic,
498 	    APIC_LOCAL_MEMLEN, PROT_READ | PROT_WRITE);
499 	if (!apicadr)
500 		goto apic_fail1;
501 
502 	/* Parse all information in the tables */
503 	bypass_cpu_and_ioapics_in_mptables = (retval == PSM_SUCCESS);
504 	if (apic_parse_mpct(mpct, bypass_cpu_and_ioapics_in_mptables) ==
505 	    PSM_SUCCESS) {
506 		retval = PSM_SUCCESS;
507 		goto apic_ret;
508 	}
509 
510 apic_fail1:
511 	psm_unmap_phys(mpct, mpct_size);
512 	mpct = NULL;
513 
514 apic_ret:
515 	if (retval == PSM_SUCCESS) {
516 		extern int apic_ioapic_method_probe();
517 
518 		if ((retval = apic_ioapic_method_probe()) == PSM_SUCCESS)
519 			return (PSM_SUCCESS);
520 	}
521 
522 	for (i = 0; i < apic_io_max; i++)
523 		mapout_ioapic((caddr_t)apicioadr[i], APIC_IO_MEMLEN);
524 	if (apic_cpus) {
525 		kmem_free(apic_cpus, apic_cpus_size);
526 		apic_cpus = NULL;
527 	}
528 	if (apicadr) {
529 		mapout_apic((caddr_t)apicadr, APIC_LOCAL_MEMLEN);
530 		apicadr = NULL;
531 	}
532 	if (mpct)
533 		psm_unmap_phys(mpct, mpct_size);
534 
535 	return (retval);
536 }
537 
538 static void
539 apic_set_pwroff_method_from_mpcnfhdr(struct apic_mp_cnf_hdr *hdrp)
540 {
541 	int	i;
542 
543 	for (i = 0; i < (sizeof (apic_mps_ids) / sizeof (apic_mps_ids[0]));
544 	    i++) {
545 		if ((strncmp(hdrp->mpcnf_oem_str, apic_mps_ids[i].oem_id,
546 		    strlen(apic_mps_ids[i].oem_id)) == 0) &&
547 		    (strncmp(hdrp->mpcnf_prod_str, apic_mps_ids[i].prod_id,
548 		    strlen(apic_mps_ids[i].prod_id)) == 0)) {
549 
550 			apic_poweroff_method = apic_mps_ids[i].poweroff_method;
551 			break;
552 		}
553 	}
554 
555 	if (apic_debug_mps_id != 0) {
556 		cmn_err(CE_CONT, "%s: MPS OEM ID = '%c%c%c%c%c%c%c%c'"
557 		    "Product ID = '%c%c%c%c%c%c%c%c%c%c%c%c'\n",
558 		    psm_name,
559 		    hdrp->mpcnf_oem_str[0],
560 		    hdrp->mpcnf_oem_str[1],
561 		    hdrp->mpcnf_oem_str[2],
562 		    hdrp->mpcnf_oem_str[3],
563 		    hdrp->mpcnf_oem_str[4],
564 		    hdrp->mpcnf_oem_str[5],
565 		    hdrp->mpcnf_oem_str[6],
566 		    hdrp->mpcnf_oem_str[7],
567 		    hdrp->mpcnf_prod_str[0],
568 		    hdrp->mpcnf_prod_str[1],
569 		    hdrp->mpcnf_prod_str[2],
570 		    hdrp->mpcnf_prod_str[3],
571 		    hdrp->mpcnf_prod_str[4],
572 		    hdrp->mpcnf_prod_str[5],
573 		    hdrp->mpcnf_prod_str[6],
574 		    hdrp->mpcnf_prod_str[7],
575 		    hdrp->mpcnf_prod_str[8],
576 		    hdrp->mpcnf_prod_str[9],
577 		    hdrp->mpcnf_prod_str[10],
578 		    hdrp->mpcnf_prod_str[11]);
579 	}
580 }
581 
582 static void
583 apic_free_apic_cpus(void)
584 {
585 	if (apic_cpus != NULL) {
586 		kmem_free(apic_cpus, apic_cpus_size);
587 		apic_cpus = NULL;
588 		apic_cpus_size = 0;
589 	}
590 }
591 
592 static uint32_t
593 acpi_get_apic_lid(void)
594 {
595 	uint32_t	id;
596 
597 	id = apic_reg_ops->apic_read(APIC_LID_REG);
598 	if (apic_mode != LOCAL_X2APIC)
599 		id >>= APIC_ID_BIT_OFFSET;
600 
601 	return (id);
602 }
603 
604 static int
605 acpi_probe(char *modname)
606 {
607 	int			i, intmax;
608 	uint32_t		id, ver;
609 	int			acpi_verboseflags = 0;
610 	int			madt_seen, madt_size;
611 	ACPI_SUBTABLE_HEADER		*ap;
612 	ACPI_MADT_LOCAL_APIC	*mpa;
613 	ACPI_MADT_LOCAL_X2APIC	*mpx2a;
614 	ACPI_MADT_IO_APIC		*mia;
615 	ACPI_MADT_IO_SAPIC		*misa;
616 	ACPI_MADT_INTERRUPT_OVERRIDE	*mio;
617 	ACPI_MADT_NMI_SOURCE		*mns;
618 	ACPI_MADT_INTERRUPT_SOURCE	*mis;
619 	ACPI_MADT_LOCAL_APIC_NMI	*mlan;
620 	ACPI_MADT_LOCAL_X2APIC_NMI	*mx2alan;
621 	ACPI_MADT_LOCAL_APIC_OVERRIDE	*mao;
622 	int			sci;
623 	iflag_t			sci_flags;
624 	volatile uint32_t	*ioapic;
625 	int			ioapic_ix;
626 	uint32_t		*local_ids;
627 	uint32_t		*proc_ids;
628 	uchar_t			hid;
629 	int			warned = 0;
630 
631 	if (!apic_use_acpi)
632 		return (PSM_FAILURE);
633 
634 	if (AcpiGetTable(ACPI_SIG_MADT, 1,
635 	    (ACPI_TABLE_HEADER **) &acpi_mapic_dtp) != AE_OK) {
636 		cmn_err(CE_WARN, "!acpi_probe: No MADT found!");
637 		return (PSM_FAILURE);
638 	}
639 
640 	apicadr = mapin_apic((uint32_t)acpi_mapic_dtp->Address,
641 	    APIC_LOCAL_MEMLEN, PROT_READ | PROT_WRITE);
642 	if (!apicadr)
643 		return (PSM_FAILURE);
644 
645 	if ((local_ids = (uint32_t *)kmem_zalloc(NCPU * sizeof (uint32_t),
646 	    KM_NOSLEEP)) == NULL)
647 		return (PSM_FAILURE);
648 
649 	if ((proc_ids = (uint32_t *)kmem_zalloc(NCPU * sizeof (uint32_t),
650 	    KM_NOSLEEP)) == NULL) {
651 		kmem_free(local_ids, NCPU * sizeof (uint32_t));
652 		return (PSM_FAILURE);
653 	}
654 
655 	local_ids[0] = acpi_get_apic_lid();
656 
657 	apic_nproc = 1;
658 	apic_io_max = 0;
659 
660 	ap = (ACPI_SUBTABLE_HEADER *) (acpi_mapic_dtp + 1);
661 	madt_size = acpi_mapic_dtp->Header.Length;
662 	madt_seen = sizeof (*acpi_mapic_dtp);
663 
664 	while (madt_seen < madt_size) {
665 		switch (ap->Type) {
666 		case ACPI_MADT_TYPE_LOCAL_APIC:
667 			mpa = (ACPI_MADT_LOCAL_APIC *) ap;
668 			if (mpa->LapicFlags & ACPI_MADT_ENABLED) {
669 				if (mpa->Id == 255) {
670 					cmn_err(CE_WARN, "!%s: encountered "
671 					    "invalid entry in MADT: CPU %d "
672 					    "has Local APIC Id equal to 255",
673 					    psm_name, mpa->ProcessorId);
674 				}
675 				if (mpa->Id == local_ids[0]) {
676 					proc_ids[0] = mpa->ProcessorId;
677 				} else if (apic_nproc < NCPU && use_mp &&
678 				    apic_nproc < boot_ncpus) {
679 					local_ids[apic_nproc] = mpa->Id;
680 					proc_ids[apic_nproc] = mpa->ProcessorId;
681 					apic_nproc++;
682 				} else if (apic_nproc == NCPU && !warned) {
683 					cmn_err(CE_WARN, "%s: CPU limit "
684 					    "exceeded; will use %d CPUs.",
685 					    psm_name,  NCPU);
686 					warned = 1;
687 				}
688 			}
689 			break;
690 
691 		case ACPI_MADT_TYPE_IO_APIC:
692 			mia = (ACPI_MADT_IO_APIC *) ap;
693 			if (apic_io_max < MAX_IO_APIC) {
694 				ioapic_ix = apic_io_max;
695 				apic_io_id[apic_io_max] = mia->Id;
696 				apic_io_vectbase[apic_io_max] =
697 				    mia->GlobalIrqBase;
698 				apic_physaddr[apic_io_max] =
699 				    (uint32_t)mia->Address;
700 				ioapic = apicioadr[apic_io_max] =
701 				    mapin_ioapic((uint32_t)mia->Address,
702 				    APIC_IO_MEMLEN, PROT_READ | PROT_WRITE);
703 				if (!ioapic)
704 					goto cleanup;
705 				ioapic_mask_workaround[apic_io_max] =
706 				    apic_is_ioapic_AMD_813x(mia->Address);
707 				apic_io_max++;
708 			}
709 			break;
710 
711 		case ACPI_MADT_TYPE_INTERRUPT_OVERRIDE:
712 			mio = (ACPI_MADT_INTERRUPT_OVERRIDE *) ap;
713 			if (acpi_isop == NULL)
714 				acpi_isop = mio;
715 			acpi_iso_cnt++;
716 			break;
717 
718 		case ACPI_MADT_TYPE_NMI_SOURCE:
719 			/* UNIMPLEMENTED */
720 			mns = (ACPI_MADT_NMI_SOURCE *) ap;
721 			if (acpi_nmi_sp == NULL)
722 				acpi_nmi_sp = mns;
723 			acpi_nmi_scnt++;
724 
725 			cmn_err(CE_NOTE, "!apic: nmi source: %d 0x%x",
726 			    mns->GlobalIrq, mns->IntiFlags);
727 			break;
728 
729 		case ACPI_MADT_TYPE_LOCAL_APIC_NMI:
730 			/* UNIMPLEMENTED */
731 			mlan = (ACPI_MADT_LOCAL_APIC_NMI *) ap;
732 			if (acpi_nmi_cp == NULL)
733 				acpi_nmi_cp = mlan;
734 			acpi_nmi_ccnt++;
735 
736 			cmn_err(CE_NOTE, "!apic: local nmi: %d 0x%x %d",
737 			    mlan->ProcessorId, mlan->IntiFlags,
738 			    mlan->Lint);
739 			break;
740 
741 		case ACPI_MADT_TYPE_LOCAL_APIC_OVERRIDE:
742 			/* UNIMPLEMENTED */
743 			mao = (ACPI_MADT_LOCAL_APIC_OVERRIDE *) ap;
744 			cmn_err(CE_NOTE, "!apic: address override: %lx",
745 			    (long)mao->Address);
746 			break;
747 
748 		case ACPI_MADT_TYPE_IO_SAPIC:
749 			/* UNIMPLEMENTED */
750 			misa = (ACPI_MADT_IO_SAPIC *) ap;
751 
752 			cmn_err(CE_NOTE, "!apic: io sapic: %d %d %lx",
753 			    misa->Id, misa->GlobalIrqBase,
754 			    (long)misa->Address);
755 			break;
756 
757 		case ACPI_MADT_TYPE_INTERRUPT_SOURCE:
758 			/* UNIMPLEMENTED */
759 			mis = (ACPI_MADT_INTERRUPT_SOURCE *) ap;
760 
761 			cmn_err(CE_NOTE,
762 			    "!apic: irq source: %d %d %d 0x%x %d %d",
763 			    mis->Id, mis->Eid, mis->GlobalIrq,
764 			    mis->IntiFlags, mis->Type,
765 			    mis->IoSapicVector);
766 			break;
767 
768 		case ACPI_MADT_TYPE_LOCAL_X2APIC:
769 			mpx2a = (ACPI_MADT_LOCAL_X2APIC *) ap;
770 
771 			if (mpx2a->LapicFlags & ACPI_MADT_ENABLED) {
772 				if (mpx2a->LocalApicId == local_ids[0]) {
773 					proc_ids[0] = mpx2a->Uid;
774 				} else if (apic_nproc < NCPU && use_mp &&
775 				    apic_nproc < boot_ncpus) {
776 					local_ids[apic_nproc] =
777 					    mpx2a->LocalApicId;
778 					proc_ids[apic_nproc] = mpx2a->Uid;
779 					apic_nproc++;
780 				} else if (apic_nproc == NCPU && !warned) {
781 					cmn_err(CE_WARN, "%s: CPU limit "
782 					    "exceeded; will use %d CPUs.",
783 					    psm_name,  NCPU);
784 					warned = 1;
785 				}
786 			}
787 
788 			break;
789 
790 		case ACPI_MADT_TYPE_LOCAL_X2APIC_NMI:
791 			/* UNIMPLEMENTED */
792 			mx2alan = (ACPI_MADT_LOCAL_X2APIC_NMI *) ap;
793 			if (mx2alan->Uid >> 8)
794 				acpi_nmi_ccnt++;
795 
796 #ifdef DEBUG
797 			cmn_err(CE_NOTE,
798 			    "!apic: local x2apic nmi: %d 0x%x %d",
799 			    mx2alan->Uid, mx2alan->IntiFlags, mx2alan->Lint);
800 #endif
801 
802 			break;
803 
804 		case ACPI_MADT_TYPE_RESERVED:
805 		default:
806 			break;
807 		}
808 
809 		/* advance to next entry */
810 		madt_seen += ap->Length;
811 		ap = (ACPI_SUBTABLE_HEADER *)(((char *)ap) + ap->Length);
812 	}
813 
814 	/* We found multiple enabled cpus via MADT */
815 	if ((apic_nproc > 1) && (apic_io_max > 0)) {
816 		acpi_found_smp_config = B_TRUE;
817 		cmn_err(CE_NOTE,
818 		    "!apic: Using ACPI (MADT) for SMP configuration");
819 	}
820 
821 	/*
822 	 * allocate enough space for possible hot-adding of CPUs.
823 	 * max_ncpus may be less than apic_nproc if it's set by user.
824 	 */
825 	if (plat_dr_support_cpu()) {
826 		apic_max_nproc = max_ncpus;
827 	}
828 	apic_cpus_size = max(apic_nproc, max_ncpus) * sizeof (*apic_cpus);
829 	if ((apic_cpus = kmem_zalloc(apic_cpus_size, KM_NOSLEEP)) == NULL)
830 		goto cleanup;
831 
832 	/*
833 	 * ACPI doesn't provide the local apic ver, get it directly from the
834 	 * local apic
835 	 */
836 	ver = apic_reg_ops->apic_read(APIC_VERS_REG);
837 	for (i = 0; i < apic_nproc; i++) {
838 		apic_cpus[i].aci_local_id = local_ids[i];
839 		apic_cpus[i].aci_local_ver = (uchar_t)(ver & 0xFF);
840 		apic_cpus[i].aci_processor_id = proc_ids[i];
841 		/* Only build mapping info for CPUs present at boot. */
842 		if (i < boot_ncpus)
843 			(void) acpica_map_cpu(i, proc_ids[i]);
844 	}
845 
846 	/*
847 	 * To support CPU dynamic reconfiguration, the apic CPU info structure
848 	 * for each possible CPU will be pre-allocated at boot time.
849 	 * The state for each apic CPU info structure will be assigned according
850 	 * to the following rules:
851 	 * Rule 1:
852 	 *	Slot index range: [0, min(apic_nproc, boot_ncpus))
853 	 *	State flags: 0
854 	 *	Note: cpu exists and will be configured/enabled at boot time
855 	 * Rule 2:
856 	 *	Slot index range: [boot_ncpus, apic_nproc)
857 	 *	State flags: APIC_CPU_FREE | APIC_CPU_DIRTY
858 	 *	Note: cpu exists but won't be configured/enabled at boot time
859 	 * Rule 3:
860 	 *	Slot index range: [apic_nproc, boot_ncpus)
861 	 *	State flags: APIC_CPU_FREE
862 	 *	Note: cpu doesn't exist at boot time
863 	 * Rule 4:
864 	 *	Slot index range: [max(apic_nproc, boot_ncpus), max_ncpus)
865 	 *	State flags: APIC_CPU_FREE
866 	 *	Note: cpu doesn't exist at boot time
867 	 */
868 	CPUSET_ZERO(apic_cpumask);
869 	for (i = 0; i < min(boot_ncpus, apic_nproc); i++) {
870 		CPUSET_ADD(apic_cpumask, i);
871 		apic_cpus[i].aci_status = 0;
872 	}
873 	for (i = boot_ncpus; i < apic_nproc; i++) {
874 		apic_cpus[i].aci_status = APIC_CPU_FREE | APIC_CPU_DIRTY;
875 	}
876 	for (i = apic_nproc; i < boot_ncpus; i++) {
877 		apic_cpus[i].aci_status = APIC_CPU_FREE;
878 	}
879 	for (i = max(boot_ncpus, apic_nproc); i < max_ncpus; i++) {
880 		apic_cpus[i].aci_status = APIC_CPU_FREE;
881 	}
882 
883 	for (i = 0; i < apic_io_max; i++) {
884 		ioapic_ix = i;
885 
886 		/*
887 		 * need to check Sitka on the following acpi problem
888 		 * On the Sitka, the ioapic's apic_id field isn't reporting
889 		 * the actual io apic id. We have reported this problem
890 		 * to Intel. Until they fix the problem, we will get the
891 		 * actual id directly from the ioapic.
892 		 */
893 		id = ioapic_read(ioapic_ix, APIC_ID_CMD);
894 		hid = (uchar_t)(id >> 24);
895 
896 		if (hid != apic_io_id[i]) {
897 			if (apic_io_id[i] == 0)
898 				apic_io_id[i] = hid;
899 			else { /* set ioapic id to whatever reported by ACPI */
900 				id = ((uint32_t)apic_io_id[i]) << 24;
901 				ioapic_write(ioapic_ix, APIC_ID_CMD, id);
902 			}
903 		}
904 		ver = ioapic_read(ioapic_ix, APIC_VERS_CMD);
905 		apic_io_ver[i] = (uchar_t)(ver & 0xff);
906 		intmax = (ver >> 16) & 0xff;
907 		apic_io_vectend[i] = apic_io_vectbase[i] + intmax;
908 		if (apic_first_avail_irq <= apic_io_vectend[i])
909 			apic_first_avail_irq = apic_io_vectend[i] + 1;
910 	}
911 
912 
913 	/*
914 	 * Process SCI configuration here
915 	 * An error may be returned here if
916 	 * acpi-user-options specifies legacy mode
917 	 * (no SCI, no ACPI mode)
918 	 */
919 	if (acpica_get_sci(&sci, &sci_flags) != AE_OK)
920 		sci = -1;
921 
922 	/*
923 	 * Now call acpi_init() to generate namespaces
924 	 * If this fails, we don't attempt to use ACPI
925 	 * even if we were able to get a MADT above
926 	 */
927 	if (acpica_init() != AE_OK) {
928 		cmn_err(CE_WARN, "!apic: Failed to initialize acpica!");
929 		goto cleanup;
930 	}
931 
932 	/*
933 	 * Call acpica_build_processor_map() now that we have
934 	 * ACPI namesspace access
935 	 */
936 	(void) acpica_build_processor_map();
937 
938 	/*
939 	 * Squirrel away the SCI and flags for later on
940 	 * in apic_picinit() when we're ready
941 	 */
942 	apic_sci_vect = sci;
943 	apic_sci_flags = sci_flags;
944 
945 	if (apic_verbose & APIC_VERBOSE_IRQ_FLAG)
946 		acpi_verboseflags |= PSM_VERBOSE_IRQ_FLAG;
947 
948 	if (apic_verbose & APIC_VERBOSE_POWEROFF_FLAG)
949 		acpi_verboseflags |= PSM_VERBOSE_POWEROFF_FLAG;
950 
951 	if (apic_verbose & APIC_VERBOSE_POWEROFF_PAUSE_FLAG)
952 		acpi_verboseflags |= PSM_VERBOSE_POWEROFF_PAUSE_FLAG;
953 
954 	if (acpi_psm_init(modname, acpi_verboseflags) == ACPI_PSM_FAILURE)
955 		goto cleanup;
956 
957 	/* Enable ACPI APIC interrupt routing */
958 	if (apic_acpi_enter_apicmode() != PSM_FAILURE) {
959 		cmn_err(CE_NOTE, "!apic: Using APIC interrupt routing mode");
960 		build_reserved_irqlist((uchar_t *)apic_reserved_irqlist);
961 		apic_enable_acpi = 1;
962 		if (apic_sci_vect > 0) {
963 			acpica_set_core_feature(ACPI_FEATURE_SCI_EVENT);
964 		}
965 		if (apic_use_acpi_madt_only) {
966 			cmn_err(CE_CONT,
967 			    "?Using ACPI for CPU/IOAPIC information ONLY\n");
968 		}
969 
970 #if !defined(__xpv)
971 		/*
972 		 * probe ACPI for hpet information here which is used later
973 		 * in apic_picinit().
974 		 */
975 		if (hpet_acpi_init(&apic_hpet_vect, &apic_hpet_flags) < 0) {
976 			cmn_err(CE_NOTE, "!ACPI HPET table query failed\n");
977 		}
978 #endif
979 
980 		kmem_free(local_ids, NCPU * sizeof (uint32_t));
981 		kmem_free(proc_ids, NCPU * sizeof (uint32_t));
982 		return (PSM_SUCCESS);
983 	}
984 	/* if setting APIC mode failed above, we fall through to cleanup */
985 
986 cleanup:
987 	cmn_err(CE_WARN, "!apic: Failed acpi_probe, SMP config was %s",
988 	    acpi_found_smp_config ? "found" : "not found");
989 	apic_free_apic_cpus();
990 	if (apicadr != NULL) {
991 		mapout_apic((caddr_t)apicadr, APIC_LOCAL_MEMLEN);
992 		apicadr = NULL;
993 	}
994 	apic_max_nproc = -1;
995 	apic_nproc = 0;
996 	for (i = 0; i < apic_io_max; i++) {
997 		mapout_ioapic((caddr_t)apicioadr[i], APIC_IO_MEMLEN);
998 		apicioadr[i] = NULL;
999 	}
1000 	apic_io_max = 0;
1001 	acpi_isop = NULL;
1002 	acpi_iso_cnt = 0;
1003 	acpi_nmi_sp = NULL;
1004 	acpi_nmi_scnt = 0;
1005 	acpi_nmi_cp = NULL;
1006 	acpi_nmi_ccnt = 0;
1007 	acpi_found_smp_config = B_FALSE;
1008 	kmem_free(local_ids, NCPU * sizeof (uint32_t));
1009 	kmem_free(proc_ids, NCPU * sizeof (uint32_t));
1010 	return (PSM_FAILURE);
1011 }
1012 
1013 /*
1014  * Handle default configuration. Fill in reqd global variables & tables
1015  * Fill all details as MP table does not give any more info
1016  */
1017 static int
1018 apic_handle_defconf(void)
1019 {
1020 	/* Failed to probe ACPI MADT tables, disable CPU DR. */
1021 	apic_max_nproc = -1;
1022 	apic_free_apic_cpus();
1023 	plat_dr_disable_cpu();
1024 
1025 	apicioadr[0] = (void *)mapin_ioapic(APIC_IO_ADDR,
1026 	    APIC_IO_MEMLEN, PROT_READ | PROT_WRITE);
1027 	apicadr = (void *)psm_map_phys(APIC_LOCAL_ADDR,
1028 	    APIC_LOCAL_MEMLEN, PROT_READ);
1029 	apic_cpus_size = 2 * sizeof (*apic_cpus);
1030 	apic_cpus = (apic_cpus_info_t *)
1031 	    kmem_zalloc(apic_cpus_size, KM_NOSLEEP);
1032 	if ((!apicadr) || (!apicioadr[0]) || (!apic_cpus))
1033 		goto apic_handle_defconf_fail;
1034 	CPUSET_ONLY(apic_cpumask, 0);
1035 	CPUSET_ADD(apic_cpumask, 1);
1036 	apic_nproc = 2;
1037 	apic_cpus[0].aci_local_id = acpi_get_apic_lid();
1038 	/*
1039 	 * According to the PC+MP spec 1.1, the local ids
1040 	 * for the default configuration has to be 0 or 1
1041 	 */
1042 	if (apic_cpus[0].aci_local_id == 1)
1043 		apic_cpus[1].aci_local_id = 0;
1044 	else if (apic_cpus[0].aci_local_id == 0)
1045 		apic_cpus[1].aci_local_id = 1;
1046 	else
1047 		goto apic_handle_defconf_fail;
1048 
1049 	apic_io_id[0] = 2;
1050 	apic_io_max = 1;
1051 	if (apic_defconf >= 5) {
1052 		apic_cpus[0].aci_local_ver = APIC_INTEGRATED_VERS;
1053 		apic_cpus[1].aci_local_ver = APIC_INTEGRATED_VERS;
1054 		apic_io_ver[0] = APIC_INTEGRATED_VERS;
1055 	} else {
1056 		apic_cpus[0].aci_local_ver = 0;		/* 82489 DX */
1057 		apic_cpus[1].aci_local_ver = 0;
1058 		apic_io_ver[0] = 0;
1059 	}
1060 	if (apic_defconf == 2 || apic_defconf == 3 || apic_defconf == 6)
1061 		eisa_level_intr_mask = (inb(EISA_LEVEL_CNTL + 1) << 8) |
1062 		    inb(EISA_LEVEL_CNTL) | ((uint_t)INT32_MAX + 1);
1063 	return (PSM_SUCCESS);
1064 
1065 apic_handle_defconf_fail:
1066 	if (apicadr)
1067 		mapout_apic((caddr_t)apicadr, APIC_LOCAL_MEMLEN);
1068 	if (apicioadr[0])
1069 		mapout_ioapic((caddr_t)apicioadr[0], APIC_IO_MEMLEN);
1070 	return (PSM_FAILURE);
1071 }
1072 
1073 /* Parse the entries in MP configuration table and collect info that we need */
1074 static int
1075 apic_parse_mpct(caddr_t mpct, int bypass_cpus_and_ioapics)
1076 {
1077 	struct	apic_procent	*procp;
1078 	struct	apic_bus	*busp;
1079 	struct	apic_io_entry	*ioapicp;
1080 	struct	apic_io_intr	*intrp;
1081 	int			ioapic_ix;
1082 	uint32_t		lid, id;
1083 	uchar_t			hid;
1084 	int			warned = 0;
1085 
1086 	/*LINTED: pointer cast may result in improper alignment */
1087 	procp = (struct apic_procent *)(mpct + sizeof (struct apic_mp_cnf_hdr));
1088 
1089 	/* No need to count cpu entries if we won't use them */
1090 	if (!bypass_cpus_and_ioapics) {
1091 
1092 		/* Find max # of CPUS and allocate structure accordingly */
1093 		apic_nproc = 0;
1094 		CPUSET_ZERO(apic_cpumask);
1095 		while (procp->proc_entry == APIC_CPU_ENTRY) {
1096 			if (procp->proc_cpuflags & CPUFLAGS_EN) {
1097 				if (apic_nproc < NCPU && use_mp &&
1098 				    apic_nproc < boot_ncpus) {
1099 					CPUSET_ADD(apic_cpumask, apic_nproc);
1100 					apic_nproc++;
1101 				} else if (apic_nproc == NCPU && !warned) {
1102 					cmn_err(CE_WARN, "%s: CPU limit "
1103 					    "exceeded; will use %d CPUs.",
1104 					    psm_name,  NCPU);
1105 					warned = 1;
1106 				}
1107 
1108 			}
1109 			procp++;
1110 		}
1111 		apic_cpus_size = apic_nproc * sizeof (*apic_cpus);
1112 		if (!apic_nproc || !(apic_cpus = (apic_cpus_info_t *)
1113 		    kmem_zalloc(apic_cpus_size, KM_NOSLEEP)))
1114 			return (PSM_FAILURE);
1115 	}
1116 
1117 	/*LINTED: pointer cast may result in improper alignment */
1118 	procp = (struct apic_procent *)(mpct + sizeof (struct apic_mp_cnf_hdr));
1119 
1120 	/*
1121 	 * start with index 1 as 0 needs to be filled in with Boot CPU, but
1122 	 * if we're bypassing this information, it has already been filled
1123 	 * in by acpi_probe(), so don't overwrite it.
1124 	 */
1125 	if (!bypass_cpus_and_ioapics)
1126 		apic_nproc = 1;
1127 
1128 	while (procp->proc_entry == APIC_CPU_ENTRY) {
1129 		/* check whether the cpu exists or not */
1130 		if (!bypass_cpus_and_ioapics &&
1131 		    procp->proc_cpuflags & CPUFLAGS_EN) {
1132 			if (procp->proc_cpuflags & CPUFLAGS_BP) { /* Boot CPU */
1133 				lid = acpi_get_apic_lid();
1134 				apic_cpus[0].aci_local_id = procp->proc_apicid;
1135 				if (apic_cpus[0].aci_local_id != lid) {
1136 					return (PSM_FAILURE);
1137 				}
1138 				apic_cpus[0].aci_local_ver =
1139 				    procp->proc_version;
1140 			} else if (apic_nproc < NCPU && use_mp &&
1141 			    apic_nproc < boot_ncpus) {
1142 				apic_cpus[apic_nproc].aci_local_id =
1143 				    procp->proc_apicid;
1144 
1145 				apic_cpus[apic_nproc].aci_local_ver =
1146 				    procp->proc_version;
1147 				apic_nproc++;
1148 
1149 			}
1150 		}
1151 		procp++;
1152 	}
1153 
1154 	/*
1155 	 * Save start of bus entries for later use.
1156 	 * Get EISA level cntrl if EISA bus is present.
1157 	 * Also get the CPI bus id for single CPI bus case
1158 	 */
1159 	apic_busp = busp = (struct apic_bus *)procp;
1160 	while (busp->bus_entry == APIC_BUS_ENTRY) {
1161 		lid = apic_find_bus_type((char *)&busp->bus_str1);
1162 		if (lid	== BUS_EISA) {
1163 			eisa_level_intr_mask = (inb(EISA_LEVEL_CNTL + 1) << 8) |
1164 			    inb(EISA_LEVEL_CNTL) | ((uint_t)INT32_MAX + 1);
1165 		} else if (lid == BUS_PCI) {
1166 			/*
1167 			 * apic_single_pci_busid will be used only if
1168 			 * apic_pic_bus_total is equal to 1
1169 			 */
1170 			apic_pci_bus_total++;
1171 			apic_single_pci_busid = busp->bus_id;
1172 		}
1173 		busp++;
1174 	}
1175 
1176 	ioapicp = (struct apic_io_entry *)busp;
1177 
1178 	if (!bypass_cpus_and_ioapics)
1179 		apic_io_max = 0;
1180 	do {
1181 		if (!bypass_cpus_and_ioapics && apic_io_max < MAX_IO_APIC) {
1182 			if (ioapicp->io_flags & IOAPIC_FLAGS_EN) {
1183 				apic_io_id[apic_io_max] = ioapicp->io_apicid;
1184 				apic_io_ver[apic_io_max] = ioapicp->io_version;
1185 				apicioadr[apic_io_max] =
1186 				    (void *)mapin_ioapic(
1187 				    (uint32_t)ioapicp->io_apic_addr,
1188 				    APIC_IO_MEMLEN, PROT_READ | PROT_WRITE);
1189 
1190 				if (!apicioadr[apic_io_max])
1191 					return (PSM_FAILURE);
1192 
1193 				ioapic_mask_workaround[apic_io_max] =
1194 				    apic_is_ioapic_AMD_813x(
1195 				    ioapicp->io_apic_addr);
1196 
1197 				ioapic_ix = apic_io_max;
1198 				id = ioapic_read(ioapic_ix, APIC_ID_CMD);
1199 				hid = (uchar_t)(id >> 24);
1200 
1201 				if (hid != apic_io_id[apic_io_max]) {
1202 					if (apic_io_id[apic_io_max] == 0)
1203 						apic_io_id[apic_io_max] = hid;
1204 					else {
1205 						/*
1206 						 * set ioapic id to whatever
1207 						 * reported by MPS
1208 						 *
1209 						 * may not need to set index
1210 						 * again ???
1211 						 * take it out and try
1212 						 */
1213 
1214 						id = ((uint32_t)
1215 						    apic_io_id[apic_io_max]) <<
1216 						    24;
1217 
1218 						ioapic_write(ioapic_ix,
1219 						    APIC_ID_CMD, id);
1220 					}
1221 				}
1222 				apic_io_max++;
1223 			}
1224 		}
1225 		ioapicp++;
1226 	} while (ioapicp->io_entry == APIC_IO_ENTRY);
1227 
1228 	apic_io_intrp = (struct apic_io_intr *)ioapicp;
1229 
1230 	intrp = apic_io_intrp;
1231 	while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
1232 		if ((intrp->intr_irq > APIC_MAX_ISA_IRQ) ||
1233 		    (apic_find_bus(intrp->intr_busid) == BUS_PCI)) {
1234 			apic_irq_translate = 1;
1235 			break;
1236 		}
1237 		intrp++;
1238 	}
1239 
1240 	return (PSM_SUCCESS);
1241 }
1242 
1243 boolean_t
1244 apic_cpu_in_range(int cpu)
1245 {
1246 	cpu &= ~IRQ_USER_BOUND;
1247 	/* Check whether cpu id is in valid range. */
1248 	if (cpu < 0 || cpu >= apic_nproc) {
1249 		return (B_FALSE);
1250 	} else if (apic_max_nproc != -1 && cpu >= apic_max_nproc) {
1251 		/*
1252 		 * Check whether cpuid is in valid range if CPU DR is enabled.
1253 		 */
1254 		return (B_FALSE);
1255 	} else if (!CPU_IN_SET(apic_cpumask, cpu)) {
1256 		return (B_FALSE);
1257 	}
1258 
1259 	return (B_TRUE);
1260 }
1261 
1262 processorid_t
1263 apic_get_next_bind_cpu(void)
1264 {
1265 	int i, count;
1266 	processorid_t cpuid = 0;
1267 
1268 	for (count = 0; count < apic_nproc; count++) {
1269 		if (apic_next_bind_cpu >= apic_nproc) {
1270 			apic_next_bind_cpu = 0;
1271 		}
1272 		i = apic_next_bind_cpu++;
1273 		if (apic_cpu_in_range(i)) {
1274 			cpuid = i;
1275 			break;
1276 		}
1277 	}
1278 
1279 	return (cpuid);
1280 }
1281 
1282 uint16_t
1283 apic_get_apic_version()
1284 {
1285 	int i;
1286 	uchar_t min_io_apic_ver = 0;
1287 	static uint16_t version;		/* Cache as value is constant */
1288 	static boolean_t found = B_FALSE;	/* Accomodate zero version */
1289 
1290 	if (found == B_FALSE) {
1291 		found = B_TRUE;
1292 
1293 		/*
1294 		 * Don't assume all IO APICs in the system are the same.
1295 		 *
1296 		 * Set to the minimum version.
1297 		 */
1298 		for (i = 0; i < apic_io_max; i++) {
1299 			if ((apic_io_ver[i] != 0) &&
1300 			    ((min_io_apic_ver == 0) ||
1301 			    (min_io_apic_ver >= apic_io_ver[i])))
1302 				min_io_apic_ver = apic_io_ver[i];
1303 		}
1304 
1305 		/* Assume all local APICs are of the same version. */
1306 		version = (min_io_apic_ver << 8) | apic_cpus[0].aci_local_ver;
1307 	}
1308 	return (version);
1309 }
1310 
1311 static struct apic_mpfps_hdr *
1312 apic_find_fps_sig(caddr_t cptr, int len)
1313 {
1314 	int	i;
1315 
1316 	/* Look for the pattern "_MP_" */
1317 	for (i = 0; i < len; i += 16) {
1318 		if ((*(cptr+i) == '_') &&
1319 		    (*(cptr+i+1) == 'M') &&
1320 		    (*(cptr+i+2) == 'P') &&
1321 		    (*(cptr+i+3) == '_'))
1322 		    /*LINTED: pointer cast may result in improper alignment */
1323 			return ((struct apic_mpfps_hdr *)(cptr + i));
1324 	}
1325 	return (NULL);
1326 }
1327 
1328 static int
1329 apic_checksum(caddr_t bptr, int len)
1330 {
1331 	int	i;
1332 	uchar_t	cksum;
1333 
1334 	cksum = 0;
1335 	for (i = 0; i < len; i++)
1336 		cksum += *bptr++;
1337 	return ((int)cksum);
1338 }
1339 
1340 /*
1341  * On machines with PCI-PCI bridges, a device behind a PCI-PCI bridge
1342  * needs special handling.  We may need to chase up the device tree,
1343  * using the PCI-PCI Bridge specification's "rotating IPIN assumptions",
1344  * to find the IPIN at the root bus that relates to the IPIN on the
1345  * subsidiary bus (for ACPI or MP).  We may, however, have an entry
1346  * in the MP table or the ACPI namespace for this device itself.
1347  * We handle both cases in the search below.
1348  */
1349 /* this is the non-acpi version */
1350 int
1351 apic_handle_pci_pci_bridge(dev_info_t *idip, int child_devno, int child_ipin,
1352     struct apic_io_intr **intrp)
1353 {
1354 	dev_info_t *dipp, *dip;
1355 	int pci_irq;
1356 	ddi_acc_handle_t cfg_handle;
1357 	int bridge_devno, bridge_bus;
1358 	int ipin;
1359 
1360 	dip = idip;
1361 
1362 	/*CONSTCOND*/
1363 	while (1) {
1364 		if (((dipp = ddi_get_parent(dip)) == (dev_info_t *)NULL) ||
1365 		    (pci_config_setup(dipp, &cfg_handle) != DDI_SUCCESS))
1366 			return (-1);
1367 		if ((pci_config_get8(cfg_handle, PCI_CONF_BASCLASS) ==
1368 		    PCI_CLASS_BRIDGE) && (pci_config_get8(cfg_handle,
1369 		    PCI_CONF_SUBCLASS) == PCI_BRIDGE_PCI)) {
1370 			pci_config_teardown(&cfg_handle);
1371 			if (acpica_get_bdf(dipp, &bridge_bus, &bridge_devno,
1372 			    NULL) != 0)
1373 				return (-1);
1374 			/*
1375 			 * This is the rotating scheme documented in the
1376 			 * PCI-to-PCI spec.  If the PCI-to-PCI bridge is
1377 			 * behind another PCI-to-PCI bridge, then it needs
1378 			 * to keep ascending until an interrupt entry is
1379 			 * found or the root is reached.
1380 			 */
1381 			ipin = (child_devno + child_ipin) % PCI_INTD;
1382 			if (bridge_bus == 0 && apic_pci_bus_total == 1)
1383 				bridge_bus = (int)apic_single_pci_busid;
1384 			pci_irq = ((bridge_devno & 0x1f) << 2) |
1385 			    (ipin & 0x3);
1386 			if ((*intrp = apic_find_io_intr_w_busid(pci_irq,
1387 			    bridge_bus)) != NULL) {
1388 				return (pci_irq);
1389 			}
1390 			dip = dipp;
1391 			child_devno = bridge_devno;
1392 			child_ipin = ipin;
1393 		} else {
1394 			pci_config_teardown(&cfg_handle);
1395 			return (-1);
1396 		}
1397 	}
1398 	/*LINTED: function will not fall off the bottom */
1399 }
1400 
1401 uchar_t
1402 acpi_find_ioapic(int irq)
1403 {
1404 	int i;
1405 
1406 	for (i = 0; i < apic_io_max; i++) {
1407 		if (irq >= apic_io_vectbase[i] && irq <= apic_io_vectend[i])
1408 			return ((uchar_t)i);
1409 	}
1410 	return (0xFF);	/* shouldn't happen */
1411 }
1412 
1413 /*
1414  * See if two irqs are compatible for sharing a vector.
1415  * Currently we only support sharing of PCI devices.
1416  */
1417 static int
1418 acpi_intr_compatible(iflag_t iflag1, iflag_t iflag2)
1419 {
1420 	uint_t	level1, po1;
1421 	uint_t	level2, po2;
1422 
1423 	/* Assume active high by default */
1424 	po1 = 0;
1425 	po2 = 0;
1426 
1427 	if (iflag1.bustype != iflag2.bustype || iflag1.bustype != BUS_PCI)
1428 		return (0);
1429 
1430 	if (iflag1.intr_el == INTR_EL_CONFORM)
1431 		level1 = AV_LEVEL;
1432 	else
1433 		level1 = (iflag1.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
1434 
1435 	if (level1 && ((iflag1.intr_po == INTR_PO_ACTIVE_LOW) ||
1436 	    (iflag1.intr_po == INTR_PO_CONFORM)))
1437 		po1 = AV_ACTIVE_LOW;
1438 
1439 	if (iflag2.intr_el == INTR_EL_CONFORM)
1440 		level2 = AV_LEVEL;
1441 	else
1442 		level2 = (iflag2.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
1443 
1444 	if (level2 && ((iflag2.intr_po == INTR_PO_ACTIVE_LOW) ||
1445 	    (iflag2.intr_po == INTR_PO_CONFORM)))
1446 		po2 = AV_ACTIVE_LOW;
1447 
1448 	if ((level1 == level2) && (po1 == po2))
1449 		return (1);
1450 
1451 	return (0);
1452 }
1453 
1454 struct apic_io_intr *
1455 apic_find_io_intr_w_busid(int irqno, int busid)
1456 {
1457 	struct	apic_io_intr	*intrp;
1458 
1459 	/*
1460 	 * It can have more than 1 entry with same source bus IRQ,
1461 	 * but unique with the source bus id
1462 	 */
1463 	intrp = apic_io_intrp;
1464 	if (intrp != NULL) {
1465 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
1466 			if (intrp->intr_irq == irqno &&
1467 			    intrp->intr_busid == busid &&
1468 			    intrp->intr_type == IO_INTR_INT)
1469 				return (intrp);
1470 			intrp++;
1471 		}
1472 	}
1473 	APIC_VERBOSE_IOAPIC((CE_NOTE, "Did not find io intr for irqno:"
1474 	    "busid %x:%x\n", irqno, busid));
1475 	return ((struct apic_io_intr *)NULL);
1476 }
1477 
1478 
1479 struct mps_bus_info {
1480 	char	*bus_name;
1481 	int	bus_id;
1482 } bus_info_array[] = {
1483 	"ISA ", BUS_ISA,
1484 	"PCI ", BUS_PCI,
1485 	"EISA ", BUS_EISA,
1486 	"XPRESS", BUS_XPRESS,
1487 	"PCMCIA", BUS_PCMCIA,
1488 	"VL ", BUS_VL,
1489 	"CBUS ", BUS_CBUS,
1490 	"CBUSII", BUS_CBUSII,
1491 	"FUTURE", BUS_FUTURE,
1492 	"INTERN", BUS_INTERN,
1493 	"MBI ", BUS_MBI,
1494 	"MBII ", BUS_MBII,
1495 	"MPI ", BUS_MPI,
1496 	"MPSA ", BUS_MPSA,
1497 	"NUBUS ", BUS_NUBUS,
1498 	"TC ", BUS_TC,
1499 	"VME ", BUS_VME,
1500 	"PCI-E ", BUS_PCIE
1501 };
1502 
1503 static int
1504 apic_find_bus_type(char *bus)
1505 {
1506 	int	i = 0;
1507 
1508 	for (; i < sizeof (bus_info_array)/sizeof (struct mps_bus_info); i++)
1509 		if (strncmp(bus, bus_info_array[i].bus_name,
1510 		    strlen(bus_info_array[i].bus_name)) == 0)
1511 			return (bus_info_array[i].bus_id);
1512 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus type for bus %s", bus));
1513 	return (0);
1514 }
1515 
1516 static int
1517 apic_find_bus(int busid)
1518 {
1519 	struct	apic_bus	*busp;
1520 
1521 	busp = apic_busp;
1522 	while (busp->bus_entry == APIC_BUS_ENTRY) {
1523 		if (busp->bus_id == busid)
1524 			return (apic_find_bus_type((char *)&busp->bus_str1));
1525 		busp++;
1526 	}
1527 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus for bus id %x", busid));
1528 	return (0);
1529 }
1530 
1531 int
1532 apic_find_bus_id(int bustype)
1533 {
1534 	struct	apic_bus	*busp;
1535 
1536 	busp = apic_busp;
1537 	while (busp->bus_entry == APIC_BUS_ENTRY) {
1538 		if (apic_find_bus_type((char *)&busp->bus_str1) == bustype)
1539 			return (busp->bus_id);
1540 		busp++;
1541 	}
1542 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus id for bustype %x",
1543 	    bustype));
1544 	return (-1);
1545 }
1546 
1547 /*
1548  * Check if a particular irq need to be reserved for any io_intr
1549  */
1550 static struct apic_io_intr *
1551 apic_find_io_intr(int irqno)
1552 {
1553 	struct	apic_io_intr	*intrp;
1554 
1555 	intrp = apic_io_intrp;
1556 	if (intrp != NULL) {
1557 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
1558 			if (intrp->intr_irq == irqno &&
1559 			    intrp->intr_type == IO_INTR_INT)
1560 				return (intrp);
1561 			intrp++;
1562 		}
1563 	}
1564 	return ((struct apic_io_intr *)NULL);
1565 }
1566 
1567 /*
1568  * Check if the given ioapicindex intin combination has already been assigned
1569  * an irq. If so return irqno. Else -1
1570  */
1571 int
1572 apic_find_intin(uchar_t ioapic, uchar_t intin)
1573 {
1574 	apic_irq_t *irqptr;
1575 	int	i;
1576 
1577 	/* find ioapic and intin in the apic_irq_table[] and return the index */
1578 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
1579 		irqptr = apic_irq_table[i];
1580 		while (irqptr) {
1581 			if ((irqptr->airq_mps_intr_index >= 0) &&
1582 			    (irqptr->airq_intin_no == intin) &&
1583 			    (irqptr->airq_ioapicindex == ioapic)) {
1584 				APIC_VERBOSE_IOAPIC((CE_NOTE, "!Found irq "
1585 				    "entry for ioapic:intin %x:%x "
1586 				    "shared interrupts ?", ioapic, intin));
1587 				return (i);
1588 			}
1589 			irqptr = irqptr->airq_next;
1590 		}
1591 	}
1592 	return (-1);
1593 }
1594 
1595 int
1596 apic_allocate_irq(int irq)
1597 {
1598 	int	freeirq, i;
1599 
1600 	if ((freeirq = apic_find_free_irq(irq, (APIC_RESV_IRQ - 1))) == -1) {
1601 		if ((freeirq = apic_find_free_irq(APIC_FIRST_FREE_IRQ,
1602 		    (irq - 1))) == -1) {
1603 			/*
1604 			 * if BIOS really defines every single irq in the mps
1605 			 * table, then don't worry about conflicting with
1606 			 * them, just use any free slot in apic_irq_table
1607 			 */
1608 			for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
1609 				if ((apic_irq_table[i] == NULL) ||
1610 				    apic_irq_table[i]->airq_mps_intr_index ==
1611 				    FREE_INDEX) {
1612 					freeirq = i;
1613 					break;
1614 				}
1615 			}
1616 
1617 			if (freeirq == -1) {
1618 				/* This shouldn't happen, but just in case */
1619 				cmn_err(CE_WARN, "%s: NO available IRQ",
1620 				    psm_name);
1621 				return (-1);
1622 			}
1623 		}
1624 	}
1625 
1626 	if (apic_irq_table[freeirq] == NULL) {
1627 		apic_irq_table[freeirq] =
1628 		    kmem_zalloc(sizeof (apic_irq_t), KM_NOSLEEP);
1629 		if (apic_irq_table[freeirq] == NULL) {
1630 			cmn_err(CE_WARN, "%s: NO memory to allocate IRQ",
1631 			    psm_name);
1632 			return (-1);
1633 		}
1634 		apic_irq_table[freeirq]->airq_temp_cpu = IRQ_UNINIT;
1635 		apic_irq_table[freeirq]->airq_mps_intr_index = FREE_INDEX;
1636 	}
1637 	return (freeirq);
1638 }
1639 
1640 static int
1641 apic_find_free_irq(int start, int end)
1642 {
1643 	int	i;
1644 
1645 	for (i = start; i <= end; i++)
1646 		/* Check if any I/O entry needs this IRQ */
1647 		if (apic_find_io_intr(i) == NULL) {
1648 			/* Then see if it is free */
1649 			if ((apic_irq_table[i] == NULL) ||
1650 			    (apic_irq_table[i]->airq_mps_intr_index ==
1651 			    FREE_INDEX)) {
1652 				return (i);
1653 			}
1654 		}
1655 	return (-1);
1656 }
1657 
1658 /*
1659  * compute the polarity, trigger mode and vector for programming into
1660  * the I/O apic and record in airq_rdt_entry.
1661  */
1662 void
1663 apic_record_rdt_entry(apic_irq_t *irqptr, int irq)
1664 {
1665 	int	ioapicindex, bus_type, vector;
1666 	short	intr_index;
1667 	uint_t	level, po, io_po;
1668 	struct apic_io_intr *iointrp;
1669 
1670 	intr_index = irqptr->airq_mps_intr_index;
1671 	DDI_INTR_IMPLDBG((CE_CONT, "apic_record_rdt_entry: intr_index=%d "
1672 	    "irq = 0x%x dip = 0x%p vector = 0x%x\n", intr_index, irq,
1673 	    (void *)irqptr->airq_dip, irqptr->airq_vector));
1674 
1675 	if (intr_index == RESERVE_INDEX) {
1676 		apic_error |= APIC_ERR_INVALID_INDEX;
1677 		return;
1678 	} else if (APIC_IS_MSI_OR_MSIX_INDEX(intr_index)) {
1679 		return;
1680 	}
1681 
1682 	vector = irqptr->airq_vector;
1683 	ioapicindex = irqptr->airq_ioapicindex;
1684 	/* Assume edge triggered by default */
1685 	level = 0;
1686 	/* Assume active high by default */
1687 	po = 0;
1688 
1689 	if (intr_index == DEFAULT_INDEX || intr_index == FREE_INDEX) {
1690 		ASSERT(irq < 16);
1691 		if (eisa_level_intr_mask & (1 << irq))
1692 			level = AV_LEVEL;
1693 		if (intr_index == FREE_INDEX && apic_defconf == 0)
1694 			apic_error |= APIC_ERR_INVALID_INDEX;
1695 	} else if (intr_index == ACPI_INDEX) {
1696 		bus_type = irqptr->airq_iflag.bustype;
1697 		if (irqptr->airq_iflag.intr_el == INTR_EL_CONFORM) {
1698 			if (bus_type == BUS_PCI)
1699 				level = AV_LEVEL;
1700 		} else
1701 			level = (irqptr->airq_iflag.intr_el == INTR_EL_LEVEL) ?
1702 			    AV_LEVEL : 0;
1703 		if (level &&
1704 		    ((irqptr->airq_iflag.intr_po == INTR_PO_ACTIVE_LOW) ||
1705 		    (irqptr->airq_iflag.intr_po == INTR_PO_CONFORM &&
1706 		    bus_type == BUS_PCI)))
1707 			po = AV_ACTIVE_LOW;
1708 	} else {
1709 		iointrp = apic_io_intrp + intr_index;
1710 		bus_type = apic_find_bus(iointrp->intr_busid);
1711 		if (iointrp->intr_el == INTR_EL_CONFORM) {
1712 			if ((irq < 16) && (eisa_level_intr_mask & (1 << irq)))
1713 				level = AV_LEVEL;
1714 			else if (bus_type == BUS_PCI)
1715 				level = AV_LEVEL;
1716 		} else
1717 			level = (iointrp->intr_el == INTR_EL_LEVEL) ?
1718 			    AV_LEVEL : 0;
1719 		if (level && ((iointrp->intr_po == INTR_PO_ACTIVE_LOW) ||
1720 		    (iointrp->intr_po == INTR_PO_CONFORM &&
1721 		    bus_type == BUS_PCI)))
1722 			po = AV_ACTIVE_LOW;
1723 	}
1724 	if (level)
1725 		apic_level_intr[irq] = 1;
1726 	/*
1727 	 * The 82489DX External APIC cannot do active low polarity interrupts.
1728 	 */
1729 	if (po && (apic_io_ver[ioapicindex] != IOAPIC_VER_82489DX))
1730 		io_po = po;
1731 	else
1732 		io_po = 0;
1733 
1734 	if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG)
1735 		prom_printf("setio: ioapic=0x%x intin=0x%x level=0x%x po=0x%x "
1736 		    "vector=0x%x cpu=0x%x\n\n", ioapicindex,
1737 		    irqptr->airq_intin_no, level, io_po, vector,
1738 		    irqptr->airq_cpu);
1739 
1740 	irqptr->airq_rdt_entry = level|io_po|vector;
1741 }
1742 
1743 int
1744 apic_acpi_translate_pci_irq(dev_info_t *dip, int busid, int devid,
1745     int ipin, int *pci_irqp, iflag_t *intr_flagp)
1746 {
1747 
1748 	int status;
1749 	acpi_psm_lnk_t acpipsmlnk;
1750 
1751 	if ((status = acpi_get_irq_cache_ent(busid, devid, ipin, pci_irqp,
1752 	    intr_flagp)) == ACPI_PSM_SUCCESS) {
1753 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Found irqno %d "
1754 		    "from cache for device %s, instance #%d\n", psm_name,
1755 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
1756 		return (status);
1757 	}
1758 
1759 	bzero(&acpipsmlnk, sizeof (acpi_psm_lnk_t));
1760 
1761 	if ((status = acpi_translate_pci_irq(dip, ipin, pci_irqp, intr_flagp,
1762 	    &acpipsmlnk)) == ACPI_PSM_FAILURE) {
1763 		APIC_VERBOSE_IRQ((CE_WARN, "%s: "
1764 		    " acpi_translate_pci_irq failed for device %s, instance"
1765 		    " #%d", psm_name, ddi_get_name(dip),
1766 		    ddi_get_instance(dip)));
1767 		return (status);
1768 	}
1769 
1770 	if (status == ACPI_PSM_PARTIAL && acpipsmlnk.lnkobj != NULL) {
1771 		status = apic_acpi_irq_configure(&acpipsmlnk, dip, pci_irqp,
1772 		    intr_flagp);
1773 		if (status != ACPI_PSM_SUCCESS) {
1774 			status = acpi_get_current_irq_resource(&acpipsmlnk,
1775 			    pci_irqp, intr_flagp);
1776 		}
1777 	}
1778 
1779 	if (status == ACPI_PSM_SUCCESS) {
1780 		acpi_new_irq_cache_ent(busid, devid, ipin, *pci_irqp,
1781 		    intr_flagp, &acpipsmlnk);
1782 
1783 		APIC_VERBOSE_IRQ((CE_CONT, "%s: [ACPI] "
1784 		    "new irq %d for device %s, instance #%d\n", psm_name,
1785 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
1786 	}
1787 
1788 	return (status);
1789 }
1790 
1791 /*
1792  * Adds an entry to the irq list passed in, and returns the new list.
1793  * Entries are added in priority order (lower numerical priorities are
1794  * placed closer to the head of the list)
1795  */
1796 static prs_irq_list_t *
1797 acpi_insert_prs_irq_ent(prs_irq_list_t *listp, int priority, int irq,
1798     iflag_t *iflagp, acpi_prs_private_t *prsprvp)
1799 {
1800 	struct prs_irq_list_ent *newent, *prevp = NULL, *origlistp;
1801 
1802 	newent = kmem_zalloc(sizeof (struct prs_irq_list_ent), KM_SLEEP);
1803 
1804 	newent->list_prio = priority;
1805 	newent->irq = irq;
1806 	newent->intrflags = *iflagp;
1807 	newent->prsprv = *prsprvp;
1808 	/* ->next is NULL from kmem_zalloc */
1809 
1810 	/*
1811 	 * New list -- return the new entry as the list.
1812 	 */
1813 	if (listp == NULL)
1814 		return (newent);
1815 
1816 	/*
1817 	 * Save original list pointer for return (since we're not modifying
1818 	 * the head)
1819 	 */
1820 	origlistp = listp;
1821 
1822 	/*
1823 	 * Insertion sort, with entries with identical keys stored AFTER
1824 	 * existing entries (the less-than-or-equal test of priority does
1825 	 * this for us).
1826 	 */
1827 	while (listp != NULL && listp->list_prio <= priority) {
1828 		prevp = listp;
1829 		listp = listp->next;
1830 	}
1831 
1832 	newent->next = listp;
1833 
1834 	if (prevp == NULL) { /* Add at head of list (newent is the new head) */
1835 		return (newent);
1836 	} else {
1837 		prevp->next = newent;
1838 		return (origlistp);
1839 	}
1840 }
1841 
1842 /*
1843  * Frees the list passed in, deallocating all memory and leaving *listpp
1844  * set to NULL.
1845  */
1846 static void
1847 acpi_destroy_prs_irq_list(prs_irq_list_t **listpp)
1848 {
1849 	struct prs_irq_list_ent *nextp;
1850 
1851 	ASSERT(listpp != NULL);
1852 
1853 	while (*listpp != NULL) {
1854 		nextp = (*listpp)->next;
1855 		kmem_free(*listpp, sizeof (struct prs_irq_list_ent));
1856 		*listpp = nextp;
1857 	}
1858 }
1859 
1860 /*
1861  * apic_choose_irqs_from_prs returns a list of irqs selected from the list of
1862  * irqs returned by the link device's _PRS method.  The irqs are chosen
1863  * to minimize contention in situations where the interrupt link device
1864  * can be programmed to steer interrupts to different interrupt controller
1865  * inputs (some of which may already be in use).  The list is sorted in order
1866  * of irqs to use, with the highest priority given to interrupt controller
1867  * inputs that are not shared.   When an interrupt controller input
1868  * must be shared, apic_choose_irqs_from_prs adds the possible irqs to the
1869  * returned list in the order that minimizes sharing (thereby ensuring lowest
1870  * possible latency from interrupt trigger time to ISR execution time).
1871  */
1872 static prs_irq_list_t *
1873 apic_choose_irqs_from_prs(acpi_irqlist_t *irqlistent, dev_info_t *dip,
1874     int crs_irq)
1875 {
1876 	int32_t irq;
1877 	int i;
1878 	prs_irq_list_t *prsirqlistp = NULL;
1879 	iflag_t iflags;
1880 
1881 	while (irqlistent != NULL) {
1882 		irqlistent->intr_flags.bustype = BUS_PCI;
1883 
1884 		for (i = 0; i < irqlistent->num_irqs; i++) {
1885 
1886 			irq = irqlistent->irqs[i];
1887 
1888 			if (irq <= 0) {
1889 				/* invalid irq number */
1890 				continue;
1891 			}
1892 
1893 			if ((irq < 16) && (apic_reserved_irqlist[irq]))
1894 				continue;
1895 
1896 			if ((apic_irq_table[irq] == NULL) ||
1897 			    (apic_irq_table[irq]->airq_dip == dip)) {
1898 
1899 				prsirqlistp = acpi_insert_prs_irq_ent(
1900 				    prsirqlistp, 0 /* Highest priority */, irq,
1901 				    &irqlistent->intr_flags,
1902 				    &irqlistent->acpi_prs_prv);
1903 
1904 				/*
1905 				 * If we do not prefer the current irq from _CRS
1906 				 * or if we do and this irq is the same as the
1907 				 * current irq from _CRS, this is the one
1908 				 * to pick.
1909 				 */
1910 				if (!(apic_prefer_crs) || (irq == crs_irq)) {
1911 					return (prsirqlistp);
1912 				}
1913 				continue;
1914 			}
1915 
1916 			/*
1917 			 * Edge-triggered interrupts cannot be shared
1918 			 */
1919 			if (irqlistent->intr_flags.intr_el == INTR_EL_EDGE)
1920 				continue;
1921 
1922 			/*
1923 			 * To work around BIOSes that contain incorrect
1924 			 * interrupt polarity information in interrupt
1925 			 * descriptors returned by _PRS, we assume that
1926 			 * the polarity of the other device sharing this
1927 			 * interrupt controller input is compatible.
1928 			 * If it's not, the caller will catch it when
1929 			 * the caller invokes the link device's _CRS method
1930 			 * (after invoking its _SRS method).
1931 			 */
1932 			iflags = irqlistent->intr_flags;
1933 			iflags.intr_po =
1934 			    apic_irq_table[irq]->airq_iflag.intr_po;
1935 
1936 			if (!acpi_intr_compatible(iflags,
1937 			    apic_irq_table[irq]->airq_iflag)) {
1938 				APIC_VERBOSE_IRQ((CE_CONT, "!%s: irq %d "
1939 				    "not compatible [%x:%x:%x !~ %x:%x:%x]",
1940 				    psm_name, irq,
1941 				    iflags.intr_po,
1942 				    iflags.intr_el,
1943 				    iflags.bustype,
1944 				    apic_irq_table[irq]->airq_iflag.intr_po,
1945 				    apic_irq_table[irq]->airq_iflag.intr_el,
1946 				    apic_irq_table[irq]->airq_iflag.bustype));
1947 				continue;
1948 			}
1949 
1950 			/*
1951 			 * If we prefer the irq from _CRS, no need
1952 			 * to search any further (and make sure
1953 			 * to add this irq with the highest priority
1954 			 * so it's tried first).
1955 			 */
1956 			if (crs_irq == irq && apic_prefer_crs) {
1957 
1958 				return (acpi_insert_prs_irq_ent(
1959 				    prsirqlistp,
1960 				    0 /* Highest priority */,
1961 				    irq, &iflags,
1962 				    &irqlistent->acpi_prs_prv));
1963 			}
1964 
1965 			/*
1966 			 * Priority is equal to the share count (lower
1967 			 * share count is higher priority). Note that
1968 			 * the intr flags passed in here are the ones we
1969 			 * changed above -- if incorrect, it will be
1970 			 * caught by the caller's _CRS flags comparison.
1971 			 */
1972 			prsirqlistp = acpi_insert_prs_irq_ent(
1973 			    prsirqlistp,
1974 			    apic_irq_table[irq]->airq_share, irq,
1975 			    &iflags, &irqlistent->acpi_prs_prv);
1976 		}
1977 
1978 		/* Go to the next irqlist entry */
1979 		irqlistent = irqlistent->next;
1980 	}
1981 
1982 	return (prsirqlistp);
1983 }
1984 
1985 /*
1986  * Configures the irq for the interrupt link device identified by
1987  * acpipsmlnkp.
1988  *
1989  * Gets the current and the list of possible irq settings for the
1990  * device. If apic_unconditional_srs is not set, and the current
1991  * resource setting is in the list of possible irq settings,
1992  * current irq resource setting is passed to the caller.
1993  *
1994  * Otherwise, picks an irq number from the list of possible irq
1995  * settings, and sets the irq of the device to this value.
1996  * If prefer_crs is set, among a set of irq numbers in the list that have
1997  * the least number of devices sharing the interrupt, we pick current irq
1998  * resource setting if it is a member of this set.
1999  *
2000  * Passes the irq number in the value pointed to by pci_irqp, and
2001  * polarity and sensitivity in the structure pointed to by dipintrflagp
2002  * to the caller.
2003  *
2004  * Note that if setting the irq resource failed, but successfuly obtained
2005  * the current irq resource settings, passes the current irq resources
2006  * and considers it a success.
2007  *
2008  * Returns:
2009  * ACPI_PSM_SUCCESS on success.
2010  *
2011  * ACPI_PSM_FAILURE if an error occured during the configuration or
2012  * if a suitable irq was not found for this device, or if setting the
2013  * irq resource and obtaining the current resource fails.
2014  *
2015  */
2016 static int
2017 apic_acpi_irq_configure(acpi_psm_lnk_t *acpipsmlnkp, dev_info_t *dip,
2018     int *pci_irqp, iflag_t *dipintr_flagp)
2019 {
2020 	int32_t irq;
2021 	int cur_irq = -1;
2022 	acpi_irqlist_t *irqlistp;
2023 	prs_irq_list_t *prs_irq_listp, *prs_irq_entp;
2024 	boolean_t found_irq = B_FALSE;
2025 
2026 	dipintr_flagp->bustype = BUS_PCI;
2027 
2028 	if ((acpi_get_possible_irq_resources(acpipsmlnkp, &irqlistp))
2029 	    == ACPI_PSM_FAILURE) {
2030 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Unable to determine "
2031 		    "or assign IRQ for device %s, instance #%d: The system was "
2032 		    "unable to get the list of potential IRQs from ACPI.",
2033 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
2034 
2035 		return (ACPI_PSM_FAILURE);
2036 	}
2037 
2038 	if ((acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
2039 	    dipintr_flagp) == ACPI_PSM_SUCCESS) && (!apic_unconditional_srs) &&
2040 	    (cur_irq > 0)) {
2041 		/*
2042 		 * If an IRQ is set in CRS and that IRQ exists in the set
2043 		 * returned from _PRS, return that IRQ, otherwise print
2044 		 * a warning
2045 		 */
2046 
2047 		if (acpi_irqlist_find_irq(irqlistp, cur_irq, NULL)
2048 		    == ACPI_PSM_SUCCESS) {
2049 
2050 			ASSERT(pci_irqp != NULL);
2051 			*pci_irqp = cur_irq;
2052 			acpi_free_irqlist(irqlistp);
2053 			return (ACPI_PSM_SUCCESS);
2054 		}
2055 
2056 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find the "
2057 		    "current irq %d for device %s, instance #%d in ACPI's "
2058 		    "list of possible irqs for this device. Picking one from "
2059 		    " the latter list.", psm_name, cur_irq, ddi_get_name(dip),
2060 		    ddi_get_instance(dip)));
2061 	}
2062 
2063 	if ((prs_irq_listp = apic_choose_irqs_from_prs(irqlistp, dip,
2064 	    cur_irq)) == NULL) {
2065 
2066 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find a "
2067 		    "suitable irq from the list of possible irqs for device "
2068 		    "%s, instance #%d in ACPI's list of possible irqs",
2069 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
2070 
2071 		acpi_free_irqlist(irqlistp);
2072 		return (ACPI_PSM_FAILURE);
2073 	}
2074 
2075 	acpi_free_irqlist(irqlistp);
2076 
2077 	for (prs_irq_entp = prs_irq_listp;
2078 	    prs_irq_entp != NULL && found_irq == B_FALSE;
2079 	    prs_irq_entp = prs_irq_entp->next) {
2080 
2081 		acpipsmlnkp->acpi_prs_prv = prs_irq_entp->prsprv;
2082 		irq = prs_irq_entp->irq;
2083 
2084 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Setting irq %d for "
2085 		    "device %s instance #%d\n", psm_name, irq,
2086 		    ddi_get_name(dip), ddi_get_instance(dip)));
2087 
2088 		if ((acpi_set_irq_resource(acpipsmlnkp, irq))
2089 		    == ACPI_PSM_SUCCESS) {
2090 			/*
2091 			 * setting irq was successful, check to make sure CRS
2092 			 * reflects that. If CRS does not agree with what we
2093 			 * set, return the irq that was set.
2094 			 */
2095 
2096 			if (acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
2097 			    dipintr_flagp) == ACPI_PSM_SUCCESS) {
2098 
2099 				if (cur_irq != irq)
2100 					APIC_VERBOSE_IRQ((CE_WARN,
2101 					    "!%s: IRQ resource set "
2102 					    "(irqno %d) for device %s "
2103 					    "instance #%d, differs from "
2104 					    "current setting irqno %d",
2105 					    psm_name, irq, ddi_get_name(dip),
2106 					    ddi_get_instance(dip), cur_irq));
2107 			} else {
2108 				/*
2109 				 * On at least one system, there was a bug in
2110 				 * a DSDT method called by _STA, causing _STA to
2111 				 * indicate that the link device was disabled
2112 				 * (when, in fact, it was enabled).  Since _SRS
2113 				 * succeeded, assume that _CRS is lying and use
2114 				 * the iflags from this _PRS interrupt choice.
2115 				 * If we're wrong about the flags, the polarity
2116 				 * will be incorrect and we may get an interrupt
2117 				 * storm, but there's not much else we can do
2118 				 * at this point.
2119 				 */
2120 				*dipintr_flagp = prs_irq_entp->intrflags;
2121 			}
2122 
2123 			/*
2124 			 * Return the irq that was set, and not what _CRS
2125 			 * reports, since _CRS has been seen to return
2126 			 * different IRQs than what was passed to _SRS on some
2127 			 * systems (and just not return successfully on others).
2128 			 */
2129 			cur_irq = irq;
2130 			found_irq = B_TRUE;
2131 		} else {
2132 			APIC_VERBOSE_IRQ((CE_WARN, "!%s: set resource "
2133 			    "irq %d failed for device %s instance #%d",
2134 			    psm_name, irq, ddi_get_name(dip),
2135 			    ddi_get_instance(dip)));
2136 
2137 			if (cur_irq == -1) {
2138 				acpi_destroy_prs_irq_list(&prs_irq_listp);
2139 				return (ACPI_PSM_FAILURE);
2140 			}
2141 		}
2142 	}
2143 
2144 	acpi_destroy_prs_irq_list(&prs_irq_listp);
2145 
2146 	if (!found_irq)
2147 		return (ACPI_PSM_FAILURE);
2148 
2149 	ASSERT(pci_irqp != NULL);
2150 	*pci_irqp = cur_irq;
2151 	return (ACPI_PSM_SUCCESS);
2152 }
2153 
2154 void
2155 ioapic_disable_redirection()
2156 {
2157 	int ioapic_ix;
2158 	int intin_max;
2159 	int intin_ix;
2160 
2161 	/* Disable the I/O APIC redirection entries */
2162 	for (ioapic_ix = 0; ioapic_ix < apic_io_max; ioapic_ix++) {
2163 
2164 		/* Bits 23-16 define the maximum redirection entries */
2165 		intin_max = (ioapic_read(ioapic_ix, APIC_VERS_CMD) >> 16)
2166 		    & 0xff;
2167 
2168 		for (intin_ix = 0; intin_ix <= intin_max; intin_ix++) {
2169 			/*
2170 			 * The assumption here is that this is safe, even for
2171 			 * systems with IOAPICs that suffer from the hardware
2172 			 * erratum because all devices have been quiesced before
2173 			 * this function is called from apic_shutdown()
2174 			 * (or equivalent). If that assumption turns out to be
2175 			 * false, this mask operation can induce the same
2176 			 * erratum result we're trying to avoid.
2177 			 */
2178 			ioapic_write(ioapic_ix, APIC_RDT_CMD + 2 * intin_ix,
2179 			    AV_MASK);
2180 		}
2181 	}
2182 }
2183 
2184 /*
2185  * Looks for an IOAPIC with the specified physical address in the /ioapics
2186  * node in the device tree (created by the PCI enumerator).
2187  */
2188 static boolean_t
2189 apic_is_ioapic_AMD_813x(uint32_t physaddr)
2190 {
2191 	/*
2192 	 * Look in /ioapics, for the ioapic with
2193 	 * the physical address given
2194 	 */
2195 	dev_info_t *ioapicsnode = ddi_find_devinfo(IOAPICS_NODE_NAME, -1, 0);
2196 	dev_info_t *ioapic_child;
2197 	boolean_t rv = B_FALSE;
2198 	int vid, did;
2199 	uint64_t ioapic_paddr;
2200 	boolean_t done = B_FALSE;
2201 
2202 	if (ioapicsnode == NULL)
2203 		return (B_FALSE);
2204 
2205 	/* Load first child: */
2206 	ioapic_child = ddi_get_child(ioapicsnode);
2207 	while (!done && ioapic_child != 0) { /* Iterate over children */
2208 
2209 		if ((ioapic_paddr = (uint64_t)ddi_prop_get_int64(DDI_DEV_T_ANY,
2210 		    ioapic_child, DDI_PROP_DONTPASS, "reg", 0))
2211 		    != 0 && physaddr == ioapic_paddr) {
2212 
2213 			vid = ddi_prop_get_int(DDI_DEV_T_ANY, ioapic_child,
2214 			    DDI_PROP_DONTPASS, IOAPICS_PROP_VENID, 0);
2215 
2216 			if (vid == VENID_AMD) {
2217 
2218 				did = ddi_prop_get_int(DDI_DEV_T_ANY,
2219 				    ioapic_child, DDI_PROP_DONTPASS,
2220 				    IOAPICS_PROP_DEVID, 0);
2221 
2222 				if (did == DEVID_8131_IOAPIC ||
2223 				    did == DEVID_8132_IOAPIC) {
2224 					rv = B_TRUE;
2225 					done = B_TRUE;
2226 				}
2227 			}
2228 		}
2229 
2230 		if (!done)
2231 			ioapic_child = ddi_get_next_sibling(ioapic_child);
2232 	}
2233 
2234 	/* The ioapics node was held by ddi_find_devinfo, so release it */
2235 	ndi_rele_devi(ioapicsnode);
2236 	return (rv);
2237 }
2238 
2239 struct apic_state {
2240 	int32_t as_task_reg;
2241 	int32_t as_dest_reg;
2242 	int32_t as_format_reg;
2243 	int32_t as_local_timer;
2244 	int32_t as_pcint_vect;
2245 	int32_t as_int_vect0;
2246 	int32_t as_int_vect1;
2247 	int32_t as_err_vect;
2248 	int32_t as_init_count;
2249 	int32_t as_divide_reg;
2250 	int32_t as_spur_int_reg;
2251 	uint32_t as_ioapic_ids[MAX_IO_APIC];
2252 };
2253 
2254 
2255 static int
2256 apic_acpi_enter_apicmode(void)
2257 {
2258 	ACPI_OBJECT_LIST	arglist;
2259 	ACPI_OBJECT		arg;
2260 	ACPI_STATUS		status;
2261 
2262 	/* Setup parameter object */
2263 	arglist.Count = 1;
2264 	arglist.Pointer = &arg;
2265 	arg.Type = ACPI_TYPE_INTEGER;
2266 	arg.Integer.Value = ACPI_APIC_MODE;
2267 
2268 	status = AcpiEvaluateObject(NULL, "\\_PIC", &arglist, NULL);
2269 	/*
2270 	 * Per ACPI spec - section 5.8.1 _PIC Method
2271 	 * calling the \_PIC control method is optional for the OS
2272 	 * and might not be found. It's ok to not fail in such cases.
2273 	 * This is the case on linux KVM and qemu (status AE_NOT_FOUND)
2274 	 */
2275 	if (ACPI_FAILURE(status) && (status != AE_NOT_FOUND)) {
2276 		cmn_err(CE_NOTE,
2277 		    "!apic: Reporting APIC mode failed (via _PIC), err: 0x%x",
2278 		    ACPI_FAILURE(status));
2279 		return (PSM_FAILURE);
2280 	} else {
2281 		return (PSM_SUCCESS);
2282 	}
2283 }
2284 
2285 
2286 static void
2287 apic_save_state(struct apic_state *sp)
2288 {
2289 	int	i, cpuid;
2290 	ulong_t	iflag;
2291 
2292 	PMD(PMD_SX, ("apic_save_state %p\n", (void *)sp))
2293 	/*
2294 	 * First the local APIC.
2295 	 */
2296 	sp->as_task_reg = apic_reg_ops->apic_get_pri();
2297 	sp->as_dest_reg =  apic_reg_ops->apic_read(APIC_DEST_REG);
2298 	if (apic_mode == LOCAL_APIC)
2299 		sp->as_format_reg = apic_reg_ops->apic_read(APIC_FORMAT_REG);
2300 	sp->as_local_timer = apic_reg_ops->apic_read(APIC_LOCAL_TIMER);
2301 	sp->as_pcint_vect = apic_reg_ops->apic_read(APIC_PCINT_VECT);
2302 	sp->as_int_vect0 = apic_reg_ops->apic_read(APIC_INT_VECT0);
2303 	sp->as_int_vect1 = apic_reg_ops->apic_read(APIC_INT_VECT1);
2304 	sp->as_err_vect = apic_reg_ops->apic_read(APIC_ERR_VECT);
2305 	sp->as_init_count = apic_reg_ops->apic_read(APIC_INIT_COUNT);
2306 	sp->as_divide_reg = apic_reg_ops->apic_read(APIC_DIVIDE_REG);
2307 	sp->as_spur_int_reg = apic_reg_ops->apic_read(APIC_SPUR_INT_REG);
2308 
2309 	/*
2310 	 * If on the boot processor then save the IOAPICs' IDs
2311 	 */
2312 	if ((cpuid = psm_get_cpu_id()) == 0) {
2313 
2314 		iflag = intr_clear();
2315 		lock_set(&apic_ioapic_lock);
2316 
2317 		for (i = 0; i < apic_io_max; i++)
2318 			sp->as_ioapic_ids[i] = ioapic_read(i, APIC_ID_CMD);
2319 
2320 		lock_clear(&apic_ioapic_lock);
2321 		intr_restore(iflag);
2322 	}
2323 
2324 	/* apic_state() is currently invoked only in Suspend/Resume */
2325 	apic_cpus[cpuid].aci_status |= APIC_CPU_SUSPEND;
2326 }
2327 
2328 static void
2329 apic_restore_state(struct apic_state *sp)
2330 {
2331 	int	i;
2332 	ulong_t	iflag;
2333 
2334 	/*
2335 	 * First the local APIC.
2336 	 */
2337 	apic_reg_ops->apic_write_task_reg(sp->as_task_reg);
2338 	if (apic_mode == LOCAL_APIC) {
2339 		apic_reg_ops->apic_write(APIC_DEST_REG, sp->as_dest_reg);
2340 		apic_reg_ops->apic_write(APIC_FORMAT_REG, sp->as_format_reg);
2341 	}
2342 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, sp->as_local_timer);
2343 	apic_reg_ops->apic_write(APIC_PCINT_VECT, sp->as_pcint_vect);
2344 	apic_reg_ops->apic_write(APIC_INT_VECT0, sp->as_int_vect0);
2345 	apic_reg_ops->apic_write(APIC_INT_VECT1, sp->as_int_vect1);
2346 	apic_reg_ops->apic_write(APIC_ERR_VECT, sp->as_err_vect);
2347 	apic_reg_ops->apic_write(APIC_INIT_COUNT, sp->as_init_count);
2348 	apic_reg_ops->apic_write(APIC_DIVIDE_REG, sp->as_divide_reg);
2349 	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, sp->as_spur_int_reg);
2350 
2351 	/*
2352 	 * the following only needs to be done once, so we do it on the
2353 	 * boot processor, since we know that we only have one of those
2354 	 */
2355 	if (psm_get_cpu_id() == 0) {
2356 
2357 		iflag = intr_clear();
2358 		lock_set(&apic_ioapic_lock);
2359 
2360 		/* Restore IOAPICs' APIC IDs */
2361 		for (i = 0; i < apic_io_max; i++) {
2362 			ioapic_write(i, APIC_ID_CMD, sp->as_ioapic_ids[i]);
2363 		}
2364 
2365 		lock_clear(&apic_ioapic_lock);
2366 		intr_restore(iflag);
2367 
2368 		/*
2369 		 * Reenter APIC mode before restoring LNK devices
2370 		 */
2371 		(void) apic_acpi_enter_apicmode();
2372 
2373 		/*
2374 		 * restore acpi link device mappings
2375 		 */
2376 		acpi_restore_link_devices();
2377 	}
2378 }
2379 
2380 /*
2381  * Returns 0 on success
2382  */
2383 int
2384 apic_state(psm_state_request_t *rp)
2385 {
2386 	PMD(PMD_SX, ("apic_state "))
2387 	switch (rp->psr_cmd) {
2388 	case PSM_STATE_ALLOC:
2389 		rp->req.psm_state_req.psr_state =
2390 		    kmem_zalloc(sizeof (struct apic_state), KM_NOSLEEP);
2391 		if (rp->req.psm_state_req.psr_state == NULL)
2392 			return (ENOMEM);
2393 		rp->req.psm_state_req.psr_state_size =
2394 		    sizeof (struct apic_state);
2395 		PMD(PMD_SX, (":STATE_ALLOC: state %p, size %lx\n",
2396 		    rp->req.psm_state_req.psr_state,
2397 		    rp->req.psm_state_req.psr_state_size))
2398 		return (0);
2399 
2400 	case PSM_STATE_FREE:
2401 		kmem_free(rp->req.psm_state_req.psr_state,
2402 		    rp->req.psm_state_req.psr_state_size);
2403 		PMD(PMD_SX, (" STATE_FREE: state %p, size %lx\n",
2404 		    rp->req.psm_state_req.psr_state,
2405 		    rp->req.psm_state_req.psr_state_size))
2406 		return (0);
2407 
2408 	case PSM_STATE_SAVE:
2409 		PMD(PMD_SX, (" STATE_SAVE: state %p, size %lx\n",
2410 		    rp->req.psm_state_req.psr_state,
2411 		    rp->req.psm_state_req.psr_state_size))
2412 		apic_save_state(rp->req.psm_state_req.psr_state);
2413 		return (0);
2414 
2415 	case PSM_STATE_RESTORE:
2416 		apic_restore_state(rp->req.psm_state_req.psr_state);
2417 		PMD(PMD_SX, (" STATE_RESTORE: state %p, size %lx\n",
2418 		    rp->req.psm_state_req.psr_state,
2419 		    rp->req.psm_state_req.psr_state_size))
2420 		return (0);
2421 
2422 	default:
2423 		return (EINVAL);
2424 	}
2425 }
2426