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