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