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