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