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