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