xref: /illumos-gate/usr/src/uts/i86pc/io/mp_platform_common.c (revision 6cefaae1e90a413ba01560575bb3998e1a3df40e)
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 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * PSMI 1.1 extensions are supported only in 2.6 and later versions.
28  * PSMI 1.2 extensions are supported only in 2.7 and later versions.
29  * PSMI 1.3 and 1.4 extensions are supported in Solaris 10.
30  * PSMI 1.5 extensions are supported in Solaris Nevada.
31  * PSMI 1.6 extensions are supported in Solaris Nevada.
32  */
33 #define	PSMI_1_6
34 
35 #include <sys/processor.h>
36 #include <sys/time.h>
37 #include <sys/psm.h>
38 #include <sys/smp_impldefs.h>
39 #include <sys/cram.h>
40 #include <sys/acpi/acpi.h>
41 #include <sys/acpica.h>
42 #include <sys/psm_common.h>
43 #include <sys/apic.h>
44 #include <sys/pit.h>
45 #include <sys/ddi.h>
46 #include <sys/sunddi.h>
47 #include <sys/ddi_impldefs.h>
48 #include <sys/pci.h>
49 #include <sys/promif.h>
50 #include <sys/x86_archext.h>
51 #include <sys/cpc_impl.h>
52 #include <sys/uadmin.h>
53 #include <sys/panic.h>
54 #include <sys/debug.h>
55 #include <sys/archsystm.h>
56 #include <sys/trap.h>
57 #include <sys/machsystm.h>
58 #include <sys/cpuvar.h>
59 #include <sys/rm_platter.h>
60 #include <sys/privregs.h>
61 #include <sys/cyclic.h>
62 #include <sys/note.h>
63 #include <sys/pci_intr_lib.h>
64 #include <sys/sunndi.h>
65 
66 
67 /*
68  *	Local Function Prototypes
69  */
70 static int apic_handle_defconf();
71 static int apic_parse_mpct(caddr_t mpct, int bypass);
72 static struct apic_mpfps_hdr *apic_find_fps_sig(caddr_t fptr, int size);
73 static int apic_checksum(caddr_t bptr, int len);
74 static int apic_find_bus_type(char *bus);
75 static int apic_find_bus(int busid);
76 static int apic_find_bus_id(int bustype);
77 static struct apic_io_intr *apic_find_io_intr(int irqno);
78 static int apic_find_free_irq(int start, int end);
79 static void apic_mark_vector(uchar_t oldvector, uchar_t newvector);
80 static void apic_xlate_vector_free_timeout_handler(void *arg);
81 static int apic_check_stuck_interrupt(apic_irq_t *irq_ptr, int old_bind_cpu,
82     int new_bind_cpu, int apicindex, int intin_no, int which_irq,
83     struct ioapic_reprogram_data *drep);
84 static void apic_record_rdt_entry(apic_irq_t *irqptr, int irq);
85 static struct apic_io_intr *apic_find_io_intr_w_busid(int irqno, int busid);
86 static int apic_find_intin(uchar_t ioapic, uchar_t intin);
87 static int apic_handle_pci_pci_bridge(dev_info_t *idip, int child_devno,
88     int child_ipin, struct apic_io_intr **intrp);
89 static int apic_setup_irq_table(dev_info_t *dip, int irqno,
90     struct apic_io_intr *intrp, struct intrspec *ispec, iflag_t *intr_flagp,
91     int type);
92 static void apic_set_pwroff_method_from_mpcnfhdr(struct apic_mp_cnf_hdr *hdrp);
93 static void apic_try_deferred_reprogram(int ipl, int vect);
94 static void delete_defer_repro_ent(int which_irq);
95 static void apic_ioapic_wait_pending_clear(int ioapicindex,
96     int intin_no);
97 static boolean_t apic_is_ioapic_AMD_813x(uint32_t physaddr);
98 static int apic_acpi_enter_apicmode(void);
99 
100 int apic_debug_mps_id = 0;	/* 1 - print MPS ID strings */
101 
102 /* ACPI SCI interrupt configuration; -1 if SCI not used */
103 int apic_sci_vect = -1;
104 iflag_t apic_sci_flags;
105 
106 /*
107  * psm name pointer
108  */
109 static char *psm_name;
110 
111 /* ACPI support routines */
112 static int acpi_probe(char *);
113 static int apic_acpi_irq_configure(acpi_psm_lnk_t *acpipsmlnkp, dev_info_t *dip,
114     int *pci_irqp, iflag_t *intr_flagp);
115 
116 static int apic_acpi_translate_pci_irq(dev_info_t *dip, int busid, int devid,
117     int ipin, int *pci_irqp, iflag_t *intr_flagp);
118 static uchar_t acpi_find_ioapic(int irq);
119 static int acpi_intr_compatible(iflag_t iflag1, iflag_t iflag2);
120 
121 /*
122  * number of bits per byte, from <sys/param.h>
123  */
124 #define	UCHAR_MAX	((1 << NBBY) - 1)
125 
126 /* Max wait time (in repetitions) for flags to clear in an RDT entry. */
127 int apic_max_reps_clear_pending = 1000;
128 
129 /* The irq # is implicit in the array index: */
130 struct ioapic_reprogram_data apic_reprogram_info[APIC_MAX_VECTOR+1];
131 /*
132  * APIC_MAX_VECTOR + 1 is the maximum # of IRQs as well. ioapic_reprogram_info
133  * is indexed by IRQ number, NOT by vector number.
134  */
135 
136 int	apic_intr_policy = INTR_ROUND_ROBIN_WITH_AFFINITY;
137 
138 int	apic_next_bind_cpu = 1; /* For round robin assignment */
139 				/* start with cpu 1 */
140 
141 /*
142  * If enabled, the distribution works as follows:
143  * On every interrupt entry, the current ipl for the CPU is set in cpu_info
144  * and the irq corresponding to the ipl is also set in the aci_current array.
145  * interrupt exit and setspl (due to soft interrupts) will cause the current
146  * ipl to be be changed. This is cache friendly as these frequently used
147  * paths write into a per cpu structure.
148  *
149  * Sampling is done by checking the structures for all CPUs and incrementing
150  * the busy field of the irq (if any) executing on each CPU and the busy field
151  * of the corresponding CPU.
152  * In periodic mode this is done on every clock interrupt.
153  * In one-shot mode, this is done thru a cyclic with an interval of
154  * apic_redistribute_sample_interval (default 10 milli sec).
155  *
156  * Every apic_sample_factor_redistribution times we sample, we do computations
157  * to decide which interrupt needs to be migrated (see comments
158  * before apic_intr_redistribute().
159  */
160 
161 /*
162  * Following 3 variables start as % and can be patched or set using an
163  * API to be defined in future. They will be scaled to
164  * sample_factor_redistribution which is in turn set to hertz+1 (in periodic
165  * mode), or 101 in one-shot mode to stagger it away from one sec processing
166  */
167 
168 int	apic_int_busy_mark = 60;
169 int	apic_int_free_mark = 20;
170 int	apic_diff_for_redistribution = 10;
171 
172 /* sampling interval for interrupt redistribution for dynamic migration */
173 int	apic_redistribute_sample_interval = NANOSEC / 100; /* 10 millisec */
174 
175 /*
176  * number of times we sample before deciding to redistribute interrupts
177  * for dynamic migration
178  */
179 int	apic_sample_factor_redistribution = 101;
180 
181 /* timeout for xlate_vector, mark_vector */
182 int	apic_revector_timeout = 16 * 10000; /* 160 millisec */
183 
184 int	apic_redist_cpu_skip = 0;
185 int	apic_num_imbalance = 0;
186 int	apic_num_rebind = 0;
187 
188 int	apic_nproc = 0;
189 size_t	apic_cpus_size = 0;
190 int	apic_defconf = 0;
191 int	apic_irq_translate = 0;
192 int	apic_spec_rev = 0;
193 int	apic_imcrp = 0;
194 
195 int	apic_use_acpi = 1;	/* 1 = use ACPI, 0 = don't use ACPI */
196 int	apic_use_acpi_madt_only = 0;	/* 1=ONLY use MADT from ACPI */
197 
198 /*
199  * For interrupt link devices, if apic_unconditional_srs is set, an irq resource
200  * will be assigned (via _SRS). If it is not set, use the current
201  * irq setting (via _CRS), but only if that irq is in the set of possible
202  * irqs (returned by _PRS) for the device.
203  */
204 int	apic_unconditional_srs = 1;
205 
206 /*
207  * For interrupt link devices, if apic_prefer_crs is set when we are
208  * assigning an IRQ resource to a device, prefer the current IRQ setting
209  * over other possible irq settings under same conditions.
210  */
211 
212 int	apic_prefer_crs = 1;
213 
214 uchar_t	apic_io_id[MAX_IO_APIC];
215 volatile uint32_t *apicioadr[MAX_IO_APIC];
216 static	uchar_t	apic_io_ver[MAX_IO_APIC];
217 static	uchar_t	apic_io_vectbase[MAX_IO_APIC];
218 static	uchar_t	apic_io_vectend[MAX_IO_APIC];
219 uchar_t apic_reserved_irqlist[MAX_ISA_IRQ + 1];
220 uint32_t apic_physaddr[MAX_IO_APIC];
221 
222 static	boolean_t ioapic_mask_workaround[MAX_IO_APIC];
223 
224 /*
225  * First available slot to be used as IRQ index into the apic_irq_table
226  * for those interrupts (like MSI/X) that don't have a physical IRQ.
227  */
228 int apic_first_avail_irq  = APIC_FIRST_FREE_IRQ;
229 
230 /*
231  * apic_ioapic_lock protects the ioapics (reg select), the status, temp_bound
232  * and bound elements of cpus_info and the temp_cpu element of irq_struct
233  */
234 lock_t	apic_ioapic_lock;
235 
236 /*
237  * apic_defer_reprogram_lock ensures that only one processor is handling
238  * deferred interrupt programming at *_intr_exit time.
239  */
240 static	lock_t	apic_defer_reprogram_lock;
241 
242 /*
243  * The current number of deferred reprogrammings outstanding
244  */
245 uint_t	apic_reprogram_outstanding = 0;
246 
247 #ifdef DEBUG
248 /*
249  * Counters that keep track of deferred reprogramming stats
250  */
251 uint_t	apic_intr_deferrals = 0;
252 uint_t	apic_intr_deliver_timeouts = 0;
253 uint_t	apic_last_ditch_reprogram_failures = 0;
254 uint_t	apic_deferred_setup_failures = 0;
255 uint_t	apic_defer_repro_total_retries = 0;
256 uint_t	apic_defer_repro_successes = 0;
257 uint_t	apic_deferred_spurious_enters = 0;
258 #endif
259 
260 static	int	apic_io_max = 0;	/* no. of i/o apics enabled */
261 
262 static	struct apic_io_intr *apic_io_intrp = 0;
263 static	struct apic_bus	*apic_busp;
264 
265 uchar_t	apic_vector_to_irq[APIC_MAX_VECTOR+1];
266 uchar_t	apic_resv_vector[MAXIPL+1];
267 
268 char	apic_level_intr[APIC_MAX_VECTOR+1];
269 
270 static	uint32_t	eisa_level_intr_mask = 0;
271 	/* At least MSB will be set if EISA bus */
272 
273 static	int	apic_pci_bus_total = 0;
274 static	uchar_t	apic_single_pci_busid = 0;
275 
276 /*
277  * airq_mutex protects additions to the apic_irq_table - the first
278  * pointer and any airq_nexts off of that one. It also protects
279  * apic_max_device_irq & apic_min_device_irq. It also guarantees
280  * that share_id is unique as new ids are generated only when new
281  * irq_t structs are linked in. Once linked in the structs are never
282  * deleted. temp_cpu & mps_intr_index field indicate if it is programmed
283  * or allocated. Note that there is a slight gap between allocating in
284  * apic_introp_xlate and programming in addspl.
285  */
286 kmutex_t	airq_mutex;
287 apic_irq_t	*apic_irq_table[APIC_MAX_VECTOR+1];
288 int		apic_max_device_irq = 0;
289 int		apic_min_device_irq = APIC_MAX_VECTOR;
290 
291 /*
292  * Following declarations are for revectoring; used when ISRs at different
293  * IPLs share an irq.
294  */
295 static	lock_t	apic_revector_lock;
296 int	apic_revector_pending = 0;
297 static	uchar_t	*apic_oldvec_to_newvec;
298 static	uchar_t	*apic_newvec_to_oldvec;
299 
300 typedef struct prs_irq_list_ent {
301 	int			list_prio;
302 	int32_t			irq;
303 	iflag_t			intrflags;
304 	acpi_prs_private_t	prsprv;
305 	struct prs_irq_list_ent	*next;
306 } prs_irq_list_t;
307 
308 
309 /*
310  * ACPI variables
311  */
312 /* 1 = acpi is enabled & working, 0 = acpi is not enabled or not there */
313 int apic_enable_acpi = 0;
314 
315 /* ACPI Multiple APIC Description Table ptr */
316 static	ACPI_TABLE_MADT *acpi_mapic_dtp = NULL;
317 
318 /* ACPI Interrupt Source Override Structure ptr */
319 static	ACPI_MADT_INTERRUPT_OVERRIDE *acpi_isop = NULL;
320 static	int acpi_iso_cnt = 0;
321 
322 /* ACPI Non-maskable Interrupt Sources ptr */
323 static	ACPI_MADT_NMI_SOURCE *acpi_nmi_sp = NULL;
324 static	int acpi_nmi_scnt = 0;
325 static	ACPI_MADT_LOCAL_APIC_NMI *acpi_nmi_cp = NULL;
326 static	int acpi_nmi_ccnt = 0;
327 
328 /*
329  * The following added to identify a software poweroff method if available.
330  */
331 
332 static struct {
333 	int	poweroff_method;
334 	char	oem_id[APIC_MPS_OEM_ID_LEN + 1];	/* MAX + 1 for NULL */
335 	char	prod_id[APIC_MPS_PROD_ID_LEN + 1];	/* MAX + 1 for NULL */
336 } apic_mps_ids[] = {
337 	{ APIC_POWEROFF_VIA_RTC,	"INTEL",	"ALDER" },   /* 4300 */
338 	{ APIC_POWEROFF_VIA_RTC,	"NCR",		"AMC" },    /* 4300 */
339 	{ APIC_POWEROFF_VIA_ASPEN_BMC,	"INTEL",	"A450NX" },  /* 4400? */
340 	{ APIC_POWEROFF_VIA_ASPEN_BMC,	"INTEL",	"AD450NX" }, /* 4400 */
341 	{ APIC_POWEROFF_VIA_ASPEN_BMC,	"INTEL",	"AC450NX" }, /* 4400R */
342 	{ APIC_POWEROFF_VIA_SITKA_BMC,	"INTEL",	"S450NX" },  /* S50  */
343 	{ APIC_POWEROFF_VIA_SITKA_BMC,	"INTEL",	"SC450NX" }  /* S50? */
344 };
345 
346 int	apic_poweroff_method = APIC_POWEROFF_NONE;
347 
348 /*
349  * Auto-configuration routines
350  */
351 
352 /*
353  * Look at MPSpec 1.4 (Intel Order # 242016-005) for details of what we do here
354  * May work with 1.1 - but not guaranteed.
355  * According to the MP Spec, the MP floating pointer structure
356  * will be searched in the order described below:
357  * 1. In the first kilobyte of Extended BIOS Data Area (EBDA)
358  * 2. Within the last kilobyte of system base memory
359  * 3. In the BIOS ROM address space between 0F0000h and 0FFFFh
360  * Once we find the right signature with proper checksum, we call
361  * either handle_defconf or parse_mpct to get all info necessary for
362  * subsequent operations.
363  */
364 int
365 apic_probe_common(char *modname)
366 {
367 	uint32_t mpct_addr, ebda_start = 0, base_mem_end;
368 	caddr_t	biosdatap;
369 	caddr_t	mpct;
370 	caddr_t	fptr;
371 	int	i, mpct_size, mapsize, retval = PSM_FAILURE;
372 	ushort_t	ebda_seg, base_mem_size;
373 	struct	apic_mpfps_hdr	*fpsp;
374 	struct	apic_mp_cnf_hdr	*hdrp;
375 	int bypass_cpu_and_ioapics_in_mptables;
376 	int acpi_user_options;
377 
378 	if (apic_forceload < 0)
379 		return (retval);
380 
381 	/*
382 	 * Remember who we are
383 	 */
384 	psm_name = modname;
385 
386 	/* Allow override for MADT-only mode */
387 	acpi_user_options = ddi_prop_get_int(DDI_DEV_T_ANY, ddi_root_node(), 0,
388 	    "acpi-user-options", 0);
389 	apic_use_acpi_madt_only = ((acpi_user_options & ACPI_OUSER_MADT) != 0);
390 
391 	/* Allow apic_use_acpi to override MADT-only mode */
392 	if (!apic_use_acpi)
393 		apic_use_acpi_madt_only = 0;
394 
395 	retval = acpi_probe(modname);
396 
397 	/*
398 	 * mapin the bios data area 40:0
399 	 * 40:13h - two-byte location reports the base memory size
400 	 * 40:0Eh - two-byte location for the exact starting address of
401 	 *	    the EBDA segment for EISA
402 	 */
403 	biosdatap = psm_map_phys(0x400, 0x20, PROT_READ);
404 	if (!biosdatap)
405 		return (retval);
406 	fpsp = (struct apic_mpfps_hdr *)NULL;
407 	mapsize = MPFPS_RAM_WIN_LEN;
408 	/*LINTED: pointer cast may result in improper alignment */
409 	ebda_seg = *((ushort_t *)(biosdatap+0xe));
410 	/* check the 1k of EBDA */
411 	if (ebda_seg) {
412 		ebda_start = ((uint32_t)ebda_seg) << 4;
413 		fptr = psm_map_phys(ebda_start, MPFPS_RAM_WIN_LEN, PROT_READ);
414 		if (fptr) {
415 			if (!(fpsp =
416 			    apic_find_fps_sig(fptr, MPFPS_RAM_WIN_LEN)))
417 				psm_unmap_phys(fptr, MPFPS_RAM_WIN_LEN);
418 		}
419 	}
420 	/* If not in EBDA, check the last k of system base memory */
421 	if (!fpsp) {
422 		/*LINTED: pointer cast may result in improper alignment */
423 		base_mem_size = *((ushort_t *)(biosdatap + 0x13));
424 
425 		if (base_mem_size > 512)
426 			base_mem_end = 639 * 1024;
427 		else
428 			base_mem_end = 511 * 1024;
429 		/* if ebda == last k of base mem, skip to check BIOS ROM */
430 		if (base_mem_end != ebda_start) {
431 
432 			fptr = psm_map_phys(base_mem_end, MPFPS_RAM_WIN_LEN,
433 			    PROT_READ);
434 
435 			if (fptr) {
436 				if (!(fpsp = apic_find_fps_sig(fptr,
437 				    MPFPS_RAM_WIN_LEN)))
438 					psm_unmap_phys(fptr, MPFPS_RAM_WIN_LEN);
439 			}
440 		}
441 	}
442 	psm_unmap_phys(biosdatap, 0x20);
443 
444 	/* If still cannot find it, check the BIOS ROM space */
445 	if (!fpsp) {
446 		mapsize = MPFPS_ROM_WIN_LEN;
447 		fptr = psm_map_phys(MPFPS_ROM_WIN_START,
448 		    MPFPS_ROM_WIN_LEN, PROT_READ);
449 		if (fptr) {
450 			if (!(fpsp =
451 			    apic_find_fps_sig(fptr, MPFPS_ROM_WIN_LEN))) {
452 				psm_unmap_phys(fptr, MPFPS_ROM_WIN_LEN);
453 				return (retval);
454 			}
455 		}
456 	}
457 
458 	if (apic_checksum((caddr_t)fpsp, fpsp->mpfps_length * 16) != 0) {
459 		psm_unmap_phys(fptr, MPFPS_ROM_WIN_LEN);
460 		return (retval);
461 	}
462 
463 	apic_spec_rev = fpsp->mpfps_spec_rev;
464 	if ((apic_spec_rev != 04) && (apic_spec_rev != 01)) {
465 		psm_unmap_phys(fptr, MPFPS_ROM_WIN_LEN);
466 		return (retval);
467 	}
468 
469 	/* check IMCR is present or not */
470 	apic_imcrp = fpsp->mpfps_featinfo2 & MPFPS_FEATINFO2_IMCRP;
471 
472 	/* check default configuration (dual CPUs) */
473 	if ((apic_defconf = fpsp->mpfps_featinfo1) != 0) {
474 		psm_unmap_phys(fptr, mapsize);
475 		return (apic_handle_defconf());
476 	}
477 
478 	/* MP Configuration Table */
479 	mpct_addr = (uint32_t)(fpsp->mpfps_mpct_paddr);
480 
481 	psm_unmap_phys(fptr, mapsize); /* unmap floating ptr struct */
482 
483 	/*
484 	 * Map in enough memory for the MP Configuration Table Header.
485 	 * Use this table to read the total length of the BIOS data and
486 	 * map in all the info
487 	 */
488 	/*LINTED: pointer cast may result in improper alignment */
489 	hdrp = (struct apic_mp_cnf_hdr *)psm_map_phys(mpct_addr,
490 	    sizeof (struct apic_mp_cnf_hdr), PROT_READ);
491 	if (!hdrp)
492 		return (retval);
493 
494 	/* check mp configuration table signature PCMP */
495 	if (hdrp->mpcnf_sig != 0x504d4350) {
496 		psm_unmap_phys((caddr_t)hdrp, sizeof (struct apic_mp_cnf_hdr));
497 		return (retval);
498 	}
499 	mpct_size = (int)hdrp->mpcnf_tbl_length;
500 
501 	apic_set_pwroff_method_from_mpcnfhdr(hdrp);
502 
503 	psm_unmap_phys((caddr_t)hdrp, sizeof (struct apic_mp_cnf_hdr));
504 
505 	if ((retval == PSM_SUCCESS) && !apic_use_acpi_madt_only) {
506 		/* This is an ACPI machine No need for further checks */
507 		return (retval);
508 	}
509 
510 	/*
511 	 * Map in the entries for this machine, ie. Processor
512 	 * Entry Tables, Bus Entry Tables, etc.
513 	 * They are in fixed order following one another
514 	 */
515 	mpct = psm_map_phys(mpct_addr, mpct_size, PROT_READ);
516 	if (!mpct)
517 		return (retval);
518 
519 	if (apic_checksum(mpct, mpct_size) != 0)
520 		goto apic_fail1;
521 
522 
523 	/*LINTED: pointer cast may result in improper alignment */
524 	hdrp = (struct apic_mp_cnf_hdr *)mpct;
525 	apicadr = (uint32_t *)mapin_apic((uint32_t)hdrp->mpcnf_local_apic,
526 	    APIC_LOCAL_MEMLEN, PROT_READ | PROT_WRITE);
527 	if (!apicadr)
528 		goto apic_fail1;
529 
530 	/* Parse all information in the tables */
531 	bypass_cpu_and_ioapics_in_mptables = (retval == PSM_SUCCESS);
532 	if (apic_parse_mpct(mpct, bypass_cpu_and_ioapics_in_mptables) ==
533 	    PSM_SUCCESS)
534 		return (PSM_SUCCESS);
535 
536 	for (i = 0; i < apic_io_max; i++)
537 		mapout_ioapic((caddr_t)apicioadr[i], APIC_IO_MEMLEN);
538 	if (apic_cpus)
539 		kmem_free(apic_cpus, apic_cpus_size);
540 	if (apicadr)
541 		mapout_apic((caddr_t)apicadr, APIC_LOCAL_MEMLEN);
542 apic_fail1:
543 	psm_unmap_phys(mpct, mpct_size);
544 	return (retval);
545 }
546 
547 static void
548 apic_set_pwroff_method_from_mpcnfhdr(struct apic_mp_cnf_hdr *hdrp)
549 {
550 	int	i;
551 
552 	for (i = 0; i < (sizeof (apic_mps_ids) / sizeof (apic_mps_ids[0]));
553 	    i++) {
554 		if ((strncmp(hdrp->mpcnf_oem_str, apic_mps_ids[i].oem_id,
555 		    strlen(apic_mps_ids[i].oem_id)) == 0) &&
556 		    (strncmp(hdrp->mpcnf_prod_str, apic_mps_ids[i].prod_id,
557 		    strlen(apic_mps_ids[i].prod_id)) == 0)) {
558 
559 			apic_poweroff_method = apic_mps_ids[i].poweroff_method;
560 			break;
561 		}
562 	}
563 
564 	if (apic_debug_mps_id != 0) {
565 		cmn_err(CE_CONT, "%s: MPS OEM ID = '%c%c%c%c%c%c%c%c'"
566 		    "Product ID = '%c%c%c%c%c%c%c%c%c%c%c%c'\n",
567 		    psm_name,
568 		    hdrp->mpcnf_oem_str[0],
569 		    hdrp->mpcnf_oem_str[1],
570 		    hdrp->mpcnf_oem_str[2],
571 		    hdrp->mpcnf_oem_str[3],
572 		    hdrp->mpcnf_oem_str[4],
573 		    hdrp->mpcnf_oem_str[5],
574 		    hdrp->mpcnf_oem_str[6],
575 		    hdrp->mpcnf_oem_str[7],
576 		    hdrp->mpcnf_prod_str[0],
577 		    hdrp->mpcnf_prod_str[1],
578 		    hdrp->mpcnf_prod_str[2],
579 		    hdrp->mpcnf_prod_str[3],
580 		    hdrp->mpcnf_prod_str[4],
581 		    hdrp->mpcnf_prod_str[5],
582 		    hdrp->mpcnf_prod_str[6],
583 		    hdrp->mpcnf_prod_str[7],
584 		    hdrp->mpcnf_prod_str[8],
585 		    hdrp->mpcnf_prod_str[9],
586 		    hdrp->mpcnf_prod_str[10],
587 		    hdrp->mpcnf_prod_str[11]);
588 	}
589 }
590 
591 static int
592 acpi_probe(char *modname)
593 {
594 	int			i, intmax, index;
595 	uint32_t		id, ver;
596 	int			acpi_verboseflags = 0;
597 	int			madt_seen, madt_size;
598 	ACPI_SUBTABLE_HEADER		*ap;
599 	ACPI_MADT_LOCAL_APIC	*mpa;
600 	ACPI_MADT_LOCAL_X2APIC	*mpx2a;
601 	ACPI_MADT_IO_APIC		*mia;
602 	ACPI_MADT_IO_SAPIC		*misa;
603 	ACPI_MADT_INTERRUPT_OVERRIDE	*mio;
604 	ACPI_MADT_NMI_SOURCE		*mns;
605 	ACPI_MADT_INTERRUPT_SOURCE	*mis;
606 	ACPI_MADT_LOCAL_APIC_NMI	*mlan;
607 	ACPI_MADT_LOCAL_X2APIC_NMI	*mx2alan;
608 	ACPI_MADT_LOCAL_APIC_OVERRIDE	*mao;
609 	int			sci;
610 	iflag_t			sci_flags;
611 	volatile uint32_t	*ioapic;
612 	int			ioapic_ix;
613 	uint32_t		local_ids[NCPU];
614 	uint32_t		proc_ids[NCPU];
615 	uchar_t			hid;
616 
617 	if (!apic_use_acpi)
618 		return (PSM_FAILURE);
619 
620 	if (AcpiGetTable(ACPI_SIG_MADT, 1,
621 	    (ACPI_TABLE_HEADER **) &acpi_mapic_dtp) != AE_OK)
622 		return (PSM_FAILURE);
623 
624 	apicadr = mapin_apic((uint32_t)acpi_mapic_dtp->Address,
625 	    APIC_LOCAL_MEMLEN, PROT_READ | PROT_WRITE);
626 	if (!apicadr)
627 		return (PSM_FAILURE);
628 
629 	/*
630 	 * We don't enable x2APIC when Solaris is running under xVM.
631 	 */
632 #if !defined(__xpv)
633 	if (apic_detect_x2apic()) {
634 		apic_enable_x2apic();
635 	}
636 #endif
637 
638 	id = apic_reg_ops->apic_read(APIC_LID_REG);
639 	local_ids[0] = (uchar_t)(id >> 24);
640 	apic_nproc = index = 1;
641 	CPUSET_ONLY(apic_cpumask, 0);
642 	apic_io_max = 0;
643 
644 	ap = (ACPI_SUBTABLE_HEADER *) (acpi_mapic_dtp + 1);
645 	madt_size = acpi_mapic_dtp->Header.Length;
646 	madt_seen = sizeof (*acpi_mapic_dtp);
647 
648 	while (madt_seen < madt_size) {
649 		switch (ap->Type) {
650 		case ACPI_MADT_TYPE_LOCAL_APIC:
651 			mpa = (ACPI_MADT_LOCAL_APIC *) ap;
652 			if (mpa->LapicFlags & ACPI_MADT_ENABLED) {
653 				if (mpa->Id == local_ids[0]) {
654 					proc_ids[0] = mpa->ProcessorId;
655 					acpica_map_cpu(0, mpa->ProcessorId);
656 				} else if (apic_nproc < NCPU && use_mp &&
657 				    apic_nproc < boot_ncpus) {
658 					local_ids[index] = mpa->Id;
659 					proc_ids[index] = mpa->ProcessorId;
660 					CPUSET_ADD(apic_cpumask, index);
661 					acpica_map_cpu(index, mpa->ProcessorId);
662 					index++;
663 					apic_nproc++;
664 				} else if (apic_nproc == NCPU)
665 					cmn_err(CE_WARN, "%s: exceeded "
666 					    "maximum no. of CPUs (= %d)",
667 					    psm_name,  NCPU);
668 			}
669 			break;
670 
671 		case ACPI_MADT_TYPE_IO_APIC:
672 			mia = (ACPI_MADT_IO_APIC *) ap;
673 			if (apic_io_max < MAX_IO_APIC) {
674 				ioapic_ix = apic_io_max;
675 				apic_io_id[apic_io_max] = mia->Id;
676 				apic_io_vectbase[apic_io_max] =
677 				    mia->GlobalIrqBase;
678 				apic_physaddr[apic_io_max] =
679 				    (uint32_t)mia->Address;
680 				ioapic = apicioadr[apic_io_max] =
681 				    mapin_ioapic((uint32_t)mia->Address,
682 				    APIC_IO_MEMLEN, PROT_READ | PROT_WRITE);
683 				if (!ioapic)
684 					goto cleanup;
685 				ioapic_mask_workaround[apic_io_max] =
686 				    apic_is_ioapic_AMD_813x(mia->Address);
687 				apic_io_max++;
688 			}
689 			break;
690 
691 		case ACPI_MADT_TYPE_INTERRUPT_OVERRIDE:
692 			mio = (ACPI_MADT_INTERRUPT_OVERRIDE *) ap;
693 			if (acpi_isop == NULL)
694 				acpi_isop = mio;
695 			acpi_iso_cnt++;
696 			break;
697 
698 		case ACPI_MADT_TYPE_NMI_SOURCE:
699 			/* UNIMPLEMENTED */
700 			mns = (ACPI_MADT_NMI_SOURCE *) ap;
701 			if (acpi_nmi_sp == NULL)
702 				acpi_nmi_sp = mns;
703 			acpi_nmi_scnt++;
704 
705 			cmn_err(CE_NOTE, "!apic: nmi source: %d 0x%x\n",
706 			    mns->GlobalIrq, mns->IntiFlags);
707 			break;
708 
709 		case ACPI_MADT_TYPE_LOCAL_APIC_NMI:
710 			/* UNIMPLEMENTED */
711 			mlan = (ACPI_MADT_LOCAL_APIC_NMI *) ap;
712 			if (acpi_nmi_cp == NULL)
713 				acpi_nmi_cp = mlan;
714 			acpi_nmi_ccnt++;
715 
716 			cmn_err(CE_NOTE, "!apic: local nmi: %d 0x%x %d\n",
717 			    mlan->ProcessorId, mlan->IntiFlags,
718 			    mlan->Lint);
719 			break;
720 
721 		case ACPI_MADT_TYPE_LOCAL_APIC_OVERRIDE:
722 			/* UNIMPLEMENTED */
723 			mao = (ACPI_MADT_LOCAL_APIC_OVERRIDE *) ap;
724 			cmn_err(CE_NOTE, "!apic: address override: %lx\n",
725 			    (long)mao->Address);
726 			break;
727 
728 		case ACPI_MADT_TYPE_IO_SAPIC:
729 			/* UNIMPLEMENTED */
730 			misa = (ACPI_MADT_IO_SAPIC *) ap;
731 
732 			cmn_err(CE_NOTE, "!apic: io sapic: %d %d %lx\n",
733 			    misa->Id, misa->GlobalIrqBase,
734 			    (long)misa->Address);
735 			break;
736 
737 		case ACPI_MADT_TYPE_INTERRUPT_SOURCE:
738 			/* UNIMPLEMENTED */
739 			mis = (ACPI_MADT_INTERRUPT_SOURCE *) ap;
740 
741 			cmn_err(CE_NOTE,
742 			    "!apic: irq source: %d %d %d 0x%x %d %d\n",
743 			    mis->Id, mis->Eid, mis->GlobalIrq,
744 			    mis->IntiFlags, mis->Type,
745 			    mis->IoSapicVector);
746 			break;
747 
748 		case ACPI_MADT_TYPE_LOCAL_X2APIC:
749 			mpx2a = (ACPI_MADT_LOCAL_X2APIC *) ap;
750 
751 			/*
752 			 * All logical processors with APIC ID values
753 			 * of 255 and greater will have their APIC
754 			 * reported through Processor X2APIC structure.
755 			 * All logical processors with APIC ID less than
756 			 * 255 will have their APIC reported through
757 			 * Processor Local APIC.
758 			 */
759 			if ((mpx2a->LapicFlags & ACPI_MADT_ENABLED) &&
760 			    (mpx2a->LocalApicId >> 8)) {
761 				if (apic_nproc < NCPU && use_mp &&
762 				    apic_nproc < boot_ncpus) {
763 					local_ids[index] = mpx2a->LocalApicId;
764 					CPUSET_ADD(apic_cpumask, index);
765 					acpica_map_cpu(index, mpx2a->Uid);
766 					index++;
767 					apic_nproc++;
768 				} else if (apic_nproc == NCPU) {
769 					cmn_err(CE_WARN, "%s: exceeded"
770 					    " maximum no. of CPUs ("
771 					    "=%d)", psm_name, NCPU);
772 				}
773 			}
774 
775 			break;
776 
777 		case ACPI_MADT_TYPE_LOCAL_X2APIC_NMI:
778 			/* UNIMPLEMENTED */
779 			mx2alan = (ACPI_MADT_LOCAL_X2APIC_NMI *) ap;
780 			if (mx2alan->Uid >> 8)
781 				acpi_nmi_ccnt++;
782 
783 #ifdef	DEBUG
784 			cmn_err(CE_NOTE,
785 			    "!apic: local x2apic nmi: %d 0x%x %d\n",
786 			    mx2alan->Uid, mx2alan->IntiFlags, mx2alan->Lint);
787 #endif
788 
789 			break;
790 
791 		case ACPI_MADT_TYPE_RESERVED:
792 		default:
793 			break;
794 		}
795 
796 		/* advance to next entry */
797 		madt_seen += ap->Length;
798 		ap = (ACPI_SUBTABLE_HEADER *)(((char *)ap) + ap->Length);
799 	}
800 
801 	apic_cpus_size = apic_nproc * sizeof (*apic_cpus);
802 	if ((apic_cpus = kmem_zalloc(apic_cpus_size, KM_NOSLEEP)) == NULL)
803 		goto cleanup;
804 
805 	/*
806 	 * ACPI doesn't provide the local apic ver, get it directly from the
807 	 * local apic
808 	 */
809 	ver = apic_reg_ops->apic_read(APIC_VERS_REG);
810 	for (i = 0; i < apic_nproc; i++) {
811 		apic_cpus[i].aci_local_id = local_ids[i];
812 		apic_cpus[i].aci_local_ver = (uchar_t)(ver & 0xFF);
813 	}
814 
815 	for (i = 0; i < apic_io_max; i++) {
816 		ioapic_ix = i;
817 
818 		/*
819 		 * need to check Sitka on the following acpi problem
820 		 * On the Sitka, the ioapic's apic_id field isn't reporting
821 		 * the actual io apic id. We have reported this problem
822 		 * to Intel. Until they fix the problem, we will get the
823 		 * actual id directly from the ioapic.
824 		 */
825 		id = ioapic_read(ioapic_ix, APIC_ID_CMD);
826 		hid = (uchar_t)(id >> 24);
827 
828 		if (hid != apic_io_id[i]) {
829 			if (apic_io_id[i] == 0)
830 				apic_io_id[i] = hid;
831 			else { /* set ioapic id to whatever reported by ACPI */
832 				id = ((uint32_t)apic_io_id[i]) << 24;
833 				ioapic_write(ioapic_ix, APIC_ID_CMD, id);
834 			}
835 		}
836 		ver = ioapic_read(ioapic_ix, APIC_VERS_CMD);
837 		apic_io_ver[i] = (uchar_t)(ver & 0xff);
838 		intmax = (ver >> 16) & 0xff;
839 		apic_io_vectend[i] = apic_io_vectbase[i] + intmax;
840 		if (apic_first_avail_irq <= apic_io_vectend[i])
841 			apic_first_avail_irq = apic_io_vectend[i] + 1;
842 	}
843 
844 
845 	/*
846 	 * Process SCI configuration here
847 	 * An error may be returned here if
848 	 * acpi-user-options specifies legacy mode
849 	 * (no SCI, no ACPI mode)
850 	 */
851 	if (acpica_get_sci(&sci, &sci_flags) != AE_OK)
852 		sci = -1;
853 
854 	/*
855 	 * Now call acpi_init() to generate namespaces
856 	 * If this fails, we don't attempt to use ACPI
857 	 * even if we were able to get a MADT above
858 	 */
859 	if (acpica_init() != AE_OK)
860 		goto cleanup;
861 
862 	/*
863 	 * Call acpica_build_processor_map() now that we have
864 	 * ACPI namesspace access
865 	 */
866 	acpica_build_processor_map();
867 
868 	/*
869 	 * Squirrel away the SCI and flags for later on
870 	 * in apic_picinit() when we're ready
871 	 */
872 	apic_sci_vect = sci;
873 	apic_sci_flags = sci_flags;
874 
875 	if (apic_verbose & APIC_VERBOSE_IRQ_FLAG)
876 		acpi_verboseflags |= PSM_VERBOSE_IRQ_FLAG;
877 
878 	if (apic_verbose & APIC_VERBOSE_POWEROFF_FLAG)
879 		acpi_verboseflags |= PSM_VERBOSE_POWEROFF_FLAG;
880 
881 	if (apic_verbose & APIC_VERBOSE_POWEROFF_PAUSE_FLAG)
882 		acpi_verboseflags |= PSM_VERBOSE_POWEROFF_PAUSE_FLAG;
883 
884 	if (acpi_psm_init(modname, acpi_verboseflags) == ACPI_PSM_FAILURE)
885 		goto cleanup;
886 
887 	/* Enable ACPI APIC interrupt routing */
888 	if (apic_acpi_enter_apicmode() != PSM_FAILURE) {
889 		build_reserved_irqlist((uchar_t *)apic_reserved_irqlist);
890 		apic_enable_acpi = 1;
891 		if (apic_use_acpi_madt_only) {
892 			cmn_err(CE_CONT,
893 			    "?Using ACPI for CPU/IOAPIC information ONLY\n");
894 		}
895 		return (PSM_SUCCESS);
896 	}
897 	/* if setting APIC mode failed above, we fall through to cleanup */
898 
899 cleanup:
900 	if (apicadr != NULL) {
901 		mapout_apic((caddr_t)apicadr, APIC_LOCAL_MEMLEN);
902 		apicadr = NULL;
903 	}
904 	apic_nproc = 0;
905 	for (i = 0; i < apic_io_max; i++) {
906 		mapout_ioapic((caddr_t)apicioadr[i], APIC_IO_MEMLEN);
907 		apicioadr[i] = NULL;
908 	}
909 	apic_io_max = 0;
910 	acpi_isop = NULL;
911 	acpi_iso_cnt = 0;
912 	acpi_nmi_sp = NULL;
913 	acpi_nmi_scnt = 0;
914 	acpi_nmi_cp = NULL;
915 	acpi_nmi_ccnt = 0;
916 	return (PSM_FAILURE);
917 }
918 
919 /*
920  * Handle default configuration. Fill in reqd global variables & tables
921  * Fill all details as MP table does not give any more info
922  */
923 static int
924 apic_handle_defconf()
925 {
926 	uint_t	lid;
927 
928 	/*LINTED: pointer cast may result in improper alignment */
929 	apicioadr[0] = mapin_ioapic(APIC_IO_ADDR,
930 	    APIC_IO_MEMLEN, PROT_READ | PROT_WRITE);
931 	/*LINTED: pointer cast may result in improper alignment */
932 	apicadr = (uint32_t *)psm_map_phys(APIC_LOCAL_ADDR,
933 	    APIC_LOCAL_MEMLEN, PROT_READ);
934 	apic_cpus_size = 2 * sizeof (*apic_cpus);
935 	apic_cpus = (apic_cpus_info_t *)
936 	    kmem_zalloc(apic_cpus_size, KM_NOSLEEP);
937 	if ((!apicadr) || (!apicioadr[0]) || (!apic_cpus))
938 		goto apic_handle_defconf_fail;
939 	CPUSET_ONLY(apic_cpumask, 0);
940 	CPUSET_ADD(apic_cpumask, 1);
941 	apic_nproc = 2;
942 	lid = apic_reg_ops->apic_read(APIC_LID_REG);
943 	apic_cpus[0].aci_local_id = (uchar_t)(lid >> APIC_ID_BIT_OFFSET);
944 	/*
945 	 * According to the PC+MP spec 1.1, the local ids
946 	 * for the default configuration has to be 0 or 1
947 	 */
948 	if (apic_cpus[0].aci_local_id == 1)
949 		apic_cpus[1].aci_local_id = 0;
950 	else if (apic_cpus[0].aci_local_id == 0)
951 		apic_cpus[1].aci_local_id = 1;
952 	else
953 		goto apic_handle_defconf_fail;
954 
955 	apic_io_id[0] = 2;
956 	apic_io_max = 1;
957 	if (apic_defconf >= 5) {
958 		apic_cpus[0].aci_local_ver = APIC_INTEGRATED_VERS;
959 		apic_cpus[1].aci_local_ver = APIC_INTEGRATED_VERS;
960 		apic_io_ver[0] = APIC_INTEGRATED_VERS;
961 	} else {
962 		apic_cpus[0].aci_local_ver = 0;		/* 82489 DX */
963 		apic_cpus[1].aci_local_ver = 0;
964 		apic_io_ver[0] = 0;
965 	}
966 	if (apic_defconf == 2 || apic_defconf == 3 || apic_defconf == 6)
967 		eisa_level_intr_mask = (inb(EISA_LEVEL_CNTL + 1) << 8) |
968 		    inb(EISA_LEVEL_CNTL) | ((uint_t)INT32_MAX + 1);
969 	return (PSM_SUCCESS);
970 
971 apic_handle_defconf_fail:
972 	if (apic_cpus)
973 		kmem_free(apic_cpus, apic_cpus_size);
974 	if (apicadr)
975 		mapout_apic((caddr_t)apicadr, APIC_LOCAL_MEMLEN);
976 	if (apicioadr[0])
977 		mapout_ioapic((caddr_t)apicioadr[0], APIC_IO_MEMLEN);
978 	return (PSM_FAILURE);
979 }
980 
981 /* Parse the entries in MP configuration table and collect info that we need */
982 static int
983 apic_parse_mpct(caddr_t mpct, int bypass_cpus_and_ioapics)
984 {
985 	struct	apic_procent	*procp;
986 	struct	apic_bus	*busp;
987 	struct	apic_io_entry	*ioapicp;
988 	struct	apic_io_intr	*intrp;
989 	int			ioapic_ix;
990 	uint_t	lid;
991 	uint32_t	id;
992 	uchar_t hid;
993 	int	warned = 0;
994 
995 	/*LINTED: pointer cast may result in improper alignment */
996 	procp = (struct apic_procent *)(mpct + sizeof (struct apic_mp_cnf_hdr));
997 
998 	/* No need to count cpu entries if we won't use them */
999 	if (!bypass_cpus_and_ioapics) {
1000 
1001 		/* Find max # of CPUS and allocate structure accordingly */
1002 		apic_nproc = 0;
1003 		CPUSET_ZERO(apic_cpumask);
1004 		while (procp->proc_entry == APIC_CPU_ENTRY) {
1005 			if (procp->proc_cpuflags & CPUFLAGS_EN) {
1006 				if (apic_nproc < NCPU && use_mp &&
1007 				    apic_nproc < boot_ncpus) {
1008 					CPUSET_ADD(apic_cpumask, apic_nproc);
1009 					apic_nproc++;
1010 				} else if (apic_nproc == NCPU && !warned) {
1011 					cmn_err(CE_WARN, "%s: exceeded "
1012 					    "maximum no. of CPUs (= %d)",
1013 					    psm_name, NCPU);
1014 					warned = 1;
1015 				}
1016 
1017 			}
1018 			procp++;
1019 		}
1020 		apic_cpus_size = apic_nproc * sizeof (*apic_cpus);
1021 		if (!apic_nproc || !(apic_cpus = (apic_cpus_info_t *)
1022 		    kmem_zalloc(apic_cpus_size, KM_NOSLEEP)))
1023 			return (PSM_FAILURE);
1024 	}
1025 
1026 	/*LINTED: pointer cast may result in improper alignment */
1027 	procp = (struct apic_procent *)(mpct + sizeof (struct apic_mp_cnf_hdr));
1028 
1029 	/*
1030 	 * start with index 1 as 0 needs to be filled in with Boot CPU, but
1031 	 * if we're bypassing this information, it has already been filled
1032 	 * in by acpi_probe(), so don't overwrite it.
1033 	 */
1034 	if (!bypass_cpus_and_ioapics)
1035 		apic_nproc = 1;
1036 
1037 	while (procp->proc_entry == APIC_CPU_ENTRY) {
1038 		/* check whether the cpu exists or not */
1039 		if (!bypass_cpus_and_ioapics &&
1040 		    procp->proc_cpuflags & CPUFLAGS_EN) {
1041 			if (procp->proc_cpuflags & CPUFLAGS_BP) { /* Boot CPU */
1042 				lid = apic_reg_ops->apic_read(APIC_LID_REG);
1043 				apic_cpus[0].aci_local_id = procp->proc_apicid;
1044 				if (apic_cpus[0].aci_local_id !=
1045 				    (uchar_t)(lid >> APIC_ID_BIT_OFFSET)) {
1046 					return (PSM_FAILURE);
1047 				}
1048 				apic_cpus[0].aci_local_ver =
1049 				    procp->proc_version;
1050 			} else if (apic_nproc < NCPU && use_mp &&
1051 			    apic_nproc < boot_ncpus) {
1052 				apic_cpus[apic_nproc].aci_local_id =
1053 				    procp->proc_apicid;
1054 
1055 				apic_cpus[apic_nproc].aci_local_ver =
1056 				    procp->proc_version;
1057 				apic_nproc++;
1058 
1059 			}
1060 		}
1061 		procp++;
1062 	}
1063 
1064 	/*
1065 	 * Save start of bus entries for later use.
1066 	 * Get EISA level cntrl if EISA bus is present.
1067 	 * Also get the CPI bus id for single CPI bus case
1068 	 */
1069 	apic_busp = busp = (struct apic_bus *)procp;
1070 	while (busp->bus_entry == APIC_BUS_ENTRY) {
1071 		lid = apic_find_bus_type((char *)&busp->bus_str1);
1072 		if (lid	== BUS_EISA) {
1073 			eisa_level_intr_mask = (inb(EISA_LEVEL_CNTL + 1) << 8) |
1074 			    inb(EISA_LEVEL_CNTL) | ((uint_t)INT32_MAX + 1);
1075 		} else if (lid == BUS_PCI) {
1076 			/*
1077 			 * apic_single_pci_busid will be used only if
1078 			 * apic_pic_bus_total is equal to 1
1079 			 */
1080 			apic_pci_bus_total++;
1081 			apic_single_pci_busid = busp->bus_id;
1082 		}
1083 		busp++;
1084 	}
1085 
1086 	ioapicp = (struct apic_io_entry *)busp;
1087 
1088 	if (!bypass_cpus_and_ioapics)
1089 		apic_io_max = 0;
1090 	do {
1091 		if (!bypass_cpus_and_ioapics && apic_io_max < MAX_IO_APIC) {
1092 			if (ioapicp->io_flags & IOAPIC_FLAGS_EN) {
1093 				apic_io_id[apic_io_max] = ioapicp->io_apicid;
1094 				apic_io_ver[apic_io_max] = ioapicp->io_version;
1095 		/*LINTED: pointer cast may result in improper alignment */
1096 				apicioadr[apic_io_max] =
1097 				    mapin_ioapic(
1098 				    (uint32_t)ioapicp->io_apic_addr,
1099 				    APIC_IO_MEMLEN, PROT_READ | PROT_WRITE);
1100 
1101 				if (!apicioadr[apic_io_max])
1102 					return (PSM_FAILURE);
1103 
1104 				ioapic_mask_workaround[apic_io_max] =
1105 				    apic_is_ioapic_AMD_813x(
1106 				    ioapicp->io_apic_addr);
1107 
1108 				ioapic_ix = apic_io_max;
1109 				id = ioapic_read(ioapic_ix, APIC_ID_CMD);
1110 				hid = (uchar_t)(id >> 24);
1111 
1112 				if (hid != apic_io_id[apic_io_max]) {
1113 					if (apic_io_id[apic_io_max] == 0)
1114 						apic_io_id[apic_io_max] = hid;
1115 					else {
1116 						/*
1117 						 * set ioapic id to whatever
1118 						 * reported by MPS
1119 						 *
1120 						 * may not need to set index
1121 						 * again ???
1122 						 * take it out and try
1123 						 */
1124 
1125 						id = ((uint32_t)
1126 						    apic_io_id[apic_io_max]) <<
1127 						    24;
1128 
1129 						ioapic_write(ioapic_ix,
1130 						    APIC_ID_CMD, id);
1131 					}
1132 				}
1133 				apic_io_max++;
1134 			}
1135 		}
1136 		ioapicp++;
1137 	} while (ioapicp->io_entry == APIC_IO_ENTRY);
1138 
1139 	apic_io_intrp = (struct apic_io_intr *)ioapicp;
1140 
1141 	intrp = apic_io_intrp;
1142 	while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
1143 		if ((intrp->intr_irq > APIC_MAX_ISA_IRQ) ||
1144 		    (apic_find_bus(intrp->intr_busid) == BUS_PCI)) {
1145 			apic_irq_translate = 1;
1146 			break;
1147 		}
1148 		intrp++;
1149 	}
1150 
1151 	return (PSM_SUCCESS);
1152 }
1153 
1154 boolean_t
1155 apic_cpu_in_range(int cpu)
1156 {
1157 	return ((cpu & ~IRQ_USER_BOUND) < apic_nproc);
1158 }
1159 
1160 uint16_t
1161 apic_get_apic_version()
1162 {
1163 	int i;
1164 	uchar_t min_io_apic_ver = 0;
1165 	static uint16_t version;		/* Cache as value is constant */
1166 	static boolean_t found = B_FALSE;	/* Accomodate zero version */
1167 
1168 	if (found == B_FALSE) {
1169 		found = B_TRUE;
1170 
1171 		/*
1172 		 * Don't assume all IO APICs in the system are the same.
1173 		 *
1174 		 * Set to the minimum version.
1175 		 */
1176 		for (i = 0; i < apic_io_max; i++) {
1177 			if ((apic_io_ver[i] != 0) &&
1178 			    ((min_io_apic_ver == 0) ||
1179 			    (min_io_apic_ver >= apic_io_ver[i])))
1180 				min_io_apic_ver = apic_io_ver[i];
1181 		}
1182 
1183 		/* Assume all local APICs are of the same version. */
1184 		version = (min_io_apic_ver << 8) | apic_cpus[0].aci_local_ver;
1185 	}
1186 	return (version);
1187 }
1188 
1189 static struct apic_mpfps_hdr *
1190 apic_find_fps_sig(caddr_t cptr, int len)
1191 {
1192 	int	i;
1193 
1194 	/* Look for the pattern "_MP_" */
1195 	for (i = 0; i < len; i += 16) {
1196 		if ((*(cptr+i) == '_') &&
1197 		    (*(cptr+i+1) == 'M') &&
1198 		    (*(cptr+i+2) == 'P') &&
1199 		    (*(cptr+i+3) == '_'))
1200 		    /*LINTED: pointer cast may result in improper alignment */
1201 			return ((struct apic_mpfps_hdr *)(cptr + i));
1202 	}
1203 	return (NULL);
1204 }
1205 
1206 static int
1207 apic_checksum(caddr_t bptr, int len)
1208 {
1209 	int	i;
1210 	uchar_t	cksum;
1211 
1212 	cksum = 0;
1213 	for (i = 0; i < len; i++)
1214 		cksum += *bptr++;
1215 	return ((int)cksum);
1216 }
1217 
1218 
1219 /*
1220  * Initialise vector->ipl and ipl->pri arrays. level_intr and irqtable
1221  * are also set to NULL. vector->irq is set to a value which cannot map
1222  * to a real irq to show that it is free.
1223  */
1224 void
1225 apic_init_common()
1226 {
1227 	int	i, j, indx;
1228 	int	*iptr;
1229 
1230 	/*
1231 	 * Initialize apic_ipls from apic_vectortoipl.  This array is
1232 	 * used in apic_intr_enter to determine the IPL to use for the
1233 	 * corresponding vector.  On some systems, due to hardware errata
1234 	 * and interrupt sharing, the IPL may not correspond to the IPL listed
1235 	 * in apic_vectortoipl (see apic_addspl and apic_delspl).
1236 	 */
1237 	for (i = 0; i < (APIC_AVAIL_VECTOR / APIC_VECTOR_PER_IPL); i++) {
1238 		indx = i * APIC_VECTOR_PER_IPL;
1239 
1240 		for (j = 0; j < APIC_VECTOR_PER_IPL; j++, indx++)
1241 			apic_ipls[indx] = apic_vectortoipl[i];
1242 	}
1243 
1244 	/* cpu 0 is always up (for now) */
1245 	apic_cpus[0].aci_status = APIC_CPU_ONLINE | APIC_CPU_INTR_ENABLE;
1246 
1247 	iptr = (int *)&apic_irq_table[0];
1248 	for (i = 0; i <= APIC_MAX_VECTOR; i++) {
1249 		apic_level_intr[i] = 0;
1250 		*iptr++ = NULL;
1251 		apic_vector_to_irq[i] = APIC_RESV_IRQ;
1252 
1253 		/* These *must* be initted to B_TRUE! */
1254 		apic_reprogram_info[i].done = B_TRUE;
1255 		apic_reprogram_info[i].irqp = NULL;
1256 		apic_reprogram_info[i].tries = 0;
1257 		apic_reprogram_info[i].bindcpu = 0;
1258 	}
1259 
1260 	/*
1261 	 * Allocate a dummy irq table entry for the reserved entry.
1262 	 * This takes care of the race between removing an irq and
1263 	 * clock detecting a CPU in that irq during interrupt load
1264 	 * sampling.
1265 	 */
1266 	apic_irq_table[APIC_RESV_IRQ] =
1267 	    kmem_zalloc(sizeof (apic_irq_t), KM_NOSLEEP);
1268 
1269 	mutex_init(&airq_mutex, NULL, MUTEX_DEFAULT, NULL);
1270 }
1271 
1272 void
1273 ioapic_init_intr(int mask_apic)
1274 {
1275 	int ioapic_ix;
1276 	struct intrspec ispec;
1277 	apic_irq_t *irqptr;
1278 	int i, j;
1279 	ulong_t iflag;
1280 
1281 	LOCK_INIT_CLEAR(&apic_revector_lock);
1282 	LOCK_INIT_CLEAR(&apic_defer_reprogram_lock);
1283 
1284 	/* mask interrupt vectors */
1285 	for (j = 0; j < apic_io_max && mask_apic; j++) {
1286 		int intin_max;
1287 
1288 		ioapic_ix = j;
1289 		/* Bits 23-16 define the maximum redirection entries */
1290 		intin_max = (ioapic_read(ioapic_ix, APIC_VERS_CMD) >> 16)
1291 		    & 0xff;
1292 		for (i = 0; i <= intin_max; i++)
1293 			ioapic_write(ioapic_ix, APIC_RDT_CMD + 2 * i, AV_MASK);
1294 	}
1295 
1296 	/*
1297 	 * Hack alert: deal with ACPI SCI interrupt chicken/egg here
1298 	 */
1299 	if (apic_sci_vect > 0) {
1300 		/*
1301 		 * acpica has already done add_avintr(); we just
1302 		 * to finish the job by mimicing translate_irq()
1303 		 *
1304 		 * Fake up an intrspec and setup the tables
1305 		 */
1306 		ispec.intrspec_vec = apic_sci_vect;
1307 		ispec.intrspec_pri = SCI_IPL;
1308 
1309 		if (apic_setup_irq_table(NULL, apic_sci_vect, NULL,
1310 		    &ispec, &apic_sci_flags, DDI_INTR_TYPE_FIXED) < 0) {
1311 			cmn_err(CE_WARN, "!apic: SCI setup failed");
1312 			return;
1313 		}
1314 		irqptr = apic_irq_table[apic_sci_vect];
1315 
1316 		iflag = intr_clear();
1317 		lock_set(&apic_ioapic_lock);
1318 
1319 		/* Program I/O APIC */
1320 		(void) apic_setup_io_intr(irqptr, apic_sci_vect, B_FALSE);
1321 
1322 		lock_clear(&apic_ioapic_lock);
1323 		intr_restore(iflag);
1324 
1325 		irqptr->airq_share++;
1326 	}
1327 }
1328 
1329 /*
1330  * Add mask bits to disable interrupt vector from happening
1331  * at or above IPL. In addition, it should remove mask bits
1332  * to enable interrupt vectors below the given IPL.
1333  *
1334  * Both add and delspl are complicated by the fact that different interrupts
1335  * may share IRQs. This can happen in two ways.
1336  * 1. The same H/W line is shared by more than 1 device
1337  * 1a. with interrupts at different IPLs
1338  * 1b. with interrupts at same IPL
1339  * 2. We ran out of vectors at a given IPL and started sharing vectors.
1340  * 1b and 2 should be handled gracefully, except for the fact some ISRs
1341  * will get called often when no interrupt is pending for the device.
1342  * For 1a, we just hope that the machine blows up with the person who
1343  * set it up that way!. In the meantime, we handle it at the higher IPL.
1344  */
1345 /*ARGSUSED*/
1346 int
1347 apic_addspl_common(int irqno, int ipl, int min_ipl, int max_ipl)
1348 {
1349 	uchar_t vector;
1350 	ulong_t iflag;
1351 	apic_irq_t *irqptr, *irqheadptr;
1352 	int irqindex;
1353 
1354 	ASSERT(max_ipl <= UCHAR_MAX);
1355 	irqindex = IRQINDEX(irqno);
1356 
1357 	if ((irqindex == -1) || (!apic_irq_table[irqindex]))
1358 		return (PSM_FAILURE);
1359 
1360 	mutex_enter(&airq_mutex);
1361 	irqptr = irqheadptr = apic_irq_table[irqindex];
1362 
1363 	DDI_INTR_IMPLDBG((CE_CONT, "apic_addspl: dip=0x%p type=%d irqno=0x%x "
1364 	    "vector=0x%x\n", (void *)irqptr->airq_dip,
1365 	    irqptr->airq_mps_intr_index, irqno, irqptr->airq_vector));
1366 
1367 	while (irqptr) {
1368 		if (VIRTIRQ(irqindex, irqptr->airq_share_id) == irqno)
1369 			break;
1370 		irqptr = irqptr->airq_next;
1371 	}
1372 	irqptr->airq_share++;
1373 
1374 	mutex_exit(&airq_mutex);
1375 
1376 	/* return if it is not hardware interrupt */
1377 	if (irqptr->airq_mps_intr_index == RESERVE_INDEX)
1378 		return (PSM_SUCCESS);
1379 
1380 	/* Or if there are more interupts at a higher IPL */
1381 	if (ipl != max_ipl)
1382 		return (PSM_SUCCESS);
1383 
1384 	/*
1385 	 * if apic_picinit() has not been called yet, just return.
1386 	 * At the end of apic_picinit(), we will call setup_io_intr().
1387 	 */
1388 
1389 	if (!apic_picinit_called)
1390 		return (PSM_SUCCESS);
1391 
1392 	/*
1393 	 * Upgrade vector if max_ipl is not earlier ipl. If we cannot allocate,
1394 	 * return failure. Not very elegant, but then we hope the
1395 	 * machine will blow up with ...
1396 	 */
1397 	if (irqptr->airq_ipl != max_ipl &&
1398 	    !ioapic_mask_workaround[irqptr->airq_ioapicindex]) {
1399 
1400 		vector = apic_allocate_vector(max_ipl, irqindex, 1);
1401 		if (vector == 0) {
1402 			irqptr->airq_share--;
1403 			return (PSM_FAILURE);
1404 		}
1405 		irqptr = irqheadptr;
1406 		apic_mark_vector(irqptr->airq_vector, vector);
1407 		while (irqptr) {
1408 			irqptr->airq_vector = vector;
1409 			irqptr->airq_ipl = (uchar_t)max_ipl;
1410 			/*
1411 			 * reprogram irq being added and every one else
1412 			 * who is not in the UNINIT state
1413 			 */
1414 			if ((VIRTIRQ(irqindex, irqptr->airq_share_id) ==
1415 			    irqno) || (irqptr->airq_temp_cpu != IRQ_UNINIT)) {
1416 				apic_record_rdt_entry(irqptr, irqindex);
1417 
1418 				iflag = intr_clear();
1419 				lock_set(&apic_ioapic_lock);
1420 
1421 				(void) apic_setup_io_intr(irqptr, irqindex,
1422 				    B_FALSE);
1423 
1424 				lock_clear(&apic_ioapic_lock);
1425 				intr_restore(iflag);
1426 			}
1427 			irqptr = irqptr->airq_next;
1428 		}
1429 		return (PSM_SUCCESS);
1430 
1431 	} else if (irqptr->airq_ipl != max_ipl &&
1432 	    ioapic_mask_workaround[irqptr->airq_ioapicindex]) {
1433 		/*
1434 		 * We cannot upgrade the vector, but we can change
1435 		 * the IPL that this vector induces.
1436 		 *
1437 		 * Note that we subtract APIC_BASE_VECT from the vector
1438 		 * here because this array is used in apic_intr_enter
1439 		 * (no need to add APIC_BASE_VECT in that hot code
1440 		 * path since we can do it in the rarely-executed path
1441 		 * here).
1442 		 */
1443 		apic_ipls[irqptr->airq_vector - APIC_BASE_VECT] =
1444 		    (uchar_t)max_ipl;
1445 
1446 		irqptr = irqheadptr;
1447 		while (irqptr) {
1448 			irqptr->airq_ipl = (uchar_t)max_ipl;
1449 			irqptr = irqptr->airq_next;
1450 		}
1451 
1452 		return (PSM_SUCCESS);
1453 	}
1454 
1455 	ASSERT(irqptr);
1456 
1457 	iflag = intr_clear();
1458 	lock_set(&apic_ioapic_lock);
1459 
1460 	(void) apic_setup_io_intr(irqptr, irqindex, B_FALSE);
1461 
1462 	lock_clear(&apic_ioapic_lock);
1463 	intr_restore(iflag);
1464 
1465 	return (PSM_SUCCESS);
1466 }
1467 
1468 /*
1469  * Recompute mask bits for the given interrupt vector.
1470  * If there is no interrupt servicing routine for this
1471  * vector, this function should disable interrupt vector
1472  * from happening at all IPLs. If there are still
1473  * handlers using the given vector, this function should
1474  * disable the given vector from happening below the lowest
1475  * IPL of the remaining hadlers.
1476  */
1477 /*ARGSUSED*/
1478 int
1479 apic_delspl_common(int irqno, int ipl, int min_ipl, int max_ipl)
1480 {
1481 	uchar_t vector;
1482 	uint32_t bind_cpu;
1483 	int intin, irqindex;
1484 	int ioapic_ix;
1485 	apic_irq_t	*irqptr, *irqheadptr, *irqp;
1486 	ulong_t iflag;
1487 
1488 	mutex_enter(&airq_mutex);
1489 	irqindex = IRQINDEX(irqno);
1490 	irqptr = irqheadptr = apic_irq_table[irqindex];
1491 
1492 	DDI_INTR_IMPLDBG((CE_CONT, "apic_delspl: dip=0x%p type=%d irqno=0x%x "
1493 	    "vector=0x%x\n", (void *)irqptr->airq_dip,
1494 	    irqptr->airq_mps_intr_index, irqno, irqptr->airq_vector));
1495 
1496 	while (irqptr) {
1497 		if (VIRTIRQ(irqindex, irqptr->airq_share_id) == irqno)
1498 			break;
1499 		irqptr = irqptr->airq_next;
1500 	}
1501 	ASSERT(irqptr);
1502 
1503 	irqptr->airq_share--;
1504 
1505 	mutex_exit(&airq_mutex);
1506 
1507 	if (ipl < max_ipl)
1508 		return (PSM_SUCCESS);
1509 
1510 	/* return if it is not hardware interrupt */
1511 	if (irqptr->airq_mps_intr_index == RESERVE_INDEX)
1512 		return (PSM_SUCCESS);
1513 
1514 	if (!apic_picinit_called) {
1515 		/*
1516 		 * Clear irq_struct. If two devices shared an intpt
1517 		 * line & 1 unloaded before picinit, we are hosed. But, then
1518 		 * we hope the machine will ...
1519 		 */
1520 		irqptr->airq_mps_intr_index = FREE_INDEX;
1521 		irqptr->airq_temp_cpu = IRQ_UNINIT;
1522 		apic_free_vector(irqptr->airq_vector);
1523 		return (PSM_SUCCESS);
1524 	}
1525 	/*
1526 	 * Downgrade vector to new max_ipl if needed.If we cannot allocate,
1527 	 * use old IPL. Not very elegant, but then we hope ...
1528 	 */
1529 	if ((irqptr->airq_ipl != max_ipl) && (max_ipl != PSM_INVALID_IPL) &&
1530 	    !ioapic_mask_workaround[irqptr->airq_ioapicindex]) {
1531 		apic_irq_t	*irqp;
1532 		if (vector = apic_allocate_vector(max_ipl, irqno, 1)) {
1533 			apic_mark_vector(irqheadptr->airq_vector, vector);
1534 			irqp = irqheadptr;
1535 			while (irqp) {
1536 				irqp->airq_vector = vector;
1537 				irqp->airq_ipl = (uchar_t)max_ipl;
1538 				if (irqp->airq_temp_cpu != IRQ_UNINIT) {
1539 					apic_record_rdt_entry(irqp, irqindex);
1540 
1541 					iflag = intr_clear();
1542 					lock_set(&apic_ioapic_lock);
1543 
1544 					(void) apic_setup_io_intr(irqp,
1545 					    irqindex, B_FALSE);
1546 
1547 					lock_clear(&apic_ioapic_lock);
1548 					intr_restore(iflag);
1549 				}
1550 				irqp = irqp->airq_next;
1551 			}
1552 		}
1553 
1554 	} else if (irqptr->airq_ipl != max_ipl &&
1555 	    max_ipl != PSM_INVALID_IPL &&
1556 	    ioapic_mask_workaround[irqptr->airq_ioapicindex]) {
1557 
1558 	/*
1559 	 * We cannot downgrade the IPL of the vector below the vector's
1560 	 * hardware priority. If we did, it would be possible for a
1561 	 * higher-priority hardware vector to interrupt a CPU running at an IPL
1562 	 * lower than the hardware priority of the interrupting vector (but
1563 	 * higher than the soft IPL of this IRQ). When this happens, we would
1564 	 * then try to drop the IPL BELOW what it was (effectively dropping
1565 	 * below base_spl) which would be potentially catastrophic.
1566 	 *
1567 	 * (e.g. Suppose the hardware vector associated with this IRQ is 0x40
1568 	 * (hardware IPL of 4).  Further assume that the old IPL of this IRQ
1569 	 * was 4, but the new IPL is 1.  If we forced vector 0x40 to result in
1570 	 * an IPL of 1, it would be possible for the processor to be executing
1571 	 * at IPL 3 and for an interrupt to come in on vector 0x40, interrupting
1572 	 * the currently-executing ISR.  When apic_intr_enter consults
1573 	 * apic_irqs[], it will return 1, bringing the IPL of the CPU down to 1
1574 	 * so even though the processor was running at IPL 4, an IPL 1
1575 	 * interrupt will have interrupted it, which must not happen)).
1576 	 *
1577 	 * Effectively, this means that the hardware priority corresponding to
1578 	 * the IRQ's IPL (in apic_ipls[]) cannot be lower than the vector's
1579 	 * hardware priority.
1580 	 *
1581 	 * (In the above example, then, after removal of the IPL 4 device's
1582 	 * interrupt handler, the new IPL will continue to be 4 because the
1583 	 * hardware priority that IPL 1 implies is lower than the hardware
1584 	 * priority of the vector used.)
1585 	 */
1586 		/* apic_ipls is indexed by vector, starting at APIC_BASE_VECT */
1587 		const int apic_ipls_index = irqptr->airq_vector -
1588 		    APIC_BASE_VECT;
1589 		const int vect_inherent_hwpri = irqptr->airq_vector >>
1590 		    APIC_IPL_SHIFT;
1591 
1592 		/*
1593 		 * If there are still devices using this IRQ, determine the
1594 		 * new ipl to use.
1595 		 */
1596 		if (irqptr->airq_share) {
1597 			int vect_desired_hwpri, hwpri;
1598 
1599 			ASSERT(max_ipl < MAXIPL);
1600 			vect_desired_hwpri = apic_ipltopri[max_ipl] >>
1601 			    APIC_IPL_SHIFT;
1602 
1603 			/*
1604 			 * If the desired IPL's hardware priority is lower
1605 			 * than that of the vector, use the hardware priority
1606 			 * of the vector to determine the new IPL.
1607 			 */
1608 			hwpri = (vect_desired_hwpri < vect_inherent_hwpri) ?
1609 			    vect_inherent_hwpri : vect_desired_hwpri;
1610 
1611 			/*
1612 			 * Now, to get the right index for apic_vectortoipl,
1613 			 * we need to subtract APIC_BASE_VECT from the
1614 			 * hardware-vector-equivalent (in hwpri).  Since hwpri
1615 			 * is already shifted, we shift APIC_BASE_VECT before
1616 			 * doing the subtraction.
1617 			 */
1618 			hwpri -= (APIC_BASE_VECT >> APIC_IPL_SHIFT);
1619 
1620 			ASSERT(hwpri >= 0);
1621 			ASSERT(hwpri < MAXIPL);
1622 			max_ipl = apic_vectortoipl[hwpri];
1623 			apic_ipls[apic_ipls_index] = max_ipl;
1624 
1625 			irqp = irqheadptr;
1626 			while (irqp) {
1627 				irqp->airq_ipl = (uchar_t)max_ipl;
1628 				irqp = irqp->airq_next;
1629 			}
1630 		} else {
1631 			/*
1632 			 * No more devices on this IRQ, so reset this vector's
1633 			 * element in apic_ipls to the original IPL for this
1634 			 * vector
1635 			 */
1636 			apic_ipls[apic_ipls_index] =
1637 			    apic_vectortoipl[vect_inherent_hwpri];
1638 		}
1639 	}
1640 
1641 	if (irqptr->airq_share)
1642 		return (PSM_SUCCESS);
1643 
1644 	iflag = intr_clear();
1645 	lock_set(&apic_ioapic_lock);
1646 
1647 	if (irqptr->airq_mps_intr_index == MSI_INDEX) {
1648 		/*
1649 		 * Disable the MSI vector
1650 		 * Make sure we only disable on the last
1651 		 * of the multi-MSI support
1652 		 */
1653 		if (i_ddi_intr_get_current_nintrs(irqptr->airq_dip) == 1) {
1654 			apic_pci_msi_unconfigure(irqptr->airq_dip,
1655 			    DDI_INTR_TYPE_MSI, irqptr->airq_ioapicindex);
1656 
1657 			apic_pci_msi_disable_mode(irqptr->airq_dip,
1658 			    DDI_INTR_TYPE_MSI);
1659 		}
1660 	} else if (irqptr->airq_mps_intr_index == MSIX_INDEX) {
1661 		/*
1662 		 * Disable the MSI-X vector
1663 		 * needs to clear its mask and addr/data for each MSI-X
1664 		 */
1665 		apic_pci_msi_unconfigure(irqptr->airq_dip, DDI_INTR_TYPE_MSIX,
1666 		    irqptr->airq_origirq);
1667 		/*
1668 		 * Make sure we only disable on the last MSI-X
1669 		 */
1670 		if (i_ddi_intr_get_current_nintrs(irqptr->airq_dip) == 1) {
1671 			apic_pci_msi_disable_mode(irqptr->airq_dip,
1672 			    DDI_INTR_TYPE_MSIX);
1673 		}
1674 	} else {
1675 		/*
1676 		 * The assumption here is that this is safe, even for
1677 		 * systems with IOAPICs that suffer from the hardware
1678 		 * erratum because all devices have been quiesced before
1679 		 * they unregister their interrupt handlers.  If that
1680 		 * assumption turns out to be false, this mask operation
1681 		 * can induce the same erratum result we're trying to
1682 		 * avoid.
1683 		 */
1684 		ioapic_ix = irqptr->airq_ioapicindex;
1685 		intin = irqptr->airq_intin_no;
1686 		ioapic_write(ioapic_ix, APIC_RDT_CMD + 2 * intin, AV_MASK);
1687 	}
1688 
1689 	if (max_ipl == PSM_INVALID_IPL) {
1690 		ASSERT(irqheadptr == irqptr);
1691 		bind_cpu = irqptr->airq_temp_cpu;
1692 		if (((uint32_t)bind_cpu != IRQ_UNBOUND) &&
1693 		    ((uint32_t)bind_cpu != IRQ_UNINIT)) {
1694 			ASSERT((bind_cpu & ~IRQ_USER_BOUND) < apic_nproc);
1695 			if (bind_cpu & IRQ_USER_BOUND) {
1696 				/* If hardbound, temp_cpu == cpu */
1697 				bind_cpu &= ~IRQ_USER_BOUND;
1698 				apic_cpus[bind_cpu].aci_bound--;
1699 			} else
1700 				apic_cpus[bind_cpu].aci_temp_bound--;
1701 		}
1702 		irqptr->airq_temp_cpu = IRQ_UNINIT;
1703 		irqptr->airq_mps_intr_index = FREE_INDEX;
1704 		lock_clear(&apic_ioapic_lock);
1705 		intr_restore(iflag);
1706 		apic_free_vector(irqptr->airq_vector);
1707 		return (PSM_SUCCESS);
1708 	}
1709 	lock_clear(&apic_ioapic_lock);
1710 	intr_restore(iflag);
1711 
1712 	mutex_enter(&airq_mutex);
1713 	if ((irqptr == apic_irq_table[irqindex])) {
1714 		apic_irq_t	*oldirqptr;
1715 		/* Move valid irq entry to the head */
1716 		irqheadptr = oldirqptr = irqptr;
1717 		irqptr = irqptr->airq_next;
1718 		ASSERT(irqptr);
1719 		while (irqptr) {
1720 			if (irqptr->airq_mps_intr_index != FREE_INDEX)
1721 				break;
1722 			oldirqptr = irqptr;
1723 			irqptr = irqptr->airq_next;
1724 		}
1725 		/* remove all invalid ones from the beginning */
1726 		apic_irq_table[irqindex] = irqptr;
1727 		/*
1728 		 * and link them back after the head. The invalid ones
1729 		 * begin with irqheadptr and end at oldirqptr
1730 		 */
1731 		oldirqptr->airq_next = irqptr->airq_next;
1732 		irqptr->airq_next = irqheadptr;
1733 	}
1734 	mutex_exit(&airq_mutex);
1735 
1736 	irqptr->airq_temp_cpu = IRQ_UNINIT;
1737 	irqptr->airq_mps_intr_index = FREE_INDEX;
1738 
1739 	return (PSM_SUCCESS);
1740 }
1741 
1742 /*
1743  * apic_introp_xlate() replaces apic_translate_irq() and is
1744  * called only from apic_intr_ops().  With the new ADII framework,
1745  * the priority can no longer be retrieved through i_ddi_get_intrspec().
1746  * It has to be passed in from the caller.
1747  */
1748 int
1749 apic_introp_xlate(dev_info_t *dip, struct intrspec *ispec, int type)
1750 {
1751 	char dev_type[16];
1752 	int dev_len, pci_irq, newirq, bustype, devid, busid, i;
1753 	int irqno = ispec->intrspec_vec;
1754 	ddi_acc_handle_t cfg_handle;
1755 	uchar_t ipin;
1756 	struct apic_io_intr *intrp;
1757 	iflag_t intr_flag;
1758 	ACPI_SUBTABLE_HEADER	*hp;
1759 	ACPI_MADT_INTERRUPT_OVERRIDE *isop;
1760 	apic_irq_t *airqp;
1761 	int parent_is_pci_or_pciex = 0;
1762 	int child_is_pciex = 0;
1763 
1764 	DDI_INTR_IMPLDBG((CE_CONT, "apic_introp_xlate: dip=0x%p name=%s "
1765 	    "type=%d irqno=0x%x\n", (void *)dip, ddi_get_name(dip), type,
1766 	    irqno));
1767 
1768 	dev_len = sizeof (dev_type);
1769 	if (ddi_getlongprop_buf(DDI_DEV_T_ANY, ddi_get_parent(dip),
1770 	    DDI_PROP_DONTPASS, "device_type", (caddr_t)dev_type,
1771 	    &dev_len) == DDI_PROP_SUCCESS) {
1772 		if ((strcmp(dev_type, "pci") == 0) ||
1773 		    (strcmp(dev_type, "pciex") == 0))
1774 			parent_is_pci_or_pciex = 1;
1775 	}
1776 
1777 	if (ddi_getlongprop_buf(DDI_DEV_T_ANY, dip,
1778 	    DDI_PROP_DONTPASS, "compatible", (caddr_t)dev_type,
1779 	    &dev_len) == DDI_PROP_SUCCESS) {
1780 		if (strstr(dev_type, "pciex"))
1781 			child_is_pciex = 1;
1782 	}
1783 
1784 
1785 	if (DDI_INTR_IS_MSI_OR_MSIX(type)) {
1786 		if ((airqp = apic_find_irq(dip, ispec, type)) != NULL) {
1787 			airqp->airq_iflag.bustype =
1788 			    child_is_pciex ? BUS_PCIE : BUS_PCI;
1789 			return (apic_vector_to_irq[airqp->airq_vector]);
1790 		}
1791 		return (apic_setup_irq_table(dip, irqno, NULL, ispec,
1792 		    NULL, type));
1793 	}
1794 
1795 	bustype = 0;
1796 
1797 	/* check if we have already translated this irq */
1798 	mutex_enter(&airq_mutex);
1799 	newirq = apic_min_device_irq;
1800 	for (; newirq <= apic_max_device_irq; newirq++) {
1801 		airqp = apic_irq_table[newirq];
1802 		while (airqp) {
1803 			if ((airqp->airq_dip == dip) &&
1804 			    (airqp->airq_origirq == irqno) &&
1805 			    (airqp->airq_mps_intr_index != FREE_INDEX)) {
1806 
1807 				mutex_exit(&airq_mutex);
1808 				return (VIRTIRQ(newirq, airqp->airq_share_id));
1809 			}
1810 			airqp = airqp->airq_next;
1811 		}
1812 	}
1813 	mutex_exit(&airq_mutex);
1814 
1815 	if (apic_defconf)
1816 		goto defconf;
1817 
1818 	if ((dip == NULL) || (!apic_irq_translate && !apic_enable_acpi))
1819 		goto nonpci;
1820 
1821 	if (parent_is_pci_or_pciex) {
1822 		/* pci device */
1823 		if (acpica_get_bdf(dip, &busid, &devid, NULL) != 0)
1824 			goto nonpci;
1825 		if (busid == 0 && apic_pci_bus_total == 1)
1826 			busid = (int)apic_single_pci_busid;
1827 
1828 		if (pci_config_setup(dip, &cfg_handle) != DDI_SUCCESS)
1829 			goto nonpci;
1830 		ipin = pci_config_get8(cfg_handle, PCI_CONF_IPIN) - PCI_INTA;
1831 		pci_config_teardown(&cfg_handle);
1832 		if (apic_enable_acpi && !apic_use_acpi_madt_only) {
1833 			if (apic_acpi_translate_pci_irq(dip, busid, devid,
1834 			    ipin, &pci_irq, &intr_flag) != ACPI_PSM_SUCCESS)
1835 				goto nonpci;
1836 
1837 			intr_flag.bustype = child_is_pciex ? BUS_PCIE : BUS_PCI;
1838 			if ((newirq = apic_setup_irq_table(dip, pci_irq, NULL,
1839 			    ispec, &intr_flag, type)) == -1)
1840 				goto nonpci;
1841 			return (newirq);
1842 		} else {
1843 			pci_irq = ((devid & 0x1f) << 2) | (ipin & 0x3);
1844 			if ((intrp = apic_find_io_intr_w_busid(pci_irq, busid))
1845 			    == NULL) {
1846 				if ((pci_irq = apic_handle_pci_pci_bridge(dip,
1847 				    devid, ipin, &intrp)) == -1)
1848 					goto nonpci;
1849 			}
1850 			if ((newirq = apic_setup_irq_table(dip, pci_irq, intrp,
1851 			    ispec, NULL, type)) == -1)
1852 				goto nonpci;
1853 			return (newirq);
1854 		}
1855 	} else if (strcmp(dev_type, "isa") == 0)
1856 		bustype = BUS_ISA;
1857 	else if (strcmp(dev_type, "eisa") == 0)
1858 		bustype = BUS_EISA;
1859 
1860 nonpci:
1861 	if (apic_enable_acpi && !apic_use_acpi_madt_only) {
1862 		/* search iso entries first */
1863 		if (acpi_iso_cnt != 0) {
1864 			hp = (ACPI_SUBTABLE_HEADER *)acpi_isop;
1865 			i = 0;
1866 			while (i < acpi_iso_cnt) {
1867 				if (hp->Type ==
1868 				    ACPI_MADT_TYPE_INTERRUPT_OVERRIDE) {
1869 					isop =
1870 					    (ACPI_MADT_INTERRUPT_OVERRIDE *) hp;
1871 					if (isop->Bus == 0 &&
1872 					    isop->SourceIrq == irqno) {
1873 						newirq = isop->GlobalIrq;
1874 						intr_flag.intr_po =
1875 						    isop->IntiFlags &
1876 						    ACPI_MADT_POLARITY_MASK;
1877 						intr_flag.intr_el =
1878 						    (isop->IntiFlags &
1879 						    ACPI_MADT_TRIGGER_MASK)
1880 						    >> 2;
1881 						intr_flag.bustype = BUS_ISA;
1882 
1883 						return (apic_setup_irq_table(
1884 						    dip, newirq, NULL, ispec,
1885 						    &intr_flag, type));
1886 
1887 					}
1888 					i++;
1889 				}
1890 				hp = (ACPI_SUBTABLE_HEADER *)(((char *)hp) +
1891 				    hp->Length);
1892 			}
1893 		}
1894 		intr_flag.intr_po = INTR_PO_ACTIVE_HIGH;
1895 		intr_flag.intr_el = INTR_EL_EDGE;
1896 		intr_flag.bustype = BUS_ISA;
1897 		return (apic_setup_irq_table(dip, irqno, NULL, ispec,
1898 		    &intr_flag, type));
1899 	} else {
1900 		if (bustype == 0)
1901 			bustype = eisa_level_intr_mask ? BUS_EISA : BUS_ISA;
1902 		for (i = 0; i < 2; i++) {
1903 			if (((busid = apic_find_bus_id(bustype)) != -1) &&
1904 			    ((intrp = apic_find_io_intr_w_busid(irqno, busid))
1905 			    != NULL)) {
1906 				if ((newirq = apic_setup_irq_table(dip, irqno,
1907 				    intrp, ispec, NULL, type)) != -1) {
1908 					return (newirq);
1909 				}
1910 				goto defconf;
1911 			}
1912 			bustype = (bustype == BUS_EISA) ? BUS_ISA : BUS_EISA;
1913 		}
1914 	}
1915 
1916 /* MPS default configuration */
1917 defconf:
1918 	newirq = apic_setup_irq_table(dip, irqno, NULL, ispec, NULL, type);
1919 	if (newirq == -1)
1920 		return (newirq);
1921 	ASSERT(IRQINDEX(newirq) == irqno);
1922 	ASSERT(apic_irq_table[irqno]);
1923 	return (newirq);
1924 }
1925 
1926 
1927 
1928 
1929 
1930 
1931 /*
1932  * On machines with PCI-PCI bridges, a device behind a PCI-PCI bridge
1933  * needs special handling.  We may need to chase up the device tree,
1934  * using the PCI-PCI Bridge specification's "rotating IPIN assumptions",
1935  * to find the IPIN at the root bus that relates to the IPIN on the
1936  * subsidiary bus (for ACPI or MP).  We may, however, have an entry
1937  * in the MP table or the ACPI namespace for this device itself.
1938  * We handle both cases in the search below.
1939  */
1940 /* this is the non-acpi version */
1941 static int
1942 apic_handle_pci_pci_bridge(dev_info_t *idip, int child_devno, int child_ipin,
1943 			struct apic_io_intr **intrp)
1944 {
1945 	dev_info_t *dipp, *dip;
1946 	int pci_irq;
1947 	ddi_acc_handle_t cfg_handle;
1948 	int bridge_devno, bridge_bus;
1949 	int ipin;
1950 
1951 	dip = idip;
1952 
1953 	/*CONSTCOND*/
1954 	while (1) {
1955 		if (((dipp = ddi_get_parent(dip)) == (dev_info_t *)NULL) ||
1956 		    (pci_config_setup(dipp, &cfg_handle) != DDI_SUCCESS))
1957 			return (-1);
1958 		if ((pci_config_get8(cfg_handle, PCI_CONF_BASCLASS) ==
1959 		    PCI_CLASS_BRIDGE) && (pci_config_get8(cfg_handle,
1960 		    PCI_CONF_SUBCLASS) == PCI_BRIDGE_PCI)) {
1961 			pci_config_teardown(&cfg_handle);
1962 			if (acpica_get_bdf(dipp, &bridge_bus, &bridge_devno,
1963 			    NULL) != 0)
1964 				return (-1);
1965 			/*
1966 			 * This is the rotating scheme documented in the
1967 			 * PCI-to-PCI spec.  If the PCI-to-PCI bridge is
1968 			 * behind another PCI-to-PCI bridge, then it needs
1969 			 * to keep ascending until an interrupt entry is
1970 			 * found or the root is reached.
1971 			 */
1972 			ipin = (child_devno + child_ipin) % PCI_INTD;
1973 				if (bridge_bus == 0 && apic_pci_bus_total == 1)
1974 					bridge_bus = (int)apic_single_pci_busid;
1975 				pci_irq = ((bridge_devno & 0x1f) << 2) |
1976 				    (ipin & 0x3);
1977 				if ((*intrp = apic_find_io_intr_w_busid(pci_irq,
1978 				    bridge_bus)) != NULL) {
1979 					return (pci_irq);
1980 				}
1981 			dip = dipp;
1982 			child_devno = bridge_devno;
1983 			child_ipin = ipin;
1984 		} else {
1985 			pci_config_teardown(&cfg_handle);
1986 			return (-1);
1987 		}
1988 	}
1989 	/*LINTED: function will not fall off the bottom */
1990 }
1991 
1992 
1993 
1994 
1995 static uchar_t
1996 acpi_find_ioapic(int irq)
1997 {
1998 	int i;
1999 
2000 	for (i = 0; i < apic_io_max; i++) {
2001 		if (irq >= apic_io_vectbase[i] && irq <= apic_io_vectend[i])
2002 			return (i);
2003 	}
2004 	return (0xFF);	/* shouldn't happen */
2005 }
2006 
2007 /*
2008  * See if two irqs are compatible for sharing a vector.
2009  * Currently we only support sharing of PCI devices.
2010  */
2011 static int
2012 acpi_intr_compatible(iflag_t iflag1, iflag_t iflag2)
2013 {
2014 	uint_t	level1, po1;
2015 	uint_t	level2, po2;
2016 
2017 	/* Assume active high by default */
2018 	po1 = 0;
2019 	po2 = 0;
2020 
2021 	if (iflag1.bustype != iflag2.bustype || iflag1.bustype != BUS_PCI)
2022 		return (0);
2023 
2024 	if (iflag1.intr_el == INTR_EL_CONFORM)
2025 		level1 = AV_LEVEL;
2026 	else
2027 		level1 = (iflag1.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
2028 
2029 	if (level1 && ((iflag1.intr_po == INTR_PO_ACTIVE_LOW) ||
2030 	    (iflag1.intr_po == INTR_PO_CONFORM)))
2031 		po1 = AV_ACTIVE_LOW;
2032 
2033 	if (iflag2.intr_el == INTR_EL_CONFORM)
2034 		level2 = AV_LEVEL;
2035 	else
2036 		level2 = (iflag2.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
2037 
2038 	if (level2 && ((iflag2.intr_po == INTR_PO_ACTIVE_LOW) ||
2039 	    (iflag2.intr_po == INTR_PO_CONFORM)))
2040 		po2 = AV_ACTIVE_LOW;
2041 
2042 	if ((level1 == level2) && (po1 == po2))
2043 		return (1);
2044 
2045 	return (0);
2046 }
2047 
2048 /*
2049  * Attempt to share vector with someone else
2050  */
2051 static int
2052 apic_share_vector(int irqno, iflag_t *intr_flagp, short intr_index, int ipl,
2053 	uchar_t ioapicindex, uchar_t ipin, apic_irq_t **irqptrp)
2054 {
2055 #ifdef DEBUG
2056 	apic_irq_t *tmpirqp = NULL;
2057 #endif /* DEBUG */
2058 	apic_irq_t *irqptr, dummyirq;
2059 	int	newirq, chosen_irq = -1, share = 127;
2060 	int	lowest, highest, i;
2061 	uchar_t	share_id;
2062 
2063 	DDI_INTR_IMPLDBG((CE_CONT, "apic_share_vector: irqno=0x%x "
2064 	    "intr_index=0x%x ipl=0x%x\n", irqno, intr_index, ipl));
2065 
2066 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
2067 	lowest = apic_ipltopri[ipl-1] + APIC_VECTOR_PER_IPL;
2068 
2069 	if (highest < lowest) /* Both ipl and ipl-1 map to same pri */
2070 		lowest -= APIC_VECTOR_PER_IPL;
2071 	dummyirq.airq_mps_intr_index = intr_index;
2072 	dummyirq.airq_ioapicindex = ioapicindex;
2073 	dummyirq.airq_intin_no = ipin;
2074 	if (intr_flagp)
2075 		dummyirq.airq_iflag = *intr_flagp;
2076 	apic_record_rdt_entry(&dummyirq, irqno);
2077 	for (i = lowest; i <= highest; i++) {
2078 		newirq = apic_vector_to_irq[i];
2079 		if (newirq == APIC_RESV_IRQ)
2080 			continue;
2081 		irqptr = apic_irq_table[newirq];
2082 
2083 		if ((dummyirq.airq_rdt_entry & 0xFF00) !=
2084 		    (irqptr->airq_rdt_entry & 0xFF00))
2085 			/* not compatible */
2086 			continue;
2087 
2088 		if (irqptr->airq_share < share) {
2089 			share = irqptr->airq_share;
2090 			chosen_irq = newirq;
2091 		}
2092 	}
2093 	if (chosen_irq != -1) {
2094 		/*
2095 		 * Assign a share id which is free or which is larger
2096 		 * than the largest one.
2097 		 */
2098 		share_id = 1;
2099 		mutex_enter(&airq_mutex);
2100 		irqptr = apic_irq_table[chosen_irq];
2101 		while (irqptr) {
2102 			if (irqptr->airq_mps_intr_index == FREE_INDEX) {
2103 				share_id = irqptr->airq_share_id;
2104 				break;
2105 			}
2106 			if (share_id <= irqptr->airq_share_id)
2107 				share_id = irqptr->airq_share_id + 1;
2108 #ifdef DEBUG
2109 			tmpirqp = irqptr;
2110 #endif /* DEBUG */
2111 			irqptr = irqptr->airq_next;
2112 		}
2113 		if (!irqptr) {
2114 			irqptr = kmem_zalloc(sizeof (apic_irq_t), KM_SLEEP);
2115 			irqptr->airq_temp_cpu = IRQ_UNINIT;
2116 			irqptr->airq_next =
2117 			    apic_irq_table[chosen_irq]->airq_next;
2118 			apic_irq_table[chosen_irq]->airq_next = irqptr;
2119 #ifdef	DEBUG
2120 			tmpirqp = apic_irq_table[chosen_irq];
2121 #endif /* DEBUG */
2122 		}
2123 		irqptr->airq_mps_intr_index = intr_index;
2124 		irqptr->airq_ioapicindex = ioapicindex;
2125 		irqptr->airq_intin_no = ipin;
2126 		if (intr_flagp)
2127 			irqptr->airq_iflag = *intr_flagp;
2128 		irqptr->airq_vector = apic_irq_table[chosen_irq]->airq_vector;
2129 		irqptr->airq_share_id = share_id;
2130 		apic_record_rdt_entry(irqptr, irqno);
2131 		*irqptrp = irqptr;
2132 #ifdef	DEBUG
2133 		/* shuffle the pointers to test apic_delspl path */
2134 		if (tmpirqp) {
2135 			tmpirqp->airq_next = irqptr->airq_next;
2136 			irqptr->airq_next = apic_irq_table[chosen_irq];
2137 			apic_irq_table[chosen_irq] = irqptr;
2138 		}
2139 #endif /* DEBUG */
2140 		mutex_exit(&airq_mutex);
2141 		return (VIRTIRQ(chosen_irq, share_id));
2142 	}
2143 	return (-1);
2144 }
2145 
2146 /*
2147  *
2148  */
2149 static int
2150 apic_setup_irq_table(dev_info_t *dip, int irqno, struct apic_io_intr *intrp,
2151     struct intrspec *ispec, iflag_t *intr_flagp, int type)
2152 {
2153 	int origirq = ispec->intrspec_vec;
2154 	uchar_t ipl = ispec->intrspec_pri;
2155 	int	newirq, intr_index;
2156 	uchar_t	ipin, ioapic, ioapicindex, vector;
2157 	apic_irq_t *irqptr;
2158 	major_t	major;
2159 	dev_info_t	*sdip;
2160 
2161 	DDI_INTR_IMPLDBG((CE_CONT, "apic_setup_irq_table: dip=0x%p type=%d "
2162 	    "irqno=0x%x origirq=0x%x\n", (void *)dip, type, irqno, origirq));
2163 
2164 	ASSERT(ispec != NULL);
2165 
2166 	major =  (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
2167 
2168 	if (DDI_INTR_IS_MSI_OR_MSIX(type)) {
2169 		/* MSI/X doesn't need to setup ioapic stuffs */
2170 		ioapicindex = 0xff;
2171 		ioapic = 0xff;
2172 		ipin = (uchar_t)0xff;
2173 		intr_index = (type == DDI_INTR_TYPE_MSI) ? MSI_INDEX :
2174 		    MSIX_INDEX;
2175 		mutex_enter(&airq_mutex);
2176 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) == -1) {
2177 			mutex_exit(&airq_mutex);
2178 			/* need an irq for MSI/X to index into autovect[] */
2179 			cmn_err(CE_WARN, "No interrupt irq: %s instance %d",
2180 			    ddi_get_name(dip), ddi_get_instance(dip));
2181 			return (-1);
2182 		}
2183 		mutex_exit(&airq_mutex);
2184 
2185 	} else if (intrp != NULL) {
2186 		intr_index = (int)(intrp - apic_io_intrp);
2187 		ioapic = intrp->intr_destid;
2188 		ipin = intrp->intr_destintin;
2189 		/* Find ioapicindex. If destid was ALL, we will exit with 0. */
2190 		for (ioapicindex = apic_io_max - 1; ioapicindex; ioapicindex--)
2191 			if (apic_io_id[ioapicindex] == ioapic)
2192 				break;
2193 		ASSERT((ioapic == apic_io_id[ioapicindex]) ||
2194 		    (ioapic == INTR_ALL_APIC));
2195 
2196 		/* check whether this intin# has been used by another irqno */
2197 		if ((newirq = apic_find_intin(ioapicindex, ipin)) != -1) {
2198 			return (newirq);
2199 		}
2200 
2201 	} else if (intr_flagp != NULL) {
2202 		/* ACPI case */
2203 		intr_index = ACPI_INDEX;
2204 		ioapicindex = acpi_find_ioapic(irqno);
2205 		ASSERT(ioapicindex != 0xFF);
2206 		ioapic = apic_io_id[ioapicindex];
2207 		ipin = irqno - apic_io_vectbase[ioapicindex];
2208 		if (apic_irq_table[irqno] &&
2209 		    apic_irq_table[irqno]->airq_mps_intr_index == ACPI_INDEX) {
2210 			ASSERT(apic_irq_table[irqno]->airq_intin_no == ipin &&
2211 			    apic_irq_table[irqno]->airq_ioapicindex ==
2212 			    ioapicindex);
2213 			return (irqno);
2214 		}
2215 
2216 	} else {
2217 		/* default configuration */
2218 		ioapicindex = 0;
2219 		ioapic = apic_io_id[ioapicindex];
2220 		ipin = (uchar_t)irqno;
2221 		intr_index = DEFAULT_INDEX;
2222 	}
2223 
2224 	if (ispec == NULL) {
2225 		APIC_VERBOSE_IOAPIC((CE_WARN, "No intrspec for irqno = %x\n",
2226 		    irqno));
2227 	} else if ((vector = apic_allocate_vector(ipl, irqno, 0)) == 0) {
2228 		if ((newirq = apic_share_vector(irqno, intr_flagp, intr_index,
2229 		    ipl, ioapicindex, ipin, &irqptr)) != -1) {
2230 			irqptr->airq_ipl = ipl;
2231 			irqptr->airq_origirq = (uchar_t)origirq;
2232 			irqptr->airq_dip = dip;
2233 			irqptr->airq_major = major;
2234 			sdip = apic_irq_table[IRQINDEX(newirq)]->airq_dip;
2235 			/* This is OK to do really */
2236 			if (sdip == NULL) {
2237 				cmn_err(CE_WARN, "Sharing vectors: %s"
2238 				    " instance %d and SCI",
2239 				    ddi_get_name(dip), ddi_get_instance(dip));
2240 			} else {
2241 				cmn_err(CE_WARN, "Sharing vectors: %s"
2242 				    " instance %d and %s instance %d",
2243 				    ddi_get_name(sdip), ddi_get_instance(sdip),
2244 				    ddi_get_name(dip), ddi_get_instance(dip));
2245 			}
2246 			return (newirq);
2247 		}
2248 		/* try high priority allocation now  that share has failed */
2249 		if ((vector = apic_allocate_vector(ipl, irqno, 1)) == 0) {
2250 			cmn_err(CE_WARN, "No interrupt vector: %s instance %d",
2251 			    ddi_get_name(dip), ddi_get_instance(dip));
2252 			return (-1);
2253 		}
2254 	}
2255 
2256 	mutex_enter(&airq_mutex);
2257 	if (apic_irq_table[irqno] == NULL) {
2258 		irqptr = kmem_zalloc(sizeof (apic_irq_t), KM_SLEEP);
2259 		irqptr->airq_temp_cpu = IRQ_UNINIT;
2260 		apic_irq_table[irqno] = irqptr;
2261 	} else {
2262 		irqptr = apic_irq_table[irqno];
2263 		if (irqptr->airq_mps_intr_index != FREE_INDEX) {
2264 			/*
2265 			 * The slot is used by another irqno, so allocate
2266 			 * a free irqno for this interrupt
2267 			 */
2268 			newirq = apic_allocate_irq(apic_first_avail_irq);
2269 			if (newirq == -1) {
2270 				mutex_exit(&airq_mutex);
2271 				return (-1);
2272 			}
2273 			irqno = newirq;
2274 			irqptr = apic_irq_table[irqno];
2275 			if (irqptr == NULL) {
2276 				irqptr = kmem_zalloc(sizeof (apic_irq_t),
2277 				    KM_SLEEP);
2278 				irqptr->airq_temp_cpu = IRQ_UNINIT;
2279 				apic_irq_table[irqno] = irqptr;
2280 			}
2281 			vector = apic_modify_vector(vector, newirq);
2282 		}
2283 	}
2284 	apic_max_device_irq = max(irqno, apic_max_device_irq);
2285 	apic_min_device_irq = min(irqno, apic_min_device_irq);
2286 	mutex_exit(&airq_mutex);
2287 	irqptr->airq_ioapicindex = ioapicindex;
2288 	irqptr->airq_intin_no = ipin;
2289 	irqptr->airq_ipl = ipl;
2290 	irqptr->airq_vector = vector;
2291 	irqptr->airq_origirq = (uchar_t)origirq;
2292 	irqptr->airq_share_id = 0;
2293 	irqptr->airq_mps_intr_index = (short)intr_index;
2294 	irqptr->airq_dip = dip;
2295 	irqptr->airq_major = major;
2296 	irqptr->airq_cpu = apic_bind_intr(dip, irqno, ioapic, ipin);
2297 	if (intr_flagp)
2298 		irqptr->airq_iflag = *intr_flagp;
2299 
2300 	if (!DDI_INTR_IS_MSI_OR_MSIX(type)) {
2301 		/* setup I/O APIC entry for non-MSI/X interrupts */
2302 		apic_record_rdt_entry(irqptr, irqno);
2303 	}
2304 	return (irqno);
2305 }
2306 
2307 /*
2308  * return the cpu to which this intr should be bound.
2309  * Check properties or any other mechanism to see if user wants it
2310  * bound to a specific CPU. If so, return the cpu id with high bit set.
2311  * If not, use the policy to choose a cpu and return the id.
2312  */
2313 uint32_t
2314 apic_bind_intr(dev_info_t *dip, int irq, uchar_t ioapicid, uchar_t intin)
2315 {
2316 	int	instance, instno, prop_len, bind_cpu, count;
2317 	uint_t	i, rc;
2318 	uint32_t cpu;
2319 	major_t	major;
2320 	char	*name, *drv_name, *prop_val, *cptr;
2321 	char	prop_name[32];
2322 
2323 
2324 	if (apic_intr_policy == INTR_LOWEST_PRIORITY)
2325 		return (IRQ_UNBOUND);
2326 
2327 	if (apic_nproc == 1)
2328 		return (0);
2329 
2330 	drv_name = NULL;
2331 	rc = DDI_PROP_NOT_FOUND;
2332 	major = (major_t)-1;
2333 	if (dip != NULL) {
2334 		name = ddi_get_name(dip);
2335 		major = ddi_name_to_major(name);
2336 		drv_name = ddi_major_to_name(major);
2337 		instance = ddi_get_instance(dip);
2338 		if (apic_intr_policy == INTR_ROUND_ROBIN_WITH_AFFINITY) {
2339 			i = apic_min_device_irq;
2340 			for (; i <= apic_max_device_irq; i++) {
2341 
2342 				if ((i == irq) || (apic_irq_table[i] == NULL) ||
2343 				    (apic_irq_table[i]->airq_mps_intr_index
2344 				    == FREE_INDEX))
2345 					continue;
2346 
2347 				if ((apic_irq_table[i]->airq_major == major) &&
2348 				    (!(apic_irq_table[i]->airq_cpu &
2349 				    IRQ_USER_BOUND))) {
2350 
2351 					cpu = apic_irq_table[i]->airq_cpu;
2352 
2353 					cmn_err(CE_CONT,
2354 					    "!%s: %s (%s) instance #%d "
2355 					    "vector 0x%x ioapic 0x%x "
2356 					    "intin 0x%x is bound to cpu %d\n",
2357 					    psm_name,
2358 					    name, drv_name, instance, irq,
2359 					    ioapicid, intin, cpu);
2360 					return (cpu);
2361 				}
2362 			}
2363 		}
2364 		/*
2365 		 * search for "drvname"_intpt_bind_cpus property first, the
2366 		 * syntax of the property should be "a[,b,c,...]" where
2367 		 * instance 0 binds to cpu a, instance 1 binds to cpu b,
2368 		 * instance 3 binds to cpu c...
2369 		 * ddi_getlongprop() will search /option first, then /
2370 		 * if "drvname"_intpt_bind_cpus doesn't exist, then find
2371 		 * intpt_bind_cpus property.  The syntax is the same, and
2372 		 * it applies to all the devices if its "drvname" specific
2373 		 * property doesn't exist
2374 		 */
2375 		(void) strcpy(prop_name, drv_name);
2376 		(void) strcat(prop_name, "_intpt_bind_cpus");
2377 		rc = ddi_getlongprop(DDI_DEV_T_ANY, dip, 0, prop_name,
2378 		    (caddr_t)&prop_val, &prop_len);
2379 		if (rc != DDI_PROP_SUCCESS) {
2380 			rc = ddi_getlongprop(DDI_DEV_T_ANY, dip, 0,
2381 			    "intpt_bind_cpus", (caddr_t)&prop_val, &prop_len);
2382 		}
2383 	}
2384 	if (rc == DDI_PROP_SUCCESS) {
2385 		for (i = count = 0; i < (prop_len - 1); i++)
2386 			if (prop_val[i] == ',')
2387 				count++;
2388 		if (prop_val[i-1] != ',')
2389 			count++;
2390 		/*
2391 		 * if somehow the binding instances defined in the
2392 		 * property are not enough for this instno., then
2393 		 * reuse the pattern for the next instance until
2394 		 * it reaches the requested instno
2395 		 */
2396 		instno = instance % count;
2397 		i = 0;
2398 		cptr = prop_val;
2399 		while (i < instno)
2400 			if (*cptr++ == ',')
2401 				i++;
2402 		bind_cpu = stoi(&cptr);
2403 		kmem_free(prop_val, prop_len);
2404 		/* if specific cpu is bogus, then default to cpu 0 */
2405 		if (bind_cpu >= apic_nproc) {
2406 			cmn_err(CE_WARN, "%s: %s=%s: CPU %d not present",
2407 			    psm_name, prop_name, prop_val, bind_cpu);
2408 			bind_cpu = 0;
2409 		} else {
2410 			/* indicate that we are bound at user request */
2411 			bind_cpu |= IRQ_USER_BOUND;
2412 		}
2413 		/*
2414 		 * no need to check apic_cpus[].aci_status, if specific cpu is
2415 		 * not up, then post_cpu_start will handle it.
2416 		 */
2417 	} else {
2418 		bind_cpu = apic_next_bind_cpu++;
2419 		if (bind_cpu >= apic_nproc) {
2420 			apic_next_bind_cpu = 1;
2421 			bind_cpu = 0;
2422 		}
2423 	}
2424 	if (drv_name != NULL)
2425 		cmn_err(CE_CONT, "!%s: %s (%s) instance %d "
2426 		    "vector 0x%x ioapic 0x%x intin 0x%x is bound to cpu %d\n",
2427 		    psm_name, name, drv_name, instance,
2428 		    irq, ioapicid, intin, bind_cpu & ~IRQ_USER_BOUND);
2429 	else
2430 		cmn_err(CE_CONT, "!%s: "
2431 		    "vector 0x%x ioapic 0x%x intin 0x%x is bound to cpu %d\n",
2432 		    psm_name, irq, ioapicid, intin, bind_cpu & ~IRQ_USER_BOUND);
2433 
2434 	return ((uint32_t)bind_cpu);
2435 }
2436 
2437 static struct apic_io_intr *
2438 apic_find_io_intr_w_busid(int irqno, int busid)
2439 {
2440 	struct	apic_io_intr	*intrp;
2441 
2442 	/*
2443 	 * It can have more than 1 entry with same source bus IRQ,
2444 	 * but unique with the source bus id
2445 	 */
2446 	intrp = apic_io_intrp;
2447 	if (intrp != NULL) {
2448 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
2449 			if (intrp->intr_irq == irqno &&
2450 			    intrp->intr_busid == busid &&
2451 			    intrp->intr_type == IO_INTR_INT)
2452 				return (intrp);
2453 			intrp++;
2454 		}
2455 	}
2456 	APIC_VERBOSE_IOAPIC((CE_NOTE, "Did not find io intr for irqno:"
2457 	    "busid %x:%x\n", irqno, busid));
2458 	return ((struct apic_io_intr *)NULL);
2459 }
2460 
2461 
2462 struct mps_bus_info {
2463 	char	*bus_name;
2464 	int	bus_id;
2465 } bus_info_array[] = {
2466 	"ISA ", BUS_ISA,
2467 	"PCI ", BUS_PCI,
2468 	"EISA ", BUS_EISA,
2469 	"XPRESS", BUS_XPRESS,
2470 	"PCMCIA", BUS_PCMCIA,
2471 	"VL ", BUS_VL,
2472 	"CBUS ", BUS_CBUS,
2473 	"CBUSII", BUS_CBUSII,
2474 	"FUTURE", BUS_FUTURE,
2475 	"INTERN", BUS_INTERN,
2476 	"MBI ", BUS_MBI,
2477 	"MBII ", BUS_MBII,
2478 	"MPI ", BUS_MPI,
2479 	"MPSA ", BUS_MPSA,
2480 	"NUBUS ", BUS_NUBUS,
2481 	"TC ", BUS_TC,
2482 	"VME ", BUS_VME,
2483 	"PCI-E ", BUS_PCIE
2484 };
2485 
2486 static int
2487 apic_find_bus_type(char *bus)
2488 {
2489 	int	i = 0;
2490 
2491 	for (; i < sizeof (bus_info_array)/sizeof (struct mps_bus_info); i++)
2492 		if (strncmp(bus, bus_info_array[i].bus_name,
2493 		    strlen(bus_info_array[i].bus_name)) == 0)
2494 			return (bus_info_array[i].bus_id);
2495 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus type for bus %s", bus));
2496 	return (0);
2497 }
2498 
2499 static int
2500 apic_find_bus(int busid)
2501 {
2502 	struct	apic_bus	*busp;
2503 
2504 	busp = apic_busp;
2505 	while (busp->bus_entry == APIC_BUS_ENTRY) {
2506 		if (busp->bus_id == busid)
2507 			return (apic_find_bus_type((char *)&busp->bus_str1));
2508 		busp++;
2509 	}
2510 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus for bus id %x", busid));
2511 	return (0);
2512 }
2513 
2514 static int
2515 apic_find_bus_id(int bustype)
2516 {
2517 	struct	apic_bus	*busp;
2518 
2519 	busp = apic_busp;
2520 	while (busp->bus_entry == APIC_BUS_ENTRY) {
2521 		if (apic_find_bus_type((char *)&busp->bus_str1) == bustype)
2522 			return (busp->bus_id);
2523 		busp++;
2524 	}
2525 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus id for bustype %x",
2526 	    bustype));
2527 	return (-1);
2528 }
2529 
2530 /*
2531  * Check if a particular irq need to be reserved for any io_intr
2532  */
2533 static struct apic_io_intr *
2534 apic_find_io_intr(int irqno)
2535 {
2536 	struct	apic_io_intr	*intrp;
2537 
2538 	intrp = apic_io_intrp;
2539 	if (intrp != NULL) {
2540 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
2541 			if (intrp->intr_irq == irqno &&
2542 			    intrp->intr_type == IO_INTR_INT)
2543 				return (intrp);
2544 			intrp++;
2545 		}
2546 	}
2547 	return ((struct apic_io_intr *)NULL);
2548 }
2549 
2550 /*
2551  * Check if the given ioapicindex intin combination has already been assigned
2552  * an irq. If so return irqno. Else -1
2553  */
2554 static int
2555 apic_find_intin(uchar_t ioapic, uchar_t intin)
2556 {
2557 	apic_irq_t *irqptr;
2558 	int	i;
2559 
2560 	/* find ioapic and intin in the apic_irq_table[] and return the index */
2561 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
2562 		irqptr = apic_irq_table[i];
2563 		while (irqptr) {
2564 			if ((irqptr->airq_mps_intr_index >= 0) &&
2565 			    (irqptr->airq_intin_no == intin) &&
2566 			    (irqptr->airq_ioapicindex == ioapic)) {
2567 				APIC_VERBOSE_IOAPIC((CE_NOTE, "!Found irq "
2568 				    "entry for ioapic:intin %x:%x "
2569 				    "shared interrupts ?", ioapic, intin));
2570 				return (i);
2571 			}
2572 			irqptr = irqptr->airq_next;
2573 		}
2574 	}
2575 	return (-1);
2576 }
2577 
2578 int
2579 apic_allocate_irq(int irq)
2580 {
2581 	int	freeirq, i;
2582 
2583 	if ((freeirq = apic_find_free_irq(irq, (APIC_RESV_IRQ - 1))) == -1)
2584 		if ((freeirq = apic_find_free_irq(APIC_FIRST_FREE_IRQ,
2585 		    (irq - 1))) == -1) {
2586 			/*
2587 			 * if BIOS really defines every single irq in the mps
2588 			 * table, then don't worry about conflicting with
2589 			 * them, just use any free slot in apic_irq_table
2590 			 */
2591 			for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
2592 				if ((apic_irq_table[i] == NULL) ||
2593 				    apic_irq_table[i]->airq_mps_intr_index ==
2594 				    FREE_INDEX) {
2595 				freeirq = i;
2596 				break;
2597 			}
2598 		}
2599 		if (freeirq == -1) {
2600 			/* This shouldn't happen, but just in case */
2601 			cmn_err(CE_WARN, "%s: NO available IRQ", psm_name);
2602 			return (-1);
2603 		}
2604 	}
2605 	if (apic_irq_table[freeirq] == NULL) {
2606 		apic_irq_table[freeirq] =
2607 		    kmem_zalloc(sizeof (apic_irq_t), KM_NOSLEEP);
2608 		if (apic_irq_table[freeirq] == NULL) {
2609 			cmn_err(CE_WARN, "%s: NO memory to allocate IRQ",
2610 			    psm_name);
2611 			return (-1);
2612 		}
2613 		apic_irq_table[freeirq]->airq_mps_intr_index = FREE_INDEX;
2614 	}
2615 	return (freeirq);
2616 }
2617 
2618 static int
2619 apic_find_free_irq(int start, int end)
2620 {
2621 	int	i;
2622 
2623 	for (i = start; i <= end; i++)
2624 		/* Check if any I/O entry needs this IRQ */
2625 		if (apic_find_io_intr(i) == NULL) {
2626 			/* Then see if it is free */
2627 			if ((apic_irq_table[i] == NULL) ||
2628 			    (apic_irq_table[i]->airq_mps_intr_index ==
2629 			    FREE_INDEX)) {
2630 				return (i);
2631 			}
2632 		}
2633 	return (-1);
2634 }
2635 
2636 
2637 /*
2638  * Mark vector as being in the process of being deleted. Interrupts
2639  * may still come in on some CPU. The moment an interrupt comes with
2640  * the new vector, we know we can free the old one. Called only from
2641  * addspl and delspl with interrupts disabled. Because an interrupt
2642  * can be shared, but no interrupt from either device may come in,
2643  * we also use a timeout mechanism, which we arbitrarily set to
2644  * apic_revector_timeout microseconds.
2645  */
2646 static void
2647 apic_mark_vector(uchar_t oldvector, uchar_t newvector)
2648 {
2649 	ulong_t iflag;
2650 
2651 	iflag = intr_clear();
2652 	lock_set(&apic_revector_lock);
2653 	if (!apic_oldvec_to_newvec) {
2654 		apic_oldvec_to_newvec =
2655 		    kmem_zalloc(sizeof (newvector) * APIC_MAX_VECTOR * 2,
2656 		    KM_NOSLEEP);
2657 
2658 		if (!apic_oldvec_to_newvec) {
2659 			/*
2660 			 * This failure is not catastrophic.
2661 			 * But, the oldvec will never be freed.
2662 			 */
2663 			apic_error |= APIC_ERR_MARK_VECTOR_FAIL;
2664 			lock_clear(&apic_revector_lock);
2665 			intr_restore(iflag);
2666 			return;
2667 		}
2668 		apic_newvec_to_oldvec = &apic_oldvec_to_newvec[APIC_MAX_VECTOR];
2669 	}
2670 
2671 	/* See if we already did this for drivers which do double addintrs */
2672 	if (apic_oldvec_to_newvec[oldvector] != newvector) {
2673 		apic_oldvec_to_newvec[oldvector] = newvector;
2674 		apic_newvec_to_oldvec[newvector] = oldvector;
2675 		apic_revector_pending++;
2676 	}
2677 	lock_clear(&apic_revector_lock);
2678 	intr_restore(iflag);
2679 	(void) timeout(apic_xlate_vector_free_timeout_handler,
2680 	    (void *)(uintptr_t)oldvector, drv_usectohz(apic_revector_timeout));
2681 }
2682 
2683 /*
2684  * xlate_vector is called from intr_enter if revector_pending is set.
2685  * It will xlate it if needed and mark the old vector as free.
2686  */
2687 uchar_t
2688 apic_xlate_vector(uchar_t vector)
2689 {
2690 	uchar_t	newvector, oldvector = 0;
2691 
2692 	lock_set(&apic_revector_lock);
2693 	/* Do we really need to do this ? */
2694 	if (!apic_revector_pending) {
2695 		lock_clear(&apic_revector_lock);
2696 		return (vector);
2697 	}
2698 	if ((newvector = apic_oldvec_to_newvec[vector]) != 0)
2699 		oldvector = vector;
2700 	else {
2701 		/*
2702 		 * The incoming vector is new . See if a stale entry is
2703 		 * remaining
2704 		 */
2705 		if ((oldvector = apic_newvec_to_oldvec[vector]) != 0)
2706 			newvector = vector;
2707 	}
2708 
2709 	if (oldvector) {
2710 		apic_revector_pending--;
2711 		apic_oldvec_to_newvec[oldvector] = 0;
2712 		apic_newvec_to_oldvec[newvector] = 0;
2713 		apic_free_vector(oldvector);
2714 		lock_clear(&apic_revector_lock);
2715 		/* There could have been more than one reprogramming! */
2716 		return (apic_xlate_vector(newvector));
2717 	}
2718 	lock_clear(&apic_revector_lock);
2719 	return (vector);
2720 }
2721 
2722 void
2723 apic_xlate_vector_free_timeout_handler(void *arg)
2724 {
2725 	ulong_t iflag;
2726 	uchar_t oldvector, newvector;
2727 
2728 	oldvector = (uchar_t)(uintptr_t)arg;
2729 	iflag = intr_clear();
2730 	lock_set(&apic_revector_lock);
2731 	if ((newvector = apic_oldvec_to_newvec[oldvector]) != 0) {
2732 		apic_free_vector(oldvector);
2733 		apic_oldvec_to_newvec[oldvector] = 0;
2734 		apic_newvec_to_oldvec[newvector] = 0;
2735 		apic_revector_pending--;
2736 	}
2737 
2738 	lock_clear(&apic_revector_lock);
2739 	intr_restore(iflag);
2740 }
2741 
2742 
2743 /*
2744  * compute the polarity, trigger mode and vector for programming into
2745  * the I/O apic and record in airq_rdt_entry.
2746  */
2747 static void
2748 apic_record_rdt_entry(apic_irq_t *irqptr, int irq)
2749 {
2750 	int	ioapicindex, bus_type, vector;
2751 	short	intr_index;
2752 	uint_t	level, po, io_po;
2753 	struct apic_io_intr *iointrp;
2754 
2755 	intr_index = irqptr->airq_mps_intr_index;
2756 	DDI_INTR_IMPLDBG((CE_CONT, "apic_record_rdt_entry: intr_index=%d "
2757 	    "irq = 0x%x dip = 0x%p vector = 0x%x\n", intr_index, irq,
2758 	    (void *)irqptr->airq_dip, irqptr->airq_vector));
2759 
2760 	if (intr_index == RESERVE_INDEX) {
2761 		apic_error |= APIC_ERR_INVALID_INDEX;
2762 		return;
2763 	} else if (APIC_IS_MSI_OR_MSIX_INDEX(intr_index)) {
2764 		return;
2765 	}
2766 
2767 	vector = irqptr->airq_vector;
2768 	ioapicindex = irqptr->airq_ioapicindex;
2769 	/* Assume edge triggered by default */
2770 	level = 0;
2771 	/* Assume active high by default */
2772 	po = 0;
2773 
2774 	if (intr_index == DEFAULT_INDEX || intr_index == FREE_INDEX) {
2775 		ASSERT(irq < 16);
2776 		if (eisa_level_intr_mask & (1 << irq))
2777 			level = AV_LEVEL;
2778 		if (intr_index == FREE_INDEX && apic_defconf == 0)
2779 			apic_error |= APIC_ERR_INVALID_INDEX;
2780 	} else if (intr_index == ACPI_INDEX) {
2781 		bus_type = irqptr->airq_iflag.bustype;
2782 		if (irqptr->airq_iflag.intr_el == INTR_EL_CONFORM) {
2783 			if (bus_type == BUS_PCI)
2784 				level = AV_LEVEL;
2785 		} else
2786 			level = (irqptr->airq_iflag.intr_el == INTR_EL_LEVEL) ?
2787 			    AV_LEVEL : 0;
2788 		if (level &&
2789 		    ((irqptr->airq_iflag.intr_po == INTR_PO_ACTIVE_LOW) ||
2790 		    (irqptr->airq_iflag.intr_po == INTR_PO_CONFORM &&
2791 		    bus_type == BUS_PCI)))
2792 			po = AV_ACTIVE_LOW;
2793 	} else {
2794 		iointrp = apic_io_intrp + intr_index;
2795 		bus_type = apic_find_bus(iointrp->intr_busid);
2796 		if (iointrp->intr_el == INTR_EL_CONFORM) {
2797 			if ((irq < 16) && (eisa_level_intr_mask & (1 << irq)))
2798 				level = AV_LEVEL;
2799 			else if (bus_type == BUS_PCI)
2800 				level = AV_LEVEL;
2801 		} else
2802 			level = (iointrp->intr_el == INTR_EL_LEVEL) ?
2803 			    AV_LEVEL : 0;
2804 		if (level && ((iointrp->intr_po == INTR_PO_ACTIVE_LOW) ||
2805 		    (iointrp->intr_po == INTR_PO_CONFORM &&
2806 		    bus_type == BUS_PCI)))
2807 			po = AV_ACTIVE_LOW;
2808 	}
2809 	if (level)
2810 		apic_level_intr[irq] = 1;
2811 	/*
2812 	 * The 82489DX External APIC cannot do active low polarity interrupts.
2813 	 */
2814 	if (po && (apic_io_ver[ioapicindex] != IOAPIC_VER_82489DX))
2815 		io_po = po;
2816 	else
2817 		io_po = 0;
2818 
2819 	if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG)
2820 		printf("setio: ioapic=%x intin=%x level=%x po=%x vector=%x\n",
2821 		    ioapicindex, irqptr->airq_intin_no, level, io_po, vector);
2822 
2823 	irqptr->airq_rdt_entry = level|io_po|vector;
2824 }
2825 
2826 /*
2827  * Bind interrupt corresponding to irq_ptr to bind_cpu.
2828  * Must be called with interrupts disabled and apic_ioapic_lock held
2829  */
2830 int
2831 apic_rebind(apic_irq_t *irq_ptr, int bind_cpu,
2832     struct ioapic_reprogram_data *drep)
2833 {
2834 	int			ioapicindex, intin_no;
2835 	uint32_t		airq_temp_cpu;
2836 	apic_cpus_info_t	*cpu_infop;
2837 	uint32_t		rdt_entry;
2838 	int			which_irq;
2839 
2840 	which_irq = apic_vector_to_irq[irq_ptr->airq_vector];
2841 
2842 	intin_no = irq_ptr->airq_intin_no;
2843 	ioapicindex = irq_ptr->airq_ioapicindex;
2844 	airq_temp_cpu = irq_ptr->airq_temp_cpu;
2845 	if (airq_temp_cpu != IRQ_UNINIT && airq_temp_cpu != IRQ_UNBOUND) {
2846 		if (airq_temp_cpu & IRQ_USER_BOUND)
2847 			/* Mask off high bit so it can be used as array index */
2848 			airq_temp_cpu &= ~IRQ_USER_BOUND;
2849 
2850 		ASSERT(airq_temp_cpu < apic_nproc);
2851 	}
2852 
2853 	/*
2854 	 * Can't bind to a CPU that's not accepting interrupts:
2855 	 */
2856 	cpu_infop = &apic_cpus[bind_cpu & ~IRQ_USER_BOUND];
2857 	if (!(cpu_infop->aci_status & APIC_CPU_INTR_ENABLE))
2858 		return (1);
2859 
2860 	/*
2861 	 * If we are about to change the interrupt vector for this interrupt,
2862 	 * and this interrupt is level-triggered, attached to an IOAPIC,
2863 	 * has been delivered to a CPU and that CPU has not handled it
2864 	 * yet, we cannot reprogram the IOAPIC now.
2865 	 */
2866 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2867 
2868 		rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex,
2869 		    intin_no);
2870 
2871 		if ((irq_ptr->airq_vector != RDT_VECTOR(rdt_entry)) &&
2872 		    apic_check_stuck_interrupt(irq_ptr, airq_temp_cpu,
2873 		    bind_cpu, ioapicindex, intin_no, which_irq, drep) != 0) {
2874 
2875 			return (0);
2876 		}
2877 
2878 		/*
2879 		 * NOTE: We do not unmask the RDT here, as an interrupt MAY
2880 		 * still come in before we have a chance to reprogram it below.
2881 		 * The reprogramming below will simultaneously change and
2882 		 * unmask the RDT entry.
2883 		 */
2884 
2885 		if ((uint32_t)bind_cpu == IRQ_UNBOUND) {
2886 			rdt_entry = AV_LDEST | AV_LOPRI |
2887 			    irq_ptr->airq_rdt_entry;
2888 
2889 			/* Write the RDT entry -- no specific CPU binding */
2890 			WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2891 			    AV_TOALL);
2892 
2893 			if (airq_temp_cpu != IRQ_UNINIT && airq_temp_cpu !=
2894 			    IRQ_UNBOUND)
2895 				apic_cpus[airq_temp_cpu].aci_temp_bound--;
2896 
2897 			/*
2898 			 * Write the vector, trigger, and polarity portion of
2899 			 * the RDT
2900 			 */
2901 			WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex, intin_no,
2902 			    rdt_entry);
2903 
2904 			irq_ptr->airq_temp_cpu = IRQ_UNBOUND;
2905 			return (0);
2906 		}
2907 	}
2908 
2909 	if (bind_cpu & IRQ_USER_BOUND) {
2910 		cpu_infop->aci_bound++;
2911 	} else {
2912 		cpu_infop->aci_temp_bound++;
2913 	}
2914 	ASSERT((bind_cpu & ~IRQ_USER_BOUND) < apic_nproc);
2915 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2916 		/* Write the RDT entry -- bind to a specific CPU: */
2917 		WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2918 		    cpu_infop->aci_local_id << APIC_ID_BIT_OFFSET);
2919 	}
2920 	if ((airq_temp_cpu != IRQ_UNBOUND) && (airq_temp_cpu != IRQ_UNINIT)) {
2921 		apic_cpus[airq_temp_cpu].aci_temp_bound--;
2922 	}
2923 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2924 
2925 		rdt_entry = AV_PDEST | AV_FIXED | irq_ptr->airq_rdt_entry;
2926 
2927 		/* Write the vector, trigger, and polarity portion of the RDT */
2928 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex, intin_no,
2929 		    rdt_entry);
2930 
2931 	} else {
2932 		int type = (irq_ptr->airq_mps_intr_index == MSI_INDEX) ?
2933 		    DDI_INTR_TYPE_MSI : DDI_INTR_TYPE_MSIX;
2934 		if (type == DDI_INTR_TYPE_MSI) {
2935 			if (irq_ptr->airq_ioapicindex ==
2936 			    irq_ptr->airq_origirq) {
2937 				/* first one */
2938 				DDI_INTR_IMPLDBG((CE_CONT, "apic_rebind: call "
2939 				    "apic_pci_msi_enable_vector\n"));
2940 				apic_pci_msi_enable_vector(irq_ptr->airq_dip,
2941 				    type, which_irq, irq_ptr->airq_vector,
2942 				    irq_ptr->airq_intin_no,
2943 				    cpu_infop->aci_local_id);
2944 			}
2945 			if ((irq_ptr->airq_ioapicindex +
2946 			    irq_ptr->airq_intin_no - 1) ==
2947 			    irq_ptr->airq_origirq) { /* last one */
2948 				DDI_INTR_IMPLDBG((CE_CONT, "apic_rebind: call "
2949 				    "apic_pci_msi_enable_mode\n"));
2950 				apic_pci_msi_enable_mode(irq_ptr->airq_dip,
2951 				    type, which_irq);
2952 			}
2953 		} else { /* MSI-X */
2954 			apic_pci_msi_enable_vector(irq_ptr->airq_dip, type,
2955 			    irq_ptr->airq_origirq, irq_ptr->airq_vector, 1,
2956 			    cpu_infop->aci_local_id);
2957 			apic_pci_msi_enable_mode(irq_ptr->airq_dip, type,
2958 			    irq_ptr->airq_origirq);
2959 		}
2960 	}
2961 	irq_ptr->airq_temp_cpu = (uint32_t)bind_cpu;
2962 	apic_redist_cpu_skip &= ~(1 << (bind_cpu & ~IRQ_USER_BOUND));
2963 	return (0);
2964 }
2965 
2966 static void
2967 apic_last_ditch_clear_remote_irr(int ioapic_ix, int intin_no)
2968 {
2969 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no)
2970 	    & AV_REMOTE_IRR) != 0) {
2971 		/*
2972 		 * Trying to clear the bit through normal
2973 		 * channels has failed.  So as a last-ditch
2974 		 * effort, try to set the trigger mode to
2975 		 * edge, then to level.  This has been
2976 		 * observed to work on many systems.
2977 		 */
2978 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2979 		    intin_no,
2980 		    READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2981 		    intin_no) & ~AV_LEVEL);
2982 
2983 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2984 		    intin_no,
2985 		    READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2986 		    intin_no) | AV_LEVEL);
2987 
2988 		/*
2989 		 * If the bit's STILL set, this interrupt may
2990 		 * be hosed.
2991 		 */
2992 		if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2993 		    intin_no) & AV_REMOTE_IRR) != 0) {
2994 
2995 			prom_printf("%s: Remote IRR still "
2996 			    "not clear for IOAPIC %d intin %d.\n"
2997 			    "\tInterrupts to this pin may cease "
2998 			    "functioning.\n", psm_name, ioapic_ix,
2999 			    intin_no);
3000 #ifdef DEBUG
3001 			apic_last_ditch_reprogram_failures++;
3002 #endif
3003 		}
3004 	}
3005 }
3006 
3007 /*
3008  * This function is protected by apic_ioapic_lock coupled with the
3009  * fact that interrupts are disabled.
3010  */
3011 static void
3012 delete_defer_repro_ent(int which_irq)
3013 {
3014 	ASSERT(which_irq >= 0);
3015 	ASSERT(which_irq <= 255);
3016 
3017 	if (apic_reprogram_info[which_irq].done)
3018 		return;
3019 
3020 	apic_reprogram_info[which_irq].done = B_TRUE;
3021 
3022 #ifdef DEBUG
3023 	apic_defer_repro_total_retries +=
3024 	    apic_reprogram_info[which_irq].tries;
3025 
3026 	apic_defer_repro_successes++;
3027 #endif
3028 
3029 	if (--apic_reprogram_outstanding == 0) {
3030 
3031 		setlvlx = psm_intr_exit_fn();
3032 	}
3033 }
3034 
3035 
3036 /*
3037  * Interrupts must be disabled during this function to prevent
3038  * self-deadlock.  Interrupts are disabled because this function
3039  * is called from apic_check_stuck_interrupt(), which is called
3040  * from apic_rebind(), which requires its caller to disable interrupts.
3041  */
3042 static void
3043 add_defer_repro_ent(apic_irq_t *irq_ptr, int which_irq, int new_bind_cpu)
3044 {
3045 	ASSERT(which_irq >= 0);
3046 	ASSERT(which_irq <= 255);
3047 
3048 	/*
3049 	 * On the off-chance that there's already a deferred
3050 	 * reprogramming on this irq, check, and if so, just update the
3051 	 * CPU and irq pointer to which the interrupt is targeted, then return.
3052 	 */
3053 	if (!apic_reprogram_info[which_irq].done) {
3054 		apic_reprogram_info[which_irq].bindcpu = new_bind_cpu;
3055 		apic_reprogram_info[which_irq].irqp = irq_ptr;
3056 		return;
3057 	}
3058 
3059 	apic_reprogram_info[which_irq].irqp = irq_ptr;
3060 	apic_reprogram_info[which_irq].bindcpu = new_bind_cpu;
3061 	apic_reprogram_info[which_irq].tries = 0;
3062 	/*
3063 	 * This must be the last thing set, since we're not
3064 	 * grabbing any locks, apic_try_deferred_reprogram() will
3065 	 * make its decision about using this entry iff done
3066 	 * is false.
3067 	 */
3068 	apic_reprogram_info[which_irq].done = B_FALSE;
3069 
3070 	/*
3071 	 * If there were previously no deferred reprogrammings, change
3072 	 * setlvlx to call apic_try_deferred_reprogram()
3073 	 */
3074 	if (++apic_reprogram_outstanding == 1) {
3075 
3076 		setlvlx = apic_try_deferred_reprogram;
3077 	}
3078 }
3079 
3080 static void
3081 apic_try_deferred_reprogram(int prev_ipl, int irq)
3082 {
3083 	int reproirq;
3084 	ulong_t iflag;
3085 	struct ioapic_reprogram_data *drep;
3086 
3087 	(*psm_intr_exit_fn())(prev_ipl, irq);
3088 
3089 	if (!lock_try(&apic_defer_reprogram_lock)) {
3090 		return;
3091 	}
3092 
3093 	/*
3094 	 * Acquire the apic_ioapic_lock so that any other operations that
3095 	 * may affect the apic_reprogram_info state are serialized.
3096 	 * It's still possible for the last deferred reprogramming to clear
3097 	 * between the time we entered this function and the time we get to
3098 	 * the for loop below.  In that case, *setlvlx will have been set
3099 	 * back to *_intr_exit and drep will be NULL. (There's no way to
3100 	 * stop that from happening -- we would need to grab a lock before
3101 	 * calling *setlvlx, which is neither realistic nor prudent).
3102 	 */
3103 	iflag = intr_clear();
3104 	lock_set(&apic_ioapic_lock);
3105 
3106 	/*
3107 	 * For each deferred RDT entry, try to reprogram it now.  Note that
3108 	 * there is no lock acquisition to read apic_reprogram_info because
3109 	 * '.done' is set only after the other fields in the structure are set.
3110 	 */
3111 
3112 	drep = NULL;
3113 	for (reproirq = 0; reproirq <= APIC_MAX_VECTOR; reproirq++) {
3114 		if (apic_reprogram_info[reproirq].done == B_FALSE) {
3115 			drep = &apic_reprogram_info[reproirq];
3116 			break;
3117 		}
3118 	}
3119 
3120 	/*
3121 	 * Either we found a deferred action to perform, or
3122 	 * we entered this function spuriously, after *setlvlx
3123 	 * was restored to point to *_intr_exit.  Any other
3124 	 * permutation is invalid.
3125 	 */
3126 	ASSERT(drep != NULL || *setlvlx == psm_intr_exit_fn());
3127 
3128 	/*
3129 	 * Though we can't really do anything about errors
3130 	 * at this point, keep track of them for reporting.
3131 	 * Note that it is very possible for apic_setup_io_intr
3132 	 * to re-register this very timeout if the Remote IRR bit
3133 	 * has not yet cleared.
3134 	 */
3135 
3136 #ifdef DEBUG
3137 	if (drep != NULL) {
3138 		if (apic_setup_io_intr(drep, reproirq, B_TRUE) != 0) {
3139 			apic_deferred_setup_failures++;
3140 		}
3141 	} else {
3142 		apic_deferred_spurious_enters++;
3143 	}
3144 #else
3145 	if (drep != NULL)
3146 		(void) apic_setup_io_intr(drep, reproirq, B_TRUE);
3147 #endif
3148 
3149 	lock_clear(&apic_ioapic_lock);
3150 	intr_restore(iflag);
3151 
3152 	lock_clear(&apic_defer_reprogram_lock);
3153 }
3154 
3155 static void
3156 apic_ioapic_wait_pending_clear(int ioapic_ix, int intin_no)
3157 {
3158 	int waited;
3159 
3160 	/*
3161 	 * Wait for the delivery pending bit to clear.
3162 	 */
3163 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no) &
3164 	    (AV_LEVEL|AV_PENDING)) == (AV_LEVEL|AV_PENDING)) {
3165 
3166 		/*
3167 		 * If we're still waiting on the delivery of this interrupt,
3168 		 * continue to wait here until it is delivered (this should be
3169 		 * a very small amount of time, but include a timeout just in
3170 		 * case).
3171 		 */
3172 		for (waited = 0; waited < apic_max_reps_clear_pending;
3173 		    waited++) {
3174 			if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3175 			    intin_no) & AV_PENDING) == 0) {
3176 				break;
3177 			}
3178 		}
3179 	}
3180 }
3181 
3182 
3183 /*
3184  * Checks to see if the IOAPIC interrupt entry specified has its Remote IRR
3185  * bit set.  Calls functions that modify the function that setlvlx points to,
3186  * so that the reprogramming can be retried very shortly.
3187  *
3188  * This function will mask the RDT entry if the interrupt is level-triggered.
3189  * (The caller is responsible for unmasking the RDT entry.)
3190  *
3191  * Returns non-zero if the caller should defer IOAPIC reprogramming.
3192  */
3193 static int
3194 apic_check_stuck_interrupt(apic_irq_t *irq_ptr, int old_bind_cpu,
3195     int new_bind_cpu, int ioapic_ix, int intin_no, int which_irq,
3196     struct ioapic_reprogram_data *drep)
3197 {
3198 	int32_t			rdt_entry;
3199 	int			waited;
3200 	int			reps = 0;
3201 
3202 	/*
3203 	 * Wait for the delivery pending bit to clear.
3204 	 */
3205 	do {
3206 		++reps;
3207 
3208 		apic_ioapic_wait_pending_clear(ioapic_ix, intin_no);
3209 
3210 		/*
3211 		 * Mask the RDT entry, but only if it's a level-triggered
3212 		 * interrupt
3213 		 */
3214 		rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3215 		    intin_no);
3216 		if ((rdt_entry & (AV_LEVEL|AV_MASK)) == AV_LEVEL) {
3217 
3218 			/* Mask it */
3219 			WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no,
3220 			    AV_MASK | rdt_entry);
3221 		}
3222 
3223 		if ((rdt_entry & AV_LEVEL) == AV_LEVEL) {
3224 			/*
3225 			 * If there was a race and an interrupt was injected
3226 			 * just before we masked, check for that case here.
3227 			 * Then, unmask the RDT entry and try again.  If we're
3228 			 * on our last try, don't unmask (because we want the
3229 			 * RDT entry to remain masked for the rest of the
3230 			 * function).
3231 			 */
3232 			rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3233 			    intin_no);
3234 			if ((rdt_entry & AV_PENDING) &&
3235 			    (reps < apic_max_reps_clear_pending)) {
3236 				/* Unmask it */
3237 				WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3238 				    intin_no, rdt_entry & ~AV_MASK);
3239 			}
3240 		}
3241 
3242 	} while ((rdt_entry & AV_PENDING) &&
3243 	    (reps < apic_max_reps_clear_pending));
3244 
3245 #ifdef DEBUG
3246 		if (rdt_entry & AV_PENDING)
3247 			apic_intr_deliver_timeouts++;
3248 #endif
3249 
3250 	/*
3251 	 * If the remote IRR bit is set, then the interrupt has been sent
3252 	 * to a CPU for processing.  We have no choice but to wait for
3253 	 * that CPU to process the interrupt, at which point the remote IRR
3254 	 * bit will be cleared.
3255 	 */
3256 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no) &
3257 	    (AV_LEVEL|AV_REMOTE_IRR)) == (AV_LEVEL|AV_REMOTE_IRR)) {
3258 
3259 		/*
3260 		 * If the CPU that this RDT is bound to is NOT the current
3261 		 * CPU, wait until that CPU handles the interrupt and ACKs
3262 		 * it.  If this interrupt is not bound to any CPU (that is,
3263 		 * if it's bound to the logical destination of "anyone"), it
3264 		 * may have been delivered to the current CPU so handle that
3265 		 * case by deferring the reprogramming (below).
3266 		 */
3267 		if ((old_bind_cpu != IRQ_UNBOUND) &&
3268 		    (old_bind_cpu != IRQ_UNINIT) &&
3269 		    (old_bind_cpu != psm_get_cpu_id())) {
3270 			for (waited = 0; waited < apic_max_reps_clear_pending;
3271 			    waited++) {
3272 				if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3273 				    intin_no) & AV_REMOTE_IRR) == 0) {
3274 
3275 					delete_defer_repro_ent(which_irq);
3276 
3277 					/* Remote IRR has cleared! */
3278 					return (0);
3279 				}
3280 			}
3281 		}
3282 
3283 		/*
3284 		 * If we waited and the Remote IRR bit is still not cleared,
3285 		 * AND if we've invoked the timeout APIC_REPROGRAM_MAX_TIMEOUTS
3286 		 * times for this interrupt, try the last-ditch workaround:
3287 		 */
3288 		if (drep && drep->tries >= APIC_REPROGRAM_MAX_TRIES) {
3289 
3290 			apic_last_ditch_clear_remote_irr(ioapic_ix, intin_no);
3291 
3292 			/* Mark this one as reprogrammed: */
3293 			delete_defer_repro_ent(which_irq);
3294 
3295 			return (0);
3296 		} else {
3297 #ifdef DEBUG
3298 			apic_intr_deferrals++;
3299 #endif
3300 
3301 			/*
3302 			 * If waiting for the Remote IRR bit (above) didn't
3303 			 * allow it to clear, defer the reprogramming.
3304 			 * Add a new deferred-programming entry if the
3305 			 * caller passed a NULL one (and update the existing one
3306 			 * in case anything changed).
3307 			 */
3308 			add_defer_repro_ent(irq_ptr, which_irq, new_bind_cpu);
3309 			if (drep)
3310 				drep->tries++;
3311 
3312 			/* Inform caller to defer IOAPIC programming: */
3313 			return (1);
3314 		}
3315 
3316 	}
3317 
3318 	/* Remote IRR is clear */
3319 	delete_defer_repro_ent(which_irq);
3320 
3321 	return (0);
3322 }
3323 
3324 /*
3325  * Called to migrate all interrupts at an irq to another cpu.
3326  * Must be called with interrupts disabled and apic_ioapic_lock held
3327  */
3328 int
3329 apic_rebind_all(apic_irq_t *irq_ptr, int bind_cpu)
3330 {
3331 	apic_irq_t	*irqptr = irq_ptr;
3332 	int		retval = 0;
3333 
3334 	while (irqptr) {
3335 		if (irqptr->airq_temp_cpu != IRQ_UNINIT)
3336 			retval |= apic_rebind(irqptr, bind_cpu, NULL);
3337 		irqptr = irqptr->airq_next;
3338 	}
3339 
3340 	return (retval);
3341 }
3342 
3343 /*
3344  * apic_intr_redistribute does all the messy computations for identifying
3345  * which interrupt to move to which CPU. Currently we do just one interrupt
3346  * at a time. This reduces the time we spent doing all this within clock
3347  * interrupt. When it is done in idle, we could do more than 1.
3348  * First we find the most busy and the most free CPU (time in ISR only)
3349  * skipping those CPUs that has been identified as being ineligible (cpu_skip)
3350  * Then we look for IRQs which are closest to the difference between the
3351  * most busy CPU and the average ISR load. We try to find one whose load
3352  * is less than difference.If none exists, then we chose one larger than the
3353  * difference, provided it does not make the most idle CPU worse than the
3354  * most busy one. In the end, we clear all the busy fields for CPUs. For
3355  * IRQs, they are cleared as they are scanned.
3356  */
3357 void
3358 apic_intr_redistribute()
3359 {
3360 	int busiest_cpu, most_free_cpu;
3361 	int cpu_free, cpu_busy, max_busy, min_busy;
3362 	int min_free, diff;
3363 	int average_busy, cpus_online;
3364 	int i, busy;
3365 	ulong_t iflag;
3366 	apic_cpus_info_t *cpu_infop;
3367 	apic_irq_t *min_busy_irq = NULL;
3368 	apic_irq_t *max_busy_irq = NULL;
3369 
3370 	busiest_cpu = most_free_cpu = -1;
3371 	cpu_free = cpu_busy = max_busy = average_busy = 0;
3372 	min_free = apic_sample_factor_redistribution;
3373 	cpus_online = 0;
3374 	/*
3375 	 * Below we will check for CPU_INTR_ENABLE, bound, temp_bound, temp_cpu
3376 	 * without ioapic_lock. That is OK as we are just doing statistical
3377 	 * sampling anyway and any inaccuracy now will get corrected next time
3378 	 * The call to rebind which actually changes things will make sure
3379 	 * we are consistent.
3380 	 */
3381 	for (i = 0; i < apic_nproc; i++) {
3382 		if (!(apic_redist_cpu_skip & (1 << i)) &&
3383 		    (apic_cpus[i].aci_status & APIC_CPU_INTR_ENABLE)) {
3384 
3385 			cpu_infop = &apic_cpus[i];
3386 			/*
3387 			 * If no unbound interrupts or only 1 total on this
3388 			 * CPU, skip
3389 			 */
3390 			if (!cpu_infop->aci_temp_bound ||
3391 			    (cpu_infop->aci_bound + cpu_infop->aci_temp_bound)
3392 			    == 1) {
3393 				apic_redist_cpu_skip |= 1 << i;
3394 				continue;
3395 			}
3396 
3397 			busy = cpu_infop->aci_busy;
3398 			average_busy += busy;
3399 			cpus_online++;
3400 			if (max_busy < busy) {
3401 				max_busy = busy;
3402 				busiest_cpu = i;
3403 			}
3404 			if (min_free > busy) {
3405 				min_free = busy;
3406 				most_free_cpu = i;
3407 			}
3408 			if (busy > apic_int_busy_mark) {
3409 				cpu_busy |= 1 << i;
3410 			} else {
3411 				if (busy < apic_int_free_mark)
3412 					cpu_free |= 1 << i;
3413 			}
3414 		}
3415 	}
3416 	if ((cpu_busy && cpu_free) ||
3417 	    (max_busy >= (min_free + apic_diff_for_redistribution))) {
3418 
3419 		apic_num_imbalance++;
3420 #ifdef	DEBUG
3421 		if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3422 			prom_printf(
3423 			    "redistribute busy=%x free=%x max=%x min=%x",
3424 			    cpu_busy, cpu_free, max_busy, min_free);
3425 		}
3426 #endif /* DEBUG */
3427 
3428 
3429 		average_busy /= cpus_online;
3430 
3431 		diff = max_busy - average_busy;
3432 		min_busy = max_busy; /* start with the max possible value */
3433 		max_busy = 0;
3434 		min_busy_irq = max_busy_irq = NULL;
3435 		i = apic_min_device_irq;
3436 		for (; i <= apic_max_device_irq; i++) {
3437 			apic_irq_t *irq_ptr;
3438 			/* Change to linked list per CPU ? */
3439 			if ((irq_ptr = apic_irq_table[i]) == NULL)
3440 				continue;
3441 			/* Check for irq_busy & decide which one to move */
3442 			/* Also zero them for next round */
3443 			if ((irq_ptr->airq_temp_cpu == busiest_cpu) &&
3444 			    irq_ptr->airq_busy) {
3445 				if (irq_ptr->airq_busy < diff) {
3446 					/*
3447 					 * Check for least busy CPU,
3448 					 * best fit or what ?
3449 					 */
3450 					if (max_busy < irq_ptr->airq_busy) {
3451 						/*
3452 						 * Most busy within the
3453 						 * required differential
3454 						 */
3455 						max_busy = irq_ptr->airq_busy;
3456 						max_busy_irq = irq_ptr;
3457 					}
3458 				} else {
3459 					if (min_busy > irq_ptr->airq_busy) {
3460 						/*
3461 						 * least busy, but more than
3462 						 * the reqd diff
3463 						 */
3464 						if (min_busy <
3465 						    (diff + average_busy -
3466 						    min_free)) {
3467 							/*
3468 							 * Making sure new cpu
3469 							 * will not end up
3470 							 * worse
3471 							 */
3472 							min_busy =
3473 							    irq_ptr->airq_busy;
3474 
3475 							min_busy_irq = irq_ptr;
3476 						}
3477 					}
3478 				}
3479 			}
3480 			irq_ptr->airq_busy = 0;
3481 		}
3482 
3483 		if (max_busy_irq != NULL) {
3484 #ifdef	DEBUG
3485 			if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3486 				prom_printf("rebinding %x to %x",
3487 				    max_busy_irq->airq_vector, most_free_cpu);
3488 			}
3489 #endif /* DEBUG */
3490 			iflag = intr_clear();
3491 			if (lock_try(&apic_ioapic_lock)) {
3492 				if (apic_rebind_all(max_busy_irq,
3493 				    most_free_cpu) == 0) {
3494 					/* Make change permenant */
3495 					max_busy_irq->airq_cpu =
3496 					    (uint32_t)most_free_cpu;
3497 				}
3498 				lock_clear(&apic_ioapic_lock);
3499 			}
3500 			intr_restore(iflag);
3501 
3502 		} else if (min_busy_irq != NULL) {
3503 #ifdef	DEBUG
3504 			if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3505 				prom_printf("rebinding %x to %x",
3506 				    min_busy_irq->airq_vector, most_free_cpu);
3507 			}
3508 #endif /* DEBUG */
3509 
3510 			iflag = intr_clear();
3511 			if (lock_try(&apic_ioapic_lock)) {
3512 				if (apic_rebind_all(min_busy_irq,
3513 				    most_free_cpu) == 0) {
3514 					/* Make change permenant */
3515 					min_busy_irq->airq_cpu =
3516 					    (uint32_t)most_free_cpu;
3517 				}
3518 				lock_clear(&apic_ioapic_lock);
3519 			}
3520 			intr_restore(iflag);
3521 
3522 		} else {
3523 			if (cpu_busy != (1 << busiest_cpu)) {
3524 				apic_redist_cpu_skip |= 1 << busiest_cpu;
3525 				/*
3526 				 * We leave cpu_skip set so that next time we
3527 				 * can choose another cpu
3528 				 */
3529 			}
3530 		}
3531 		apic_num_rebind++;
3532 	} else {
3533 		/*
3534 		 * found nothing. Could be that we skipped over valid CPUs
3535 		 * or we have balanced everything. If we had a variable
3536 		 * ticks_for_redistribution, it could be increased here.
3537 		 * apic_int_busy, int_free etc would also need to be
3538 		 * changed.
3539 		 */
3540 		if (apic_redist_cpu_skip)
3541 			apic_redist_cpu_skip = 0;
3542 	}
3543 	for (i = 0; i < apic_nproc; i++) {
3544 		apic_cpus[i].aci_busy = 0;
3545 	}
3546 }
3547 
3548 void
3549 apic_cleanup_busy()
3550 {
3551 	int i;
3552 	apic_irq_t *irq_ptr;
3553 
3554 	for (i = 0; i < apic_nproc; i++) {
3555 		apic_cpus[i].aci_busy = 0;
3556 	}
3557 
3558 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
3559 		if ((irq_ptr = apic_irq_table[i]) != NULL)
3560 			irq_ptr->airq_busy = 0;
3561 	}
3562 }
3563 
3564 
3565 static int
3566 apic_acpi_translate_pci_irq(dev_info_t *dip, int busid, int devid,
3567     int ipin, int *pci_irqp, iflag_t *intr_flagp)
3568 {
3569 
3570 	int status;
3571 	acpi_psm_lnk_t acpipsmlnk;
3572 
3573 	if ((status = acpi_get_irq_cache_ent(busid, devid, ipin, pci_irqp,
3574 	    intr_flagp)) == ACPI_PSM_SUCCESS) {
3575 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Found irqno %d "
3576 		    "from cache for device %s, instance #%d\n", psm_name,
3577 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
3578 		return (status);
3579 	}
3580 
3581 	bzero(&acpipsmlnk, sizeof (acpi_psm_lnk_t));
3582 
3583 	if ((status = acpi_translate_pci_irq(dip, ipin, pci_irqp, intr_flagp,
3584 	    &acpipsmlnk)) == ACPI_PSM_FAILURE) {
3585 		APIC_VERBOSE_IRQ((CE_WARN, "%s: "
3586 		    " acpi_translate_pci_irq failed for device %s, instance"
3587 		    " #%d", psm_name, ddi_get_name(dip),
3588 		    ddi_get_instance(dip)));
3589 		return (status);
3590 	}
3591 
3592 	if (status == ACPI_PSM_PARTIAL && acpipsmlnk.lnkobj != NULL) {
3593 		status = apic_acpi_irq_configure(&acpipsmlnk, dip, pci_irqp,
3594 		    intr_flagp);
3595 		if (status != ACPI_PSM_SUCCESS) {
3596 			status = acpi_get_current_irq_resource(&acpipsmlnk,
3597 			    pci_irqp, intr_flagp);
3598 		}
3599 	}
3600 
3601 	if (status == ACPI_PSM_SUCCESS) {
3602 		acpi_new_irq_cache_ent(busid, devid, ipin, *pci_irqp,
3603 		    intr_flagp, &acpipsmlnk);
3604 
3605 		APIC_VERBOSE_IRQ((CE_CONT, "%s: [ACPI] "
3606 		    "new irq %d for device %s, instance #%d\n", psm_name,
3607 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
3608 	}
3609 
3610 	return (status);
3611 }
3612 
3613 /*
3614  * Adds an entry to the irq list passed in, and returns the new list.
3615  * Entries are added in priority order (lower numerical priorities are
3616  * placed closer to the head of the list)
3617  */
3618 static prs_irq_list_t *
3619 acpi_insert_prs_irq_ent(prs_irq_list_t *listp, int priority, int irq,
3620     iflag_t *iflagp, acpi_prs_private_t *prsprvp)
3621 {
3622 	struct prs_irq_list_ent *newent, *prevp = NULL, *origlistp;
3623 
3624 	newent = kmem_zalloc(sizeof (struct prs_irq_list_ent), KM_SLEEP);
3625 
3626 	newent->list_prio = priority;
3627 	newent->irq = irq;
3628 	newent->intrflags = *iflagp;
3629 	newent->prsprv = *prsprvp;
3630 	/* ->next is NULL from kmem_zalloc */
3631 
3632 	/*
3633 	 * New list -- return the new entry as the list.
3634 	 */
3635 	if (listp == NULL)
3636 		return (newent);
3637 
3638 	/*
3639 	 * Save original list pointer for return (since we're not modifying
3640 	 * the head)
3641 	 */
3642 	origlistp = listp;
3643 
3644 	/*
3645 	 * Insertion sort, with entries with identical keys stored AFTER
3646 	 * existing entries (the less-than-or-equal test of priority does
3647 	 * this for us).
3648 	 */
3649 	while (listp != NULL && listp->list_prio <= priority) {
3650 		prevp = listp;
3651 		listp = listp->next;
3652 	}
3653 
3654 	newent->next = listp;
3655 
3656 	if (prevp == NULL) { /* Add at head of list (newent is the new head) */
3657 		return (newent);
3658 	} else {
3659 		prevp->next = newent;
3660 		return (origlistp);
3661 	}
3662 }
3663 
3664 /*
3665  * Frees the list passed in, deallocating all memory and leaving *listpp
3666  * set to NULL.
3667  */
3668 static void
3669 acpi_destroy_prs_irq_list(prs_irq_list_t **listpp)
3670 {
3671 	struct prs_irq_list_ent *nextp;
3672 
3673 	ASSERT(listpp != NULL);
3674 
3675 	while (*listpp != NULL) {
3676 		nextp = (*listpp)->next;
3677 		kmem_free(*listpp, sizeof (struct prs_irq_list_ent));
3678 		*listpp = nextp;
3679 	}
3680 }
3681 
3682 /*
3683  * apic_choose_irqs_from_prs returns a list of irqs selected from the list of
3684  * irqs returned by the link device's _PRS method.  The irqs are chosen
3685  * to minimize contention in situations where the interrupt link device
3686  * can be programmed to steer interrupts to different interrupt controller
3687  * inputs (some of which may already be in use).  The list is sorted in order
3688  * of irqs to use, with the highest priority given to interrupt controller
3689  * inputs that are not shared.   When an interrupt controller input
3690  * must be shared, apic_choose_irqs_from_prs adds the possible irqs to the
3691  * returned list in the order that minimizes sharing (thereby ensuring lowest
3692  * possible latency from interrupt trigger time to ISR execution time).
3693  */
3694 static prs_irq_list_t *
3695 apic_choose_irqs_from_prs(acpi_irqlist_t *irqlistent, dev_info_t *dip,
3696     int crs_irq)
3697 {
3698 	int32_t irq;
3699 	int i;
3700 	prs_irq_list_t *prsirqlistp = NULL;
3701 	iflag_t iflags;
3702 
3703 	while (irqlistent != NULL) {
3704 		irqlistent->intr_flags.bustype = BUS_PCI;
3705 
3706 		for (i = 0; i < irqlistent->num_irqs; i++) {
3707 
3708 			irq = irqlistent->irqs[i];
3709 
3710 			if (irq <= 0) {
3711 				/* invalid irq number */
3712 				continue;
3713 			}
3714 
3715 			if ((irq < 16) && (apic_reserved_irqlist[irq]))
3716 				continue;
3717 
3718 			if ((apic_irq_table[irq] == NULL) ||
3719 			    (apic_irq_table[irq]->airq_dip == dip)) {
3720 
3721 				prsirqlistp = acpi_insert_prs_irq_ent(
3722 				    prsirqlistp, 0 /* Highest priority */, irq,
3723 				    &irqlistent->intr_flags,
3724 				    &irqlistent->acpi_prs_prv);
3725 
3726 				/*
3727 				 * If we do not prefer the current irq from _CRS
3728 				 * or if we do and this irq is the same as the
3729 				 * current irq from _CRS, this is the one
3730 				 * to pick.
3731 				 */
3732 				if (!(apic_prefer_crs) || (irq == crs_irq)) {
3733 					return (prsirqlistp);
3734 				}
3735 				continue;
3736 			}
3737 
3738 			/*
3739 			 * Edge-triggered interrupts cannot be shared
3740 			 */
3741 			if (irqlistent->intr_flags.intr_el == INTR_EL_EDGE)
3742 				continue;
3743 
3744 			/*
3745 			 * To work around BIOSes that contain incorrect
3746 			 * interrupt polarity information in interrupt
3747 			 * descriptors returned by _PRS, we assume that
3748 			 * the polarity of the other device sharing this
3749 			 * interrupt controller input is compatible.
3750 			 * If it's not, the caller will catch it when
3751 			 * the caller invokes the link device's _CRS method
3752 			 * (after invoking its _SRS method).
3753 			 */
3754 			iflags = irqlistent->intr_flags;
3755 			iflags.intr_po =
3756 			    apic_irq_table[irq]->airq_iflag.intr_po;
3757 
3758 			if (!acpi_intr_compatible(iflags,
3759 			    apic_irq_table[irq]->airq_iflag)) {
3760 				APIC_VERBOSE_IRQ((CE_CONT, "!%s: irq %d "
3761 				    "not compatible [%x:%x:%x !~ %x:%x:%x]",
3762 				    psm_name, irq,
3763 				    iflags.intr_po,
3764 				    iflags.intr_el,
3765 				    iflags.bustype,
3766 				    apic_irq_table[irq]->airq_iflag.intr_po,
3767 				    apic_irq_table[irq]->airq_iflag.intr_el,
3768 				    apic_irq_table[irq]->airq_iflag.bustype));
3769 				continue;
3770 			}
3771 
3772 			/*
3773 			 * If we prefer the irq from _CRS, no need
3774 			 * to search any further (and make sure
3775 			 * to add this irq with the highest priority
3776 			 * so it's tried first).
3777 			 */
3778 			if (crs_irq == irq && apic_prefer_crs) {
3779 
3780 				return (acpi_insert_prs_irq_ent(
3781 				    prsirqlistp,
3782 				    0 /* Highest priority */,
3783 				    irq, &iflags,
3784 				    &irqlistent->acpi_prs_prv));
3785 			}
3786 
3787 			/*
3788 			 * Priority is equal to the share count (lower
3789 			 * share count is higher priority). Note that
3790 			 * the intr flags passed in here are the ones we
3791 			 * changed above -- if incorrect, it will be
3792 			 * caught by the caller's _CRS flags comparison.
3793 			 */
3794 			prsirqlistp = acpi_insert_prs_irq_ent(
3795 			    prsirqlistp,
3796 			    apic_irq_table[irq]->airq_share, irq,
3797 			    &iflags, &irqlistent->acpi_prs_prv);
3798 		}
3799 
3800 		/* Go to the next irqlist entry */
3801 		irqlistent = irqlistent->next;
3802 	}
3803 
3804 	return (prsirqlistp);
3805 }
3806 
3807 /*
3808  * Configures the irq for the interrupt link device identified by
3809  * acpipsmlnkp.
3810  *
3811  * Gets the current and the list of possible irq settings for the
3812  * device. If apic_unconditional_srs is not set, and the current
3813  * resource setting is in the list of possible irq settings,
3814  * current irq resource setting is passed to the caller.
3815  *
3816  * Otherwise, picks an irq number from the list of possible irq
3817  * settings, and sets the irq of the device to this value.
3818  * If prefer_crs is set, among a set of irq numbers in the list that have
3819  * the least number of devices sharing the interrupt, we pick current irq
3820  * resource setting if it is a member of this set.
3821  *
3822  * Passes the irq number in the value pointed to by pci_irqp, and
3823  * polarity and sensitivity in the structure pointed to by dipintrflagp
3824  * to the caller.
3825  *
3826  * Note that if setting the irq resource failed, but successfuly obtained
3827  * the current irq resource settings, passes the current irq resources
3828  * and considers it a success.
3829  *
3830  * Returns:
3831  * ACPI_PSM_SUCCESS on success.
3832  *
3833  * ACPI_PSM_FAILURE if an error occured during the configuration or
3834  * if a suitable irq was not found for this device, or if setting the
3835  * irq resource and obtaining the current resource fails.
3836  *
3837  */
3838 static int
3839 apic_acpi_irq_configure(acpi_psm_lnk_t *acpipsmlnkp, dev_info_t *dip,
3840     int *pci_irqp, iflag_t *dipintr_flagp)
3841 {
3842 	int32_t irq;
3843 	int cur_irq = -1;
3844 	acpi_irqlist_t *irqlistp;
3845 	prs_irq_list_t *prs_irq_listp, *prs_irq_entp;
3846 	boolean_t found_irq = B_FALSE;
3847 
3848 	dipintr_flagp->bustype = BUS_PCI;
3849 
3850 	if ((acpi_get_possible_irq_resources(acpipsmlnkp, &irqlistp))
3851 	    == ACPI_PSM_FAILURE) {
3852 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Unable to determine "
3853 		    "or assign IRQ for device %s, instance #%d: The system was "
3854 		    "unable to get the list of potential IRQs from ACPI.",
3855 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
3856 
3857 		return (ACPI_PSM_FAILURE);
3858 	}
3859 
3860 	if ((acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
3861 	    dipintr_flagp) == ACPI_PSM_SUCCESS) && (!apic_unconditional_srs) &&
3862 	    (cur_irq > 0)) {
3863 		/*
3864 		 * If an IRQ is set in CRS and that IRQ exists in the set
3865 		 * returned from _PRS, return that IRQ, otherwise print
3866 		 * a warning
3867 		 */
3868 
3869 		if (acpi_irqlist_find_irq(irqlistp, cur_irq, NULL)
3870 		    == ACPI_PSM_SUCCESS) {
3871 
3872 			ASSERT(pci_irqp != NULL);
3873 			*pci_irqp = cur_irq;
3874 			acpi_free_irqlist(irqlistp);
3875 			return (ACPI_PSM_SUCCESS);
3876 		}
3877 
3878 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find the "
3879 		    "current irq %d for device %s, instance #%d in ACPI's "
3880 		    "list of possible irqs for this device. Picking one from "
3881 		    " the latter list.", psm_name, cur_irq, ddi_get_name(dip),
3882 		    ddi_get_instance(dip)));
3883 	}
3884 
3885 	if ((prs_irq_listp = apic_choose_irqs_from_prs(irqlistp, dip,
3886 	    cur_irq)) == NULL) {
3887 
3888 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find a "
3889 		    "suitable irq from the list of possible irqs for device "
3890 		    "%s, instance #%d in ACPI's list of possible irqs",
3891 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
3892 
3893 		acpi_free_irqlist(irqlistp);
3894 		return (ACPI_PSM_FAILURE);
3895 	}
3896 
3897 	acpi_free_irqlist(irqlistp);
3898 
3899 	for (prs_irq_entp = prs_irq_listp;
3900 	    prs_irq_entp != NULL && found_irq == B_FALSE;
3901 	    prs_irq_entp = prs_irq_entp->next) {
3902 
3903 		acpipsmlnkp->acpi_prs_prv = prs_irq_entp->prsprv;
3904 		irq = prs_irq_entp->irq;
3905 
3906 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Setting irq %d for "
3907 		    "device %s instance #%d\n", psm_name, irq,
3908 		    ddi_get_name(dip), ddi_get_instance(dip)));
3909 
3910 		if ((acpi_set_irq_resource(acpipsmlnkp, irq))
3911 		    == ACPI_PSM_SUCCESS) {
3912 			/*
3913 			 * setting irq was successful, check to make sure CRS
3914 			 * reflects that. If CRS does not agree with what we
3915 			 * set, return the irq that was set.
3916 			 */
3917 
3918 			if (acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
3919 			    dipintr_flagp) == ACPI_PSM_SUCCESS) {
3920 
3921 				if (cur_irq != irq)
3922 					APIC_VERBOSE_IRQ((CE_WARN,
3923 					    "!%s: IRQ resource set "
3924 					    "(irqno %d) for device %s "
3925 					    "instance #%d, differs from "
3926 					    "current setting irqno %d",
3927 					    psm_name, irq, ddi_get_name(dip),
3928 					    ddi_get_instance(dip), cur_irq));
3929 			} else {
3930 				/*
3931 				 * On at least one system, there was a bug in
3932 				 * a DSDT method called by _STA, causing _STA to
3933 				 * indicate that the link device was disabled
3934 				 * (when, in fact, it was enabled).  Since _SRS
3935 				 * succeeded, assume that _CRS is lying and use
3936 				 * the iflags from this _PRS interrupt choice.
3937 				 * If we're wrong about the flags, the polarity
3938 				 * will be incorrect and we may get an interrupt
3939 				 * storm, but there's not much else we can do
3940 				 * at this point.
3941 				 */
3942 				*dipintr_flagp = prs_irq_entp->intrflags;
3943 			}
3944 
3945 			/*
3946 			 * Return the irq that was set, and not what _CRS
3947 			 * reports, since _CRS has been seen to return
3948 			 * different IRQs than what was passed to _SRS on some
3949 			 * systems (and just not return successfully on others).
3950 			 */
3951 			cur_irq = irq;
3952 			found_irq = B_TRUE;
3953 		} else {
3954 			APIC_VERBOSE_IRQ((CE_WARN, "!%s: set resource "
3955 			    "irq %d failed for device %s instance #%d",
3956 			    psm_name, irq, ddi_get_name(dip),
3957 			    ddi_get_instance(dip)));
3958 
3959 			if (cur_irq == -1) {
3960 				acpi_destroy_prs_irq_list(&prs_irq_listp);
3961 				return (ACPI_PSM_FAILURE);
3962 			}
3963 		}
3964 	}
3965 
3966 	acpi_destroy_prs_irq_list(&prs_irq_listp);
3967 
3968 	if (!found_irq)
3969 		return (ACPI_PSM_FAILURE);
3970 
3971 	ASSERT(pci_irqp != NULL);
3972 	*pci_irqp = cur_irq;
3973 	return (ACPI_PSM_SUCCESS);
3974 }
3975 
3976 void
3977 ioapic_disable_redirection()
3978 {
3979 	int ioapic_ix;
3980 	int intin_max;
3981 	int intin_ix;
3982 
3983 	/* Disable the I/O APIC redirection entries */
3984 	for (ioapic_ix = 0; ioapic_ix < apic_io_max; ioapic_ix++) {
3985 
3986 		/* Bits 23-16 define the maximum redirection entries */
3987 		intin_max = (ioapic_read(ioapic_ix, APIC_VERS_CMD) >> 16)
3988 		    & 0xff;
3989 
3990 		for (intin_ix = 0; intin_ix <= intin_max; intin_ix++) {
3991 			/*
3992 			 * The assumption here is that this is safe, even for
3993 			 * systems with IOAPICs that suffer from the hardware
3994 			 * erratum because all devices have been quiesced before
3995 			 * this function is called from apic_shutdown()
3996 			 * (or equivalent). If that assumption turns out to be
3997 			 * false, this mask operation can induce the same
3998 			 * erratum result we're trying to avoid.
3999 			 */
4000 			ioapic_write(ioapic_ix, APIC_RDT_CMD + 2 * intin_ix,
4001 			    AV_MASK);
4002 		}
4003 	}
4004 }
4005 
4006 /*
4007  * Looks for an IOAPIC with the specified physical address in the /ioapics
4008  * node in the device tree (created by the PCI enumerator).
4009  */
4010 static boolean_t
4011 apic_is_ioapic_AMD_813x(uint32_t physaddr)
4012 {
4013 	/*
4014 	 * Look in /ioapics, for the ioapic with
4015 	 * the physical address given
4016 	 */
4017 	dev_info_t *ioapicsnode = ddi_find_devinfo(IOAPICS_NODE_NAME, -1, 0);
4018 	dev_info_t *ioapic_child;
4019 	boolean_t rv = B_FALSE;
4020 	int vid, did;
4021 	uint64_t ioapic_paddr;
4022 	boolean_t done = B_FALSE;
4023 
4024 	if (ioapicsnode == NULL)
4025 		return (B_FALSE);
4026 
4027 	/* Load first child: */
4028 	ioapic_child = ddi_get_child(ioapicsnode);
4029 	while (!done && ioapic_child != 0) { /* Iterate over children */
4030 
4031 		if ((ioapic_paddr = (uint64_t)ddi_prop_get_int64(DDI_DEV_T_ANY,
4032 		    ioapic_child, DDI_PROP_DONTPASS, "reg", 0))
4033 		    != 0 && physaddr == ioapic_paddr) {
4034 
4035 			vid = ddi_prop_get_int(DDI_DEV_T_ANY, ioapic_child,
4036 			    DDI_PROP_DONTPASS, IOAPICS_PROP_VENID, 0);
4037 
4038 			if (vid == VENID_AMD) {
4039 
4040 				did = ddi_prop_get_int(DDI_DEV_T_ANY,
4041 				    ioapic_child, DDI_PROP_DONTPASS,
4042 				    IOAPICS_PROP_DEVID, 0);
4043 
4044 				if (did == DEVID_8131_IOAPIC ||
4045 				    did == DEVID_8132_IOAPIC) {
4046 
4047 					rv = B_TRUE;
4048 					done = B_TRUE;
4049 				}
4050 			}
4051 		}
4052 
4053 		if (!done)
4054 			ioapic_child = ddi_get_next_sibling(ioapic_child);
4055 	}
4056 
4057 	/* The ioapics node was held by ddi_find_devinfo, so release it */
4058 	ndi_rele_devi(ioapicsnode);
4059 	return (rv);
4060 }
4061 
4062 struct apic_state {
4063 	int32_t as_task_reg;
4064 	int32_t as_dest_reg;
4065 	int32_t as_format_reg;
4066 	int32_t as_local_timer;
4067 	int32_t as_pcint_vect;
4068 	int32_t as_int_vect0;
4069 	int32_t as_int_vect1;
4070 	int32_t as_err_vect;
4071 	int32_t as_init_count;
4072 	int32_t as_divide_reg;
4073 	int32_t as_spur_int_reg;
4074 	uint32_t as_ioapic_ids[MAX_IO_APIC];
4075 };
4076 
4077 
4078 static int
4079 apic_acpi_enter_apicmode(void)
4080 {
4081 	ACPI_OBJECT_LIST	arglist;
4082 	ACPI_OBJECT		arg;
4083 	ACPI_STATUS		status;
4084 
4085 	/* Setup parameter object */
4086 	arglist.Count = 1;
4087 	arglist.Pointer = &arg;
4088 	arg.Type = ACPI_TYPE_INTEGER;
4089 	arg.Integer.Value = ACPI_APIC_MODE;
4090 
4091 	status = AcpiEvaluateObject(NULL, "\\_PIC", &arglist, NULL);
4092 	if (ACPI_FAILURE(status))
4093 		return (PSM_FAILURE);
4094 	else
4095 		return (PSM_SUCCESS);
4096 }
4097 
4098 
4099 static void
4100 apic_save_state(struct apic_state *sp)
4101 {
4102 	int	i;
4103 	ulong_t	iflag;
4104 
4105 	PMD(PMD_SX, ("apic_save_state %p\n", (void *)sp))
4106 	/*
4107 	 * First the local APIC.
4108 	 */
4109 	sp->as_task_reg = apic_reg_ops->apic_get_pri();
4110 	sp->as_dest_reg =  apic_reg_ops->apic_read(APIC_DEST_REG);
4111 	if (apic_mode == LOCAL_APIC)
4112 		sp->as_format_reg = apic_reg_ops->apic_read(APIC_FORMAT_REG);
4113 	sp->as_local_timer = apic_reg_ops->apic_read(APIC_LOCAL_TIMER);
4114 	sp->as_pcint_vect = apic_reg_ops->apic_read(APIC_PCINT_VECT);
4115 	sp->as_int_vect0 = apic_reg_ops->apic_read(APIC_INT_VECT0);
4116 	sp->as_int_vect1 = apic_reg_ops->apic_read(APIC_INT_VECT1);
4117 	sp->as_err_vect = apic_reg_ops->apic_read(APIC_ERR_VECT);
4118 	sp->as_init_count = apic_reg_ops->apic_read(APIC_INIT_COUNT);
4119 	sp->as_divide_reg = apic_reg_ops->apic_read(APIC_DIVIDE_REG);
4120 	sp->as_spur_int_reg = apic_reg_ops->apic_read(APIC_SPUR_INT_REG);
4121 
4122 	/*
4123 	 * If on the boot processor then save the IOAPICs' IDs
4124 	 */
4125 	if (psm_get_cpu_id() == 0) {
4126 
4127 		iflag = intr_clear();
4128 		lock_set(&apic_ioapic_lock);
4129 
4130 		for (i = 0; i < apic_io_max; i++)
4131 			sp->as_ioapic_ids[i] = ioapic_read(i, APIC_ID_CMD);
4132 
4133 		lock_clear(&apic_ioapic_lock);
4134 		intr_restore(iflag);
4135 	}
4136 }
4137 
4138 static void
4139 apic_restore_state(struct apic_state *sp)
4140 {
4141 	int	i;
4142 	ulong_t	iflag;
4143 
4144 	/*
4145 	 * First the local APIC.
4146 	 */
4147 	apic_reg_ops->apic_write_task_reg(sp->as_task_reg);
4148 	if (apic_mode == LOCAL_APIC) {
4149 		apic_reg_ops->apic_write(APIC_DEST_REG, sp->as_dest_reg);
4150 		apic_reg_ops->apic_write(APIC_FORMAT_REG, sp->as_format_reg);
4151 	}
4152 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, sp->as_local_timer);
4153 	apic_reg_ops->apic_write(APIC_PCINT_VECT, sp->as_pcint_vect);
4154 	apic_reg_ops->apic_write(APIC_INT_VECT0, sp->as_int_vect0);
4155 	apic_reg_ops->apic_write(APIC_INT_VECT1, sp->as_int_vect1);
4156 	apic_reg_ops->apic_write(APIC_ERR_VECT, sp->as_err_vect);
4157 	apic_reg_ops->apic_write(APIC_INIT_COUNT, sp->as_init_count);
4158 	apic_reg_ops->apic_write(APIC_DIVIDE_REG, sp->as_divide_reg);
4159 	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, sp->as_spur_int_reg);
4160 
4161 	/*
4162 	 * the following only needs to be done once, so we do it on the
4163 	 * boot processor, since we know that we only have one of those
4164 	 */
4165 	if (psm_get_cpu_id() == 0) {
4166 
4167 		iflag = intr_clear();
4168 		lock_set(&apic_ioapic_lock);
4169 
4170 		/* Restore IOAPICs' APIC IDs */
4171 		for (i = 0; i < apic_io_max; i++) {
4172 			ioapic_write(i, APIC_ID_CMD, sp->as_ioapic_ids[i]);
4173 		}
4174 
4175 		lock_clear(&apic_ioapic_lock);
4176 		intr_restore(iflag);
4177 
4178 		/*
4179 		 * Reenter APIC mode before restoring LNK devices
4180 		 */
4181 		(void) apic_acpi_enter_apicmode();
4182 
4183 		/*
4184 		 * restore acpi link device mappings
4185 		 */
4186 		acpi_restore_link_devices();
4187 	}
4188 }
4189 
4190 /*
4191  * Returns 0 on success
4192  */
4193 int
4194 apic_state(psm_state_request_t *rp)
4195 {
4196 	PMD(PMD_SX, ("apic_state "))
4197 	switch (rp->psr_cmd) {
4198 	case PSM_STATE_ALLOC:
4199 		rp->req.psm_state_req.psr_state =
4200 		    kmem_zalloc(sizeof (struct apic_state), KM_NOSLEEP);
4201 		if (rp->req.psm_state_req.psr_state == NULL)
4202 			return (ENOMEM);
4203 		rp->req.psm_state_req.psr_state_size =
4204 		    sizeof (struct apic_state);
4205 		PMD(PMD_SX, (":STATE_ALLOC: state %p, size %lx\n",
4206 		    rp->req.psm_state_req.psr_state,
4207 		    rp->req.psm_state_req.psr_state_size))
4208 		return (0);
4209 
4210 	case PSM_STATE_FREE:
4211 		kmem_free(rp->req.psm_state_req.psr_state,
4212 		    rp->req.psm_state_req.psr_state_size);
4213 		PMD(PMD_SX, (" STATE_FREE: state %p, size %lx\n",
4214 		    rp->req.psm_state_req.psr_state,
4215 		    rp->req.psm_state_req.psr_state_size))
4216 		return (0);
4217 
4218 	case PSM_STATE_SAVE:
4219 		PMD(PMD_SX, (" STATE_SAVE: state %p, size %lx\n",
4220 		    rp->req.psm_state_req.psr_state,
4221 		    rp->req.psm_state_req.psr_state_size))
4222 		apic_save_state(rp->req.psm_state_req.psr_state);
4223 		return (0);
4224 
4225 	case PSM_STATE_RESTORE:
4226 		apic_restore_state(rp->req.psm_state_req.psr_state);
4227 		PMD(PMD_SX, (" STATE_RESTORE: state %p, size %lx\n",
4228 		    rp->req.psm_state_req.psr_state,
4229 		    rp->req.psm_state_req.psr_state_size))
4230 		return (0);
4231 
4232 	default:
4233 		return (EINVAL);
4234 	}
4235 }
4236