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