xref: /illumos-gate/usr/src/uts/i86pc/io/mp_platform_common.c (revision 2264ca7f5db194583c672cb5779a67f52bcd92a9)
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 2009 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_nenables(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_nenables(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 !defined(__xpv)
1690 	apic_vt_ops->apic_intrr_free_entry(irqptr);
1691 #endif
1692 
1693 	if (max_ipl == PSM_INVALID_IPL) {
1694 		ASSERT(irqheadptr == irqptr);
1695 		bind_cpu = irqptr->airq_temp_cpu;
1696 		if (((uint32_t)bind_cpu != IRQ_UNBOUND) &&
1697 		    ((uint32_t)bind_cpu != IRQ_UNINIT)) {
1698 			ASSERT((bind_cpu & ~IRQ_USER_BOUND) < apic_nproc);
1699 			if (bind_cpu & IRQ_USER_BOUND) {
1700 				/* If hardbound, temp_cpu == cpu */
1701 				bind_cpu &= ~IRQ_USER_BOUND;
1702 				apic_cpus[bind_cpu].aci_bound--;
1703 			} else
1704 				apic_cpus[bind_cpu].aci_temp_bound--;
1705 		}
1706 		irqptr->airq_temp_cpu = IRQ_UNINIT;
1707 		irqptr->airq_mps_intr_index = FREE_INDEX;
1708 		lock_clear(&apic_ioapic_lock);
1709 		intr_restore(iflag);
1710 		apic_free_vector(irqptr->airq_vector);
1711 		return (PSM_SUCCESS);
1712 	}
1713 	lock_clear(&apic_ioapic_lock);
1714 	intr_restore(iflag);
1715 
1716 	mutex_enter(&airq_mutex);
1717 	if ((irqptr == apic_irq_table[irqindex])) {
1718 		apic_irq_t	*oldirqptr;
1719 		/* Move valid irq entry to the head */
1720 		irqheadptr = oldirqptr = irqptr;
1721 		irqptr = irqptr->airq_next;
1722 		ASSERT(irqptr);
1723 		while (irqptr) {
1724 			if (irqptr->airq_mps_intr_index != FREE_INDEX)
1725 				break;
1726 			oldirqptr = irqptr;
1727 			irqptr = irqptr->airq_next;
1728 		}
1729 		/* remove all invalid ones from the beginning */
1730 		apic_irq_table[irqindex] = irqptr;
1731 		/*
1732 		 * and link them back after the head. The invalid ones
1733 		 * begin with irqheadptr and end at oldirqptr
1734 		 */
1735 		oldirqptr->airq_next = irqptr->airq_next;
1736 		irqptr->airq_next = irqheadptr;
1737 	}
1738 	mutex_exit(&airq_mutex);
1739 
1740 	irqptr->airq_temp_cpu = IRQ_UNINIT;
1741 	irqptr->airq_mps_intr_index = FREE_INDEX;
1742 
1743 	return (PSM_SUCCESS);
1744 }
1745 
1746 /*
1747  * apic_introp_xlate() replaces apic_translate_irq() and is
1748  * called only from apic_intr_ops().  With the new ADII framework,
1749  * the priority can no longer be retrieved through i_ddi_get_intrspec().
1750  * It has to be passed in from the caller.
1751  */
1752 int
1753 apic_introp_xlate(dev_info_t *dip, struct intrspec *ispec, int type)
1754 {
1755 	char dev_type[16];
1756 	int dev_len, pci_irq, newirq, bustype, devid, busid, i;
1757 	int irqno = ispec->intrspec_vec;
1758 	ddi_acc_handle_t cfg_handle;
1759 	uchar_t ipin;
1760 	struct apic_io_intr *intrp;
1761 	iflag_t intr_flag;
1762 	ACPI_SUBTABLE_HEADER	*hp;
1763 	ACPI_MADT_INTERRUPT_OVERRIDE *isop;
1764 	apic_irq_t *airqp;
1765 	int parent_is_pci_or_pciex = 0;
1766 	int child_is_pciex = 0;
1767 
1768 	DDI_INTR_IMPLDBG((CE_CONT, "apic_introp_xlate: dip=0x%p name=%s "
1769 	    "type=%d irqno=0x%x\n", (void *)dip, ddi_get_name(dip), type,
1770 	    irqno));
1771 
1772 	dev_len = sizeof (dev_type);
1773 	if (ddi_getlongprop_buf(DDI_DEV_T_ANY, ddi_get_parent(dip),
1774 	    DDI_PROP_DONTPASS, "device_type", (caddr_t)dev_type,
1775 	    &dev_len) == DDI_PROP_SUCCESS) {
1776 		if ((strcmp(dev_type, "pci") == 0) ||
1777 		    (strcmp(dev_type, "pciex") == 0))
1778 			parent_is_pci_or_pciex = 1;
1779 	}
1780 
1781 	if (ddi_getlongprop_buf(DDI_DEV_T_ANY, dip,
1782 	    DDI_PROP_DONTPASS, "compatible", (caddr_t)dev_type,
1783 	    &dev_len) == DDI_PROP_SUCCESS) {
1784 		if (strstr(dev_type, "pciex"))
1785 			child_is_pciex = 1;
1786 	}
1787 
1788 
1789 	if (DDI_INTR_IS_MSI_OR_MSIX(type)) {
1790 		if ((airqp = apic_find_irq(dip, ispec, type)) != NULL) {
1791 			airqp->airq_iflag.bustype =
1792 			    child_is_pciex ? BUS_PCIE : BUS_PCI;
1793 			return (apic_vector_to_irq[airqp->airq_vector]);
1794 		}
1795 		return (apic_setup_irq_table(dip, irqno, NULL, ispec,
1796 		    NULL, type));
1797 	}
1798 
1799 	bustype = 0;
1800 
1801 	/* check if we have already translated this irq */
1802 	mutex_enter(&airq_mutex);
1803 	newirq = apic_min_device_irq;
1804 	for (; newirq <= apic_max_device_irq; newirq++) {
1805 		airqp = apic_irq_table[newirq];
1806 		while (airqp) {
1807 			if ((airqp->airq_dip == dip) &&
1808 			    (airqp->airq_origirq == irqno) &&
1809 			    (airqp->airq_mps_intr_index != FREE_INDEX)) {
1810 
1811 				mutex_exit(&airq_mutex);
1812 				return (VIRTIRQ(newirq, airqp->airq_share_id));
1813 			}
1814 			airqp = airqp->airq_next;
1815 		}
1816 	}
1817 	mutex_exit(&airq_mutex);
1818 
1819 	if (apic_defconf)
1820 		goto defconf;
1821 
1822 	if ((dip == NULL) || (!apic_irq_translate && !apic_enable_acpi))
1823 		goto nonpci;
1824 
1825 	if (parent_is_pci_or_pciex) {
1826 		/* pci device */
1827 		if (acpica_get_bdf(dip, &busid, &devid, NULL) != 0)
1828 			goto nonpci;
1829 		if (busid == 0 && apic_pci_bus_total == 1)
1830 			busid = (int)apic_single_pci_busid;
1831 
1832 		if (pci_config_setup(dip, &cfg_handle) != DDI_SUCCESS)
1833 			goto nonpci;
1834 		ipin = pci_config_get8(cfg_handle, PCI_CONF_IPIN) - PCI_INTA;
1835 		pci_config_teardown(&cfg_handle);
1836 		if (apic_enable_acpi && !apic_use_acpi_madt_only) {
1837 			if (apic_acpi_translate_pci_irq(dip, busid, devid,
1838 			    ipin, &pci_irq, &intr_flag) != ACPI_PSM_SUCCESS)
1839 				goto nonpci;
1840 
1841 			intr_flag.bustype = child_is_pciex ? BUS_PCIE : BUS_PCI;
1842 			if ((newirq = apic_setup_irq_table(dip, pci_irq, NULL,
1843 			    ispec, &intr_flag, type)) == -1)
1844 				goto nonpci;
1845 			return (newirq);
1846 		} else {
1847 			pci_irq = ((devid & 0x1f) << 2) | (ipin & 0x3);
1848 			if ((intrp = apic_find_io_intr_w_busid(pci_irq, busid))
1849 			    == NULL) {
1850 				if ((pci_irq = apic_handle_pci_pci_bridge(dip,
1851 				    devid, ipin, &intrp)) == -1)
1852 					goto nonpci;
1853 			}
1854 			if ((newirq = apic_setup_irq_table(dip, pci_irq, intrp,
1855 			    ispec, NULL, type)) == -1)
1856 				goto nonpci;
1857 			return (newirq);
1858 		}
1859 	} else if (strcmp(dev_type, "isa") == 0)
1860 		bustype = BUS_ISA;
1861 	else if (strcmp(dev_type, "eisa") == 0)
1862 		bustype = BUS_EISA;
1863 
1864 nonpci:
1865 	if (apic_enable_acpi && !apic_use_acpi_madt_only) {
1866 		/* search iso entries first */
1867 		if (acpi_iso_cnt != 0) {
1868 			hp = (ACPI_SUBTABLE_HEADER *)acpi_isop;
1869 			i = 0;
1870 			while (i < acpi_iso_cnt) {
1871 				if (hp->Type ==
1872 				    ACPI_MADT_TYPE_INTERRUPT_OVERRIDE) {
1873 					isop =
1874 					    (ACPI_MADT_INTERRUPT_OVERRIDE *) hp;
1875 					if (isop->Bus == 0 &&
1876 					    isop->SourceIrq == irqno) {
1877 						newirq = isop->GlobalIrq;
1878 						intr_flag.intr_po =
1879 						    isop->IntiFlags &
1880 						    ACPI_MADT_POLARITY_MASK;
1881 						intr_flag.intr_el =
1882 						    (isop->IntiFlags &
1883 						    ACPI_MADT_TRIGGER_MASK)
1884 						    >> 2;
1885 						intr_flag.bustype = BUS_ISA;
1886 
1887 						return (apic_setup_irq_table(
1888 						    dip, newirq, NULL, ispec,
1889 						    &intr_flag, type));
1890 
1891 					}
1892 					i++;
1893 				}
1894 				hp = (ACPI_SUBTABLE_HEADER *)(((char *)hp) +
1895 				    hp->Length);
1896 			}
1897 		}
1898 		intr_flag.intr_po = INTR_PO_ACTIVE_HIGH;
1899 		intr_flag.intr_el = INTR_EL_EDGE;
1900 		intr_flag.bustype = BUS_ISA;
1901 		return (apic_setup_irq_table(dip, irqno, NULL, ispec,
1902 		    &intr_flag, type));
1903 	} else {
1904 		if (bustype == 0)
1905 			bustype = eisa_level_intr_mask ? BUS_EISA : BUS_ISA;
1906 		for (i = 0; i < 2; i++) {
1907 			if (((busid = apic_find_bus_id(bustype)) != -1) &&
1908 			    ((intrp = apic_find_io_intr_w_busid(irqno, busid))
1909 			    != NULL)) {
1910 				if ((newirq = apic_setup_irq_table(dip, irqno,
1911 				    intrp, ispec, NULL, type)) != -1) {
1912 					return (newirq);
1913 				}
1914 				goto defconf;
1915 			}
1916 			bustype = (bustype == BUS_EISA) ? BUS_ISA : BUS_EISA;
1917 		}
1918 	}
1919 
1920 /* MPS default configuration */
1921 defconf:
1922 	newirq = apic_setup_irq_table(dip, irqno, NULL, ispec, NULL, type);
1923 	if (newirq == -1)
1924 		return (newirq);
1925 	ASSERT(IRQINDEX(newirq) == irqno);
1926 	ASSERT(apic_irq_table[irqno]);
1927 	return (newirq);
1928 }
1929 
1930 
1931 
1932 
1933 
1934 
1935 /*
1936  * On machines with PCI-PCI bridges, a device behind a PCI-PCI bridge
1937  * needs special handling.  We may need to chase up the device tree,
1938  * using the PCI-PCI Bridge specification's "rotating IPIN assumptions",
1939  * to find the IPIN at the root bus that relates to the IPIN on the
1940  * subsidiary bus (for ACPI or MP).  We may, however, have an entry
1941  * in the MP table or the ACPI namespace for this device itself.
1942  * We handle both cases in the search below.
1943  */
1944 /* this is the non-acpi version */
1945 static int
1946 apic_handle_pci_pci_bridge(dev_info_t *idip, int child_devno, int child_ipin,
1947 			struct apic_io_intr **intrp)
1948 {
1949 	dev_info_t *dipp, *dip;
1950 	int pci_irq;
1951 	ddi_acc_handle_t cfg_handle;
1952 	int bridge_devno, bridge_bus;
1953 	int ipin;
1954 
1955 	dip = idip;
1956 
1957 	/*CONSTCOND*/
1958 	while (1) {
1959 		if (((dipp = ddi_get_parent(dip)) == (dev_info_t *)NULL) ||
1960 		    (pci_config_setup(dipp, &cfg_handle) != DDI_SUCCESS))
1961 			return (-1);
1962 		if ((pci_config_get8(cfg_handle, PCI_CONF_BASCLASS) ==
1963 		    PCI_CLASS_BRIDGE) && (pci_config_get8(cfg_handle,
1964 		    PCI_CONF_SUBCLASS) == PCI_BRIDGE_PCI)) {
1965 			pci_config_teardown(&cfg_handle);
1966 			if (acpica_get_bdf(dipp, &bridge_bus, &bridge_devno,
1967 			    NULL) != 0)
1968 				return (-1);
1969 			/*
1970 			 * This is the rotating scheme documented in the
1971 			 * PCI-to-PCI spec.  If the PCI-to-PCI bridge is
1972 			 * behind another PCI-to-PCI bridge, then it needs
1973 			 * to keep ascending until an interrupt entry is
1974 			 * found or the root is reached.
1975 			 */
1976 			ipin = (child_devno + child_ipin) % PCI_INTD;
1977 				if (bridge_bus == 0 && apic_pci_bus_total == 1)
1978 					bridge_bus = (int)apic_single_pci_busid;
1979 				pci_irq = ((bridge_devno & 0x1f) << 2) |
1980 				    (ipin & 0x3);
1981 				if ((*intrp = apic_find_io_intr_w_busid(pci_irq,
1982 				    bridge_bus)) != NULL) {
1983 					return (pci_irq);
1984 				}
1985 			dip = dipp;
1986 			child_devno = bridge_devno;
1987 			child_ipin = ipin;
1988 		} else {
1989 			pci_config_teardown(&cfg_handle);
1990 			return (-1);
1991 		}
1992 	}
1993 	/*LINTED: function will not fall off the bottom */
1994 }
1995 
1996 
1997 
1998 
1999 static uchar_t
2000 acpi_find_ioapic(int irq)
2001 {
2002 	int i;
2003 
2004 	for (i = 0; i < apic_io_max; i++) {
2005 		if (irq >= apic_io_vectbase[i] && irq <= apic_io_vectend[i])
2006 			return (i);
2007 	}
2008 	return (0xFF);	/* shouldn't happen */
2009 }
2010 
2011 /*
2012  * See if two irqs are compatible for sharing a vector.
2013  * Currently we only support sharing of PCI devices.
2014  */
2015 static int
2016 acpi_intr_compatible(iflag_t iflag1, iflag_t iflag2)
2017 {
2018 	uint_t	level1, po1;
2019 	uint_t	level2, po2;
2020 
2021 	/* Assume active high by default */
2022 	po1 = 0;
2023 	po2 = 0;
2024 
2025 	if (iflag1.bustype != iflag2.bustype || iflag1.bustype != BUS_PCI)
2026 		return (0);
2027 
2028 	if (iflag1.intr_el == INTR_EL_CONFORM)
2029 		level1 = AV_LEVEL;
2030 	else
2031 		level1 = (iflag1.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
2032 
2033 	if (level1 && ((iflag1.intr_po == INTR_PO_ACTIVE_LOW) ||
2034 	    (iflag1.intr_po == INTR_PO_CONFORM)))
2035 		po1 = AV_ACTIVE_LOW;
2036 
2037 	if (iflag2.intr_el == INTR_EL_CONFORM)
2038 		level2 = AV_LEVEL;
2039 	else
2040 		level2 = (iflag2.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
2041 
2042 	if (level2 && ((iflag2.intr_po == INTR_PO_ACTIVE_LOW) ||
2043 	    (iflag2.intr_po == INTR_PO_CONFORM)))
2044 		po2 = AV_ACTIVE_LOW;
2045 
2046 	if ((level1 == level2) && (po1 == po2))
2047 		return (1);
2048 
2049 	return (0);
2050 }
2051 
2052 /*
2053  * Attempt to share vector with someone else
2054  */
2055 static int
2056 apic_share_vector(int irqno, iflag_t *intr_flagp, short intr_index, int ipl,
2057 	uchar_t ioapicindex, uchar_t ipin, apic_irq_t **irqptrp)
2058 {
2059 #ifdef DEBUG
2060 	apic_irq_t *tmpirqp = NULL;
2061 #endif /* DEBUG */
2062 	apic_irq_t *irqptr, dummyirq;
2063 	int	newirq, chosen_irq = -1, share = 127;
2064 	int	lowest, highest, i;
2065 	uchar_t	share_id;
2066 
2067 	DDI_INTR_IMPLDBG((CE_CONT, "apic_share_vector: irqno=0x%x "
2068 	    "intr_index=0x%x ipl=0x%x\n", irqno, intr_index, ipl));
2069 
2070 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
2071 	lowest = apic_ipltopri[ipl-1] + APIC_VECTOR_PER_IPL;
2072 
2073 	if (highest < lowest) /* Both ipl and ipl-1 map to same pri */
2074 		lowest -= APIC_VECTOR_PER_IPL;
2075 	dummyirq.airq_mps_intr_index = intr_index;
2076 	dummyirq.airq_ioapicindex = ioapicindex;
2077 	dummyirq.airq_intin_no = ipin;
2078 	if (intr_flagp)
2079 		dummyirq.airq_iflag = *intr_flagp;
2080 	apic_record_rdt_entry(&dummyirq, irqno);
2081 	for (i = lowest; i <= highest; i++) {
2082 		newirq = apic_vector_to_irq[i];
2083 		if (newirq == APIC_RESV_IRQ)
2084 			continue;
2085 		irqptr = apic_irq_table[newirq];
2086 
2087 		if ((dummyirq.airq_rdt_entry & 0xFF00) !=
2088 		    (irqptr->airq_rdt_entry & 0xFF00))
2089 			/* not compatible */
2090 			continue;
2091 
2092 		if (irqptr->airq_share < share) {
2093 			share = irqptr->airq_share;
2094 			chosen_irq = newirq;
2095 		}
2096 	}
2097 	if (chosen_irq != -1) {
2098 		/*
2099 		 * Assign a share id which is free or which is larger
2100 		 * than the largest one.
2101 		 */
2102 		share_id = 1;
2103 		mutex_enter(&airq_mutex);
2104 		irqptr = apic_irq_table[chosen_irq];
2105 		while (irqptr) {
2106 			if (irqptr->airq_mps_intr_index == FREE_INDEX) {
2107 				share_id = irqptr->airq_share_id;
2108 				break;
2109 			}
2110 			if (share_id <= irqptr->airq_share_id)
2111 				share_id = irqptr->airq_share_id + 1;
2112 #ifdef DEBUG
2113 			tmpirqp = irqptr;
2114 #endif /* DEBUG */
2115 			irqptr = irqptr->airq_next;
2116 		}
2117 		if (!irqptr) {
2118 			irqptr = kmem_zalloc(sizeof (apic_irq_t), KM_SLEEP);
2119 			irqptr->airq_temp_cpu = IRQ_UNINIT;
2120 			irqptr->airq_next =
2121 			    apic_irq_table[chosen_irq]->airq_next;
2122 			apic_irq_table[chosen_irq]->airq_next = irqptr;
2123 #ifdef	DEBUG
2124 			tmpirqp = apic_irq_table[chosen_irq];
2125 #endif /* DEBUG */
2126 		}
2127 		irqptr->airq_mps_intr_index = intr_index;
2128 		irqptr->airq_ioapicindex = ioapicindex;
2129 		irqptr->airq_intin_no = ipin;
2130 		if (intr_flagp)
2131 			irqptr->airq_iflag = *intr_flagp;
2132 		irqptr->airq_vector = apic_irq_table[chosen_irq]->airq_vector;
2133 		irqptr->airq_share_id = share_id;
2134 		apic_record_rdt_entry(irqptr, irqno);
2135 		*irqptrp = irqptr;
2136 #ifdef	DEBUG
2137 		/* shuffle the pointers to test apic_delspl path */
2138 		if (tmpirqp) {
2139 			tmpirqp->airq_next = irqptr->airq_next;
2140 			irqptr->airq_next = apic_irq_table[chosen_irq];
2141 			apic_irq_table[chosen_irq] = irqptr;
2142 		}
2143 #endif /* DEBUG */
2144 		mutex_exit(&airq_mutex);
2145 		return (VIRTIRQ(chosen_irq, share_id));
2146 	}
2147 	return (-1);
2148 }
2149 
2150 /*
2151  *
2152  */
2153 static int
2154 apic_setup_irq_table(dev_info_t *dip, int irqno, struct apic_io_intr *intrp,
2155     struct intrspec *ispec, iflag_t *intr_flagp, int type)
2156 {
2157 	int origirq = ispec->intrspec_vec;
2158 	uchar_t ipl = ispec->intrspec_pri;
2159 	int	newirq, intr_index;
2160 	uchar_t	ipin, ioapic, ioapicindex, vector;
2161 	apic_irq_t *irqptr;
2162 	major_t	major;
2163 	dev_info_t	*sdip;
2164 
2165 	DDI_INTR_IMPLDBG((CE_CONT, "apic_setup_irq_table: dip=0x%p type=%d "
2166 	    "irqno=0x%x origirq=0x%x\n", (void *)dip, type, irqno, origirq));
2167 
2168 	ASSERT(ispec != NULL);
2169 
2170 	major =  (dip != NULL) ? ddi_driver_major(dip) : 0;
2171 
2172 	if (DDI_INTR_IS_MSI_OR_MSIX(type)) {
2173 		/* MSI/X doesn't need to setup ioapic stuffs */
2174 		ioapicindex = 0xff;
2175 		ioapic = 0xff;
2176 		ipin = (uchar_t)0xff;
2177 		intr_index = (type == DDI_INTR_TYPE_MSI) ? MSI_INDEX :
2178 		    MSIX_INDEX;
2179 		mutex_enter(&airq_mutex);
2180 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) == -1) {
2181 			mutex_exit(&airq_mutex);
2182 			/* need an irq for MSI/X to index into autovect[] */
2183 			cmn_err(CE_WARN, "No interrupt irq: %s instance %d",
2184 			    ddi_get_name(dip), ddi_get_instance(dip));
2185 			return (-1);
2186 		}
2187 		mutex_exit(&airq_mutex);
2188 
2189 	} else if (intrp != NULL) {
2190 		intr_index = (int)(intrp - apic_io_intrp);
2191 		ioapic = intrp->intr_destid;
2192 		ipin = intrp->intr_destintin;
2193 		/* Find ioapicindex. If destid was ALL, we will exit with 0. */
2194 		for (ioapicindex = apic_io_max - 1; ioapicindex; ioapicindex--)
2195 			if (apic_io_id[ioapicindex] == ioapic)
2196 				break;
2197 		ASSERT((ioapic == apic_io_id[ioapicindex]) ||
2198 		    (ioapic == INTR_ALL_APIC));
2199 
2200 		/* check whether this intin# has been used by another irqno */
2201 		if ((newirq = apic_find_intin(ioapicindex, ipin)) != -1) {
2202 			return (newirq);
2203 		}
2204 
2205 	} else if (intr_flagp != NULL) {
2206 		/* ACPI case */
2207 		intr_index = ACPI_INDEX;
2208 		ioapicindex = acpi_find_ioapic(irqno);
2209 		ASSERT(ioapicindex != 0xFF);
2210 		ioapic = apic_io_id[ioapicindex];
2211 		ipin = irqno - apic_io_vectbase[ioapicindex];
2212 		if (apic_irq_table[irqno] &&
2213 		    apic_irq_table[irqno]->airq_mps_intr_index == ACPI_INDEX) {
2214 			ASSERT(apic_irq_table[irqno]->airq_intin_no == ipin &&
2215 			    apic_irq_table[irqno]->airq_ioapicindex ==
2216 			    ioapicindex);
2217 			return (irqno);
2218 		}
2219 
2220 	} else {
2221 		/* default configuration */
2222 		ioapicindex = 0;
2223 		ioapic = apic_io_id[ioapicindex];
2224 		ipin = (uchar_t)irqno;
2225 		intr_index = DEFAULT_INDEX;
2226 	}
2227 
2228 	if (ispec == NULL) {
2229 		APIC_VERBOSE_IOAPIC((CE_WARN, "No intrspec for irqno = %x\n",
2230 		    irqno));
2231 	} else if ((vector = apic_allocate_vector(ipl, irqno, 0)) == 0) {
2232 		if ((newirq = apic_share_vector(irqno, intr_flagp, intr_index,
2233 		    ipl, ioapicindex, ipin, &irqptr)) != -1) {
2234 			irqptr->airq_ipl = ipl;
2235 			irqptr->airq_origirq = (uchar_t)origirq;
2236 			irqptr->airq_dip = dip;
2237 			irqptr->airq_major = major;
2238 			sdip = apic_irq_table[IRQINDEX(newirq)]->airq_dip;
2239 			/* This is OK to do really */
2240 			if (sdip == NULL) {
2241 				cmn_err(CE_WARN, "Sharing vectors: %s"
2242 				    " instance %d and SCI",
2243 				    ddi_get_name(dip), ddi_get_instance(dip));
2244 			} else {
2245 				cmn_err(CE_WARN, "Sharing vectors: %s"
2246 				    " instance %d and %s instance %d",
2247 				    ddi_get_name(sdip), ddi_get_instance(sdip),
2248 				    ddi_get_name(dip), ddi_get_instance(dip));
2249 			}
2250 			return (newirq);
2251 		}
2252 		/* try high priority allocation now  that share has failed */
2253 		if ((vector = apic_allocate_vector(ipl, irqno, 1)) == 0) {
2254 			cmn_err(CE_WARN, "No interrupt vector: %s instance %d",
2255 			    ddi_get_name(dip), ddi_get_instance(dip));
2256 			return (-1);
2257 		}
2258 	}
2259 
2260 	mutex_enter(&airq_mutex);
2261 	if (apic_irq_table[irqno] == NULL) {
2262 		irqptr = kmem_zalloc(sizeof (apic_irq_t), KM_SLEEP);
2263 		irqptr->airq_temp_cpu = IRQ_UNINIT;
2264 		apic_irq_table[irqno] = irqptr;
2265 	} else {
2266 		irqptr = apic_irq_table[irqno];
2267 		if (irqptr->airq_mps_intr_index != FREE_INDEX) {
2268 			/*
2269 			 * The slot is used by another irqno, so allocate
2270 			 * a free irqno for this interrupt
2271 			 */
2272 			newirq = apic_allocate_irq(apic_first_avail_irq);
2273 			if (newirq == -1) {
2274 				mutex_exit(&airq_mutex);
2275 				return (-1);
2276 			}
2277 			irqno = newirq;
2278 			irqptr = apic_irq_table[irqno];
2279 			if (irqptr == NULL) {
2280 				irqptr = kmem_zalloc(sizeof (apic_irq_t),
2281 				    KM_SLEEP);
2282 				irqptr->airq_temp_cpu = IRQ_UNINIT;
2283 				apic_irq_table[irqno] = irqptr;
2284 			}
2285 			vector = apic_modify_vector(vector, newirq);
2286 		}
2287 	}
2288 	apic_max_device_irq = max(irqno, apic_max_device_irq);
2289 	apic_min_device_irq = min(irqno, apic_min_device_irq);
2290 	mutex_exit(&airq_mutex);
2291 	irqptr->airq_ioapicindex = ioapicindex;
2292 	irqptr->airq_intin_no = ipin;
2293 	irqptr->airq_ipl = ipl;
2294 	irqptr->airq_vector = vector;
2295 	irqptr->airq_origirq = (uchar_t)origirq;
2296 	irqptr->airq_share_id = 0;
2297 	irqptr->airq_mps_intr_index = (short)intr_index;
2298 	irqptr->airq_dip = dip;
2299 	irqptr->airq_major = major;
2300 	irqptr->airq_cpu = apic_bind_intr(dip, irqno, ioapic, ipin);
2301 	if (intr_flagp)
2302 		irqptr->airq_iflag = *intr_flagp;
2303 
2304 	if (!DDI_INTR_IS_MSI_OR_MSIX(type)) {
2305 		/* setup I/O APIC entry for non-MSI/X interrupts */
2306 		apic_record_rdt_entry(irqptr, irqno);
2307 	}
2308 	return (irqno);
2309 }
2310 
2311 /*
2312  * return the cpu to which this intr should be bound.
2313  * Check properties or any other mechanism to see if user wants it
2314  * bound to a specific CPU. If so, return the cpu id with high bit set.
2315  * If not, use the policy to choose a cpu and return the id.
2316  */
2317 uint32_t
2318 apic_bind_intr(dev_info_t *dip, int irq, uchar_t ioapicid, uchar_t intin)
2319 {
2320 	int	instance, instno, prop_len, bind_cpu, count;
2321 	uint_t	i, rc;
2322 	uint32_t cpu;
2323 	major_t	major;
2324 	char	*name, *drv_name, *prop_val, *cptr;
2325 	char	prop_name[32];
2326 
2327 
2328 	if (apic_intr_policy == INTR_LOWEST_PRIORITY)
2329 		return (IRQ_UNBOUND);
2330 
2331 	if (apic_nproc == 1)
2332 		return (0);
2333 
2334 	drv_name = NULL;
2335 	rc = DDI_PROP_NOT_FOUND;
2336 	major = (major_t)-1;
2337 	if (dip != NULL) {
2338 		name = ddi_get_name(dip);
2339 		major = ddi_name_to_major(name);
2340 		drv_name = ddi_major_to_name(major);
2341 		instance = ddi_get_instance(dip);
2342 		if (apic_intr_policy == INTR_ROUND_ROBIN_WITH_AFFINITY) {
2343 			i = apic_min_device_irq;
2344 			for (; i <= apic_max_device_irq; i++) {
2345 
2346 				if ((i == irq) || (apic_irq_table[i] == NULL) ||
2347 				    (apic_irq_table[i]->airq_mps_intr_index
2348 				    == FREE_INDEX))
2349 					continue;
2350 
2351 				if ((apic_irq_table[i]->airq_major == major) &&
2352 				    (!(apic_irq_table[i]->airq_cpu &
2353 				    IRQ_USER_BOUND))) {
2354 
2355 					cpu = apic_irq_table[i]->airq_cpu;
2356 
2357 					cmn_err(CE_CONT,
2358 					    "!%s: %s (%s) instance #%d "
2359 					    "vector 0x%x ioapic 0x%x "
2360 					    "intin 0x%x is bound to cpu %d\n",
2361 					    psm_name,
2362 					    name, drv_name, instance, irq,
2363 					    ioapicid, intin, cpu);
2364 					return (cpu);
2365 				}
2366 			}
2367 		}
2368 		/*
2369 		 * search for "drvname"_intpt_bind_cpus property first, the
2370 		 * syntax of the property should be "a[,b,c,...]" where
2371 		 * instance 0 binds to cpu a, instance 1 binds to cpu b,
2372 		 * instance 3 binds to cpu c...
2373 		 * ddi_getlongprop() will search /option first, then /
2374 		 * if "drvname"_intpt_bind_cpus doesn't exist, then find
2375 		 * intpt_bind_cpus property.  The syntax is the same, and
2376 		 * it applies to all the devices if its "drvname" specific
2377 		 * property doesn't exist
2378 		 */
2379 		(void) strcpy(prop_name, drv_name);
2380 		(void) strcat(prop_name, "_intpt_bind_cpus");
2381 		rc = ddi_getlongprop(DDI_DEV_T_ANY, dip, 0, prop_name,
2382 		    (caddr_t)&prop_val, &prop_len);
2383 		if (rc != DDI_PROP_SUCCESS) {
2384 			rc = ddi_getlongprop(DDI_DEV_T_ANY, dip, 0,
2385 			    "intpt_bind_cpus", (caddr_t)&prop_val, &prop_len);
2386 		}
2387 	}
2388 	if (rc == DDI_PROP_SUCCESS) {
2389 		for (i = count = 0; i < (prop_len - 1); i++)
2390 			if (prop_val[i] == ',')
2391 				count++;
2392 		if (prop_val[i-1] != ',')
2393 			count++;
2394 		/*
2395 		 * if somehow the binding instances defined in the
2396 		 * property are not enough for this instno., then
2397 		 * reuse the pattern for the next instance until
2398 		 * it reaches the requested instno
2399 		 */
2400 		instno = instance % count;
2401 		i = 0;
2402 		cptr = prop_val;
2403 		while (i < instno)
2404 			if (*cptr++ == ',')
2405 				i++;
2406 		bind_cpu = stoi(&cptr);
2407 		kmem_free(prop_val, prop_len);
2408 		/* if specific cpu is bogus, then default to cpu 0 */
2409 		if (bind_cpu >= apic_nproc) {
2410 			cmn_err(CE_WARN, "%s: %s=%s: CPU %d not present",
2411 			    psm_name, prop_name, prop_val, bind_cpu);
2412 			bind_cpu = 0;
2413 		} else {
2414 			/* indicate that we are bound at user request */
2415 			bind_cpu |= IRQ_USER_BOUND;
2416 		}
2417 		/*
2418 		 * no need to check apic_cpus[].aci_status, if specific cpu is
2419 		 * not up, then post_cpu_start will handle it.
2420 		 */
2421 	} else {
2422 		bind_cpu = apic_next_bind_cpu++;
2423 		if (bind_cpu >= apic_nproc) {
2424 			apic_next_bind_cpu = 1;
2425 			bind_cpu = 0;
2426 		}
2427 	}
2428 	if (drv_name != NULL)
2429 		cmn_err(CE_CONT, "!%s: %s (%s) instance %d "
2430 		    "vector 0x%x ioapic 0x%x intin 0x%x is bound to cpu %d\n",
2431 		    psm_name, name, drv_name, instance,
2432 		    irq, ioapicid, intin, bind_cpu & ~IRQ_USER_BOUND);
2433 	else
2434 		cmn_err(CE_CONT, "!%s: "
2435 		    "vector 0x%x ioapic 0x%x intin 0x%x is bound to cpu %d\n",
2436 		    psm_name, irq, ioapicid, intin, bind_cpu & ~IRQ_USER_BOUND);
2437 
2438 	return ((uint32_t)bind_cpu);
2439 }
2440 
2441 static struct apic_io_intr *
2442 apic_find_io_intr_w_busid(int irqno, int busid)
2443 {
2444 	struct	apic_io_intr	*intrp;
2445 
2446 	/*
2447 	 * It can have more than 1 entry with same source bus IRQ,
2448 	 * but unique with the source bus id
2449 	 */
2450 	intrp = apic_io_intrp;
2451 	if (intrp != NULL) {
2452 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
2453 			if (intrp->intr_irq == irqno &&
2454 			    intrp->intr_busid == busid &&
2455 			    intrp->intr_type == IO_INTR_INT)
2456 				return (intrp);
2457 			intrp++;
2458 		}
2459 	}
2460 	APIC_VERBOSE_IOAPIC((CE_NOTE, "Did not find io intr for irqno:"
2461 	    "busid %x:%x\n", irqno, busid));
2462 	return ((struct apic_io_intr *)NULL);
2463 }
2464 
2465 
2466 struct mps_bus_info {
2467 	char	*bus_name;
2468 	int	bus_id;
2469 } bus_info_array[] = {
2470 	"ISA ", BUS_ISA,
2471 	"PCI ", BUS_PCI,
2472 	"EISA ", BUS_EISA,
2473 	"XPRESS", BUS_XPRESS,
2474 	"PCMCIA", BUS_PCMCIA,
2475 	"VL ", BUS_VL,
2476 	"CBUS ", BUS_CBUS,
2477 	"CBUSII", BUS_CBUSII,
2478 	"FUTURE", BUS_FUTURE,
2479 	"INTERN", BUS_INTERN,
2480 	"MBI ", BUS_MBI,
2481 	"MBII ", BUS_MBII,
2482 	"MPI ", BUS_MPI,
2483 	"MPSA ", BUS_MPSA,
2484 	"NUBUS ", BUS_NUBUS,
2485 	"TC ", BUS_TC,
2486 	"VME ", BUS_VME,
2487 	"PCI-E ", BUS_PCIE
2488 };
2489 
2490 static int
2491 apic_find_bus_type(char *bus)
2492 {
2493 	int	i = 0;
2494 
2495 	for (; i < sizeof (bus_info_array)/sizeof (struct mps_bus_info); i++)
2496 		if (strncmp(bus, bus_info_array[i].bus_name,
2497 		    strlen(bus_info_array[i].bus_name)) == 0)
2498 			return (bus_info_array[i].bus_id);
2499 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus type for bus %s", bus));
2500 	return (0);
2501 }
2502 
2503 static int
2504 apic_find_bus(int busid)
2505 {
2506 	struct	apic_bus	*busp;
2507 
2508 	busp = apic_busp;
2509 	while (busp->bus_entry == APIC_BUS_ENTRY) {
2510 		if (busp->bus_id == busid)
2511 			return (apic_find_bus_type((char *)&busp->bus_str1));
2512 		busp++;
2513 	}
2514 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus for bus id %x", busid));
2515 	return (0);
2516 }
2517 
2518 static int
2519 apic_find_bus_id(int bustype)
2520 {
2521 	struct	apic_bus	*busp;
2522 
2523 	busp = apic_busp;
2524 	while (busp->bus_entry == APIC_BUS_ENTRY) {
2525 		if (apic_find_bus_type((char *)&busp->bus_str1) == bustype)
2526 			return (busp->bus_id);
2527 		busp++;
2528 	}
2529 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus id for bustype %x",
2530 	    bustype));
2531 	return (-1);
2532 }
2533 
2534 /*
2535  * Check if a particular irq need to be reserved for any io_intr
2536  */
2537 static struct apic_io_intr *
2538 apic_find_io_intr(int irqno)
2539 {
2540 	struct	apic_io_intr	*intrp;
2541 
2542 	intrp = apic_io_intrp;
2543 	if (intrp != NULL) {
2544 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
2545 			if (intrp->intr_irq == irqno &&
2546 			    intrp->intr_type == IO_INTR_INT)
2547 				return (intrp);
2548 			intrp++;
2549 		}
2550 	}
2551 	return ((struct apic_io_intr *)NULL);
2552 }
2553 
2554 /*
2555  * Check if the given ioapicindex intin combination has already been assigned
2556  * an irq. If so return irqno. Else -1
2557  */
2558 static int
2559 apic_find_intin(uchar_t ioapic, uchar_t intin)
2560 {
2561 	apic_irq_t *irqptr;
2562 	int	i;
2563 
2564 	/* find ioapic and intin in the apic_irq_table[] and return the index */
2565 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
2566 		irqptr = apic_irq_table[i];
2567 		while (irqptr) {
2568 			if ((irqptr->airq_mps_intr_index >= 0) &&
2569 			    (irqptr->airq_intin_no == intin) &&
2570 			    (irqptr->airq_ioapicindex == ioapic)) {
2571 				APIC_VERBOSE_IOAPIC((CE_NOTE, "!Found irq "
2572 				    "entry for ioapic:intin %x:%x "
2573 				    "shared interrupts ?", ioapic, intin));
2574 				return (i);
2575 			}
2576 			irqptr = irqptr->airq_next;
2577 		}
2578 	}
2579 	return (-1);
2580 }
2581 
2582 int
2583 apic_allocate_irq(int irq)
2584 {
2585 	int	freeirq, i;
2586 
2587 	if ((freeirq = apic_find_free_irq(irq, (APIC_RESV_IRQ - 1))) == -1)
2588 		if ((freeirq = apic_find_free_irq(APIC_FIRST_FREE_IRQ,
2589 		    (irq - 1))) == -1) {
2590 			/*
2591 			 * if BIOS really defines every single irq in the mps
2592 			 * table, then don't worry about conflicting with
2593 			 * them, just use any free slot in apic_irq_table
2594 			 */
2595 			for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
2596 				if ((apic_irq_table[i] == NULL) ||
2597 				    apic_irq_table[i]->airq_mps_intr_index ==
2598 				    FREE_INDEX) {
2599 				freeirq = i;
2600 				break;
2601 			}
2602 		}
2603 		if (freeirq == -1) {
2604 			/* This shouldn't happen, but just in case */
2605 			cmn_err(CE_WARN, "%s: NO available IRQ", psm_name);
2606 			return (-1);
2607 		}
2608 	}
2609 	if (apic_irq_table[freeirq] == NULL) {
2610 		apic_irq_table[freeirq] =
2611 		    kmem_zalloc(sizeof (apic_irq_t), KM_NOSLEEP);
2612 		if (apic_irq_table[freeirq] == NULL) {
2613 			cmn_err(CE_WARN, "%s: NO memory to allocate IRQ",
2614 			    psm_name);
2615 			return (-1);
2616 		}
2617 		apic_irq_table[freeirq]->airq_mps_intr_index = FREE_INDEX;
2618 	}
2619 	return (freeirq);
2620 }
2621 
2622 static int
2623 apic_find_free_irq(int start, int end)
2624 {
2625 	int	i;
2626 
2627 	for (i = start; i <= end; i++)
2628 		/* Check if any I/O entry needs this IRQ */
2629 		if (apic_find_io_intr(i) == NULL) {
2630 			/* Then see if it is free */
2631 			if ((apic_irq_table[i] == NULL) ||
2632 			    (apic_irq_table[i]->airq_mps_intr_index ==
2633 			    FREE_INDEX)) {
2634 				return (i);
2635 			}
2636 		}
2637 	return (-1);
2638 }
2639 
2640 
2641 /*
2642  * Mark vector as being in the process of being deleted. Interrupts
2643  * may still come in on some CPU. The moment an interrupt comes with
2644  * the new vector, we know we can free the old one. Called only from
2645  * addspl and delspl with interrupts disabled. Because an interrupt
2646  * can be shared, but no interrupt from either device may come in,
2647  * we also use a timeout mechanism, which we arbitrarily set to
2648  * apic_revector_timeout microseconds.
2649  */
2650 static void
2651 apic_mark_vector(uchar_t oldvector, uchar_t newvector)
2652 {
2653 	ulong_t iflag;
2654 
2655 	iflag = intr_clear();
2656 	lock_set(&apic_revector_lock);
2657 	if (!apic_oldvec_to_newvec) {
2658 		apic_oldvec_to_newvec =
2659 		    kmem_zalloc(sizeof (newvector) * APIC_MAX_VECTOR * 2,
2660 		    KM_NOSLEEP);
2661 
2662 		if (!apic_oldvec_to_newvec) {
2663 			/*
2664 			 * This failure is not catastrophic.
2665 			 * But, the oldvec will never be freed.
2666 			 */
2667 			apic_error |= APIC_ERR_MARK_VECTOR_FAIL;
2668 			lock_clear(&apic_revector_lock);
2669 			intr_restore(iflag);
2670 			return;
2671 		}
2672 		apic_newvec_to_oldvec = &apic_oldvec_to_newvec[APIC_MAX_VECTOR];
2673 	}
2674 
2675 	/* See if we already did this for drivers which do double addintrs */
2676 	if (apic_oldvec_to_newvec[oldvector] != newvector) {
2677 		apic_oldvec_to_newvec[oldvector] = newvector;
2678 		apic_newvec_to_oldvec[newvector] = oldvector;
2679 		apic_revector_pending++;
2680 	}
2681 	lock_clear(&apic_revector_lock);
2682 	intr_restore(iflag);
2683 	(void) timeout(apic_xlate_vector_free_timeout_handler,
2684 	    (void *)(uintptr_t)oldvector, drv_usectohz(apic_revector_timeout));
2685 }
2686 
2687 /*
2688  * xlate_vector is called from intr_enter if revector_pending is set.
2689  * It will xlate it if needed and mark the old vector as free.
2690  */
2691 uchar_t
2692 apic_xlate_vector(uchar_t vector)
2693 {
2694 	uchar_t	newvector, oldvector = 0;
2695 
2696 	lock_set(&apic_revector_lock);
2697 	/* Do we really need to do this ? */
2698 	if (!apic_revector_pending) {
2699 		lock_clear(&apic_revector_lock);
2700 		return (vector);
2701 	}
2702 	if ((newvector = apic_oldvec_to_newvec[vector]) != 0)
2703 		oldvector = vector;
2704 	else {
2705 		/*
2706 		 * The incoming vector is new . See if a stale entry is
2707 		 * remaining
2708 		 */
2709 		if ((oldvector = apic_newvec_to_oldvec[vector]) != 0)
2710 			newvector = vector;
2711 	}
2712 
2713 	if (oldvector) {
2714 		apic_revector_pending--;
2715 		apic_oldvec_to_newvec[oldvector] = 0;
2716 		apic_newvec_to_oldvec[newvector] = 0;
2717 		apic_free_vector(oldvector);
2718 		lock_clear(&apic_revector_lock);
2719 		/* There could have been more than one reprogramming! */
2720 		return (apic_xlate_vector(newvector));
2721 	}
2722 	lock_clear(&apic_revector_lock);
2723 	return (vector);
2724 }
2725 
2726 void
2727 apic_xlate_vector_free_timeout_handler(void *arg)
2728 {
2729 	ulong_t iflag;
2730 	uchar_t oldvector, newvector;
2731 
2732 	oldvector = (uchar_t)(uintptr_t)arg;
2733 	iflag = intr_clear();
2734 	lock_set(&apic_revector_lock);
2735 	if ((newvector = apic_oldvec_to_newvec[oldvector]) != 0) {
2736 		apic_free_vector(oldvector);
2737 		apic_oldvec_to_newvec[oldvector] = 0;
2738 		apic_newvec_to_oldvec[newvector] = 0;
2739 		apic_revector_pending--;
2740 	}
2741 
2742 	lock_clear(&apic_revector_lock);
2743 	intr_restore(iflag);
2744 }
2745 
2746 
2747 /*
2748  * compute the polarity, trigger mode and vector for programming into
2749  * the I/O apic and record in airq_rdt_entry.
2750  */
2751 static void
2752 apic_record_rdt_entry(apic_irq_t *irqptr, int irq)
2753 {
2754 	int	ioapicindex, bus_type, vector;
2755 	short	intr_index;
2756 	uint_t	level, po, io_po;
2757 	struct apic_io_intr *iointrp;
2758 
2759 	intr_index = irqptr->airq_mps_intr_index;
2760 	DDI_INTR_IMPLDBG((CE_CONT, "apic_record_rdt_entry: intr_index=%d "
2761 	    "irq = 0x%x dip = 0x%p vector = 0x%x\n", intr_index, irq,
2762 	    (void *)irqptr->airq_dip, irqptr->airq_vector));
2763 
2764 	if (intr_index == RESERVE_INDEX) {
2765 		apic_error |= APIC_ERR_INVALID_INDEX;
2766 		return;
2767 	} else if (APIC_IS_MSI_OR_MSIX_INDEX(intr_index)) {
2768 		return;
2769 	}
2770 
2771 	vector = irqptr->airq_vector;
2772 	ioapicindex = irqptr->airq_ioapicindex;
2773 	/* Assume edge triggered by default */
2774 	level = 0;
2775 	/* Assume active high by default */
2776 	po = 0;
2777 
2778 	if (intr_index == DEFAULT_INDEX || intr_index == FREE_INDEX) {
2779 		ASSERT(irq < 16);
2780 		if (eisa_level_intr_mask & (1 << irq))
2781 			level = AV_LEVEL;
2782 		if (intr_index == FREE_INDEX && apic_defconf == 0)
2783 			apic_error |= APIC_ERR_INVALID_INDEX;
2784 	} else if (intr_index == ACPI_INDEX) {
2785 		bus_type = irqptr->airq_iflag.bustype;
2786 		if (irqptr->airq_iflag.intr_el == INTR_EL_CONFORM) {
2787 			if (bus_type == BUS_PCI)
2788 				level = AV_LEVEL;
2789 		} else
2790 			level = (irqptr->airq_iflag.intr_el == INTR_EL_LEVEL) ?
2791 			    AV_LEVEL : 0;
2792 		if (level &&
2793 		    ((irqptr->airq_iflag.intr_po == INTR_PO_ACTIVE_LOW) ||
2794 		    (irqptr->airq_iflag.intr_po == INTR_PO_CONFORM &&
2795 		    bus_type == BUS_PCI)))
2796 			po = AV_ACTIVE_LOW;
2797 	} else {
2798 		iointrp = apic_io_intrp + intr_index;
2799 		bus_type = apic_find_bus(iointrp->intr_busid);
2800 		if (iointrp->intr_el == INTR_EL_CONFORM) {
2801 			if ((irq < 16) && (eisa_level_intr_mask & (1 << irq)))
2802 				level = AV_LEVEL;
2803 			else if (bus_type == BUS_PCI)
2804 				level = AV_LEVEL;
2805 		} else
2806 			level = (iointrp->intr_el == INTR_EL_LEVEL) ?
2807 			    AV_LEVEL : 0;
2808 		if (level && ((iointrp->intr_po == INTR_PO_ACTIVE_LOW) ||
2809 		    (iointrp->intr_po == INTR_PO_CONFORM &&
2810 		    bus_type == BUS_PCI)))
2811 			po = AV_ACTIVE_LOW;
2812 	}
2813 	if (level)
2814 		apic_level_intr[irq] = 1;
2815 	/*
2816 	 * The 82489DX External APIC cannot do active low polarity interrupts.
2817 	 */
2818 	if (po && (apic_io_ver[ioapicindex] != IOAPIC_VER_82489DX))
2819 		io_po = po;
2820 	else
2821 		io_po = 0;
2822 
2823 	if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG)
2824 		printf("setio: ioapic=%x intin=%x level=%x po=%x vector=%x\n",
2825 		    ioapicindex, irqptr->airq_intin_no, level, io_po, vector);
2826 
2827 	irqptr->airq_rdt_entry = level|io_po|vector;
2828 }
2829 
2830 /*
2831  * Bind interrupt corresponding to irq_ptr to bind_cpu.
2832  * Must be called with interrupts disabled and apic_ioapic_lock held
2833  */
2834 int
2835 apic_rebind(apic_irq_t *irq_ptr, int bind_cpu,
2836     struct ioapic_reprogram_data *drep)
2837 {
2838 	int			ioapicindex, intin_no;
2839 	uint32_t		airq_temp_cpu;
2840 	apic_cpus_info_t	*cpu_infop;
2841 	uint32_t		rdt_entry;
2842 	int			which_irq;
2843 	ioapic_rdt_t		irdt;
2844 
2845 	which_irq = apic_vector_to_irq[irq_ptr->airq_vector];
2846 
2847 	intin_no = irq_ptr->airq_intin_no;
2848 	ioapicindex = irq_ptr->airq_ioapicindex;
2849 	airq_temp_cpu = irq_ptr->airq_temp_cpu;
2850 	if (airq_temp_cpu != IRQ_UNINIT && airq_temp_cpu != IRQ_UNBOUND) {
2851 		if (airq_temp_cpu & IRQ_USER_BOUND)
2852 			/* Mask off high bit so it can be used as array index */
2853 			airq_temp_cpu &= ~IRQ_USER_BOUND;
2854 
2855 		ASSERT(airq_temp_cpu < apic_nproc);
2856 	}
2857 
2858 	/*
2859 	 * Can't bind to a CPU that's not accepting interrupts:
2860 	 */
2861 	cpu_infop = &apic_cpus[bind_cpu & ~IRQ_USER_BOUND];
2862 	if (!(cpu_infop->aci_status & APIC_CPU_INTR_ENABLE))
2863 		return (1);
2864 
2865 	/*
2866 	 * If we are about to change the interrupt vector for this interrupt,
2867 	 * and this interrupt is level-triggered, attached to an IOAPIC,
2868 	 * has been delivered to a CPU and that CPU has not handled it
2869 	 * yet, we cannot reprogram the IOAPIC now.
2870 	 */
2871 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2872 
2873 		rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex,
2874 		    intin_no);
2875 
2876 		if ((irq_ptr->airq_vector != RDT_VECTOR(rdt_entry)) &&
2877 		    apic_check_stuck_interrupt(irq_ptr, airq_temp_cpu,
2878 		    bind_cpu, ioapicindex, intin_no, which_irq, drep) != 0) {
2879 
2880 			return (0);
2881 		}
2882 
2883 		/*
2884 		 * NOTE: We do not unmask the RDT here, as an interrupt MAY
2885 		 * still come in before we have a chance to reprogram it below.
2886 		 * The reprogramming below will simultaneously change and
2887 		 * unmask the RDT entry.
2888 		 */
2889 
2890 		if ((uint32_t)bind_cpu == IRQ_UNBOUND) {
2891 			irdt.ir_lo =  AV_LDEST | AV_LOPRI |
2892 			    irq_ptr->airq_rdt_entry;
2893 #if !defined(__xpv)
2894 			irdt.ir_hi = AV_TOALL >> APIC_ID_BIT_OFFSET;
2895 
2896 			apic_vt_ops->apic_intrr_alloc_entry(irq_ptr);
2897 			apic_vt_ops->apic_intrr_map_entry(
2898 			    irq_ptr, (void *)&irdt);
2899 			apic_vt_ops->apic_intrr_record_rdt(irq_ptr, &irdt);
2900 
2901 			/* Write the RDT entry -- no specific CPU binding */
2902 			WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2903 			    irdt.ir_hi | AV_TOALL);
2904 #else
2905 			WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2906 			    AV_TOALL);
2907 #endif
2908 			if (airq_temp_cpu != IRQ_UNINIT && airq_temp_cpu !=
2909 			    IRQ_UNBOUND)
2910 				apic_cpus[airq_temp_cpu].aci_temp_bound--;
2911 
2912 			/*
2913 			 * Write the vector, trigger, and polarity portion of
2914 			 * the RDT
2915 			 */
2916 			WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex, intin_no,
2917 			    irdt.ir_lo);
2918 
2919 			irq_ptr->airq_temp_cpu = IRQ_UNBOUND;
2920 			return (0);
2921 		}
2922 	}
2923 
2924 	if (bind_cpu & IRQ_USER_BOUND) {
2925 		cpu_infop->aci_bound++;
2926 	} else {
2927 		cpu_infop->aci_temp_bound++;
2928 	}
2929 	ASSERT((bind_cpu & ~IRQ_USER_BOUND) < apic_nproc);
2930 
2931 	if ((airq_temp_cpu != IRQ_UNBOUND) && (airq_temp_cpu != IRQ_UNINIT)) {
2932 		apic_cpus[airq_temp_cpu].aci_temp_bound--;
2933 	}
2934 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2935 
2936 		irdt.ir_lo = AV_PDEST | AV_FIXED | irq_ptr->airq_rdt_entry;
2937 		irdt.ir_hi = cpu_infop->aci_local_id;
2938 
2939 #if !defined(__xpv)
2940 		apic_vt_ops->apic_intrr_alloc_entry(irq_ptr);
2941 		apic_vt_ops->apic_intrr_map_entry(irq_ptr, (void *)&irdt);
2942 		apic_vt_ops->apic_intrr_record_rdt(irq_ptr, &irdt);
2943 
2944 		/* Write the RDT entry -- bind to a specific CPU: */
2945 		WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2946 		    irdt.ir_hi);
2947 #else
2948 		/* Write the RDT entry -- bind to a specific CPU: */
2949 		WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2950 		    irdt.ir_hi << APIC_ID_BIT_OFFSET);
2951 #endif
2952 		/* Write the vector, trigger, and polarity portion of the RDT */
2953 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex, intin_no,
2954 		    irdt.ir_lo);
2955 
2956 	} else {
2957 		int type = (irq_ptr->airq_mps_intr_index == MSI_INDEX) ?
2958 		    DDI_INTR_TYPE_MSI : DDI_INTR_TYPE_MSIX;
2959 		if (type == DDI_INTR_TYPE_MSI) {
2960 			if (irq_ptr->airq_ioapicindex ==
2961 			    irq_ptr->airq_origirq) {
2962 				/* first one */
2963 				DDI_INTR_IMPLDBG((CE_CONT, "apic_rebind: call "
2964 				    "apic_pci_msi_enable_vector\n"));
2965 				apic_pci_msi_enable_vector(irq_ptr,
2966 				    type, which_irq, irq_ptr->airq_vector,
2967 				    irq_ptr->airq_intin_no,
2968 				    cpu_infop->aci_local_id);
2969 			}
2970 			if ((irq_ptr->airq_ioapicindex +
2971 			    irq_ptr->airq_intin_no - 1) ==
2972 			    irq_ptr->airq_origirq) { /* last one */
2973 				DDI_INTR_IMPLDBG((CE_CONT, "apic_rebind: call "
2974 				    "apic_pci_msi_enable_mode\n"));
2975 				apic_pci_msi_enable_mode(irq_ptr->airq_dip,
2976 				    type, which_irq);
2977 			}
2978 		} else { /* MSI-X */
2979 			apic_pci_msi_enable_vector(irq_ptr, type,
2980 			    irq_ptr->airq_origirq, irq_ptr->airq_vector, 1,
2981 			    cpu_infop->aci_local_id);
2982 			apic_pci_msi_enable_mode(irq_ptr->airq_dip, type,
2983 			    irq_ptr->airq_origirq);
2984 		}
2985 	}
2986 	irq_ptr->airq_temp_cpu = (uint32_t)bind_cpu;
2987 	apic_redist_cpu_skip &= ~(1 << (bind_cpu & ~IRQ_USER_BOUND));
2988 	return (0);
2989 }
2990 
2991 static void
2992 apic_last_ditch_clear_remote_irr(int ioapic_ix, int intin_no)
2993 {
2994 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no)
2995 	    & AV_REMOTE_IRR) != 0) {
2996 		/*
2997 		 * Trying to clear the bit through normal
2998 		 * channels has failed.  So as a last-ditch
2999 		 * effort, try to set the trigger mode to
3000 		 * edge, then to level.  This has been
3001 		 * observed to work on many systems.
3002 		 */
3003 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3004 		    intin_no,
3005 		    READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3006 		    intin_no) & ~AV_LEVEL);
3007 
3008 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3009 		    intin_no,
3010 		    READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3011 		    intin_no) | AV_LEVEL);
3012 
3013 		/*
3014 		 * If the bit's STILL set, this interrupt may
3015 		 * be hosed.
3016 		 */
3017 		if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3018 		    intin_no) & AV_REMOTE_IRR) != 0) {
3019 
3020 			prom_printf("%s: Remote IRR still "
3021 			    "not clear for IOAPIC %d intin %d.\n"
3022 			    "\tInterrupts to this pin may cease "
3023 			    "functioning.\n", psm_name, ioapic_ix,
3024 			    intin_no);
3025 #ifdef DEBUG
3026 			apic_last_ditch_reprogram_failures++;
3027 #endif
3028 		}
3029 	}
3030 }
3031 
3032 /*
3033  * This function is protected by apic_ioapic_lock coupled with the
3034  * fact that interrupts are disabled.
3035  */
3036 static void
3037 delete_defer_repro_ent(int which_irq)
3038 {
3039 	ASSERT(which_irq >= 0);
3040 	ASSERT(which_irq <= 255);
3041 
3042 	if (apic_reprogram_info[which_irq].done)
3043 		return;
3044 
3045 	apic_reprogram_info[which_irq].done = B_TRUE;
3046 
3047 #ifdef DEBUG
3048 	apic_defer_repro_total_retries +=
3049 	    apic_reprogram_info[which_irq].tries;
3050 
3051 	apic_defer_repro_successes++;
3052 #endif
3053 
3054 	if (--apic_reprogram_outstanding == 0) {
3055 
3056 		setlvlx = psm_intr_exit_fn();
3057 	}
3058 }
3059 
3060 
3061 /*
3062  * Interrupts must be disabled during this function to prevent
3063  * self-deadlock.  Interrupts are disabled because this function
3064  * is called from apic_check_stuck_interrupt(), which is called
3065  * from apic_rebind(), which requires its caller to disable interrupts.
3066  */
3067 static void
3068 add_defer_repro_ent(apic_irq_t *irq_ptr, int which_irq, int new_bind_cpu)
3069 {
3070 	ASSERT(which_irq >= 0);
3071 	ASSERT(which_irq <= 255);
3072 
3073 	/*
3074 	 * On the off-chance that there's already a deferred
3075 	 * reprogramming on this irq, check, and if so, just update the
3076 	 * CPU and irq pointer to which the interrupt is targeted, then return.
3077 	 */
3078 	if (!apic_reprogram_info[which_irq].done) {
3079 		apic_reprogram_info[which_irq].bindcpu = new_bind_cpu;
3080 		apic_reprogram_info[which_irq].irqp = irq_ptr;
3081 		return;
3082 	}
3083 
3084 	apic_reprogram_info[which_irq].irqp = irq_ptr;
3085 	apic_reprogram_info[which_irq].bindcpu = new_bind_cpu;
3086 	apic_reprogram_info[which_irq].tries = 0;
3087 	/*
3088 	 * This must be the last thing set, since we're not
3089 	 * grabbing any locks, apic_try_deferred_reprogram() will
3090 	 * make its decision about using this entry iff done
3091 	 * is false.
3092 	 */
3093 	apic_reprogram_info[which_irq].done = B_FALSE;
3094 
3095 	/*
3096 	 * If there were previously no deferred reprogrammings, change
3097 	 * setlvlx to call apic_try_deferred_reprogram()
3098 	 */
3099 	if (++apic_reprogram_outstanding == 1) {
3100 
3101 		setlvlx = apic_try_deferred_reprogram;
3102 	}
3103 }
3104 
3105 static void
3106 apic_try_deferred_reprogram(int prev_ipl, int irq)
3107 {
3108 	int reproirq;
3109 	ulong_t iflag;
3110 	struct ioapic_reprogram_data *drep;
3111 
3112 	(*psm_intr_exit_fn())(prev_ipl, irq);
3113 
3114 	if (!lock_try(&apic_defer_reprogram_lock)) {
3115 		return;
3116 	}
3117 
3118 	/*
3119 	 * Acquire the apic_ioapic_lock so that any other operations that
3120 	 * may affect the apic_reprogram_info state are serialized.
3121 	 * It's still possible for the last deferred reprogramming to clear
3122 	 * between the time we entered this function and the time we get to
3123 	 * the for loop below.  In that case, *setlvlx will have been set
3124 	 * back to *_intr_exit and drep will be NULL. (There's no way to
3125 	 * stop that from happening -- we would need to grab a lock before
3126 	 * calling *setlvlx, which is neither realistic nor prudent).
3127 	 */
3128 	iflag = intr_clear();
3129 	lock_set(&apic_ioapic_lock);
3130 
3131 	/*
3132 	 * For each deferred RDT entry, try to reprogram it now.  Note that
3133 	 * there is no lock acquisition to read apic_reprogram_info because
3134 	 * '.done' is set only after the other fields in the structure are set.
3135 	 */
3136 
3137 	drep = NULL;
3138 	for (reproirq = 0; reproirq <= APIC_MAX_VECTOR; reproirq++) {
3139 		if (apic_reprogram_info[reproirq].done == B_FALSE) {
3140 			drep = &apic_reprogram_info[reproirq];
3141 			break;
3142 		}
3143 	}
3144 
3145 	/*
3146 	 * Either we found a deferred action to perform, or
3147 	 * we entered this function spuriously, after *setlvlx
3148 	 * was restored to point to *_intr_exit.  Any other
3149 	 * permutation is invalid.
3150 	 */
3151 	ASSERT(drep != NULL || *setlvlx == psm_intr_exit_fn());
3152 
3153 	/*
3154 	 * Though we can't really do anything about errors
3155 	 * at this point, keep track of them for reporting.
3156 	 * Note that it is very possible for apic_setup_io_intr
3157 	 * to re-register this very timeout if the Remote IRR bit
3158 	 * has not yet cleared.
3159 	 */
3160 
3161 #ifdef DEBUG
3162 	if (drep != NULL) {
3163 		if (apic_setup_io_intr(drep, reproirq, B_TRUE) != 0) {
3164 			apic_deferred_setup_failures++;
3165 		}
3166 	} else {
3167 		apic_deferred_spurious_enters++;
3168 	}
3169 #else
3170 	if (drep != NULL)
3171 		(void) apic_setup_io_intr(drep, reproirq, B_TRUE);
3172 #endif
3173 
3174 	lock_clear(&apic_ioapic_lock);
3175 	intr_restore(iflag);
3176 
3177 	lock_clear(&apic_defer_reprogram_lock);
3178 }
3179 
3180 static void
3181 apic_ioapic_wait_pending_clear(int ioapic_ix, int intin_no)
3182 {
3183 	int waited;
3184 
3185 	/*
3186 	 * Wait for the delivery pending bit to clear.
3187 	 */
3188 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no) &
3189 	    (AV_LEVEL|AV_PENDING)) == (AV_LEVEL|AV_PENDING)) {
3190 
3191 		/*
3192 		 * If we're still waiting on the delivery of this interrupt,
3193 		 * continue to wait here until it is delivered (this should be
3194 		 * a very small amount of time, but include a timeout just in
3195 		 * case).
3196 		 */
3197 		for (waited = 0; waited < apic_max_reps_clear_pending;
3198 		    waited++) {
3199 			if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3200 			    intin_no) & AV_PENDING) == 0) {
3201 				break;
3202 			}
3203 		}
3204 	}
3205 }
3206 
3207 
3208 /*
3209  * Checks to see if the IOAPIC interrupt entry specified has its Remote IRR
3210  * bit set.  Calls functions that modify the function that setlvlx points to,
3211  * so that the reprogramming can be retried very shortly.
3212  *
3213  * This function will mask the RDT entry if the interrupt is level-triggered.
3214  * (The caller is responsible for unmasking the RDT entry.)
3215  *
3216  * Returns non-zero if the caller should defer IOAPIC reprogramming.
3217  */
3218 static int
3219 apic_check_stuck_interrupt(apic_irq_t *irq_ptr, int old_bind_cpu,
3220     int new_bind_cpu, int ioapic_ix, int intin_no, int which_irq,
3221     struct ioapic_reprogram_data *drep)
3222 {
3223 	int32_t			rdt_entry;
3224 	int			waited;
3225 	int			reps = 0;
3226 
3227 	/*
3228 	 * Wait for the delivery pending bit to clear.
3229 	 */
3230 	do {
3231 		++reps;
3232 
3233 		apic_ioapic_wait_pending_clear(ioapic_ix, intin_no);
3234 
3235 		/*
3236 		 * Mask the RDT entry, but only if it's a level-triggered
3237 		 * interrupt
3238 		 */
3239 		rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3240 		    intin_no);
3241 		if ((rdt_entry & (AV_LEVEL|AV_MASK)) == AV_LEVEL) {
3242 
3243 			/* Mask it */
3244 			WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no,
3245 			    AV_MASK | rdt_entry);
3246 		}
3247 
3248 		if ((rdt_entry & AV_LEVEL) == AV_LEVEL) {
3249 			/*
3250 			 * If there was a race and an interrupt was injected
3251 			 * just before we masked, check for that case here.
3252 			 * Then, unmask the RDT entry and try again.  If we're
3253 			 * on our last try, don't unmask (because we want the
3254 			 * RDT entry to remain masked for the rest of the
3255 			 * function).
3256 			 */
3257 			rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3258 			    intin_no);
3259 			if ((rdt_entry & AV_PENDING) &&
3260 			    (reps < apic_max_reps_clear_pending)) {
3261 				/* Unmask it */
3262 				WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3263 				    intin_no, rdt_entry & ~AV_MASK);
3264 			}
3265 		}
3266 
3267 	} while ((rdt_entry & AV_PENDING) &&
3268 	    (reps < apic_max_reps_clear_pending));
3269 
3270 #ifdef DEBUG
3271 		if (rdt_entry & AV_PENDING)
3272 			apic_intr_deliver_timeouts++;
3273 #endif
3274 
3275 	/*
3276 	 * If the remote IRR bit is set, then the interrupt has been sent
3277 	 * to a CPU for processing.  We have no choice but to wait for
3278 	 * that CPU to process the interrupt, at which point the remote IRR
3279 	 * bit will be cleared.
3280 	 */
3281 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no) &
3282 	    (AV_LEVEL|AV_REMOTE_IRR)) == (AV_LEVEL|AV_REMOTE_IRR)) {
3283 
3284 		/*
3285 		 * If the CPU that this RDT is bound to is NOT the current
3286 		 * CPU, wait until that CPU handles the interrupt and ACKs
3287 		 * it.  If this interrupt is not bound to any CPU (that is,
3288 		 * if it's bound to the logical destination of "anyone"), it
3289 		 * may have been delivered to the current CPU so handle that
3290 		 * case by deferring the reprogramming (below).
3291 		 */
3292 		if ((old_bind_cpu != IRQ_UNBOUND) &&
3293 		    (old_bind_cpu != IRQ_UNINIT) &&
3294 		    (old_bind_cpu != psm_get_cpu_id())) {
3295 			for (waited = 0; waited < apic_max_reps_clear_pending;
3296 			    waited++) {
3297 				if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3298 				    intin_no) & AV_REMOTE_IRR) == 0) {
3299 
3300 					delete_defer_repro_ent(which_irq);
3301 
3302 					/* Remote IRR has cleared! */
3303 					return (0);
3304 				}
3305 			}
3306 		}
3307 
3308 		/*
3309 		 * If we waited and the Remote IRR bit is still not cleared,
3310 		 * AND if we've invoked the timeout APIC_REPROGRAM_MAX_TIMEOUTS
3311 		 * times for this interrupt, try the last-ditch workaround:
3312 		 */
3313 		if (drep && drep->tries >= APIC_REPROGRAM_MAX_TRIES) {
3314 
3315 			apic_last_ditch_clear_remote_irr(ioapic_ix, intin_no);
3316 
3317 			/* Mark this one as reprogrammed: */
3318 			delete_defer_repro_ent(which_irq);
3319 
3320 			return (0);
3321 		} else {
3322 #ifdef DEBUG
3323 			apic_intr_deferrals++;
3324 #endif
3325 
3326 			/*
3327 			 * If waiting for the Remote IRR bit (above) didn't
3328 			 * allow it to clear, defer the reprogramming.
3329 			 * Add a new deferred-programming entry if the
3330 			 * caller passed a NULL one (and update the existing one
3331 			 * in case anything changed).
3332 			 */
3333 			add_defer_repro_ent(irq_ptr, which_irq, new_bind_cpu);
3334 			if (drep)
3335 				drep->tries++;
3336 
3337 			/* Inform caller to defer IOAPIC programming: */
3338 			return (1);
3339 		}
3340 
3341 	}
3342 
3343 	/* Remote IRR is clear */
3344 	delete_defer_repro_ent(which_irq);
3345 
3346 	return (0);
3347 }
3348 
3349 /*
3350  * Called to migrate all interrupts at an irq to another cpu.
3351  * Must be called with interrupts disabled and apic_ioapic_lock held
3352  */
3353 int
3354 apic_rebind_all(apic_irq_t *irq_ptr, int bind_cpu)
3355 {
3356 	apic_irq_t	*irqptr = irq_ptr;
3357 	int		retval = 0;
3358 
3359 	while (irqptr) {
3360 		if (irqptr->airq_temp_cpu != IRQ_UNINIT)
3361 			retval |= apic_rebind(irqptr, bind_cpu, NULL);
3362 		irqptr = irqptr->airq_next;
3363 	}
3364 
3365 	return (retval);
3366 }
3367 
3368 /*
3369  * apic_intr_redistribute does all the messy computations for identifying
3370  * which interrupt to move to which CPU. Currently we do just one interrupt
3371  * at a time. This reduces the time we spent doing all this within clock
3372  * interrupt. When it is done in idle, we could do more than 1.
3373  * First we find the most busy and the most free CPU (time in ISR only)
3374  * skipping those CPUs that has been identified as being ineligible (cpu_skip)
3375  * Then we look for IRQs which are closest to the difference between the
3376  * most busy CPU and the average ISR load. We try to find one whose load
3377  * is less than difference.If none exists, then we chose one larger than the
3378  * difference, provided it does not make the most idle CPU worse than the
3379  * most busy one. In the end, we clear all the busy fields for CPUs. For
3380  * IRQs, they are cleared as they are scanned.
3381  */
3382 void
3383 apic_intr_redistribute()
3384 {
3385 	int busiest_cpu, most_free_cpu;
3386 	int cpu_free, cpu_busy, max_busy, min_busy;
3387 	int min_free, diff;
3388 	int average_busy, cpus_online;
3389 	int i, busy;
3390 	ulong_t iflag;
3391 	apic_cpus_info_t *cpu_infop;
3392 	apic_irq_t *min_busy_irq = NULL;
3393 	apic_irq_t *max_busy_irq = NULL;
3394 
3395 	busiest_cpu = most_free_cpu = -1;
3396 	cpu_free = cpu_busy = max_busy = average_busy = 0;
3397 	min_free = apic_sample_factor_redistribution;
3398 	cpus_online = 0;
3399 	/*
3400 	 * Below we will check for CPU_INTR_ENABLE, bound, temp_bound, temp_cpu
3401 	 * without ioapic_lock. That is OK as we are just doing statistical
3402 	 * sampling anyway and any inaccuracy now will get corrected next time
3403 	 * The call to rebind which actually changes things will make sure
3404 	 * we are consistent.
3405 	 */
3406 	for (i = 0; i < apic_nproc; i++) {
3407 		if (!(apic_redist_cpu_skip & (1 << i)) &&
3408 		    (apic_cpus[i].aci_status & APIC_CPU_INTR_ENABLE)) {
3409 
3410 			cpu_infop = &apic_cpus[i];
3411 			/*
3412 			 * If no unbound interrupts or only 1 total on this
3413 			 * CPU, skip
3414 			 */
3415 			if (!cpu_infop->aci_temp_bound ||
3416 			    (cpu_infop->aci_bound + cpu_infop->aci_temp_bound)
3417 			    == 1) {
3418 				apic_redist_cpu_skip |= 1 << i;
3419 				continue;
3420 			}
3421 
3422 			busy = cpu_infop->aci_busy;
3423 			average_busy += busy;
3424 			cpus_online++;
3425 			if (max_busy < busy) {
3426 				max_busy = busy;
3427 				busiest_cpu = i;
3428 			}
3429 			if (min_free > busy) {
3430 				min_free = busy;
3431 				most_free_cpu = i;
3432 			}
3433 			if (busy > apic_int_busy_mark) {
3434 				cpu_busy |= 1 << i;
3435 			} else {
3436 				if (busy < apic_int_free_mark)
3437 					cpu_free |= 1 << i;
3438 			}
3439 		}
3440 	}
3441 	if ((cpu_busy && cpu_free) ||
3442 	    (max_busy >= (min_free + apic_diff_for_redistribution))) {
3443 
3444 		apic_num_imbalance++;
3445 #ifdef	DEBUG
3446 		if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3447 			prom_printf(
3448 			    "redistribute busy=%x free=%x max=%x min=%x",
3449 			    cpu_busy, cpu_free, max_busy, min_free);
3450 		}
3451 #endif /* DEBUG */
3452 
3453 
3454 		average_busy /= cpus_online;
3455 
3456 		diff = max_busy - average_busy;
3457 		min_busy = max_busy; /* start with the max possible value */
3458 		max_busy = 0;
3459 		min_busy_irq = max_busy_irq = NULL;
3460 		i = apic_min_device_irq;
3461 		for (; i <= apic_max_device_irq; i++) {
3462 			apic_irq_t *irq_ptr;
3463 			/* Change to linked list per CPU ? */
3464 			if ((irq_ptr = apic_irq_table[i]) == NULL)
3465 				continue;
3466 			/* Check for irq_busy & decide which one to move */
3467 			/* Also zero them for next round */
3468 			if ((irq_ptr->airq_temp_cpu == busiest_cpu) &&
3469 			    irq_ptr->airq_busy) {
3470 				if (irq_ptr->airq_busy < diff) {
3471 					/*
3472 					 * Check for least busy CPU,
3473 					 * best fit or what ?
3474 					 */
3475 					if (max_busy < irq_ptr->airq_busy) {
3476 						/*
3477 						 * Most busy within the
3478 						 * required differential
3479 						 */
3480 						max_busy = irq_ptr->airq_busy;
3481 						max_busy_irq = irq_ptr;
3482 					}
3483 				} else {
3484 					if (min_busy > irq_ptr->airq_busy) {
3485 						/*
3486 						 * least busy, but more than
3487 						 * the reqd diff
3488 						 */
3489 						if (min_busy <
3490 						    (diff + average_busy -
3491 						    min_free)) {
3492 							/*
3493 							 * Making sure new cpu
3494 							 * will not end up
3495 							 * worse
3496 							 */
3497 							min_busy =
3498 							    irq_ptr->airq_busy;
3499 
3500 							min_busy_irq = irq_ptr;
3501 						}
3502 					}
3503 				}
3504 			}
3505 			irq_ptr->airq_busy = 0;
3506 		}
3507 
3508 		if (max_busy_irq != NULL) {
3509 #ifdef	DEBUG
3510 			if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3511 				prom_printf("rebinding %x to %x",
3512 				    max_busy_irq->airq_vector, most_free_cpu);
3513 			}
3514 #endif /* DEBUG */
3515 			iflag = intr_clear();
3516 			if (lock_try(&apic_ioapic_lock)) {
3517 				if (apic_rebind_all(max_busy_irq,
3518 				    most_free_cpu) == 0) {
3519 					/* Make change permenant */
3520 					max_busy_irq->airq_cpu =
3521 					    (uint32_t)most_free_cpu;
3522 				}
3523 				lock_clear(&apic_ioapic_lock);
3524 			}
3525 			intr_restore(iflag);
3526 
3527 		} else if (min_busy_irq != NULL) {
3528 #ifdef	DEBUG
3529 			if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3530 				prom_printf("rebinding %x to %x",
3531 				    min_busy_irq->airq_vector, most_free_cpu);
3532 			}
3533 #endif /* DEBUG */
3534 
3535 			iflag = intr_clear();
3536 			if (lock_try(&apic_ioapic_lock)) {
3537 				if (apic_rebind_all(min_busy_irq,
3538 				    most_free_cpu) == 0) {
3539 					/* Make change permenant */
3540 					min_busy_irq->airq_cpu =
3541 					    (uint32_t)most_free_cpu;
3542 				}
3543 				lock_clear(&apic_ioapic_lock);
3544 			}
3545 			intr_restore(iflag);
3546 
3547 		} else {
3548 			if (cpu_busy != (1 << busiest_cpu)) {
3549 				apic_redist_cpu_skip |= 1 << busiest_cpu;
3550 				/*
3551 				 * We leave cpu_skip set so that next time we
3552 				 * can choose another cpu
3553 				 */
3554 			}
3555 		}
3556 		apic_num_rebind++;
3557 	} else {
3558 		/*
3559 		 * found nothing. Could be that we skipped over valid CPUs
3560 		 * or we have balanced everything. If we had a variable
3561 		 * ticks_for_redistribution, it could be increased here.
3562 		 * apic_int_busy, int_free etc would also need to be
3563 		 * changed.
3564 		 */
3565 		if (apic_redist_cpu_skip)
3566 			apic_redist_cpu_skip = 0;
3567 	}
3568 	for (i = 0; i < apic_nproc; i++) {
3569 		apic_cpus[i].aci_busy = 0;
3570 	}
3571 }
3572 
3573 void
3574 apic_cleanup_busy()
3575 {
3576 	int i;
3577 	apic_irq_t *irq_ptr;
3578 
3579 	for (i = 0; i < apic_nproc; i++) {
3580 		apic_cpus[i].aci_busy = 0;
3581 	}
3582 
3583 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
3584 		if ((irq_ptr = apic_irq_table[i]) != NULL)
3585 			irq_ptr->airq_busy = 0;
3586 	}
3587 }
3588 
3589 
3590 static int
3591 apic_acpi_translate_pci_irq(dev_info_t *dip, int busid, int devid,
3592     int ipin, int *pci_irqp, iflag_t *intr_flagp)
3593 {
3594 
3595 	int status;
3596 	acpi_psm_lnk_t acpipsmlnk;
3597 
3598 	if ((status = acpi_get_irq_cache_ent(busid, devid, ipin, pci_irqp,
3599 	    intr_flagp)) == ACPI_PSM_SUCCESS) {
3600 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Found irqno %d "
3601 		    "from cache for device %s, instance #%d\n", psm_name,
3602 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
3603 		return (status);
3604 	}
3605 
3606 	bzero(&acpipsmlnk, sizeof (acpi_psm_lnk_t));
3607 
3608 	if ((status = acpi_translate_pci_irq(dip, ipin, pci_irqp, intr_flagp,
3609 	    &acpipsmlnk)) == ACPI_PSM_FAILURE) {
3610 		APIC_VERBOSE_IRQ((CE_WARN, "%s: "
3611 		    " acpi_translate_pci_irq failed for device %s, instance"
3612 		    " #%d", psm_name, ddi_get_name(dip),
3613 		    ddi_get_instance(dip)));
3614 		return (status);
3615 	}
3616 
3617 	if (status == ACPI_PSM_PARTIAL && acpipsmlnk.lnkobj != NULL) {
3618 		status = apic_acpi_irq_configure(&acpipsmlnk, dip, pci_irqp,
3619 		    intr_flagp);
3620 		if (status != ACPI_PSM_SUCCESS) {
3621 			status = acpi_get_current_irq_resource(&acpipsmlnk,
3622 			    pci_irqp, intr_flagp);
3623 		}
3624 	}
3625 
3626 	if (status == ACPI_PSM_SUCCESS) {
3627 		acpi_new_irq_cache_ent(busid, devid, ipin, *pci_irqp,
3628 		    intr_flagp, &acpipsmlnk);
3629 
3630 		APIC_VERBOSE_IRQ((CE_CONT, "%s: [ACPI] "
3631 		    "new irq %d for device %s, instance #%d\n", psm_name,
3632 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
3633 	}
3634 
3635 	return (status);
3636 }
3637 
3638 /*
3639  * Adds an entry to the irq list passed in, and returns the new list.
3640  * Entries are added in priority order (lower numerical priorities are
3641  * placed closer to the head of the list)
3642  */
3643 static prs_irq_list_t *
3644 acpi_insert_prs_irq_ent(prs_irq_list_t *listp, int priority, int irq,
3645     iflag_t *iflagp, acpi_prs_private_t *prsprvp)
3646 {
3647 	struct prs_irq_list_ent *newent, *prevp = NULL, *origlistp;
3648 
3649 	newent = kmem_zalloc(sizeof (struct prs_irq_list_ent), KM_SLEEP);
3650 
3651 	newent->list_prio = priority;
3652 	newent->irq = irq;
3653 	newent->intrflags = *iflagp;
3654 	newent->prsprv = *prsprvp;
3655 	/* ->next is NULL from kmem_zalloc */
3656 
3657 	/*
3658 	 * New list -- return the new entry as the list.
3659 	 */
3660 	if (listp == NULL)
3661 		return (newent);
3662 
3663 	/*
3664 	 * Save original list pointer for return (since we're not modifying
3665 	 * the head)
3666 	 */
3667 	origlistp = listp;
3668 
3669 	/*
3670 	 * Insertion sort, with entries with identical keys stored AFTER
3671 	 * existing entries (the less-than-or-equal test of priority does
3672 	 * this for us).
3673 	 */
3674 	while (listp != NULL && listp->list_prio <= priority) {
3675 		prevp = listp;
3676 		listp = listp->next;
3677 	}
3678 
3679 	newent->next = listp;
3680 
3681 	if (prevp == NULL) { /* Add at head of list (newent is the new head) */
3682 		return (newent);
3683 	} else {
3684 		prevp->next = newent;
3685 		return (origlistp);
3686 	}
3687 }
3688 
3689 /*
3690  * Frees the list passed in, deallocating all memory and leaving *listpp
3691  * set to NULL.
3692  */
3693 static void
3694 acpi_destroy_prs_irq_list(prs_irq_list_t **listpp)
3695 {
3696 	struct prs_irq_list_ent *nextp;
3697 
3698 	ASSERT(listpp != NULL);
3699 
3700 	while (*listpp != NULL) {
3701 		nextp = (*listpp)->next;
3702 		kmem_free(*listpp, sizeof (struct prs_irq_list_ent));
3703 		*listpp = nextp;
3704 	}
3705 }
3706 
3707 /*
3708  * apic_choose_irqs_from_prs returns a list of irqs selected from the list of
3709  * irqs returned by the link device's _PRS method.  The irqs are chosen
3710  * to minimize contention in situations where the interrupt link device
3711  * can be programmed to steer interrupts to different interrupt controller
3712  * inputs (some of which may already be in use).  The list is sorted in order
3713  * of irqs to use, with the highest priority given to interrupt controller
3714  * inputs that are not shared.   When an interrupt controller input
3715  * must be shared, apic_choose_irqs_from_prs adds the possible irqs to the
3716  * returned list in the order that minimizes sharing (thereby ensuring lowest
3717  * possible latency from interrupt trigger time to ISR execution time).
3718  */
3719 static prs_irq_list_t *
3720 apic_choose_irqs_from_prs(acpi_irqlist_t *irqlistent, dev_info_t *dip,
3721     int crs_irq)
3722 {
3723 	int32_t irq;
3724 	int i;
3725 	prs_irq_list_t *prsirqlistp = NULL;
3726 	iflag_t iflags;
3727 
3728 	while (irqlistent != NULL) {
3729 		irqlistent->intr_flags.bustype = BUS_PCI;
3730 
3731 		for (i = 0; i < irqlistent->num_irqs; i++) {
3732 
3733 			irq = irqlistent->irqs[i];
3734 
3735 			if (irq <= 0) {
3736 				/* invalid irq number */
3737 				continue;
3738 			}
3739 
3740 			if ((irq < 16) && (apic_reserved_irqlist[irq]))
3741 				continue;
3742 
3743 			if ((apic_irq_table[irq] == NULL) ||
3744 			    (apic_irq_table[irq]->airq_dip == dip)) {
3745 
3746 				prsirqlistp = acpi_insert_prs_irq_ent(
3747 				    prsirqlistp, 0 /* Highest priority */, irq,
3748 				    &irqlistent->intr_flags,
3749 				    &irqlistent->acpi_prs_prv);
3750 
3751 				/*
3752 				 * If we do not prefer the current irq from _CRS
3753 				 * or if we do and this irq is the same as the
3754 				 * current irq from _CRS, this is the one
3755 				 * to pick.
3756 				 */
3757 				if (!(apic_prefer_crs) || (irq == crs_irq)) {
3758 					return (prsirqlistp);
3759 				}
3760 				continue;
3761 			}
3762 
3763 			/*
3764 			 * Edge-triggered interrupts cannot be shared
3765 			 */
3766 			if (irqlistent->intr_flags.intr_el == INTR_EL_EDGE)
3767 				continue;
3768 
3769 			/*
3770 			 * To work around BIOSes that contain incorrect
3771 			 * interrupt polarity information in interrupt
3772 			 * descriptors returned by _PRS, we assume that
3773 			 * the polarity of the other device sharing this
3774 			 * interrupt controller input is compatible.
3775 			 * If it's not, the caller will catch it when
3776 			 * the caller invokes the link device's _CRS method
3777 			 * (after invoking its _SRS method).
3778 			 */
3779 			iflags = irqlistent->intr_flags;
3780 			iflags.intr_po =
3781 			    apic_irq_table[irq]->airq_iflag.intr_po;
3782 
3783 			if (!acpi_intr_compatible(iflags,
3784 			    apic_irq_table[irq]->airq_iflag)) {
3785 				APIC_VERBOSE_IRQ((CE_CONT, "!%s: irq %d "
3786 				    "not compatible [%x:%x:%x !~ %x:%x:%x]",
3787 				    psm_name, irq,
3788 				    iflags.intr_po,
3789 				    iflags.intr_el,
3790 				    iflags.bustype,
3791 				    apic_irq_table[irq]->airq_iflag.intr_po,
3792 				    apic_irq_table[irq]->airq_iflag.intr_el,
3793 				    apic_irq_table[irq]->airq_iflag.bustype));
3794 				continue;
3795 			}
3796 
3797 			/*
3798 			 * If we prefer the irq from _CRS, no need
3799 			 * to search any further (and make sure
3800 			 * to add this irq with the highest priority
3801 			 * so it's tried first).
3802 			 */
3803 			if (crs_irq == irq && apic_prefer_crs) {
3804 
3805 				return (acpi_insert_prs_irq_ent(
3806 				    prsirqlistp,
3807 				    0 /* Highest priority */,
3808 				    irq, &iflags,
3809 				    &irqlistent->acpi_prs_prv));
3810 			}
3811 
3812 			/*
3813 			 * Priority is equal to the share count (lower
3814 			 * share count is higher priority). Note that
3815 			 * the intr flags passed in here are the ones we
3816 			 * changed above -- if incorrect, it will be
3817 			 * caught by the caller's _CRS flags comparison.
3818 			 */
3819 			prsirqlistp = acpi_insert_prs_irq_ent(
3820 			    prsirqlistp,
3821 			    apic_irq_table[irq]->airq_share, irq,
3822 			    &iflags, &irqlistent->acpi_prs_prv);
3823 		}
3824 
3825 		/* Go to the next irqlist entry */
3826 		irqlistent = irqlistent->next;
3827 	}
3828 
3829 	return (prsirqlistp);
3830 }
3831 
3832 /*
3833  * Configures the irq for the interrupt link device identified by
3834  * acpipsmlnkp.
3835  *
3836  * Gets the current and the list of possible irq settings for the
3837  * device. If apic_unconditional_srs is not set, and the current
3838  * resource setting is in the list of possible irq settings,
3839  * current irq resource setting is passed to the caller.
3840  *
3841  * Otherwise, picks an irq number from the list of possible irq
3842  * settings, and sets the irq of the device to this value.
3843  * If prefer_crs is set, among a set of irq numbers in the list that have
3844  * the least number of devices sharing the interrupt, we pick current irq
3845  * resource setting if it is a member of this set.
3846  *
3847  * Passes the irq number in the value pointed to by pci_irqp, and
3848  * polarity and sensitivity in the structure pointed to by dipintrflagp
3849  * to the caller.
3850  *
3851  * Note that if setting the irq resource failed, but successfuly obtained
3852  * the current irq resource settings, passes the current irq resources
3853  * and considers it a success.
3854  *
3855  * Returns:
3856  * ACPI_PSM_SUCCESS on success.
3857  *
3858  * ACPI_PSM_FAILURE if an error occured during the configuration or
3859  * if a suitable irq was not found for this device, or if setting the
3860  * irq resource and obtaining the current resource fails.
3861  *
3862  */
3863 static int
3864 apic_acpi_irq_configure(acpi_psm_lnk_t *acpipsmlnkp, dev_info_t *dip,
3865     int *pci_irqp, iflag_t *dipintr_flagp)
3866 {
3867 	int32_t irq;
3868 	int cur_irq = -1;
3869 	acpi_irqlist_t *irqlistp;
3870 	prs_irq_list_t *prs_irq_listp, *prs_irq_entp;
3871 	boolean_t found_irq = B_FALSE;
3872 
3873 	dipintr_flagp->bustype = BUS_PCI;
3874 
3875 	if ((acpi_get_possible_irq_resources(acpipsmlnkp, &irqlistp))
3876 	    == ACPI_PSM_FAILURE) {
3877 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Unable to determine "
3878 		    "or assign IRQ for device %s, instance #%d: The system was "
3879 		    "unable to get the list of potential IRQs from ACPI.",
3880 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
3881 
3882 		return (ACPI_PSM_FAILURE);
3883 	}
3884 
3885 	if ((acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
3886 	    dipintr_flagp) == ACPI_PSM_SUCCESS) && (!apic_unconditional_srs) &&
3887 	    (cur_irq > 0)) {
3888 		/*
3889 		 * If an IRQ is set in CRS and that IRQ exists in the set
3890 		 * returned from _PRS, return that IRQ, otherwise print
3891 		 * a warning
3892 		 */
3893 
3894 		if (acpi_irqlist_find_irq(irqlistp, cur_irq, NULL)
3895 		    == ACPI_PSM_SUCCESS) {
3896 
3897 			ASSERT(pci_irqp != NULL);
3898 			*pci_irqp = cur_irq;
3899 			acpi_free_irqlist(irqlistp);
3900 			return (ACPI_PSM_SUCCESS);
3901 		}
3902 
3903 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find the "
3904 		    "current irq %d for device %s, instance #%d in ACPI's "
3905 		    "list of possible irqs for this device. Picking one from "
3906 		    " the latter list.", psm_name, cur_irq, ddi_get_name(dip),
3907 		    ddi_get_instance(dip)));
3908 	}
3909 
3910 	if ((prs_irq_listp = apic_choose_irqs_from_prs(irqlistp, dip,
3911 	    cur_irq)) == NULL) {
3912 
3913 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find a "
3914 		    "suitable irq from the list of possible irqs for device "
3915 		    "%s, instance #%d in ACPI's list of possible irqs",
3916 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
3917 
3918 		acpi_free_irqlist(irqlistp);
3919 		return (ACPI_PSM_FAILURE);
3920 	}
3921 
3922 	acpi_free_irqlist(irqlistp);
3923 
3924 	for (prs_irq_entp = prs_irq_listp;
3925 	    prs_irq_entp != NULL && found_irq == B_FALSE;
3926 	    prs_irq_entp = prs_irq_entp->next) {
3927 
3928 		acpipsmlnkp->acpi_prs_prv = prs_irq_entp->prsprv;
3929 		irq = prs_irq_entp->irq;
3930 
3931 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Setting irq %d for "
3932 		    "device %s instance #%d\n", psm_name, irq,
3933 		    ddi_get_name(dip), ddi_get_instance(dip)));
3934 
3935 		if ((acpi_set_irq_resource(acpipsmlnkp, irq))
3936 		    == ACPI_PSM_SUCCESS) {
3937 			/*
3938 			 * setting irq was successful, check to make sure CRS
3939 			 * reflects that. If CRS does not agree with what we
3940 			 * set, return the irq that was set.
3941 			 */
3942 
3943 			if (acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
3944 			    dipintr_flagp) == ACPI_PSM_SUCCESS) {
3945 
3946 				if (cur_irq != irq)
3947 					APIC_VERBOSE_IRQ((CE_WARN,
3948 					    "!%s: IRQ resource set "
3949 					    "(irqno %d) for device %s "
3950 					    "instance #%d, differs from "
3951 					    "current setting irqno %d",
3952 					    psm_name, irq, ddi_get_name(dip),
3953 					    ddi_get_instance(dip), cur_irq));
3954 			} else {
3955 				/*
3956 				 * On at least one system, there was a bug in
3957 				 * a DSDT method called by _STA, causing _STA to
3958 				 * indicate that the link device was disabled
3959 				 * (when, in fact, it was enabled).  Since _SRS
3960 				 * succeeded, assume that _CRS is lying and use
3961 				 * the iflags from this _PRS interrupt choice.
3962 				 * If we're wrong about the flags, the polarity
3963 				 * will be incorrect and we may get an interrupt
3964 				 * storm, but there's not much else we can do
3965 				 * at this point.
3966 				 */
3967 				*dipintr_flagp = prs_irq_entp->intrflags;
3968 			}
3969 
3970 			/*
3971 			 * Return the irq that was set, and not what _CRS
3972 			 * reports, since _CRS has been seen to return
3973 			 * different IRQs than what was passed to _SRS on some
3974 			 * systems (and just not return successfully on others).
3975 			 */
3976 			cur_irq = irq;
3977 			found_irq = B_TRUE;
3978 		} else {
3979 			APIC_VERBOSE_IRQ((CE_WARN, "!%s: set resource "
3980 			    "irq %d failed for device %s instance #%d",
3981 			    psm_name, irq, ddi_get_name(dip),
3982 			    ddi_get_instance(dip)));
3983 
3984 			if (cur_irq == -1) {
3985 				acpi_destroy_prs_irq_list(&prs_irq_listp);
3986 				return (ACPI_PSM_FAILURE);
3987 			}
3988 		}
3989 	}
3990 
3991 	acpi_destroy_prs_irq_list(&prs_irq_listp);
3992 
3993 	if (!found_irq)
3994 		return (ACPI_PSM_FAILURE);
3995 
3996 	ASSERT(pci_irqp != NULL);
3997 	*pci_irqp = cur_irq;
3998 	return (ACPI_PSM_SUCCESS);
3999 }
4000 
4001 void
4002 ioapic_disable_redirection()
4003 {
4004 	int ioapic_ix;
4005 	int intin_max;
4006 	int intin_ix;
4007 
4008 	/* Disable the I/O APIC redirection entries */
4009 	for (ioapic_ix = 0; ioapic_ix < apic_io_max; ioapic_ix++) {
4010 
4011 		/* Bits 23-16 define the maximum redirection entries */
4012 		intin_max = (ioapic_read(ioapic_ix, APIC_VERS_CMD) >> 16)
4013 		    & 0xff;
4014 
4015 		for (intin_ix = 0; intin_ix <= intin_max; intin_ix++) {
4016 			/*
4017 			 * The assumption here is that this is safe, even for
4018 			 * systems with IOAPICs that suffer from the hardware
4019 			 * erratum because all devices have been quiesced before
4020 			 * this function is called from apic_shutdown()
4021 			 * (or equivalent). If that assumption turns out to be
4022 			 * false, this mask operation can induce the same
4023 			 * erratum result we're trying to avoid.
4024 			 */
4025 			ioapic_write(ioapic_ix, APIC_RDT_CMD + 2 * intin_ix,
4026 			    AV_MASK);
4027 		}
4028 	}
4029 }
4030 
4031 /*
4032  * Looks for an IOAPIC with the specified physical address in the /ioapics
4033  * node in the device tree (created by the PCI enumerator).
4034  */
4035 static boolean_t
4036 apic_is_ioapic_AMD_813x(uint32_t physaddr)
4037 {
4038 	/*
4039 	 * Look in /ioapics, for the ioapic with
4040 	 * the physical address given
4041 	 */
4042 	dev_info_t *ioapicsnode = ddi_find_devinfo(IOAPICS_NODE_NAME, -1, 0);
4043 	dev_info_t *ioapic_child;
4044 	boolean_t rv = B_FALSE;
4045 	int vid, did;
4046 	uint64_t ioapic_paddr;
4047 	boolean_t done = B_FALSE;
4048 
4049 	if (ioapicsnode == NULL)
4050 		return (B_FALSE);
4051 
4052 	/* Load first child: */
4053 	ioapic_child = ddi_get_child(ioapicsnode);
4054 	while (!done && ioapic_child != 0) { /* Iterate over children */
4055 
4056 		if ((ioapic_paddr = (uint64_t)ddi_prop_get_int64(DDI_DEV_T_ANY,
4057 		    ioapic_child, DDI_PROP_DONTPASS, "reg", 0))
4058 		    != 0 && physaddr == ioapic_paddr) {
4059 
4060 			vid = ddi_prop_get_int(DDI_DEV_T_ANY, ioapic_child,
4061 			    DDI_PROP_DONTPASS, IOAPICS_PROP_VENID, 0);
4062 
4063 			if (vid == VENID_AMD) {
4064 
4065 				did = ddi_prop_get_int(DDI_DEV_T_ANY,
4066 				    ioapic_child, DDI_PROP_DONTPASS,
4067 				    IOAPICS_PROP_DEVID, 0);
4068 
4069 				if (did == DEVID_8131_IOAPIC ||
4070 				    did == DEVID_8132_IOAPIC) {
4071 
4072 					rv = B_TRUE;
4073 					done = B_TRUE;
4074 				}
4075 			}
4076 		}
4077 
4078 		if (!done)
4079 			ioapic_child = ddi_get_next_sibling(ioapic_child);
4080 	}
4081 
4082 	/* The ioapics node was held by ddi_find_devinfo, so release it */
4083 	ndi_rele_devi(ioapicsnode);
4084 	return (rv);
4085 }
4086 
4087 struct apic_state {
4088 	int32_t as_task_reg;
4089 	int32_t as_dest_reg;
4090 	int32_t as_format_reg;
4091 	int32_t as_local_timer;
4092 	int32_t as_pcint_vect;
4093 	int32_t as_int_vect0;
4094 	int32_t as_int_vect1;
4095 	int32_t as_err_vect;
4096 	int32_t as_init_count;
4097 	int32_t as_divide_reg;
4098 	int32_t as_spur_int_reg;
4099 	uint32_t as_ioapic_ids[MAX_IO_APIC];
4100 };
4101 
4102 
4103 static int
4104 apic_acpi_enter_apicmode(void)
4105 {
4106 	ACPI_OBJECT_LIST	arglist;
4107 	ACPI_OBJECT		arg;
4108 	ACPI_STATUS		status;
4109 
4110 	/* Setup parameter object */
4111 	arglist.Count = 1;
4112 	arglist.Pointer = &arg;
4113 	arg.Type = ACPI_TYPE_INTEGER;
4114 	arg.Integer.Value = ACPI_APIC_MODE;
4115 
4116 	status = AcpiEvaluateObject(NULL, "\\_PIC", &arglist, NULL);
4117 	if (ACPI_FAILURE(status))
4118 		return (PSM_FAILURE);
4119 	else
4120 		return (PSM_SUCCESS);
4121 }
4122 
4123 
4124 static void
4125 apic_save_state(struct apic_state *sp)
4126 {
4127 	int	i;
4128 	ulong_t	iflag;
4129 
4130 	PMD(PMD_SX, ("apic_save_state %p\n", (void *)sp))
4131 	/*
4132 	 * First the local APIC.
4133 	 */
4134 	sp->as_task_reg = apic_reg_ops->apic_get_pri();
4135 	sp->as_dest_reg =  apic_reg_ops->apic_read(APIC_DEST_REG);
4136 	if (apic_mode == LOCAL_APIC)
4137 		sp->as_format_reg = apic_reg_ops->apic_read(APIC_FORMAT_REG);
4138 	sp->as_local_timer = apic_reg_ops->apic_read(APIC_LOCAL_TIMER);
4139 	sp->as_pcint_vect = apic_reg_ops->apic_read(APIC_PCINT_VECT);
4140 	sp->as_int_vect0 = apic_reg_ops->apic_read(APIC_INT_VECT0);
4141 	sp->as_int_vect1 = apic_reg_ops->apic_read(APIC_INT_VECT1);
4142 	sp->as_err_vect = apic_reg_ops->apic_read(APIC_ERR_VECT);
4143 	sp->as_init_count = apic_reg_ops->apic_read(APIC_INIT_COUNT);
4144 	sp->as_divide_reg = apic_reg_ops->apic_read(APIC_DIVIDE_REG);
4145 	sp->as_spur_int_reg = apic_reg_ops->apic_read(APIC_SPUR_INT_REG);
4146 
4147 	/*
4148 	 * If on the boot processor then save the IOAPICs' IDs
4149 	 */
4150 	if (psm_get_cpu_id() == 0) {
4151 
4152 		iflag = intr_clear();
4153 		lock_set(&apic_ioapic_lock);
4154 
4155 		for (i = 0; i < apic_io_max; i++)
4156 			sp->as_ioapic_ids[i] = ioapic_read(i, APIC_ID_CMD);
4157 
4158 		lock_clear(&apic_ioapic_lock);
4159 		intr_restore(iflag);
4160 	}
4161 }
4162 
4163 static void
4164 apic_restore_state(struct apic_state *sp)
4165 {
4166 	int	i;
4167 	ulong_t	iflag;
4168 
4169 	/*
4170 	 * First the local APIC.
4171 	 */
4172 	apic_reg_ops->apic_write_task_reg(sp->as_task_reg);
4173 	if (apic_mode == LOCAL_APIC) {
4174 		apic_reg_ops->apic_write(APIC_DEST_REG, sp->as_dest_reg);
4175 		apic_reg_ops->apic_write(APIC_FORMAT_REG, sp->as_format_reg);
4176 	}
4177 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, sp->as_local_timer);
4178 	apic_reg_ops->apic_write(APIC_PCINT_VECT, sp->as_pcint_vect);
4179 	apic_reg_ops->apic_write(APIC_INT_VECT0, sp->as_int_vect0);
4180 	apic_reg_ops->apic_write(APIC_INT_VECT1, sp->as_int_vect1);
4181 	apic_reg_ops->apic_write(APIC_ERR_VECT, sp->as_err_vect);
4182 	apic_reg_ops->apic_write(APIC_INIT_COUNT, sp->as_init_count);
4183 	apic_reg_ops->apic_write(APIC_DIVIDE_REG, sp->as_divide_reg);
4184 	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, sp->as_spur_int_reg);
4185 
4186 	/*
4187 	 * the following only needs to be done once, so we do it on the
4188 	 * boot processor, since we know that we only have one of those
4189 	 */
4190 	if (psm_get_cpu_id() == 0) {
4191 
4192 		iflag = intr_clear();
4193 		lock_set(&apic_ioapic_lock);
4194 
4195 		/* Restore IOAPICs' APIC IDs */
4196 		for (i = 0; i < apic_io_max; i++) {
4197 			ioapic_write(i, APIC_ID_CMD, sp->as_ioapic_ids[i]);
4198 		}
4199 
4200 		lock_clear(&apic_ioapic_lock);
4201 		intr_restore(iflag);
4202 
4203 		/*
4204 		 * Reenter APIC mode before restoring LNK devices
4205 		 */
4206 		(void) apic_acpi_enter_apicmode();
4207 
4208 		/*
4209 		 * restore acpi link device mappings
4210 		 */
4211 		acpi_restore_link_devices();
4212 	}
4213 }
4214 
4215 /*
4216  * Returns 0 on success
4217  */
4218 int
4219 apic_state(psm_state_request_t *rp)
4220 {
4221 	PMD(PMD_SX, ("apic_state "))
4222 	switch (rp->psr_cmd) {
4223 	case PSM_STATE_ALLOC:
4224 		rp->req.psm_state_req.psr_state =
4225 		    kmem_zalloc(sizeof (struct apic_state), KM_NOSLEEP);
4226 		if (rp->req.psm_state_req.psr_state == NULL)
4227 			return (ENOMEM);
4228 		rp->req.psm_state_req.psr_state_size =
4229 		    sizeof (struct apic_state);
4230 		PMD(PMD_SX, (":STATE_ALLOC: state %p, size %lx\n",
4231 		    rp->req.psm_state_req.psr_state,
4232 		    rp->req.psm_state_req.psr_state_size))
4233 		return (0);
4234 
4235 	case PSM_STATE_FREE:
4236 		kmem_free(rp->req.psm_state_req.psr_state,
4237 		    rp->req.psm_state_req.psr_state_size);
4238 		PMD(PMD_SX, (" STATE_FREE: state %p, size %lx\n",
4239 		    rp->req.psm_state_req.psr_state,
4240 		    rp->req.psm_state_req.psr_state_size))
4241 		return (0);
4242 
4243 	case PSM_STATE_SAVE:
4244 		PMD(PMD_SX, (" STATE_SAVE: state %p, size %lx\n",
4245 		    rp->req.psm_state_req.psr_state,
4246 		    rp->req.psm_state_req.psr_state_size))
4247 		apic_save_state(rp->req.psm_state_req.psr_state);
4248 		return (0);
4249 
4250 	case PSM_STATE_RESTORE:
4251 		apic_restore_state(rp->req.psm_state_req.psr_state);
4252 		PMD(PMD_SX, (" STATE_RESTORE: state %p, size %lx\n",
4253 		    rp->req.psm_state_req.psr_state,
4254 		    rp->req.psm_state_req.psr_state_size))
4255 		return (0);
4256 
4257 	default:
4258 		return (EINVAL);
4259 	}
4260 }
4261