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