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