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