xref: /illumos-gate/usr/src/uts/i86pc/io/mp_platform_common.c (revision 4e93fb0f6383eaac21897dcdae56b87118131e4d)
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 		    (pci_config_setup(dipp, &cfg_handle) == DDI_SUCCESS))
1708 			return (-1);
1709 		if ((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 documented in the
1718 			 * PCI-to-PCI spec.  If the PCI-to-PCI bridge is
1719 			 * behind another PCI-to-PCI bridge, then it needs
1720 			 * to keep ascending until an interrupt entry is
1721 			 * found or the root is reached.
1722 			 */
1723 			ipin = (child_devno + child_ipin) % PCI_INTD;
1724 				if (bridge_bus == 0 && apic_pci_bus_total == 1)
1725 					bridge_bus = (int)apic_single_pci_busid;
1726 				pci_irq = ((bridge_devno & 0x1f) << 2) |
1727 				    (ipin & 0x3);
1728 				if ((*intrp = apic_find_io_intr_w_busid(pci_irq,
1729 				    bridge_bus)) != NULL) {
1730 					return (pci_irq);
1731 				}
1732 			dip = dipp;
1733 			child_devno = bridge_devno;
1734 			child_ipin = ipin;
1735 		} else {
1736 			pci_config_teardown(&cfg_handle);
1737 			return (-1);
1738 		}
1739 	}
1740 	/*LINTED: function will not fall off the bottom */
1741 }
1742 
1743 
1744 
1745 
1746 static uchar_t
1747 acpi_find_ioapic(int irq)
1748 {
1749 	int i;
1750 
1751 	for (i = 0; i < apic_io_max; i++) {
1752 		if (irq >= apic_io_vectbase[i] && irq <= apic_io_vectend[i])
1753 			return (i);
1754 	}
1755 	return (0xFF);	/* shouldn't happen */
1756 }
1757 
1758 /*
1759  * See if two irqs are compatible for sharing a vector.
1760  * Currently we only support sharing of PCI devices.
1761  */
1762 static int
1763 acpi_intr_compatible(iflag_t iflag1, iflag_t iflag2)
1764 {
1765 	uint_t	level1, po1;
1766 	uint_t	level2, po2;
1767 
1768 	/* Assume active high by default */
1769 	po1 = 0;
1770 	po2 = 0;
1771 
1772 	if (iflag1.bustype != iflag2.bustype || iflag1.bustype != BUS_PCI)
1773 		return (0);
1774 
1775 	if (iflag1.intr_el == INTR_EL_CONFORM)
1776 		level1 = AV_LEVEL;
1777 	else
1778 		level1 = (iflag1.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
1779 
1780 	if (level1 && ((iflag1.intr_po == INTR_PO_ACTIVE_LOW) ||
1781 	    (iflag1.intr_po == INTR_PO_CONFORM)))
1782 		po1 = AV_ACTIVE_LOW;
1783 
1784 	if (iflag2.intr_el == INTR_EL_CONFORM)
1785 		level2 = AV_LEVEL;
1786 	else
1787 		level2 = (iflag2.intr_el == INTR_EL_LEVEL) ? AV_LEVEL : 0;
1788 
1789 	if (level2 && ((iflag2.intr_po == INTR_PO_ACTIVE_LOW) ||
1790 	    (iflag2.intr_po == INTR_PO_CONFORM)))
1791 		po2 = AV_ACTIVE_LOW;
1792 
1793 	if ((level1 == level2) && (po1 == po2))
1794 		return (1);
1795 
1796 	return (0);
1797 }
1798 
1799 /*
1800  * Attempt to share vector with someone else
1801  */
1802 static int
1803 apic_share_vector(int irqno, iflag_t *intr_flagp, short intr_index, int ipl,
1804 	uchar_t ioapicindex, uchar_t ipin, apic_irq_t **irqptrp)
1805 {
1806 #ifdef DEBUG
1807 	apic_irq_t *tmpirqp = NULL;
1808 #endif /* DEBUG */
1809 	apic_irq_t *irqptr, dummyirq;
1810 	int	newirq, chosen_irq = -1, share = 127;
1811 	int	lowest, highest, i;
1812 	uchar_t	share_id;
1813 
1814 	DDI_INTR_IMPLDBG((CE_CONT, "apic_share_vector: irqno=0x%x "
1815 	    "intr_index=0x%x ipl=0x%x\n", irqno, intr_index, ipl));
1816 
1817 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
1818 	lowest = apic_ipltopri[ipl-1] + APIC_VECTOR_PER_IPL;
1819 
1820 	if (highest < lowest) /* Both ipl and ipl-1 map to same pri */
1821 		lowest -= APIC_VECTOR_PER_IPL;
1822 	dummyirq.airq_mps_intr_index = intr_index;
1823 	dummyirq.airq_ioapicindex = ioapicindex;
1824 	dummyirq.airq_intin_no = ipin;
1825 	if (intr_flagp)
1826 		dummyirq.airq_iflag = *intr_flagp;
1827 	apic_record_rdt_entry(&dummyirq, irqno);
1828 	for (i = lowest; i <= highest; i++) {
1829 		newirq = apic_vector_to_irq[i];
1830 		if (newirq == APIC_RESV_IRQ)
1831 			continue;
1832 		irqptr = apic_irq_table[newirq];
1833 
1834 		if ((dummyirq.airq_rdt_entry & 0xFF00) !=
1835 		    (irqptr->airq_rdt_entry & 0xFF00))
1836 			/* not compatible */
1837 			continue;
1838 
1839 		if (irqptr->airq_share < share) {
1840 			share = irqptr->airq_share;
1841 			chosen_irq = newirq;
1842 		}
1843 	}
1844 	if (chosen_irq != -1) {
1845 		/*
1846 		 * Assign a share id which is free or which is larger
1847 		 * than the largest one.
1848 		 */
1849 		share_id = 1;
1850 		mutex_enter(&airq_mutex);
1851 		irqptr = apic_irq_table[chosen_irq];
1852 		while (irqptr) {
1853 			if (irqptr->airq_mps_intr_index == FREE_INDEX) {
1854 				share_id = irqptr->airq_share_id;
1855 				break;
1856 			}
1857 			if (share_id <= irqptr->airq_share_id)
1858 				share_id = irqptr->airq_share_id + 1;
1859 #ifdef DEBUG
1860 			tmpirqp = irqptr;
1861 #endif /* DEBUG */
1862 			irqptr = irqptr->airq_next;
1863 		}
1864 		if (!irqptr) {
1865 			irqptr = kmem_zalloc(sizeof (apic_irq_t), KM_SLEEP);
1866 			irqptr->airq_temp_cpu = IRQ_UNINIT;
1867 			irqptr->airq_next =
1868 			    apic_irq_table[chosen_irq]->airq_next;
1869 			apic_irq_table[chosen_irq]->airq_next = irqptr;
1870 #ifdef	DEBUG
1871 			tmpirqp = apic_irq_table[chosen_irq];
1872 #endif /* DEBUG */
1873 		}
1874 		irqptr->airq_mps_intr_index = intr_index;
1875 		irqptr->airq_ioapicindex = ioapicindex;
1876 		irqptr->airq_intin_no = ipin;
1877 		if (intr_flagp)
1878 			irqptr->airq_iflag = *intr_flagp;
1879 		irqptr->airq_vector = apic_irq_table[chosen_irq]->airq_vector;
1880 		irqptr->airq_share_id = share_id;
1881 		apic_record_rdt_entry(irqptr, irqno);
1882 		*irqptrp = irqptr;
1883 #ifdef	DEBUG
1884 		/* shuffle the pointers to test apic_delspl path */
1885 		if (tmpirqp) {
1886 			tmpirqp->airq_next = irqptr->airq_next;
1887 			irqptr->airq_next = apic_irq_table[chosen_irq];
1888 			apic_irq_table[chosen_irq] = irqptr;
1889 		}
1890 #endif /* DEBUG */
1891 		mutex_exit(&airq_mutex);
1892 		return (VIRTIRQ(chosen_irq, share_id));
1893 	}
1894 	return (-1);
1895 }
1896 
1897 /*
1898  *
1899  */
1900 static int
1901 apic_setup_irq_table(dev_info_t *dip, int irqno, struct apic_io_intr *intrp,
1902     struct intrspec *ispec, iflag_t *intr_flagp, int type)
1903 {
1904 	int origirq = ispec->intrspec_vec;
1905 	uchar_t ipl = ispec->intrspec_pri;
1906 	int	newirq, intr_index;
1907 	uchar_t	ipin, ioapic, ioapicindex, vector;
1908 	apic_irq_t *irqptr;
1909 	major_t	major;
1910 	dev_info_t	*sdip;
1911 
1912 	DDI_INTR_IMPLDBG((CE_CONT, "apic_setup_irq_table: dip=0x%p type=%d "
1913 	    "irqno=0x%x origirq=0x%x\n", (void *)dip, type, irqno, origirq));
1914 
1915 	ASSERT(ispec != NULL);
1916 
1917 	major =  (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
1918 
1919 	if (DDI_INTR_IS_MSI_OR_MSIX(type)) {
1920 		/* MSI/X doesn't need to setup ioapic stuffs */
1921 		ioapicindex = 0xff;
1922 		ioapic = 0xff;
1923 		ipin = (uchar_t)0xff;
1924 		intr_index = (type == DDI_INTR_TYPE_MSI) ? MSI_INDEX :
1925 		    MSIX_INDEX;
1926 		mutex_enter(&airq_mutex);
1927 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) == -1) {
1928 			mutex_exit(&airq_mutex);
1929 			/* need an irq for MSI/X to index into autovect[] */
1930 			cmn_err(CE_WARN, "No interrupt irq: %s instance %d",
1931 			    ddi_get_name(dip), ddi_get_instance(dip));
1932 			return (-1);
1933 		}
1934 		mutex_exit(&airq_mutex);
1935 
1936 	} else if (intrp != NULL) {
1937 		intr_index = (int)(intrp - apic_io_intrp);
1938 		ioapic = intrp->intr_destid;
1939 		ipin = intrp->intr_destintin;
1940 		/* Find ioapicindex. If destid was ALL, we will exit with 0. */
1941 		for (ioapicindex = apic_io_max - 1; ioapicindex; ioapicindex--)
1942 			if (apic_io_id[ioapicindex] == ioapic)
1943 				break;
1944 		ASSERT((ioapic == apic_io_id[ioapicindex]) ||
1945 		    (ioapic == INTR_ALL_APIC));
1946 
1947 		/* check whether this intin# has been used by another irqno */
1948 		if ((newirq = apic_find_intin(ioapicindex, ipin)) != -1) {
1949 			return (newirq);
1950 		}
1951 
1952 	} else if (intr_flagp != NULL) {
1953 		/* ACPI case */
1954 		intr_index = ACPI_INDEX;
1955 		ioapicindex = acpi_find_ioapic(irqno);
1956 		ASSERT(ioapicindex != 0xFF);
1957 		ioapic = apic_io_id[ioapicindex];
1958 		ipin = irqno - apic_io_vectbase[ioapicindex];
1959 		if (apic_irq_table[irqno] &&
1960 		    apic_irq_table[irqno]->airq_mps_intr_index == ACPI_INDEX) {
1961 			ASSERT(apic_irq_table[irqno]->airq_intin_no == ipin &&
1962 			    apic_irq_table[irqno]->airq_ioapicindex ==
1963 			    ioapicindex);
1964 			return (irqno);
1965 		}
1966 
1967 	} else {
1968 		/* default configuration */
1969 		ioapicindex = 0;
1970 		ioapic = apic_io_id[ioapicindex];
1971 		ipin = (uchar_t)irqno;
1972 		intr_index = DEFAULT_INDEX;
1973 	}
1974 
1975 	if (ispec == NULL) {
1976 		APIC_VERBOSE_IOAPIC((CE_WARN, "No intrspec for irqno = %x\n",
1977 		    irqno));
1978 	} else if ((vector = apic_allocate_vector(ipl, irqno, 0)) == 0) {
1979 		if ((newirq = apic_share_vector(irqno, intr_flagp, intr_index,
1980 		    ipl, ioapicindex, ipin, &irqptr)) != -1) {
1981 			irqptr->airq_ipl = ipl;
1982 			irqptr->airq_origirq = (uchar_t)origirq;
1983 			irqptr->airq_dip = dip;
1984 			irqptr->airq_major = major;
1985 			sdip = apic_irq_table[IRQINDEX(newirq)]->airq_dip;
1986 			/* This is OK to do really */
1987 			if (sdip == NULL) {
1988 				cmn_err(CE_WARN, "Sharing vectors: %s"
1989 				    " instance %d and SCI",
1990 				    ddi_get_name(dip), ddi_get_instance(dip));
1991 			} else {
1992 				cmn_err(CE_WARN, "Sharing vectors: %s"
1993 				    " instance %d and %s instance %d",
1994 				    ddi_get_name(sdip), ddi_get_instance(sdip),
1995 				    ddi_get_name(dip), ddi_get_instance(dip));
1996 			}
1997 			return (newirq);
1998 		}
1999 		/* try high priority allocation now  that share has failed */
2000 		if ((vector = apic_allocate_vector(ipl, irqno, 1)) == 0) {
2001 			cmn_err(CE_WARN, "No interrupt vector: %s instance %d",
2002 			    ddi_get_name(dip), ddi_get_instance(dip));
2003 			return (-1);
2004 		}
2005 	}
2006 
2007 	mutex_enter(&airq_mutex);
2008 	if (apic_irq_table[irqno] == NULL) {
2009 		irqptr = kmem_zalloc(sizeof (apic_irq_t), KM_SLEEP);
2010 		irqptr->airq_temp_cpu = IRQ_UNINIT;
2011 		apic_irq_table[irqno] = irqptr;
2012 	} else {
2013 		irqptr = apic_irq_table[irqno];
2014 		if (irqptr->airq_mps_intr_index != FREE_INDEX) {
2015 			/*
2016 			 * The slot is used by another irqno, so allocate
2017 			 * a free irqno for this interrupt
2018 			 */
2019 			newirq = apic_allocate_irq(apic_first_avail_irq);
2020 			if (newirq == -1) {
2021 				mutex_exit(&airq_mutex);
2022 				return (-1);
2023 			}
2024 			irqno = newirq;
2025 			irqptr = apic_irq_table[irqno];
2026 			if (irqptr == NULL) {
2027 				irqptr = kmem_zalloc(sizeof (apic_irq_t),
2028 				    KM_SLEEP);
2029 				irqptr->airq_temp_cpu = IRQ_UNINIT;
2030 				apic_irq_table[irqno] = irqptr;
2031 			}
2032 			vector = apic_modify_vector(vector, newirq);
2033 		}
2034 	}
2035 	apic_max_device_irq = max(irqno, apic_max_device_irq);
2036 	apic_min_device_irq = min(irqno, apic_min_device_irq);
2037 	mutex_exit(&airq_mutex);
2038 	irqptr->airq_ioapicindex = ioapicindex;
2039 	irqptr->airq_intin_no = ipin;
2040 	irqptr->airq_ipl = ipl;
2041 	irqptr->airq_vector = vector;
2042 	irqptr->airq_origirq = (uchar_t)origirq;
2043 	irqptr->airq_share_id = 0;
2044 	irqptr->airq_mps_intr_index = (short)intr_index;
2045 	irqptr->airq_dip = dip;
2046 	irqptr->airq_major = major;
2047 	irqptr->airq_cpu = apic_bind_intr(dip, irqno, ioapic, ipin);
2048 	if (intr_flagp)
2049 		irqptr->airq_iflag = *intr_flagp;
2050 
2051 	if (!DDI_INTR_IS_MSI_OR_MSIX(type)) {
2052 		/* setup I/O APIC entry for non-MSI/X interrupts */
2053 		apic_record_rdt_entry(irqptr, irqno);
2054 	}
2055 	return (irqno);
2056 }
2057 
2058 /*
2059  * return the cpu to which this intr should be bound.
2060  * Check properties or any other mechanism to see if user wants it
2061  * bound to a specific CPU. If so, return the cpu id with high bit set.
2062  * If not, use the policy to choose a cpu and return the id.
2063  */
2064 uchar_t
2065 apic_bind_intr(dev_info_t *dip, int irq, uchar_t ioapicid, uchar_t intin)
2066 {
2067 	int	instance, instno, prop_len, bind_cpu, count;
2068 	uint_t	i, rc;
2069 	uchar_t	cpu;
2070 	major_t	major;
2071 	char	*name, *drv_name, *prop_val, *cptr;
2072 	char	prop_name[32];
2073 
2074 
2075 	if (apic_intr_policy == INTR_LOWEST_PRIORITY)
2076 		return (IRQ_UNBOUND);
2077 
2078 	drv_name = NULL;
2079 	rc = DDI_PROP_NOT_FOUND;
2080 	major = (major_t)-1;
2081 	if (dip != NULL) {
2082 		name = ddi_get_name(dip);
2083 		major = ddi_name_to_major(name);
2084 		drv_name = ddi_major_to_name(major);
2085 		instance = ddi_get_instance(dip);
2086 		if (apic_intr_policy == INTR_ROUND_ROBIN_WITH_AFFINITY) {
2087 			i = apic_min_device_irq;
2088 			for (; i <= apic_max_device_irq; i++) {
2089 
2090 				if ((i == irq) || (apic_irq_table[i] == NULL) ||
2091 				    (apic_irq_table[i]->airq_mps_intr_index
2092 				    == FREE_INDEX))
2093 					continue;
2094 
2095 				if ((apic_irq_table[i]->airq_major == major) &&
2096 				    (!(apic_irq_table[i]->airq_cpu &
2097 				    IRQ_USER_BOUND))) {
2098 
2099 					cpu = apic_irq_table[i]->airq_cpu;
2100 
2101 					cmn_err(CE_CONT,
2102 					    "!%s: %s (%s) instance #%d "
2103 					    "vector 0x%x ioapic 0x%x "
2104 					    "intin 0x%x is bound to cpu %d\n",
2105 					    psm_name,
2106 					    name, drv_name, instance, irq,
2107 					    ioapicid, intin, cpu);
2108 					return (cpu);
2109 				}
2110 			}
2111 		}
2112 		/*
2113 		 * search for "drvname"_intpt_bind_cpus property first, the
2114 		 * syntax of the property should be "a[,b,c,...]" where
2115 		 * instance 0 binds to cpu a, instance 1 binds to cpu b,
2116 		 * instance 3 binds to cpu c...
2117 		 * ddi_getlongprop() will search /option first, then /
2118 		 * if "drvname"_intpt_bind_cpus doesn't exist, then find
2119 		 * intpt_bind_cpus property.  The syntax is the same, and
2120 		 * it applies to all the devices if its "drvname" specific
2121 		 * property doesn't exist
2122 		 */
2123 		(void) strcpy(prop_name, drv_name);
2124 		(void) strcat(prop_name, "_intpt_bind_cpus");
2125 		rc = ddi_getlongprop(DDI_DEV_T_ANY, dip, 0, prop_name,
2126 		    (caddr_t)&prop_val, &prop_len);
2127 		if (rc != DDI_PROP_SUCCESS) {
2128 			rc = ddi_getlongprop(DDI_DEV_T_ANY, dip, 0,
2129 			    "intpt_bind_cpus", (caddr_t)&prop_val, &prop_len);
2130 		}
2131 	}
2132 	if (rc == DDI_PROP_SUCCESS) {
2133 		for (i = count = 0; i < (prop_len - 1); i++)
2134 			if (prop_val[i] == ',')
2135 				count++;
2136 		if (prop_val[i-1] != ',')
2137 			count++;
2138 		/*
2139 		 * if somehow the binding instances defined in the
2140 		 * property are not enough for this instno., then
2141 		 * reuse the pattern for the next instance until
2142 		 * it reaches the requested instno
2143 		 */
2144 		instno = instance % count;
2145 		i = 0;
2146 		cptr = prop_val;
2147 		while (i < instno)
2148 			if (*cptr++ == ',')
2149 				i++;
2150 		bind_cpu = stoi(&cptr);
2151 		kmem_free(prop_val, prop_len);
2152 		/* if specific cpu is bogus, then default to cpu 0 */
2153 		if (bind_cpu >= apic_nproc) {
2154 			cmn_err(CE_WARN, "%s: %s=%s: CPU %d not present",
2155 			    psm_name, prop_name, prop_val, bind_cpu);
2156 			bind_cpu = 0;
2157 		} else {
2158 			/* indicate that we are bound at user request */
2159 			bind_cpu |= IRQ_USER_BOUND;
2160 		}
2161 		/*
2162 		 * no need to check apic_cpus[].aci_status, if specific cpu is
2163 		 * not up, then post_cpu_start will handle it.
2164 		 */
2165 	} else {
2166 		bind_cpu = apic_next_bind_cpu++;
2167 		if (bind_cpu >= apic_nproc) {
2168 			apic_next_bind_cpu = 1;
2169 			bind_cpu = 0;
2170 		}
2171 	}
2172 	if (drv_name != NULL)
2173 		cmn_err(CE_CONT, "!%s: %s (%s) instance %d "
2174 		    "vector 0x%x ioapic 0x%x intin 0x%x is bound to cpu %d\n",
2175 		    psm_name, name, drv_name, instance,
2176 		    irq, ioapicid, intin, bind_cpu & ~IRQ_USER_BOUND);
2177 	else
2178 		cmn_err(CE_CONT, "!%s: "
2179 		    "vector 0x%x ioapic 0x%x intin 0x%x is bound to cpu %d\n",
2180 		    psm_name, irq, ioapicid, intin, bind_cpu & ~IRQ_USER_BOUND);
2181 
2182 	return ((uchar_t)bind_cpu);
2183 }
2184 
2185 static struct apic_io_intr *
2186 apic_find_io_intr_w_busid(int irqno, int busid)
2187 {
2188 	struct	apic_io_intr	*intrp;
2189 
2190 	/*
2191 	 * It can have more than 1 entry with same source bus IRQ,
2192 	 * but unique with the source bus id
2193 	 */
2194 	intrp = apic_io_intrp;
2195 	if (intrp != NULL) {
2196 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
2197 			if (intrp->intr_irq == irqno &&
2198 			    intrp->intr_busid == busid &&
2199 			    intrp->intr_type == IO_INTR_INT)
2200 				return (intrp);
2201 			intrp++;
2202 		}
2203 	}
2204 	APIC_VERBOSE_IOAPIC((CE_NOTE, "Did not find io intr for irqno:"
2205 	    "busid %x:%x\n", irqno, busid));
2206 	return ((struct apic_io_intr *)NULL);
2207 }
2208 
2209 
2210 struct mps_bus_info {
2211 	char	*bus_name;
2212 	int	bus_id;
2213 } bus_info_array[] = {
2214 	"ISA ", BUS_ISA,
2215 	"PCI ", BUS_PCI,
2216 	"EISA ", BUS_EISA,
2217 	"XPRESS", BUS_XPRESS,
2218 	"PCMCIA", BUS_PCMCIA,
2219 	"VL ", BUS_VL,
2220 	"CBUS ", BUS_CBUS,
2221 	"CBUSII", BUS_CBUSII,
2222 	"FUTURE", BUS_FUTURE,
2223 	"INTERN", BUS_INTERN,
2224 	"MBI ", BUS_MBI,
2225 	"MBII ", BUS_MBII,
2226 	"MPI ", BUS_MPI,
2227 	"MPSA ", BUS_MPSA,
2228 	"NUBUS ", BUS_NUBUS,
2229 	"TC ", BUS_TC,
2230 	"VME ", BUS_VME,
2231 	"PCI-E ", BUS_PCIE
2232 };
2233 
2234 static int
2235 apic_find_bus_type(char *bus)
2236 {
2237 	int	i = 0;
2238 
2239 	for (; i < sizeof (bus_info_array)/sizeof (struct mps_bus_info); i++)
2240 		if (strncmp(bus, bus_info_array[i].bus_name,
2241 		    strlen(bus_info_array[i].bus_name)) == 0)
2242 			return (bus_info_array[i].bus_id);
2243 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus type for bus %s", bus));
2244 	return (0);
2245 }
2246 
2247 static int
2248 apic_find_bus(int busid)
2249 {
2250 	struct	apic_bus	*busp;
2251 
2252 	busp = apic_busp;
2253 	while (busp->bus_entry == APIC_BUS_ENTRY) {
2254 		if (busp->bus_id == busid)
2255 			return (apic_find_bus_type((char *)&busp->bus_str1));
2256 		busp++;
2257 	}
2258 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus for bus id %x", busid));
2259 	return (0);
2260 }
2261 
2262 static int
2263 apic_find_bus_id(int bustype)
2264 {
2265 	struct	apic_bus	*busp;
2266 
2267 	busp = apic_busp;
2268 	while (busp->bus_entry == APIC_BUS_ENTRY) {
2269 		if (apic_find_bus_type((char *)&busp->bus_str1) == bustype)
2270 			return (busp->bus_id);
2271 		busp++;
2272 	}
2273 	APIC_VERBOSE_IOAPIC((CE_WARN, "Did not find bus id for bustype %x",
2274 	    bustype));
2275 	return (-1);
2276 }
2277 
2278 /*
2279  * Check if a particular irq need to be reserved for any io_intr
2280  */
2281 static struct apic_io_intr *
2282 apic_find_io_intr(int irqno)
2283 {
2284 	struct	apic_io_intr	*intrp;
2285 
2286 	intrp = apic_io_intrp;
2287 	if (intrp != NULL) {
2288 		while (intrp->intr_entry == APIC_IO_INTR_ENTRY) {
2289 			if (intrp->intr_irq == irqno &&
2290 			    intrp->intr_type == IO_INTR_INT)
2291 				return (intrp);
2292 			intrp++;
2293 		}
2294 	}
2295 	return ((struct apic_io_intr *)NULL);
2296 }
2297 
2298 /*
2299  * Check if the given ioapicindex intin combination has already been assigned
2300  * an irq. If so return irqno. Else -1
2301  */
2302 static int
2303 apic_find_intin(uchar_t ioapic, uchar_t intin)
2304 {
2305 	apic_irq_t *irqptr;
2306 	int	i;
2307 
2308 	/* find ioapic and intin in the apic_irq_table[] and return the index */
2309 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
2310 		irqptr = apic_irq_table[i];
2311 		while (irqptr) {
2312 			if ((irqptr->airq_mps_intr_index >= 0) &&
2313 			    (irqptr->airq_intin_no == intin) &&
2314 			    (irqptr->airq_ioapicindex == ioapic)) {
2315 				APIC_VERBOSE_IOAPIC((CE_NOTE, "!Found irq "
2316 				    "entry for ioapic:intin %x:%x "
2317 				    "shared interrupts ?", ioapic, intin));
2318 				return (i);
2319 			}
2320 			irqptr = irqptr->airq_next;
2321 		}
2322 	}
2323 	return (-1);
2324 }
2325 
2326 int
2327 apic_allocate_irq(int irq)
2328 {
2329 	int	freeirq, i;
2330 
2331 	if ((freeirq = apic_find_free_irq(irq, (APIC_RESV_IRQ - 1))) == -1)
2332 		if ((freeirq = apic_find_free_irq(APIC_FIRST_FREE_IRQ,
2333 		    (irq - 1))) == -1) {
2334 			/*
2335 			 * if BIOS really defines every single irq in the mps
2336 			 * table, then don't worry about conflicting with
2337 			 * them, just use any free slot in apic_irq_table
2338 			 */
2339 			for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
2340 				if ((apic_irq_table[i] == NULL) ||
2341 				    apic_irq_table[i]->airq_mps_intr_index ==
2342 				    FREE_INDEX) {
2343 				freeirq = i;
2344 				break;
2345 			}
2346 		}
2347 		if (freeirq == -1) {
2348 			/* This shouldn't happen, but just in case */
2349 			cmn_err(CE_WARN, "%s: NO available IRQ", psm_name);
2350 			return (-1);
2351 		}
2352 	}
2353 	if (apic_irq_table[freeirq] == NULL) {
2354 		apic_irq_table[freeirq] =
2355 		    kmem_zalloc(sizeof (apic_irq_t), KM_NOSLEEP);
2356 		if (apic_irq_table[freeirq] == NULL) {
2357 			cmn_err(CE_WARN, "%s: NO memory to allocate IRQ",
2358 			psm_name);
2359 			return (-1);
2360 		}
2361 		apic_irq_table[freeirq]->airq_mps_intr_index = FREE_INDEX;
2362 	}
2363 	return (freeirq);
2364 }
2365 
2366 static int
2367 apic_find_free_irq(int start, int end)
2368 {
2369 	int	i;
2370 
2371 	for (i = start; i <= end; i++)
2372 		/* Check if any I/O entry needs this IRQ */
2373 		if (apic_find_io_intr(i) == NULL) {
2374 			/* Then see if it is free */
2375 			if ((apic_irq_table[i] == NULL) ||
2376 			    (apic_irq_table[i]->airq_mps_intr_index ==
2377 			    FREE_INDEX)) {
2378 				return (i);
2379 			}
2380 		}
2381 	return (-1);
2382 }
2383 
2384 
2385 /*
2386  * Mark vector as being in the process of being deleted. Interrupts
2387  * may still come in on some CPU. The moment an interrupt comes with
2388  * the new vector, we know we can free the old one. Called only from
2389  * addspl and delspl with interrupts disabled. Because an interrupt
2390  * can be shared, but no interrupt from either device may come in,
2391  * we also use a timeout mechanism, which we arbitrarily set to
2392  * apic_revector_timeout microseconds.
2393  */
2394 static void
2395 apic_mark_vector(uchar_t oldvector, uchar_t newvector)
2396 {
2397 	ulong_t iflag;
2398 
2399 	iflag = intr_clear();
2400 	lock_set(&apic_revector_lock);
2401 	if (!apic_oldvec_to_newvec) {
2402 		apic_oldvec_to_newvec =
2403 		    kmem_zalloc(sizeof (newvector) * APIC_MAX_VECTOR * 2,
2404 		    KM_NOSLEEP);
2405 
2406 		if (!apic_oldvec_to_newvec) {
2407 			/*
2408 			 * This failure is not catastrophic.
2409 			 * But, the oldvec will never be freed.
2410 			 */
2411 			apic_error |= APIC_ERR_MARK_VECTOR_FAIL;
2412 			lock_clear(&apic_revector_lock);
2413 			intr_restore(iflag);
2414 			return;
2415 		}
2416 		apic_newvec_to_oldvec = &apic_oldvec_to_newvec[APIC_MAX_VECTOR];
2417 	}
2418 
2419 	/* See if we already did this for drivers which do double addintrs */
2420 	if (apic_oldvec_to_newvec[oldvector] != newvector) {
2421 		apic_oldvec_to_newvec[oldvector] = newvector;
2422 		apic_newvec_to_oldvec[newvector] = oldvector;
2423 		apic_revector_pending++;
2424 	}
2425 	lock_clear(&apic_revector_lock);
2426 	intr_restore(iflag);
2427 	(void) timeout(apic_xlate_vector_free_timeout_handler,
2428 	    (void *)(uintptr_t)oldvector, drv_usectohz(apic_revector_timeout));
2429 }
2430 
2431 /*
2432  * xlate_vector is called from intr_enter if revector_pending is set.
2433  * It will xlate it if needed and mark the old vector as free.
2434  */
2435 uchar_t
2436 apic_xlate_vector(uchar_t vector)
2437 {
2438 	uchar_t	newvector, oldvector = 0;
2439 
2440 	lock_set(&apic_revector_lock);
2441 	/* Do we really need to do this ? */
2442 	if (!apic_revector_pending) {
2443 		lock_clear(&apic_revector_lock);
2444 		return (vector);
2445 	}
2446 	if ((newvector = apic_oldvec_to_newvec[vector]) != 0)
2447 		oldvector = vector;
2448 	else {
2449 		/*
2450 		 * The incoming vector is new . See if a stale entry is
2451 		 * remaining
2452 		 */
2453 		if ((oldvector = apic_newvec_to_oldvec[vector]) != 0)
2454 			newvector = vector;
2455 	}
2456 
2457 	if (oldvector) {
2458 		apic_revector_pending--;
2459 		apic_oldvec_to_newvec[oldvector] = 0;
2460 		apic_newvec_to_oldvec[newvector] = 0;
2461 		apic_free_vector(oldvector);
2462 		lock_clear(&apic_revector_lock);
2463 		/* There could have been more than one reprogramming! */
2464 		return (apic_xlate_vector(newvector));
2465 	}
2466 	lock_clear(&apic_revector_lock);
2467 	return (vector);
2468 }
2469 
2470 void
2471 apic_xlate_vector_free_timeout_handler(void *arg)
2472 {
2473 	ulong_t iflag;
2474 	uchar_t oldvector, newvector;
2475 
2476 	oldvector = (uchar_t)(uintptr_t)arg;
2477 	iflag = intr_clear();
2478 	lock_set(&apic_revector_lock);
2479 	if ((newvector = apic_oldvec_to_newvec[oldvector]) != 0) {
2480 		apic_free_vector(oldvector);
2481 		apic_oldvec_to_newvec[oldvector] = 0;
2482 		apic_newvec_to_oldvec[newvector] = 0;
2483 		apic_revector_pending--;
2484 	}
2485 
2486 	lock_clear(&apic_revector_lock);
2487 	intr_restore(iflag);
2488 }
2489 
2490 
2491 /*
2492  * compute the polarity, trigger mode and vector for programming into
2493  * the I/O apic and record in airq_rdt_entry.
2494  */
2495 static void
2496 apic_record_rdt_entry(apic_irq_t *irqptr, int irq)
2497 {
2498 	int	ioapicindex, bus_type, vector;
2499 	short	intr_index;
2500 	uint_t	level, po, io_po;
2501 	struct apic_io_intr *iointrp;
2502 
2503 	intr_index = irqptr->airq_mps_intr_index;
2504 	DDI_INTR_IMPLDBG((CE_CONT, "apic_record_rdt_entry: intr_index=%d "
2505 	    "irq = 0x%x dip = 0x%p vector = 0x%x\n", intr_index, irq,
2506 	    (void *)irqptr->airq_dip, irqptr->airq_vector));
2507 
2508 	if (intr_index == RESERVE_INDEX) {
2509 		apic_error |= APIC_ERR_INVALID_INDEX;
2510 		return;
2511 	} else if (APIC_IS_MSI_OR_MSIX_INDEX(intr_index)) {
2512 		return;
2513 	}
2514 
2515 	vector = irqptr->airq_vector;
2516 	ioapicindex = irqptr->airq_ioapicindex;
2517 	/* Assume edge triggered by default */
2518 	level = 0;
2519 	/* Assume active high by default */
2520 	po = 0;
2521 
2522 	if (intr_index == DEFAULT_INDEX || intr_index == FREE_INDEX) {
2523 		ASSERT(irq < 16);
2524 		if (eisa_level_intr_mask & (1 << irq))
2525 			level = AV_LEVEL;
2526 		if (intr_index == FREE_INDEX && apic_defconf == 0)
2527 			apic_error |= APIC_ERR_INVALID_INDEX;
2528 	} else if (intr_index == ACPI_INDEX) {
2529 		bus_type = irqptr->airq_iflag.bustype;
2530 		if (irqptr->airq_iflag.intr_el == INTR_EL_CONFORM) {
2531 			if (bus_type == BUS_PCI)
2532 				level = AV_LEVEL;
2533 		} else
2534 			level = (irqptr->airq_iflag.intr_el == INTR_EL_LEVEL) ?
2535 			    AV_LEVEL : 0;
2536 		if (level &&
2537 		    ((irqptr->airq_iflag.intr_po == INTR_PO_ACTIVE_LOW) ||
2538 		    (irqptr->airq_iflag.intr_po == INTR_PO_CONFORM &&
2539 		    bus_type == BUS_PCI)))
2540 			po = AV_ACTIVE_LOW;
2541 	} else {
2542 		iointrp = apic_io_intrp + intr_index;
2543 		bus_type = apic_find_bus(iointrp->intr_busid);
2544 		if (iointrp->intr_el == INTR_EL_CONFORM) {
2545 			if ((irq < 16) && (eisa_level_intr_mask & (1 << irq)))
2546 				level = AV_LEVEL;
2547 			else if (bus_type == BUS_PCI)
2548 				level = AV_LEVEL;
2549 		} else
2550 			level = (iointrp->intr_el == INTR_EL_LEVEL) ?
2551 			    AV_LEVEL : 0;
2552 		if (level && ((iointrp->intr_po == INTR_PO_ACTIVE_LOW) ||
2553 		    (iointrp->intr_po == INTR_PO_CONFORM &&
2554 		    bus_type == BUS_PCI)))
2555 			po = AV_ACTIVE_LOW;
2556 	}
2557 	if (level)
2558 		apic_level_intr[irq] = 1;
2559 	/*
2560 	 * The 82489DX External APIC cannot do active low polarity interrupts.
2561 	 */
2562 	if (po && (apic_io_ver[ioapicindex] != IOAPIC_VER_82489DX))
2563 		io_po = po;
2564 	else
2565 		io_po = 0;
2566 
2567 	if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG)
2568 		printf("setio: ioapic=%x intin=%x level=%x po=%x vector=%x\n",
2569 		    ioapicindex, irqptr->airq_intin_no, level, io_po, vector);
2570 
2571 	irqptr->airq_rdt_entry = level|io_po|vector;
2572 }
2573 
2574 /*
2575  * Bind interrupt corresponding to irq_ptr to bind_cpu.
2576  * Must be called with interrupts disabled and apic_ioapic_lock held
2577  */
2578 int
2579 apic_rebind(apic_irq_t *irq_ptr, int bind_cpu,
2580     struct ioapic_reprogram_data *drep)
2581 {
2582 	int			ioapicindex, intin_no;
2583 	uchar_t			airq_temp_cpu;
2584 	apic_cpus_info_t	*cpu_infop;
2585 	uint32_t		rdt_entry;
2586 	int			which_irq;
2587 
2588 	which_irq = apic_vector_to_irq[irq_ptr->airq_vector];
2589 
2590 	intin_no = irq_ptr->airq_intin_no;
2591 	ioapicindex = irq_ptr->airq_ioapicindex;
2592 	airq_temp_cpu = irq_ptr->airq_temp_cpu;
2593 	if (airq_temp_cpu != IRQ_UNINIT && airq_temp_cpu != IRQ_UNBOUND) {
2594 		if (airq_temp_cpu & IRQ_USER_BOUND)
2595 			/* Mask off high bit so it can be used as array index */
2596 			airq_temp_cpu &= ~IRQ_USER_BOUND;
2597 
2598 		ASSERT(airq_temp_cpu < apic_nproc);
2599 	}
2600 
2601 	/*
2602 	 * Can't bind to a CPU that's not accepting interrupts:
2603 	 */
2604 	cpu_infop = &apic_cpus[bind_cpu & ~IRQ_USER_BOUND];
2605 	if (!(cpu_infop->aci_status & APIC_CPU_INTR_ENABLE))
2606 		return (1);
2607 
2608 	/*
2609 	 * If we are about to change the interrupt vector for this interrupt,
2610 	 * and this interrupt is level-triggered, attached to an IOAPIC,
2611 	 * has been delivered to a CPU and that CPU has not handled it
2612 	 * yet, we cannot reprogram the IOAPIC now.
2613 	 */
2614 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2615 
2616 		rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex,
2617 		    intin_no);
2618 
2619 		if ((irq_ptr->airq_vector != RDT_VECTOR(rdt_entry)) &&
2620 		    apic_check_stuck_interrupt(irq_ptr, airq_temp_cpu,
2621 		    bind_cpu, ioapicindex, intin_no, which_irq, drep) != 0) {
2622 
2623 			return (0);
2624 		}
2625 	}
2626 
2627 	/*
2628 	 * NOTE: We do not unmask the RDT here, as an interrupt MAY still
2629 	 * come in before we have a chance to reprogram it below.  The
2630 	 * reprogramming below will simultaneously change and unmask the
2631 	 * RDT entry.
2632 	 */
2633 
2634 	if ((uchar_t)bind_cpu == IRQ_UNBOUND) {
2635 
2636 		rdt_entry = AV_LDEST | AV_LOPRI | irq_ptr->airq_rdt_entry;
2637 
2638 		/* Write the RDT entry -- no specific CPU binding */
2639 		WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2640 		    AV_TOALL);
2641 
2642 		if (airq_temp_cpu != IRQ_UNINIT && airq_temp_cpu != IRQ_UNBOUND)
2643 			apic_cpus[airq_temp_cpu].aci_temp_bound--;
2644 
2645 		/* Write the vector, trigger, and polarity portion of the RDT */
2646 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex, intin_no,
2647 		    rdt_entry);
2648 
2649 		irq_ptr->airq_temp_cpu = IRQ_UNBOUND;
2650 		return (0);
2651 	}
2652 
2653 	if (bind_cpu & IRQ_USER_BOUND) {
2654 		cpu_infop->aci_bound++;
2655 	} else {
2656 		cpu_infop->aci_temp_bound++;
2657 	}
2658 	ASSERT((bind_cpu & ~IRQ_USER_BOUND) < apic_nproc);
2659 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2660 		/* Write the RDT entry -- bind to a specific CPU: */
2661 		WRITE_IOAPIC_RDT_ENTRY_HIGH_DWORD(ioapicindex, intin_no,
2662 		    cpu_infop->aci_local_id << APIC_ID_BIT_OFFSET);
2663 	}
2664 	if ((airq_temp_cpu != IRQ_UNBOUND) && (airq_temp_cpu != IRQ_UNINIT)) {
2665 		apic_cpus[airq_temp_cpu].aci_temp_bound--;
2666 	}
2667 	if (!APIC_IS_MSI_OR_MSIX_INDEX(irq_ptr->airq_mps_intr_index)) {
2668 
2669 		rdt_entry = AV_PDEST | AV_FIXED | irq_ptr->airq_rdt_entry;
2670 
2671 		/* Write the vector, trigger, and polarity portion of the RDT */
2672 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapicindex, intin_no,
2673 		    rdt_entry);
2674 
2675 	} else {
2676 		int type = (irq_ptr->airq_mps_intr_index == MSI_INDEX) ?
2677 		    DDI_INTR_TYPE_MSI : DDI_INTR_TYPE_MSIX;
2678 		(void) apic_pci_msi_disable_mode(irq_ptr->airq_dip, type,
2679 		    ioapicindex);
2680 		if (ioapicindex == irq_ptr->airq_origirq) {
2681 			/* first one */
2682 			DDI_INTR_IMPLDBG((CE_CONT, "apic_rebind: call "
2683 			    "apic_pci_msi_enable_vector\n"));
2684 			if (apic_pci_msi_enable_vector(irq_ptr->airq_dip, type,
2685 			    which_irq, irq_ptr->airq_vector,
2686 			    irq_ptr->airq_intin_no,
2687 			    cpu_infop->aci_local_id) != PSM_SUCCESS) {
2688 				cmn_err(CE_WARN, "pcplusmp: "
2689 					"apic_pci_msi_enable_vector "
2690 					"returned PSM_FAILURE");
2691 			}
2692 		}
2693 		if ((ioapicindex + irq_ptr->airq_intin_no - 1) ==
2694 		    irq_ptr->airq_origirq) { /* last one */
2695 			DDI_INTR_IMPLDBG((CE_CONT, "apic_rebind: call "
2696 			    "pci_msi_enable_mode\n"));
2697 			if (apic_pci_msi_enable_mode(irq_ptr->airq_dip,
2698 			    type, which_irq) != PSM_SUCCESS) {
2699 				DDI_INTR_IMPLDBG((CE_CONT, "pcplusmp: "
2700 				    "pci_msi_enable failed\n"));
2701 				(void) apic_pci_msi_unconfigure(
2702 				    irq_ptr->airq_dip, type, which_irq);
2703 			}
2704 		}
2705 	}
2706 	irq_ptr->airq_temp_cpu = (uchar_t)bind_cpu;
2707 	apic_redist_cpu_skip &= ~(1 << (bind_cpu & ~IRQ_USER_BOUND));
2708 	return (0);
2709 }
2710 
2711 static void
2712 apic_last_ditch_clear_remote_irr(int ioapic_ix, int intin_no)
2713 {
2714 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no)
2715 	    & AV_REMOTE_IRR) != 0) {
2716 		/*
2717 		 * Trying to clear the bit through normal
2718 		 * channels has failed.  So as a last-ditch
2719 		 * effort, try to set the trigger mode to
2720 		 * edge, then to level.  This has been
2721 		 * observed to work on many systems.
2722 		 */
2723 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2724 		    intin_no,
2725 		    READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2726 		    intin_no) & ~AV_LEVEL);
2727 
2728 		WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2729 		    intin_no,
2730 		    READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2731 		    intin_no) | AV_LEVEL);
2732 
2733 		/*
2734 		 * If the bit's STILL set, this interrupt may
2735 		 * be hosed.
2736 		 */
2737 		if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2738 		    intin_no) & AV_REMOTE_IRR) != 0) {
2739 
2740 			prom_printf("%s: Remote IRR still "
2741 			    "not clear for IOAPIC %d intin %d.\n"
2742 			    "\tInterrupts to this pin may cease "
2743 			    "functioning.\n", psm_name, ioapic_ix,
2744 			    intin_no);
2745 #ifdef DEBUG
2746 			apic_last_ditch_reprogram_failures++;
2747 #endif
2748 		}
2749 	}
2750 }
2751 
2752 /*
2753  * This function is protected by apic_ioapic_lock coupled with the
2754  * fact that interrupts are disabled.
2755  */
2756 static void
2757 delete_defer_repro_ent(int which_irq)
2758 {
2759 	ASSERT(which_irq >= 0);
2760 	ASSERT(which_irq <= 255);
2761 
2762 	if (apic_reprogram_info[which_irq].done)
2763 		return;
2764 
2765 	apic_reprogram_info[which_irq].done = B_TRUE;
2766 
2767 #ifdef DEBUG
2768 	apic_defer_repro_total_retries +=
2769 	    apic_reprogram_info[which_irq].tries;
2770 
2771 	apic_defer_repro_successes++;
2772 #endif
2773 
2774 	if (--apic_reprogram_outstanding == 0) {
2775 
2776 		setlvlx = apic_intr_exit;
2777 	}
2778 }
2779 
2780 
2781 /*
2782  * Interrupts must be disabled during this function to prevent
2783  * self-deadlock.  Interrupts are disabled because this function
2784  * is called from apic_check_stuck_interrupt(), which is called
2785  * from apic_rebind(), which requires its caller to disable interrupts.
2786  */
2787 static void
2788 add_defer_repro_ent(apic_irq_t *irq_ptr, int which_irq, int new_bind_cpu)
2789 {
2790 	ASSERT(which_irq >= 0);
2791 	ASSERT(which_irq <= 255);
2792 
2793 	/*
2794 	 * On the off-chance that there's already a deferred
2795 	 * reprogramming on this irq, check, and if so, just update the
2796 	 * CPU and irq pointer to which the interrupt is targeted, then return.
2797 	 */
2798 	if (!apic_reprogram_info[which_irq].done) {
2799 		apic_reprogram_info[which_irq].bindcpu = new_bind_cpu;
2800 		apic_reprogram_info[which_irq].irqp = irq_ptr;
2801 		return;
2802 	}
2803 
2804 	apic_reprogram_info[which_irq].irqp = irq_ptr;
2805 	apic_reprogram_info[which_irq].bindcpu = new_bind_cpu;
2806 	apic_reprogram_info[which_irq].tries = 0;
2807 	/*
2808 	 * This must be the last thing set, since we're not
2809 	 * grabbing any locks, apic_try_deferred_reprogram() will
2810 	 * make its decision about using this entry iff done
2811 	 * is false.
2812 	 */
2813 	apic_reprogram_info[which_irq].done = B_FALSE;
2814 
2815 	/*
2816 	 * If there were previously no deferred reprogrammings, change
2817 	 * setlvlx to call apic_try_deferred_reprogram()
2818 	 */
2819 	if (++apic_reprogram_outstanding == 1) {
2820 
2821 		setlvlx = apic_try_deferred_reprogram;
2822 	}
2823 }
2824 
2825 static void
2826 apic_try_deferred_reprogram(int prev_ipl, int irq)
2827 {
2828 	int reproirq, iflag;
2829 	struct ioapic_reprogram_data *drep;
2830 
2831 	apic_intr_exit(prev_ipl, irq);
2832 
2833 	if (!lock_try(&apic_defer_reprogram_lock)) {
2834 		return;
2835 	}
2836 
2837 	/*
2838 	 * Acquire the apic_ioapic_lock so that any other operations that
2839 	 * may affect the apic_reprogram_info state are serialized.
2840 	 * It's still possible for the last deferred reprogramming to clear
2841 	 * between the time we entered this function and the time we get to
2842 	 * the for loop below.  In that case, *setlvlx will have been set
2843 	 * back to apic_intr_exit and drep will be NULL. (There's no way to
2844 	 * stop that from happening -- we would need to grab a lock before
2845 	 * calling *setlvlx, which is neither realistic nor prudent).
2846 	 */
2847 	iflag = intr_clear();
2848 	lock_set(&apic_ioapic_lock);
2849 
2850 	/*
2851 	 * For each deferred RDT entry, try to reprogram it now.  Note that
2852 	 * there is no lock acquisition to read apic_reprogram_info because
2853 	 * '.done' is set only after the other fields in the structure are set.
2854 	 */
2855 
2856 	drep = NULL;
2857 	for (reproirq = 0; reproirq <= APIC_MAX_VECTOR; reproirq++) {
2858 		if (apic_reprogram_info[reproirq].done == B_FALSE) {
2859 			drep = &apic_reprogram_info[reproirq];
2860 			break;
2861 		}
2862 	}
2863 
2864 	/*
2865 	 * Either we found a deferred action to perform, or
2866 	 * we entered this function spuriously, after *setlvlx
2867 	 * was restored to point to apic_intr_enter.  Any other
2868 	 * permutation is invalid.
2869 	 */
2870 	ASSERT(drep != NULL || *setlvlx == apic_intr_exit);
2871 
2872 	/*
2873 	 * Though we can't really do anything about errors
2874 	 * at this point, keep track of them for reporting.
2875 	 * Note that it is very possible for apic_setup_io_intr
2876 	 * to re-register this very timeout if the Remote IRR bit
2877 	 * has not yet cleared.
2878 	 */
2879 
2880 #ifdef DEBUG
2881 	if (drep != NULL) {
2882 		if (apic_setup_io_intr(drep, reproirq, B_TRUE) != 0) {
2883 			apic_deferred_setup_failures++;
2884 		}
2885 	} else {
2886 		apic_deferred_spurious_enters++;
2887 	}
2888 #else
2889 	if (drep != NULL)
2890 		(void) apic_setup_io_intr(drep, reproirq, B_TRUE);
2891 #endif
2892 
2893 	lock_clear(&apic_ioapic_lock);
2894 	intr_restore(iflag);
2895 
2896 	lock_clear(&apic_defer_reprogram_lock);
2897 }
2898 
2899 static void
2900 apic_ioapic_wait_pending_clear(int ioapic_ix, int intin_no)
2901 {
2902 	int waited;
2903 
2904 	/*
2905 	 * Wait for the delivery pending bit to clear.
2906 	 */
2907 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no) &
2908 	    (AV_LEVEL|AV_PENDING)) == (AV_LEVEL|AV_PENDING)) {
2909 
2910 		/*
2911 		 * If we're still waiting on the delivery of this interrupt,
2912 		 * continue to wait here until it is delivered (this should be
2913 		 * a very small amount of time, but include a timeout just in
2914 		 * case).
2915 		 */
2916 		for (waited = 0; waited < apic_max_reps_clear_pending;
2917 		    waited++) {
2918 			if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2919 			    intin_no) & AV_PENDING) == 0) {
2920 				break;
2921 			}
2922 		}
2923 	}
2924 }
2925 
2926 
2927 /*
2928  * Checks to see if the IOAPIC interrupt entry specified has its Remote IRR
2929  * bit set.  Calls functions that modify the function that setlvlx points to,
2930  * so that the reprogramming can be retried very shortly.
2931  *
2932  * This function will mask the RDT entry if the interrupt is level-triggered.
2933  * (The caller is responsible for unmasking the RDT entry.)
2934  *
2935  * Returns non-zero if the caller should defer IOAPIC reprogramming.
2936  */
2937 static int
2938 apic_check_stuck_interrupt(apic_irq_t *irq_ptr, int old_bind_cpu,
2939     int new_bind_cpu, int ioapic_ix, int intin_no, int which_irq,
2940     struct ioapic_reprogram_data *drep)
2941 {
2942 	int32_t			rdt_entry;
2943 	int			waited;
2944 	int			reps = 0;
2945 
2946 	/*
2947 	 * Wait for the delivery pending bit to clear.
2948 	 */
2949 	do {
2950 		++reps;
2951 
2952 		apic_ioapic_wait_pending_clear(ioapic_ix, intin_no);
2953 
2954 		/*
2955 		 * Mask the RDT entry, but only if it's a level-triggered
2956 		 * interrupt
2957 		 */
2958 		rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2959 		    intin_no);
2960 		if ((rdt_entry & (AV_LEVEL|AV_MASK)) == AV_LEVEL) {
2961 
2962 			/* Mask it */
2963 			WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no,
2964 			    AV_MASK | rdt_entry);
2965 		}
2966 
2967 		if ((rdt_entry & AV_LEVEL) == AV_LEVEL) {
2968 			/*
2969 			 * If there was a race and an interrupt was injected
2970 			 * just before we masked, check for that case here.
2971 			 * Then, unmask the RDT entry and try again.  If we're
2972 			 * on our last try, don't unmask (because we want the
2973 			 * RDT entry to remain masked for the rest of the
2974 			 * function).
2975 			 */
2976 			rdt_entry = READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2977 			    intin_no);
2978 			if ((rdt_entry & AV_PENDING) &&
2979 			    (reps < apic_max_reps_clear_pending)) {
2980 				/* Unmask it */
2981 				WRITE_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
2982 				    intin_no, rdt_entry & ~AV_MASK);
2983 			}
2984 		}
2985 
2986 	} while ((rdt_entry & AV_PENDING) &&
2987 	    (reps < apic_max_reps_clear_pending));
2988 
2989 #ifdef DEBUG
2990 		if (rdt_entry & AV_PENDING)
2991 			apic_intr_deliver_timeouts++;
2992 #endif
2993 
2994 	/*
2995 	 * If the remote IRR bit is set, then the interrupt has been sent
2996 	 * to a CPU for processing.  We have no choice but to wait for
2997 	 * that CPU to process the interrupt, at which point the remote IRR
2998 	 * bit will be cleared.
2999 	 */
3000 	if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix, intin_no) &
3001 	    (AV_LEVEL|AV_REMOTE_IRR)) == (AV_LEVEL|AV_REMOTE_IRR)) {
3002 
3003 		/*
3004 		 * If the CPU that this RDT is bound to is NOT the current
3005 		 * CPU, wait until that CPU handles the interrupt and ACKs
3006 		 * it.  If this interrupt is not bound to any CPU (that is,
3007 		 * if it's bound to the logical destination of "anyone"), it
3008 		 * may have been delivered to the current CPU so handle that
3009 		 * case by deferring the reprogramming (below).
3010 		 */
3011 		if ((old_bind_cpu != IRQ_UNBOUND) &&
3012 		    (old_bind_cpu != IRQ_UNINIT) &&
3013 		    (old_bind_cpu != psm_get_cpu_id())) {
3014 			for (waited = 0; waited < apic_max_reps_clear_pending;
3015 			    waited++) {
3016 				if ((READ_IOAPIC_RDT_ENTRY_LOW_DWORD(ioapic_ix,
3017 				    intin_no) & AV_REMOTE_IRR) == 0) {
3018 
3019 					delete_defer_repro_ent(which_irq);
3020 
3021 					/* Remote IRR has cleared! */
3022 					return (0);
3023 				}
3024 			}
3025 		}
3026 
3027 		/*
3028 		 * If we waited and the Remote IRR bit is still not cleared,
3029 		 * AND if we've invoked the timeout APIC_REPROGRAM_MAX_TIMEOUTS
3030 		 * times for this interrupt, try the last-ditch workaround:
3031 		 */
3032 		if (drep && drep->tries >= APIC_REPROGRAM_MAX_TRIES) {
3033 
3034 			apic_last_ditch_clear_remote_irr(ioapic_ix, intin_no);
3035 
3036 			/* Mark this one as reprogrammed: */
3037 			delete_defer_repro_ent(which_irq);
3038 
3039 			return (0);
3040 		} else {
3041 #ifdef DEBUG
3042 			apic_intr_deferrals++;
3043 #endif
3044 
3045 			/*
3046 			 * If waiting for the Remote IRR bit (above) didn't
3047 			 * allow it to clear, defer the reprogramming.
3048 			 * Add a new deferred-programming entry if the
3049 			 * caller passed a NULL one (and update the existing one
3050 			 * in case anything changed).
3051 			 */
3052 			add_defer_repro_ent(irq_ptr, which_irq, new_bind_cpu);
3053 			if (drep)
3054 				drep->tries++;
3055 
3056 			/* Inform caller to defer IOAPIC programming: */
3057 			return (1);
3058 		}
3059 
3060 	}
3061 
3062 	/* Remote IRR is clear */
3063 	delete_defer_repro_ent(which_irq);
3064 
3065 	return (0);
3066 }
3067 
3068 /*
3069  * Called to migrate all interrupts at an irq to another cpu.
3070  * Must be called with interrupts disabled and apic_ioapic_lock held
3071  */
3072 int
3073 apic_rebind_all(apic_irq_t *irq_ptr, int bind_cpu)
3074 {
3075 	apic_irq_t	*irqptr = irq_ptr;
3076 	int		retval = 0;
3077 
3078 	while (irqptr) {
3079 		if (irqptr->airq_temp_cpu != IRQ_UNINIT)
3080 			retval |= apic_rebind(irqptr, bind_cpu, NULL);
3081 		irqptr = irqptr->airq_next;
3082 	}
3083 
3084 	return (retval);
3085 }
3086 
3087 /*
3088  * apic_intr_redistribute does all the messy computations for identifying
3089  * which interrupt to move to which CPU. Currently we do just one interrupt
3090  * at a time. This reduces the time we spent doing all this within clock
3091  * interrupt. When it is done in idle, we could do more than 1.
3092  * First we find the most busy and the most free CPU (time in ISR only)
3093  * skipping those CPUs that has been identified as being ineligible (cpu_skip)
3094  * Then we look for IRQs which are closest to the difference between the
3095  * most busy CPU and the average ISR load. We try to find one whose load
3096  * is less than difference.If none exists, then we chose one larger than the
3097  * difference, provided it does not make the most idle CPU worse than the
3098  * most busy one. In the end, we clear all the busy fields for CPUs. For
3099  * IRQs, they are cleared as they are scanned.
3100  */
3101 void
3102 apic_intr_redistribute()
3103 {
3104 	int busiest_cpu, most_free_cpu;
3105 	int cpu_free, cpu_busy, max_busy, min_busy;
3106 	int min_free, diff;
3107 	int average_busy, cpus_online;
3108 	int i, busy, iflag;
3109 	apic_cpus_info_t *cpu_infop;
3110 	apic_irq_t *min_busy_irq = NULL;
3111 	apic_irq_t *max_busy_irq = NULL;
3112 
3113 	busiest_cpu = most_free_cpu = -1;
3114 	cpu_free = cpu_busy = max_busy = average_busy = 0;
3115 	min_free = apic_sample_factor_redistribution;
3116 	cpus_online = 0;
3117 	/*
3118 	 * Below we will check for CPU_INTR_ENABLE, bound, temp_bound, temp_cpu
3119 	 * without ioapic_lock. That is OK as we are just doing statistical
3120 	 * sampling anyway and any inaccuracy now will get corrected next time
3121 	 * The call to rebind which actually changes things will make sure
3122 	 * we are consistent.
3123 	 */
3124 	for (i = 0; i < apic_nproc; i++) {
3125 		if (!(apic_redist_cpu_skip & (1 << i)) &&
3126 		    (apic_cpus[i].aci_status & APIC_CPU_INTR_ENABLE)) {
3127 
3128 			cpu_infop = &apic_cpus[i];
3129 			/*
3130 			 * If no unbound interrupts or only 1 total on this
3131 			 * CPU, skip
3132 			 */
3133 			if (!cpu_infop->aci_temp_bound ||
3134 			    (cpu_infop->aci_bound + cpu_infop->aci_temp_bound)
3135 			    == 1) {
3136 				apic_redist_cpu_skip |= 1 << i;
3137 				continue;
3138 			}
3139 
3140 			busy = cpu_infop->aci_busy;
3141 			average_busy += busy;
3142 			cpus_online++;
3143 			if (max_busy < busy) {
3144 				max_busy = busy;
3145 				busiest_cpu = i;
3146 			}
3147 			if (min_free > busy) {
3148 				min_free = busy;
3149 				most_free_cpu = i;
3150 			}
3151 			if (busy > apic_int_busy_mark) {
3152 				cpu_busy |= 1 << i;
3153 			} else {
3154 				if (busy < apic_int_free_mark)
3155 					cpu_free |= 1 << i;
3156 			}
3157 		}
3158 	}
3159 	if ((cpu_busy && cpu_free) ||
3160 	    (max_busy >= (min_free + apic_diff_for_redistribution))) {
3161 
3162 		apic_num_imbalance++;
3163 #ifdef	DEBUG
3164 		if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3165 			prom_printf(
3166 			    "redistribute busy=%x free=%x max=%x min=%x",
3167 			    cpu_busy, cpu_free, max_busy, min_free);
3168 		}
3169 #endif /* DEBUG */
3170 
3171 
3172 		average_busy /= cpus_online;
3173 
3174 		diff = max_busy - average_busy;
3175 		min_busy = max_busy; /* start with the max possible value */
3176 		max_busy = 0;
3177 		min_busy_irq = max_busy_irq = NULL;
3178 		i = apic_min_device_irq;
3179 		for (; i < apic_max_device_irq; i++) {
3180 			apic_irq_t *irq_ptr;
3181 			/* Change to linked list per CPU ? */
3182 			if ((irq_ptr = apic_irq_table[i]) == NULL)
3183 				continue;
3184 			/* Check for irq_busy & decide which one to move */
3185 			/* Also zero them for next round */
3186 			if ((irq_ptr->airq_temp_cpu == busiest_cpu) &&
3187 			    irq_ptr->airq_busy) {
3188 				if (irq_ptr->airq_busy < diff) {
3189 					/*
3190 					 * Check for least busy CPU,
3191 					 * best fit or what ?
3192 					 */
3193 					if (max_busy < irq_ptr->airq_busy) {
3194 						/*
3195 						 * Most busy within the
3196 						 * required differential
3197 						 */
3198 						max_busy = irq_ptr->airq_busy;
3199 						max_busy_irq = irq_ptr;
3200 					}
3201 				} else {
3202 					if (min_busy > irq_ptr->airq_busy) {
3203 						/*
3204 						 * least busy, but more than
3205 						 * the reqd diff
3206 						 */
3207 						if (min_busy <
3208 						    (diff + average_busy -
3209 						    min_free)) {
3210 							/*
3211 							 * Making sure new cpu
3212 							 * will not end up
3213 							 * worse
3214 							 */
3215 							min_busy =
3216 							    irq_ptr->airq_busy;
3217 
3218 							min_busy_irq = irq_ptr;
3219 						}
3220 					}
3221 				}
3222 			}
3223 			irq_ptr->airq_busy = 0;
3224 		}
3225 
3226 		if (max_busy_irq != NULL) {
3227 #ifdef	DEBUG
3228 			if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3229 				prom_printf("rebinding %x to %x",
3230 				    max_busy_irq->airq_vector, most_free_cpu);
3231 			}
3232 #endif /* DEBUG */
3233 			iflag = intr_clear();
3234 			if (lock_try(&apic_ioapic_lock)) {
3235 				if (apic_rebind_all(max_busy_irq,
3236 				    most_free_cpu) == 0) {
3237 					/* Make change permenant */
3238 					max_busy_irq->airq_cpu =
3239 					    (uchar_t)most_free_cpu;
3240 				}
3241 				lock_clear(&apic_ioapic_lock);
3242 			}
3243 			intr_restore(iflag);
3244 
3245 		} else if (min_busy_irq != NULL) {
3246 #ifdef	DEBUG
3247 			if (apic_verbose & APIC_VERBOSE_IOAPIC_FLAG) {
3248 				prom_printf("rebinding %x to %x",
3249 				    min_busy_irq->airq_vector, most_free_cpu);
3250 			}
3251 #endif /* DEBUG */
3252 
3253 			iflag = intr_clear();
3254 			if (lock_try(&apic_ioapic_lock)) {
3255 				if (apic_rebind_all(min_busy_irq,
3256 				    most_free_cpu) == 0) {
3257 					/* Make change permenant */
3258 					min_busy_irq->airq_cpu =
3259 					    (uchar_t)most_free_cpu;
3260 				}
3261 				lock_clear(&apic_ioapic_lock);
3262 			}
3263 			intr_restore(iflag);
3264 
3265 		} else {
3266 			if (cpu_busy != (1 << busiest_cpu)) {
3267 				apic_redist_cpu_skip |= 1 << busiest_cpu;
3268 				/*
3269 				 * We leave cpu_skip set so that next time we
3270 				 * can choose another cpu
3271 				 */
3272 			}
3273 		}
3274 		apic_num_rebind++;
3275 	} else {
3276 		/*
3277 		 * found nothing. Could be that we skipped over valid CPUs
3278 		 * or we have balanced everything. If we had a variable
3279 		 * ticks_for_redistribution, it could be increased here.
3280 		 * apic_int_busy, int_free etc would also need to be
3281 		 * changed.
3282 		 */
3283 		if (apic_redist_cpu_skip)
3284 			apic_redist_cpu_skip = 0;
3285 	}
3286 	for (i = 0; i < apic_nproc; i++) {
3287 		apic_cpus[i].aci_busy = 0;
3288 	}
3289 }
3290 
3291 void
3292 apic_cleanup_busy()
3293 {
3294 	int i;
3295 	apic_irq_t *irq_ptr;
3296 
3297 	for (i = 0; i < apic_nproc; i++) {
3298 		apic_cpus[i].aci_busy = 0;
3299 	}
3300 
3301 	for (i = apic_min_device_irq; i < apic_max_device_irq; i++) {
3302 		if ((irq_ptr = apic_irq_table[i]) != NULL)
3303 			irq_ptr->airq_busy = 0;
3304 	}
3305 }
3306 
3307 
3308 static int
3309 apic_acpi_translate_pci_irq(dev_info_t *dip, int busid, int devid,
3310     int ipin, int *pci_irqp, iflag_t *intr_flagp)
3311 {
3312 
3313 	int status;
3314 	acpi_psm_lnk_t acpipsmlnk;
3315 
3316 	if ((status = acpi_get_irq_cache_ent(busid, devid, ipin, pci_irqp,
3317 	    intr_flagp)) == ACPI_PSM_SUCCESS) {
3318 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Found irqno %d "
3319 		    "from cache for device %s, instance #%d\n", psm_name,
3320 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
3321 		return (status);
3322 	}
3323 
3324 	bzero(&acpipsmlnk, sizeof (acpi_psm_lnk_t));
3325 
3326 	if ((status = acpi_translate_pci_irq(dip, ipin, pci_irqp, intr_flagp,
3327 	    &acpipsmlnk)) == ACPI_PSM_FAILURE) {
3328 		APIC_VERBOSE_IRQ((CE_WARN, "%s: "
3329 		    " acpi_translate_pci_irq failed for device %s, instance"
3330 		    " #%d", psm_name, ddi_get_name(dip),
3331 		    ddi_get_instance(dip)));
3332 		return (status);
3333 	}
3334 
3335 	if (status == ACPI_PSM_PARTIAL && acpipsmlnk.lnkobj != NULL) {
3336 		status = apic_acpi_irq_configure(&acpipsmlnk, dip, pci_irqp,
3337 		    intr_flagp);
3338 		if (status != ACPI_PSM_SUCCESS) {
3339 			status = acpi_get_current_irq_resource(&acpipsmlnk,
3340 			    pci_irqp, intr_flagp);
3341 		}
3342 	}
3343 
3344 	if (status == ACPI_PSM_SUCCESS) {
3345 		acpi_new_irq_cache_ent(busid, devid, ipin, *pci_irqp,
3346 		    intr_flagp, &acpipsmlnk);
3347 
3348 		APIC_VERBOSE_IRQ((CE_CONT, "%s: [ACPI] "
3349 		    "new irq %d for device %s, instance #%d\n", psm_name,
3350 		    *pci_irqp, ddi_get_name(dip), ddi_get_instance(dip)));
3351 	}
3352 
3353 	return (status);
3354 }
3355 
3356 /*
3357  * Adds an entry to the irq list passed in, and returns the new list.
3358  * Entries are added in priority order (lower numerical priorities are
3359  * placed closer to the head of the list)
3360  */
3361 static prs_irq_list_t *
3362 acpi_insert_prs_irq_ent(prs_irq_list_t *listp, int priority, int irq,
3363     iflag_t *iflagp, acpi_prs_private_t *prsprvp)
3364 {
3365 	struct prs_irq_list_ent *newent, *prevp = NULL, *origlistp;
3366 
3367 	newent = kmem_zalloc(sizeof (struct prs_irq_list_ent), KM_SLEEP);
3368 
3369 	newent->list_prio = priority;
3370 	newent->irq = irq;
3371 	newent->intrflags = *iflagp;
3372 	newent->prsprv = *prsprvp;
3373 	/* ->next is NULL from kmem_zalloc */
3374 
3375 	/*
3376 	 * New list -- return the new entry as the list.
3377 	 */
3378 	if (listp == NULL)
3379 		return (newent);
3380 
3381 	/*
3382 	 * Save original list pointer for return (since we're not modifying
3383 	 * the head)
3384 	 */
3385 	origlistp = listp;
3386 
3387 	/*
3388 	 * Insertion sort, with entries with identical keys stored AFTER
3389 	 * existing entries (the less-than-or-equal test of priority does
3390 	 * this for us).
3391 	 */
3392 	while (listp != NULL && listp->list_prio <= priority) {
3393 		prevp = listp;
3394 		listp = listp->next;
3395 	}
3396 
3397 	newent->next = listp;
3398 
3399 	if (prevp == NULL) { /* Add at head of list (newent is the new head) */
3400 		return (newent);
3401 	} else {
3402 		prevp->next = newent;
3403 		return (origlistp);
3404 	}
3405 }
3406 
3407 /*
3408  * Frees the list passed in, deallocating all memory and leaving *listpp
3409  * set to NULL.
3410  */
3411 static void
3412 acpi_destroy_prs_irq_list(prs_irq_list_t **listpp)
3413 {
3414 	struct prs_irq_list_ent *nextp;
3415 
3416 	ASSERT(listpp != NULL);
3417 
3418 	while (*listpp != NULL) {
3419 		nextp = (*listpp)->next;
3420 		kmem_free(*listpp, sizeof (struct prs_irq_list_ent));
3421 		*listpp = nextp;
3422 	}
3423 }
3424 
3425 /*
3426  * apic_choose_irqs_from_prs returns a list of irqs selected from the list of
3427  * irqs returned by the link device's _PRS method.  The irqs are chosen
3428  * to minimize contention in situations where the interrupt link device
3429  * can be programmed to steer interrupts to different interrupt controller
3430  * inputs (some of which may already be in use).  The list is sorted in order
3431  * of irqs to use, with the highest priority given to interrupt controller
3432  * inputs that are not shared.   When an interrupt controller input
3433  * must be shared, apic_choose_irqs_from_prs adds the possible irqs to the
3434  * returned list in the order that minimizes sharing (thereby ensuring lowest
3435  * possible latency from interrupt trigger time to ISR execution time).
3436  */
3437 static prs_irq_list_t *
3438 apic_choose_irqs_from_prs(acpi_irqlist_t *irqlistent, dev_info_t *dip,
3439     int crs_irq)
3440 {
3441 	int32_t irq;
3442 	int i;
3443 	prs_irq_list_t *prsirqlistp = NULL;
3444 	iflag_t iflags;
3445 
3446 	while (irqlistent != NULL) {
3447 		irqlistent->intr_flags.bustype = BUS_PCI;
3448 
3449 		for (i = 0; i < irqlistent->num_irqs; i++) {
3450 
3451 			irq = irqlistent->irqs[i];
3452 
3453 			if (irq <= 0) {
3454 				/* invalid irq number */
3455 				continue;
3456 			}
3457 
3458 			if ((irq < 16) && (apic_reserved_irqlist[irq]))
3459 				continue;
3460 
3461 			if ((apic_irq_table[irq] == NULL) ||
3462 			    (apic_irq_table[irq]->airq_dip == dip)) {
3463 
3464 				prsirqlistp = acpi_insert_prs_irq_ent(
3465 				    prsirqlistp, 0 /* Highest priority */, irq,
3466 				    &irqlistent->intr_flags,
3467 				    &irqlistent->acpi_prs_prv);
3468 
3469 				/*
3470 				 * If we do not prefer the current irq from _CRS
3471 				 * or if we do and this irq is the same as the
3472 				 * current irq from _CRS, this is the one
3473 				 * to pick.
3474 				 */
3475 				if (!(apic_prefer_crs) || (irq == crs_irq)) {
3476 					return (prsirqlistp);
3477 				}
3478 				continue;
3479 			}
3480 
3481 			/*
3482 			 * Edge-triggered interrupts cannot be shared
3483 			 */
3484 			if (irqlistent->intr_flags.intr_el == INTR_EL_EDGE)
3485 				continue;
3486 
3487 			/*
3488 			 * To work around BIOSes that contain incorrect
3489 			 * interrupt polarity information in interrupt
3490 			 * descriptors returned by _PRS, we assume that
3491 			 * the polarity of the other device sharing this
3492 			 * interrupt controller input is compatible.
3493 			 * If it's not, the caller will catch it when
3494 			 * the caller invokes the link device's _CRS method
3495 			 * (after invoking its _SRS method).
3496 			 */
3497 			iflags = irqlistent->intr_flags;
3498 			iflags.intr_po =
3499 			    apic_irq_table[irq]->airq_iflag.intr_po;
3500 
3501 			if (!acpi_intr_compatible(iflags,
3502 			    apic_irq_table[irq]->airq_iflag)) {
3503 				APIC_VERBOSE_IRQ((CE_CONT, "!%s: irq %d "
3504 				    "not compatible [%x:%x:%x !~ %x:%x:%x]",
3505 				    psm_name, irq,
3506 				    iflags.intr_po,
3507 				    iflags.intr_el,
3508 				    iflags.bustype,
3509 				    apic_irq_table[irq]->airq_iflag.intr_po,
3510 				    apic_irq_table[irq]->airq_iflag.intr_el,
3511 				    apic_irq_table[irq]->airq_iflag.bustype));
3512 				continue;
3513 			}
3514 
3515 			/*
3516 			 * If we prefer the irq from _CRS, no need
3517 			 * to search any further (and make sure
3518 			 * to add this irq with the highest priority
3519 			 * so it's tried first).
3520 			 */
3521 			if (crs_irq == irq && apic_prefer_crs) {
3522 
3523 				return (acpi_insert_prs_irq_ent(
3524 				    prsirqlistp,
3525 				    0 /* Highest priority */,
3526 				    irq, &iflags,
3527 				    &irqlistent->acpi_prs_prv));
3528 			}
3529 
3530 			/*
3531 			 * Priority is equal to the share count (lower
3532 			 * share count is higher priority). Note that
3533 			 * the intr flags passed in here are the ones we
3534 			 * changed above -- if incorrect, it will be
3535 			 * caught by the caller's _CRS flags comparison.
3536 			 */
3537 			prsirqlistp = acpi_insert_prs_irq_ent(
3538 			    prsirqlistp,
3539 			    apic_irq_table[irq]->airq_share, irq,
3540 			    &iflags, &irqlistent->acpi_prs_prv);
3541 		}
3542 
3543 		/* Go to the next irqlist entry */
3544 		irqlistent = irqlistent->next;
3545 	}
3546 
3547 	return (prsirqlistp);
3548 }
3549 
3550 /*
3551  * Configures the irq for the interrupt link device identified by
3552  * acpipsmlnkp.
3553  *
3554  * Gets the current and the list of possible irq settings for the
3555  * device. If apic_unconditional_srs is not set, and the current
3556  * resource setting is in the list of possible irq settings,
3557  * current irq resource setting is passed to the caller.
3558  *
3559  * Otherwise, picks an irq number from the list of possible irq
3560  * settings, and sets the irq of the device to this value.
3561  * If prefer_crs is set, among a set of irq numbers in the list that have
3562  * the least number of devices sharing the interrupt, we pick current irq
3563  * resource setting if it is a member of this set.
3564  *
3565  * Passes the irq number in the value pointed to by pci_irqp, and
3566  * polarity and sensitivity in the structure pointed to by dipintrflagp
3567  * to the caller.
3568  *
3569  * Note that if setting the irq resource failed, but successfuly obtained
3570  * the current irq resource settings, passes the current irq resources
3571  * and considers it a success.
3572  *
3573  * Returns:
3574  * ACPI_PSM_SUCCESS on success.
3575  *
3576  * ACPI_PSM_FAILURE if an error occured during the configuration or
3577  * if a suitable irq was not found for this device, or if setting the
3578  * irq resource and obtaining the current resource fails.
3579  *
3580  */
3581 static int
3582 apic_acpi_irq_configure(acpi_psm_lnk_t *acpipsmlnkp, dev_info_t *dip,
3583     int *pci_irqp, iflag_t *dipintr_flagp)
3584 {
3585 	int32_t irq;
3586 	int cur_irq = -1;
3587 	acpi_irqlist_t *irqlistp;
3588 	prs_irq_list_t *prs_irq_listp, *prs_irq_entp;
3589 	boolean_t found_irq = B_FALSE;
3590 
3591 	dipintr_flagp->bustype = BUS_PCI;
3592 
3593 	if ((acpi_get_possible_irq_resources(acpipsmlnkp, &irqlistp))
3594 	    == ACPI_PSM_FAILURE) {
3595 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Unable to determine "
3596 		    "or assign IRQ for device %s, instance #%d: The system was "
3597 		    "unable to get the list of potential IRQs from ACPI.",
3598 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
3599 
3600 		return (ACPI_PSM_FAILURE);
3601 	}
3602 
3603 	if ((acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
3604 	    dipintr_flagp) == ACPI_PSM_SUCCESS) && (!apic_unconditional_srs) &&
3605 	    (cur_irq > 0)) {
3606 		/*
3607 		 * If an IRQ is set in CRS and that IRQ exists in the set
3608 		 * returned from _PRS, return that IRQ, otherwise print
3609 		 * a warning
3610 		 */
3611 
3612 		if (acpi_irqlist_find_irq(irqlistp, cur_irq, NULL)
3613 		    == ACPI_PSM_SUCCESS) {
3614 
3615 			ASSERT(pci_irqp != NULL);
3616 			*pci_irqp = cur_irq;
3617 			acpi_free_irqlist(irqlistp);
3618 			return (ACPI_PSM_SUCCESS);
3619 		}
3620 
3621 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find the "
3622 		    "current irq %d for device %s, instance #%d in ACPI's "
3623 		    "list of possible irqs for this device. Picking one from "
3624 		    " the latter list.", psm_name, cur_irq, ddi_get_name(dip),
3625 		    ddi_get_instance(dip)));
3626 	}
3627 
3628 	if ((prs_irq_listp = apic_choose_irqs_from_prs(irqlistp, dip,
3629 	    cur_irq)) == NULL) {
3630 
3631 		APIC_VERBOSE_IRQ((CE_WARN, "!%s: Could not find a "
3632 		    "suitable irq from the list of possible irqs for device "
3633 		    "%s, instance #%d in ACPI's list of possible irqs",
3634 		    psm_name, ddi_get_name(dip), ddi_get_instance(dip)));
3635 
3636 		acpi_free_irqlist(irqlistp);
3637 		return (ACPI_PSM_FAILURE);
3638 	}
3639 
3640 	acpi_free_irqlist(irqlistp);
3641 
3642 	for (prs_irq_entp = prs_irq_listp;
3643 	    prs_irq_entp != NULL && found_irq == B_FALSE;
3644 	    prs_irq_entp = prs_irq_entp->next) {
3645 
3646 		acpipsmlnkp->acpi_prs_prv = prs_irq_entp->prsprv;
3647 		irq = prs_irq_entp->irq;
3648 
3649 		APIC_VERBOSE_IRQ((CE_CONT, "!%s: Setting irq %d for "
3650 		    "device %s instance #%d\n", psm_name, irq,
3651 		    ddi_get_name(dip), ddi_get_instance(dip)));
3652 
3653 		if ((acpi_set_irq_resource(acpipsmlnkp, irq))
3654 		    == ACPI_PSM_SUCCESS) {
3655 			/*
3656 			 * setting irq was successful, check to make sure CRS
3657 			 * reflects that. If CRS does not agree with what we
3658 			 * set, return the irq that was set.
3659 			 */
3660 
3661 			if (acpi_get_current_irq_resource(acpipsmlnkp, &cur_irq,
3662 			    dipintr_flagp) == ACPI_PSM_SUCCESS) {
3663 
3664 				if (cur_irq != irq)
3665 					APIC_VERBOSE_IRQ((CE_WARN,
3666 					    "!%s: IRQ resource set "
3667 					    "(irqno %d) for device %s "
3668 					    "instance #%d, differs from "
3669 					    "current setting irqno %d",
3670 					    psm_name, irq, ddi_get_name(dip),
3671 					    ddi_get_instance(dip), cur_irq));
3672 			} else {
3673 				/*
3674 				 * On at least one system, there was a bug in
3675 				 * a DSDT method called by _STA, causing _STA to
3676 				 * indicate that the link device was disabled
3677 				 * (when, in fact, it was enabled).  Since _SRS
3678 				 * succeeded, assume that _CRS is lying and use
3679 				 * the iflags from this _PRS interrupt choice.
3680 				 * If we're wrong about the flags, the polarity
3681 				 * will be incorrect and we may get an interrupt
3682 				 * storm, but there's not much else we can do
3683 				 * at this point.
3684 				 */
3685 				*dipintr_flagp = prs_irq_entp->intrflags;
3686 			}
3687 
3688 			/*
3689 			 * Return the irq that was set, and not what _CRS
3690 			 * reports, since _CRS has been seen to return
3691 			 * different IRQs than what was passed to _SRS on some
3692 			 * systems (and just not return successfully on others).
3693 			 */
3694 			cur_irq = irq;
3695 			found_irq = B_TRUE;
3696 		} else {
3697 			APIC_VERBOSE_IRQ((CE_WARN, "!%s: set resource "
3698 			    "irq %d failed for device %s instance #%d",
3699 			    psm_name, irq, ddi_get_name(dip),
3700 			    ddi_get_instance(dip)));
3701 
3702 			if (cur_irq == -1) {
3703 				acpi_destroy_prs_irq_list(&prs_irq_listp);
3704 				return (ACPI_PSM_FAILURE);
3705 			}
3706 		}
3707 	}
3708 
3709 	acpi_destroy_prs_irq_list(&prs_irq_listp);
3710 
3711 	if (!found_irq)
3712 		return (ACPI_PSM_FAILURE);
3713 
3714 	ASSERT(pci_irqp != NULL);
3715 	*pci_irqp = cur_irq;
3716 	return (ACPI_PSM_SUCCESS);
3717 }
3718 
3719 void
3720 ioapic_disable_redirection()
3721 {
3722 	int ioapic_ix;
3723 	int intin_max;
3724 	int intin_ix;
3725 
3726 	/* Disable the I/O APIC redirection entries */
3727 	for (ioapic_ix = 0; ioapic_ix < apic_io_max; ioapic_ix++) {
3728 
3729 		/* Bits 23-16 define the maximum redirection entries */
3730 		intin_max = (ioapic_read(ioapic_ix, APIC_VERS_CMD) >> 16)
3731 		    & 0xff;
3732 
3733 		for (intin_ix = 0; intin_ix < intin_max; intin_ix++)
3734 			ioapic_write(ioapic_ix, APIC_RDT_CMD + 2 * intin_ix,
3735 			    AV_MASK);
3736 	}
3737 }
3738