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