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