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