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