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