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