xref: /illumos-gate/usr/src/uts/i86pc/io/pcplusmp/apic.c (revision 22f5594a529d50114d839d4ddecc2c499731a3d7)
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 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * PSMI 1.1 extensions are supported only in 2.6 and later versions.
31  * PSMI 1.2 extensions are supported only in 2.7 and later versions.
32  * PSMI 1.3 and 1.4 extensions are supported in Solaris 10.
33  * PSMI 1.5 extensions are supported in Solaris Nevada.
34  * PSMI 1.6 extensions are supported in Solaris Nevada.
35  */
36 #define	PSMI_1_6
37 
38 #include <sys/processor.h>
39 #include <sys/time.h>
40 #include <sys/psm.h>
41 #include <sys/smp_impldefs.h>
42 #include <sys/cram.h>
43 #include <sys/acpi/acpi.h>
44 #include <sys/acpica.h>
45 #include <sys/psm_common.h>
46 #include <sys/apic.h>
47 #include <sys/pit.h>
48 #include <sys/ddi.h>
49 #include <sys/sunddi.h>
50 #include <sys/ddi_impldefs.h>
51 #include <sys/pci.h>
52 #include <sys/promif.h>
53 #include <sys/x86_archext.h>
54 #include <sys/cpc_impl.h>
55 #include <sys/uadmin.h>
56 #include <sys/panic.h>
57 #include <sys/debug.h>
58 #include <sys/archsystm.h>
59 #include <sys/trap.h>
60 #include <sys/machsystm.h>
61 #include <sys/sysmacros.h>
62 #include <sys/cpuvar.h>
63 #include <sys/rm_platter.h>
64 #include <sys/privregs.h>
65 #include <sys/note.h>
66 #include <sys/pci_intr_lib.h>
67 #include <sys/spl.h>
68 #include <sys/clock.h>
69 #include <sys/dditypes.h>
70 #include <sys/sunddi.h>
71 
72 /*
73  *	Local Function Prototypes
74  */
75 static void apic_init_intr();
76 static void apic_ret();
77 static int get_apic_cmd1();
78 static int get_apic_pri();
79 static void apic_nmi_intr(caddr_t arg, struct regs *rp);
80 
81 /*
82  *	standard MP entries
83  */
84 static int	apic_probe();
85 static int	apic_clkinit();
86 static int	apic_getclkirq(int ipl);
87 static uint_t	apic_calibrate(volatile uint32_t *addr,
88     uint16_t *pit_ticks_adj);
89 static hrtime_t apic_gettime();
90 static hrtime_t apic_gethrtime();
91 static void	apic_init();
92 static void	apic_picinit(void);
93 static int	apic_cpu_start(processorid_t, caddr_t);
94 static int	apic_post_cpu_start(void);
95 static void	apic_send_ipi(int cpun, int ipl);
96 static void	apic_set_idlecpu(processorid_t cpun);
97 static void	apic_unset_idlecpu(processorid_t cpun);
98 static int	apic_intr_enter(int ipl, int *vect);
99 static void	apic_setspl(int ipl);
100 static int	apic_addspl(int ipl, int vector, int min_ipl, int max_ipl);
101 static int	apic_delspl(int ipl, int vector, int min_ipl, int max_ipl);
102 static void	apic_shutdown(int cmd, int fcn);
103 static void	apic_preshutdown(int cmd, int fcn);
104 static int	apic_disable_intr(processorid_t cpun);
105 static void	apic_enable_intr(processorid_t cpun);
106 static processorid_t	apic_get_next_processorid(processorid_t cpun);
107 static int		apic_get_ipivect(int ipl, int type);
108 static void	apic_timer_reprogram(hrtime_t time);
109 static void	apic_timer_enable(void);
110 static void	apic_timer_disable(void);
111 static void	apic_post_cyclic_setup(void *arg);
112 
113 static int	apic_oneshot = 0;
114 int	apic_oneshot_enable = 1; /* to allow disabling one-shot capability */
115 
116 /* Now the ones for Dynamic Interrupt distribution */
117 int	apic_enable_dynamic_migration = 0;
118 
119 
120 /*
121  * These variables are frequently accessed in apic_intr_enter(),
122  * apic_intr_exit and apic_setspl, so group them together
123  */
124 volatile uint32_t *apicadr =  NULL;	/* virtual addr of local APIC	*/
125 int apic_setspl_delay = 1;		/* apic_setspl - delay enable	*/
126 int apic_clkvect;
127 
128 /* vector at which error interrupts come in */
129 int apic_errvect;
130 int apic_enable_error_intr = 1;
131 int apic_error_display_delay = 100;
132 
133 /* vector at which performance counter overflow interrupts come in */
134 int apic_cpcovf_vect;
135 int apic_enable_cpcovf_intr = 1;
136 
137 /*
138  * The following vector assignments influence the value of ipltopri and
139  * vectortoipl. Note that vectors 0 - 0x1f are not used. We can program
140  * idle to 0 and IPL 0 to 0xf to differentiate idle in case
141  * we care to do so in future. Note some IPLs which are rarely used
142  * will share the vector ranges and heavily used IPLs (5 and 6) have
143  * a wide range.
144  *
145  * This array is used to initialize apic_ipls[] (in apic_init()).
146  *
147  *	IPL		Vector range.		as passed to intr_enter
148  *	0		none.
149  *	1,2,3		0x20-0x2f		0x0-0xf
150  *	4		0x30-0x3f		0x10-0x1f
151  *	5		0x40-0x5f		0x20-0x3f
152  *	6		0x60-0x7f		0x40-0x5f
153  *	7,8,9		0x80-0x8f		0x60-0x6f
154  *	10		0x90-0x9f		0x70-0x7f
155  *	11		0xa0-0xaf		0x80-0x8f
156  *	...		...
157  *	15		0xe0-0xef		0xc0-0xcf
158  *	15		0xf0-0xff		0xd0-0xdf
159  */
160 uchar_t apic_vectortoipl[APIC_AVAIL_VECTOR / APIC_VECTOR_PER_IPL] = {
161 	3, 4, 5, 5, 6, 6, 9, 10, 11, 12, 13, 14, 15, 15
162 };
163 	/*
164 	 * The ipl of an ISR at vector X is apic_vectortoipl[X>>4]
165 	 * NOTE that this is vector as passed into intr_enter which is
166 	 * programmed vector - 0x20 (APIC_BASE_VECT)
167 	 */
168 
169 uchar_t	apic_ipltopri[MAXIPL + 1];	/* unix ipl to apic pri	*/
170 	/* The taskpri to be programmed into apic to mask given ipl */
171 
172 #if defined(__amd64)
173 uchar_t	apic_cr8pri[MAXIPL + 1];	/* unix ipl to cr8 pri	*/
174 #endif
175 
176 /*
177  * Correlation of the hardware vector to the IPL in use, initialized
178  * from apic_vectortoipl[] in apic_init().  The final IPLs may not correlate
179  * to the IPLs in apic_vectortoipl on some systems that share interrupt lines
180  * connected to errata-stricken IOAPICs
181  */
182 uchar_t apic_ipls[APIC_AVAIL_VECTOR];
183 
184 /*
185  * Patchable global variables.
186  */
187 int	apic_forceload = 0;
188 
189 int	apic_coarse_hrtime = 1;		/* 0 - use accurate slow gethrtime() */
190 					/* 1 - use gettime() for performance */
191 int	apic_flat_model = 0;		/* 0 - clustered. 1 - flat */
192 int	apic_enable_hwsoftint = 0;	/* 0 - disable, 1 - enable	*/
193 int	apic_enable_bind_log = 1;	/* 1 - display interrupt binding log */
194 int	apic_panic_on_nmi = 0;
195 int	apic_panic_on_apic_error = 0;
196 
197 int	apic_verbose = 0;
198 
199 /* minimum number of timer ticks to program to */
200 int apic_min_timer_ticks = 1;
201 /*
202  *	Local static data
203  */
204 static struct	psm_ops apic_ops = {
205 	apic_probe,
206 
207 	apic_init,
208 	apic_picinit,
209 	apic_intr_enter,
210 	apic_intr_exit,
211 	apic_setspl,
212 	apic_addspl,
213 	apic_delspl,
214 	apic_disable_intr,
215 	apic_enable_intr,
216 	(int (*)(int))NULL,		/* psm_softlvl_to_irq */
217 	(void (*)(int))NULL,		/* psm_set_softintr */
218 
219 	apic_set_idlecpu,
220 	apic_unset_idlecpu,
221 
222 	apic_clkinit,
223 	apic_getclkirq,
224 	(void (*)(void))NULL,		/* psm_hrtimeinit */
225 	apic_gethrtime,
226 
227 	apic_get_next_processorid,
228 	apic_cpu_start,
229 	apic_post_cpu_start,
230 	apic_shutdown,
231 	apic_get_ipivect,
232 	apic_send_ipi,
233 
234 	(int (*)(dev_info_t *, int))NULL,	/* psm_translate_irq */
235 	(void (*)(int, char *))NULL,	/* psm_notify_error */
236 	(void (*)(int))NULL,		/* psm_notify_func */
237 	apic_timer_reprogram,
238 	apic_timer_enable,
239 	apic_timer_disable,
240 	apic_post_cyclic_setup,
241 	apic_preshutdown,
242 	apic_intr_ops,			/* Advanced DDI Interrupt framework */
243 	apic_state,			/* save, restore apic state for S3 */
244 };
245 
246 
247 static struct	psm_info apic_psm_info = {
248 	PSM_INFO_VER01_6,			/* version */
249 	PSM_OWN_EXCLUSIVE,			/* ownership */
250 	(struct psm_ops *)&apic_ops,		/* operation */
251 	APIC_PCPLUSMP_NAME,			/* machine name */
252 	"pcplusmp v1.4 compatible",
253 };
254 
255 static void *apic_hdlp;
256 
257 #ifdef DEBUG
258 int	apic_debug = 0;
259 int	apic_restrict_vector = 0;
260 
261 int	apic_debug_msgbuf[APIC_DEBUG_MSGBUFSIZE];
262 int	apic_debug_msgbufindex = 0;
263 
264 #endif /* DEBUG */
265 
266 apic_cpus_info_t	*apic_cpus;
267 
268 cpuset_t	apic_cpumask;
269 uint_t	apic_picinit_called;
270 
271 /* Flag to indicate that we need to shut down all processors */
272 static uint_t	apic_shutdown_processors;
273 
274 uint_t apic_nsec_per_intr = 0;
275 
276 /*
277  * apic_let_idle_redistribute can have the following values:
278  * 0 - If clock decremented it from 1 to 0, clock has to call redistribute.
279  * apic_redistribute_lock prevents multiple idle cpus from redistributing
280  */
281 int	apic_num_idle_redistributions = 0;
282 static	int apic_let_idle_redistribute = 0;
283 static	uint_t apic_nticks = 0;
284 static	uint_t apic_skipped_redistribute = 0;
285 
286 /* to gather intr data and redistribute */
287 static void apic_redistribute_compute(void);
288 
289 static	uint_t last_count_read = 0;
290 static	lock_t	apic_gethrtime_lock;
291 volatile int	apic_hrtime_stamp = 0;
292 volatile hrtime_t apic_nsec_since_boot = 0;
293 static uint_t apic_hertz_count;
294 
295 uint64_t apic_ticks_per_SFnsecs;	/* # of ticks in SF nsecs */
296 
297 static hrtime_t apic_nsec_max;
298 
299 static	hrtime_t	apic_last_hrtime = 0;
300 int		apic_hrtime_error = 0;
301 int		apic_remote_hrterr = 0;
302 int		apic_num_nmis = 0;
303 int		apic_apic_error = 0;
304 int		apic_num_apic_errors = 0;
305 int		apic_num_cksum_errors = 0;
306 
307 int	apic_error = 0;
308 static	int	apic_cmos_ssb_set = 0;
309 
310 /* use to make sure only one cpu handles the nmi */
311 static	lock_t	apic_nmi_lock;
312 /* use to make sure only one cpu handles the error interrupt */
313 static	lock_t	apic_error_lock;
314 
315 static	struct {
316 	uchar_t	cntl;
317 	uchar_t	data;
318 } aspen_bmc[] = {
319 	{ CC_SMS_WR_START,	0x18 },		/* NetFn/LUN */
320 	{ CC_SMS_WR_NEXT,	0x24 },		/* Cmd SET_WATCHDOG_TIMER */
321 	{ CC_SMS_WR_NEXT,	0x84 },		/* DataByte 1: SMS/OS no log */
322 	{ CC_SMS_WR_NEXT,	0x2 },		/* DataByte 2: Power Down */
323 	{ CC_SMS_WR_NEXT,	0x0 },		/* DataByte 3: no pre-timeout */
324 	{ CC_SMS_WR_NEXT,	0x0 },		/* DataByte 4: timer expir. */
325 	{ CC_SMS_WR_NEXT,	0xa },		/* DataByte 5: init countdown */
326 	{ CC_SMS_WR_END,	0x0 },		/* DataByte 6: init countdown */
327 
328 	{ CC_SMS_WR_START,	0x18 },		/* NetFn/LUN */
329 	{ CC_SMS_WR_END,	0x22 }		/* Cmd RESET_WATCHDOG_TIMER */
330 };
331 
332 static	struct {
333 	int	port;
334 	uchar_t	data;
335 } sitka_bmc[] = {
336 	{ SMS_COMMAND_REGISTER,	SMS_WRITE_START },
337 	{ SMS_DATA_REGISTER,	0x18 },		/* NetFn/LUN */
338 	{ SMS_DATA_REGISTER,	0x24 },		/* Cmd SET_WATCHDOG_TIMER */
339 	{ SMS_DATA_REGISTER,	0x84 },		/* DataByte 1: SMS/OS no log */
340 	{ SMS_DATA_REGISTER,	0x2 },		/* DataByte 2: Power Down */
341 	{ SMS_DATA_REGISTER,	0x0 },		/* DataByte 3: no pre-timeout */
342 	{ SMS_DATA_REGISTER,	0x0 },		/* DataByte 4: timer expir. */
343 	{ SMS_DATA_REGISTER,	0xa },		/* DataByte 5: init countdown */
344 	{ SMS_COMMAND_REGISTER,	SMS_WRITE_END },
345 	{ SMS_DATA_REGISTER,	0x0 },		/* DataByte 6: init countdown */
346 
347 	{ SMS_COMMAND_REGISTER,	SMS_WRITE_START },
348 	{ SMS_DATA_REGISTER,	0x18 },		/* NetFn/LUN */
349 	{ SMS_COMMAND_REGISTER,	SMS_WRITE_END },
350 	{ SMS_DATA_REGISTER,	0x22 }		/* Cmd RESET_WATCHDOG_TIMER */
351 };
352 
353 /* Patchable global variables. */
354 int		apic_kmdb_on_nmi = 0;		/* 0 - no, 1 - yes enter kmdb */
355 uint32_t	apic_divide_reg_init = 0;	/* 0 - divide by 2 */
356 
357 /*
358  *	This is the loadable module wrapper
359  */
360 
361 int
362 _init(void)
363 {
364 	if (apic_coarse_hrtime)
365 		apic_ops.psm_gethrtime = &apic_gettime;
366 	return (psm_mod_init(&apic_hdlp, &apic_psm_info));
367 }
368 
369 int
370 _fini(void)
371 {
372 	return (psm_mod_fini(&apic_hdlp, &apic_psm_info));
373 }
374 
375 int
376 _info(struct modinfo *modinfop)
377 {
378 	return (psm_mod_info(&apic_hdlp, &apic_psm_info, modinfop));
379 }
380 
381 
382 static int
383 apic_probe()
384 {
385 	return (apic_probe_common(apic_psm_info.p_mach_idstring));
386 }
387 
388 void
389 apic_init()
390 {
391 	int i;
392 	int	j = 1;
393 
394 	apic_ipltopri[0] = APIC_VECTOR_PER_IPL; /* leave 0 for idle */
395 	for (i = 0; i < (APIC_AVAIL_VECTOR / APIC_VECTOR_PER_IPL); i++) {
396 		if ((i < ((APIC_AVAIL_VECTOR / APIC_VECTOR_PER_IPL) - 1)) &&
397 		    (apic_vectortoipl[i + 1] == apic_vectortoipl[i]))
398 			/* get to highest vector at the same ipl */
399 			continue;
400 		for (; j <= apic_vectortoipl[i]; j++) {
401 			apic_ipltopri[j] = (i << APIC_IPL_SHIFT) +
402 			    APIC_BASE_VECT;
403 		}
404 	}
405 	for (; j < MAXIPL + 1; j++)
406 		/* fill up any empty ipltopri slots */
407 		apic_ipltopri[j] = (i << APIC_IPL_SHIFT) + APIC_BASE_VECT;
408 	apic_init_common();
409 #if defined(__amd64)
410 	/*
411 	 * Make cpu-specific interrupt info point to cr8pri vector
412 	 */
413 	for (i = 0; i <= MAXIPL; i++)
414 		apic_cr8pri[i] = apic_ipltopri[i] >> APIC_IPL_SHIFT;
415 	CPU->cpu_pri_data = apic_cr8pri;
416 #endif	/* __amd64 */
417 }
418 
419 /*
420  * handler for APIC Error interrupt. Just print a warning and continue
421  */
422 static int
423 apic_error_intr()
424 {
425 	uint_t	error0, error1, error;
426 	uint_t	i;
427 
428 	/*
429 	 * We need to write before read as per 7.4.17 of system prog manual.
430 	 * We do both and or the results to be safe
431 	 */
432 	error0 = apicadr[APIC_ERROR_STATUS];
433 	apicadr[APIC_ERROR_STATUS] = 0;
434 	error1 = apicadr[APIC_ERROR_STATUS];
435 	error = error0 | error1;
436 
437 	/*
438 	 * Clear the APIC error status (do this on all cpus that enter here)
439 	 * (two writes are required due to the semantics of accessing the
440 	 * error status register.)
441 	 */
442 	apicadr[APIC_ERROR_STATUS] = 0;
443 	apicadr[APIC_ERROR_STATUS] = 0;
444 
445 	/*
446 	 * Prevent more than 1 CPU from handling error interrupt causing
447 	 * double printing (interleave of characters from multiple
448 	 * CPU's when using prom_printf)
449 	 */
450 	if (lock_try(&apic_error_lock) == 0)
451 		return (error ? DDI_INTR_CLAIMED : DDI_INTR_UNCLAIMED);
452 	if (error) {
453 #if	DEBUG
454 		if (apic_debug)
455 			debug_enter("pcplusmp: APIC Error interrupt received");
456 #endif /* DEBUG */
457 		if (apic_panic_on_apic_error)
458 			cmn_err(CE_PANIC,
459 			    "APIC Error interrupt on CPU %d. Status = %x\n",
460 			    psm_get_cpu_id(), error);
461 		else {
462 			if ((error & ~APIC_CS_ERRORS) == 0) {
463 				/* cksum error only */
464 				apic_error |= APIC_ERR_APIC_ERROR;
465 				apic_apic_error |= error;
466 				apic_num_apic_errors++;
467 				apic_num_cksum_errors++;
468 			} else {
469 				/*
470 				 * prom_printf is the best shot we have of
471 				 * something which is problem free from
472 				 * high level/NMI type of interrupts
473 				 */
474 				prom_printf("APIC Error interrupt on CPU %d. "
475 				    "Status 0 = %x, Status 1 = %x\n",
476 				    psm_get_cpu_id(), error0, error1);
477 				apic_error |= APIC_ERR_APIC_ERROR;
478 				apic_apic_error |= error;
479 				apic_num_apic_errors++;
480 				for (i = 0; i < apic_error_display_delay; i++) {
481 					tenmicrosec();
482 				}
483 				/*
484 				 * provide more delay next time limited to
485 				 * roughly 1 clock tick time
486 				 */
487 				if (apic_error_display_delay < 500)
488 					apic_error_display_delay *= 2;
489 			}
490 		}
491 		lock_clear(&apic_error_lock);
492 		return (DDI_INTR_CLAIMED);
493 	} else {
494 		lock_clear(&apic_error_lock);
495 		return (DDI_INTR_UNCLAIMED);
496 	}
497 	/* NOTREACHED */
498 }
499 
500 /*
501  * Turn off the mask bit in the performance counter Local Vector Table entry.
502  */
503 static void
504 apic_cpcovf_mask_clear(void)
505 {
506 	apicadr[APIC_PCINT_VECT] &= ~APIC_LVT_MASK;
507 }
508 
509 static void
510 apic_init_intr()
511 {
512 	processorid_t	cpun = psm_get_cpu_id();
513 	uint_t nlvt;
514 
515 #if defined(__amd64)
516 	setcr8((ulong_t)(APIC_MASK_ALL >> APIC_IPL_SHIFT));
517 #else
518 	apicadr[APIC_TASK_REG] = APIC_MASK_ALL;
519 #endif
520 
521 	if (apic_flat_model)
522 		apicadr[APIC_FORMAT_REG] = APIC_FLAT_MODEL;
523 	else
524 		apicadr[APIC_FORMAT_REG] = APIC_CLUSTER_MODEL;
525 	apicadr[APIC_DEST_REG] = AV_HIGH_ORDER >> cpun;
526 
527 	/* need to enable APIC before unmasking NMI */
528 	apicadr[APIC_SPUR_INT_REG] = AV_UNIT_ENABLE | APIC_SPUR_INTR;
529 
530 	/*
531 	 * Presence of an invalid vector with delivery mode AV_FIXED can
532 	 * cause an error interrupt, even if the entry is masked...so
533 	 * write a valid vector to LVT entries along with the mask bit
534 	 */
535 
536 	/* All APICs have timer and LINT0/1 */
537 	apicadr[APIC_LOCAL_TIMER] = AV_MASK|APIC_RESV_IRQ;
538 	apicadr[APIC_INT_VECT0]	= AV_MASK|APIC_RESV_IRQ;
539 	apicadr[APIC_INT_VECT1] = AV_NMI;	/* enable NMI */
540 
541 	/*
542 	 * On integrated APICs, the number of LVT entries is
543 	 * 'Max LVT entry' + 1; on 82489DX's (non-integrated
544 	 * APICs), nlvt is "3" (LINT0, LINT1, and timer)
545 	 */
546 
547 	if (apic_cpus[cpun].aci_local_ver < APIC_INTEGRATED_VERS) {
548 		nlvt = 3;
549 	} else {
550 		nlvt = ((apicadr[APIC_VERS_REG] >> 16) & 0xFF) + 1;
551 	}
552 
553 	if (nlvt >= 5) {
554 		/* Enable performance counter overflow interrupt */
555 
556 		if ((x86_feature & X86_MSR) != X86_MSR)
557 			apic_enable_cpcovf_intr = 0;
558 		if (apic_enable_cpcovf_intr) {
559 			if (apic_cpcovf_vect == 0) {
560 				int ipl = APIC_PCINT_IPL;
561 				int irq = apic_get_ipivect(ipl, -1);
562 
563 				ASSERT(irq != -1);
564 				apic_cpcovf_vect =
565 				    apic_irq_table[irq]->airq_vector;
566 				ASSERT(apic_cpcovf_vect);
567 				(void) add_avintr(NULL, ipl,
568 				    (avfunc)kcpc_hw_overflow_intr,
569 				    "apic pcint", irq, NULL, NULL, NULL, NULL);
570 				kcpc_hw_overflow_intr_installed = 1;
571 				kcpc_hw_enable_cpc_intr =
572 				    apic_cpcovf_mask_clear;
573 			}
574 			apicadr[APIC_PCINT_VECT] = apic_cpcovf_vect;
575 		}
576 	}
577 
578 	if (nlvt >= 6) {
579 		/* Only mask TM intr if the BIOS apparently doesn't use it */
580 
581 		uint32_t lvtval;
582 
583 		lvtval = apicadr[APIC_THERM_VECT];
584 		if (((lvtval & AV_MASK) == AV_MASK) ||
585 		    ((lvtval & AV_DELIV_MODE) != AV_SMI)) {
586 			apicadr[APIC_THERM_VECT] = AV_MASK|APIC_RESV_IRQ;
587 		}
588 	}
589 
590 	/* Enable error interrupt */
591 
592 	if (nlvt >= 4 && apic_enable_error_intr) {
593 		if (apic_errvect == 0) {
594 			int ipl = 0xf;	/* get highest priority intr */
595 			int irq = apic_get_ipivect(ipl, -1);
596 
597 			ASSERT(irq != -1);
598 			apic_errvect = apic_irq_table[irq]->airq_vector;
599 			ASSERT(apic_errvect);
600 			/*
601 			 * Not PSMI compliant, but we are going to merge
602 			 * with ON anyway
603 			 */
604 			(void) add_avintr((void *)NULL, ipl,
605 			    (avfunc)apic_error_intr, "apic error intr",
606 			    irq, NULL, NULL, NULL, NULL);
607 		}
608 		apicadr[APIC_ERR_VECT] = apic_errvect;
609 		apicadr[APIC_ERROR_STATUS] = 0;
610 		apicadr[APIC_ERROR_STATUS] = 0;
611 	}
612 
613 }
614 
615 static void
616 apic_disable_local_apic()
617 {
618 	apicadr[APIC_TASK_REG] = APIC_MASK_ALL;
619 	apicadr[APIC_LOCAL_TIMER] = AV_MASK;
620 	apicadr[APIC_INT_VECT0] = AV_MASK;	/* local intr reg 0 */
621 	apicadr[APIC_INT_VECT1] = AV_MASK;	/* disable NMI */
622 	apicadr[APIC_ERR_VECT] = AV_MASK;	/* and error interrupt */
623 	apicadr[APIC_PCINT_VECT] = AV_MASK;	/* and perf counter intr */
624 	apicadr[APIC_SPUR_INT_REG] = APIC_SPUR_INTR;
625 }
626 
627 static void
628 apic_picinit(void)
629 {
630 	int i, j;
631 	uint_t isr;
632 
633 	/*
634 	 * On UniSys Model 6520, the BIOS leaves vector 0x20 isr
635 	 * bit on without clearing it with EOI.  Since softint
636 	 * uses vector 0x20 to interrupt itself, so softint will
637 	 * not work on this machine.  In order to fix this problem
638 	 * a check is made to verify all the isr bits are clear.
639 	 * If not, EOIs are issued to clear the bits.
640 	 */
641 	for (i = 7; i >= 1; i--) {
642 		if ((isr = apicadr[APIC_ISR_REG + (i * 4)]) != 0)
643 			for (j = 0; ((j < 32) && (isr != 0)); j++)
644 				if (isr & (1 << j)) {
645 					apicadr[APIC_EOI_REG] = 0;
646 					isr &= ~(1 << j);
647 					apic_error |= APIC_ERR_BOOT_EOI;
648 				}
649 	}
650 
651 	/* set a flag so we know we have run apic_picinit() */
652 	apic_picinit_called = 1;
653 	LOCK_INIT_CLEAR(&apic_gethrtime_lock);
654 	LOCK_INIT_CLEAR(&apic_ioapic_lock);
655 	LOCK_INIT_CLEAR(&apic_error_lock);
656 
657 	picsetup();	 /* initialise the 8259 */
658 
659 	/* add nmi handler - least priority nmi handler */
660 	LOCK_INIT_CLEAR(&apic_nmi_lock);
661 
662 	if (!psm_add_nmintr(0, (avfunc) apic_nmi_intr,
663 	    "pcplusmp NMI handler", (caddr_t)NULL))
664 		cmn_err(CE_WARN, "pcplusmp: Unable to add nmi handler");
665 
666 	apic_init_intr();
667 
668 	/* enable apic mode if imcr present */
669 	if (apic_imcrp) {
670 		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
671 		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_APIC);
672 	}
673 
674 	ioapic_init_intr(IOAPIC_MASK);
675 }
676 
677 
678 /*ARGSUSED1*/
679 static int
680 apic_cpu_start(processorid_t cpun, caddr_t arg)
681 {
682 	int		loop_count;
683 	uint32_t	vector;
684 	uint_t		cpu_id;
685 	ulong_t		iflag;
686 
687 	cpu_id = apic_cpus[cpun].aci_local_id;
688 
689 	apic_cmos_ssb_set = 1;
690 
691 	/*
692 	 * Interrupts on BSP cpu will be disabled during these startup
693 	 * steps in order to avoid unwanted side effects from
694 	 * executing interrupt handlers on a problematic BIOS.
695 	 */
696 
697 	iflag = intr_clear();
698 	outb(CMOS_ADDR, SSB);
699 	outb(CMOS_DATA, BIOS_SHUTDOWN);
700 
701 	while (get_apic_cmd1() & AV_PENDING)
702 		apic_ret();
703 
704 	/* for integrated - make sure there is one INIT IPI in buffer */
705 	/* for external - it will wake up the cpu */
706 	apicadr[APIC_INT_CMD2] = cpu_id << APIC_ICR_ID_BIT_OFFSET;
707 	apicadr[APIC_INT_CMD1] = AV_ASSERT | AV_RESET;
708 
709 	/* If only 1 CPU is installed, PENDING bit will not go low */
710 	for (loop_count = 0x1000; loop_count; loop_count--)
711 		if (get_apic_cmd1() & AV_PENDING)
712 			apic_ret();
713 		else
714 			break;
715 
716 	apicadr[APIC_INT_CMD2] = cpu_id << APIC_ICR_ID_BIT_OFFSET;
717 	apicadr[APIC_INT_CMD1] = AV_DEASSERT | AV_RESET;
718 
719 	drv_usecwait(20000);		/* 20 milli sec */
720 
721 	if (apic_cpus[cpun].aci_local_ver >= APIC_INTEGRATED_VERS) {
722 		/* integrated apic */
723 
724 		vector = (rm_platter_pa >> MMU_PAGESHIFT) &
725 		    (APIC_VECTOR_MASK | APIC_IPL_MASK);
726 
727 		/* to offset the INIT IPI queue up in the buffer */
728 		apicadr[APIC_INT_CMD2] = cpu_id << APIC_ICR_ID_BIT_OFFSET;
729 		apicadr[APIC_INT_CMD1] = vector | AV_STARTUP;
730 
731 		drv_usecwait(200);		/* 20 micro sec */
732 
733 		apicadr[APIC_INT_CMD2] = cpu_id << APIC_ICR_ID_BIT_OFFSET;
734 		apicadr[APIC_INT_CMD1] = vector | AV_STARTUP;
735 
736 		drv_usecwait(200);		/* 20 micro sec */
737 	}
738 	intr_restore(iflag);
739 	return (0);
740 }
741 
742 
743 #ifdef	DEBUG
744 int	apic_break_on_cpu = 9;
745 int	apic_stretch_interrupts = 0;
746 int	apic_stretch_ISR = 1 << 3;	/* IPL of 3 matches nothing now */
747 
748 void
749 apic_break()
750 {
751 }
752 #endif /* DEBUG */
753 
754 /*
755  * platform_intr_enter
756  *
757  *	Called at the beginning of the interrupt service routine to
758  *	mask all level equal to and below the interrupt priority
759  *	of the interrupting vector.  An EOI should be given to
760  *	the interrupt controller to enable other HW interrupts.
761  *
762  *	Return -1 for spurious interrupts
763  *
764  */
765 /*ARGSUSED*/
766 static int
767 apic_intr_enter(int ipl, int *vectorp)
768 {
769 	uchar_t vector;
770 	int nipl;
771 	int irq;
772 	ulong_t iflag;
773 	apic_cpus_info_t *cpu_infop;
774 
775 	/*
776 	 * The real vector delivered is (*vectorp + 0x20), but our caller
777 	 * subtracts 0x20 from the vector before passing it to us.
778 	 * (That's why APIC_BASE_VECT is 0x20.)
779 	 */
780 	vector = (uchar_t)*vectorp;
781 
782 	/* if interrupted by the clock, increment apic_nsec_since_boot */
783 	if (vector == apic_clkvect) {
784 		if (!apic_oneshot) {
785 			/* NOTE: this is not MT aware */
786 			apic_hrtime_stamp++;
787 			apic_nsec_since_boot += apic_nsec_per_intr;
788 			apic_hrtime_stamp++;
789 			last_count_read = apic_hertz_count;
790 			apic_redistribute_compute();
791 		}
792 
793 		/* We will avoid all the book keeping overhead for clock */
794 		nipl = apic_ipls[vector];
795 
796 #if defined(__amd64)
797 		setcr8((ulong_t)apic_cr8pri[nipl]);
798 #else
799 		apicadr[APIC_TASK_REG] = apic_ipltopri[nipl];
800 #endif
801 		*vectorp = apic_vector_to_irq[vector + APIC_BASE_VECT];
802 		apicadr[APIC_EOI_REG] = 0;
803 		return (nipl);
804 	}
805 
806 	cpu_infop = &apic_cpus[psm_get_cpu_id()];
807 
808 	if (vector == (APIC_SPUR_INTR - APIC_BASE_VECT)) {
809 		cpu_infop->aci_spur_cnt++;
810 		return (APIC_INT_SPURIOUS);
811 	}
812 
813 	/* Check if the vector we got is really what we need */
814 	if (apic_revector_pending) {
815 		/*
816 		 * Disable interrupts for the duration of
817 		 * the vector translation to prevent a self-race for
818 		 * the apic_revector_lock.  This cannot be done
819 		 * in apic_xlate_vector because it is recursive and
820 		 * we want the vector translation to be atomic with
821 		 * respect to other (higher-priority) interrupts.
822 		 */
823 		iflag = intr_clear();
824 		vector = apic_xlate_vector(vector + APIC_BASE_VECT) -
825 		    APIC_BASE_VECT;
826 		intr_restore(iflag);
827 	}
828 
829 	nipl = apic_ipls[vector];
830 	*vectorp = irq = apic_vector_to_irq[vector + APIC_BASE_VECT];
831 
832 #if defined(__amd64)
833 	setcr8((ulong_t)apic_cr8pri[nipl]);
834 #else
835 	apicadr[APIC_TASK_REG] = apic_ipltopri[nipl];
836 #endif
837 
838 	cpu_infop->aci_current[nipl] = (uchar_t)irq;
839 	cpu_infop->aci_curipl = (uchar_t)nipl;
840 	cpu_infop->aci_ISR_in_progress |= 1 << nipl;
841 
842 	/*
843 	 * apic_level_intr could have been assimilated into the irq struct.
844 	 * but, having it as a character array is more efficient in terms of
845 	 * cache usage. So, we leave it as is.
846 	 */
847 	if (!apic_level_intr[irq])
848 		apicadr[APIC_EOI_REG] = 0;
849 
850 #ifdef	DEBUG
851 	APIC_DEBUG_BUF_PUT(vector);
852 	APIC_DEBUG_BUF_PUT(irq);
853 	APIC_DEBUG_BUF_PUT(nipl);
854 	APIC_DEBUG_BUF_PUT(psm_get_cpu_id());
855 	if ((apic_stretch_interrupts) && (apic_stretch_ISR & (1 << nipl)))
856 		drv_usecwait(apic_stretch_interrupts);
857 
858 	if (apic_break_on_cpu == psm_get_cpu_id())
859 		apic_break();
860 #endif /* DEBUG */
861 	return (nipl);
862 }
863 
864 void
865 apic_intr_exit(int prev_ipl, int irq)
866 {
867 	apic_cpus_info_t *cpu_infop;
868 
869 #if defined(__amd64)
870 	setcr8((ulong_t)apic_cr8pri[prev_ipl]);
871 #else
872 	apicadr[APIC_TASK_REG] = apic_ipltopri[prev_ipl];
873 #endif
874 
875 	cpu_infop = &apic_cpus[psm_get_cpu_id()];
876 	if (apic_level_intr[irq])
877 		apicadr[APIC_EOI_REG] = 0;
878 
879 	cpu_infop->aci_curipl = (uchar_t)prev_ipl;
880 	/* ISR above current pri could not be in progress */
881 	cpu_infop->aci_ISR_in_progress &= (2 << prev_ipl) - 1;
882 }
883 
884 intr_exit_fn_t
885 psm_intr_exit_fn(void)
886 {
887 	return (apic_intr_exit);
888 }
889 
890 /*
891  * Mask all interrupts below or equal to the given IPL
892  */
893 static void
894 apic_setspl(int ipl)
895 {
896 
897 #if defined(__amd64)
898 	setcr8((ulong_t)apic_cr8pri[ipl]);
899 #else
900 	apicadr[APIC_TASK_REG] = apic_ipltopri[ipl];
901 #endif
902 
903 	/* interrupts at ipl above this cannot be in progress */
904 	apic_cpus[psm_get_cpu_id()].aci_ISR_in_progress &= (2 << ipl) - 1;
905 	/*
906 	 * this is a patch fix for the ALR QSMP P5 machine, so that interrupts
907 	 * have enough time to come in before the priority is raised again
908 	 * during the idle() loop.
909 	 */
910 	if (apic_setspl_delay)
911 		(void) get_apic_pri();
912 }
913 
914 /*
915  * generates an interprocessor interrupt to another CPU
916  */
917 static void
918 apic_send_ipi(int cpun, int ipl)
919 {
920 	int vector;
921 	ulong_t flag;
922 
923 	vector = apic_resv_vector[ipl];
924 
925 	ASSERT((vector >= APIC_BASE_VECT) && (vector <= APIC_SPUR_INTR));
926 
927 	flag = intr_clear();
928 
929 	while (get_apic_cmd1() & AV_PENDING)
930 		apic_ret();
931 
932 	apicadr[APIC_INT_CMD2] =
933 	    apic_cpus[cpun].aci_local_id << APIC_ICR_ID_BIT_OFFSET;
934 	apicadr[APIC_INT_CMD1] = vector;
935 
936 	intr_restore(flag);
937 }
938 
939 
940 /*ARGSUSED*/
941 static void
942 apic_set_idlecpu(processorid_t cpun)
943 {
944 }
945 
946 /*ARGSUSED*/
947 static void
948 apic_unset_idlecpu(processorid_t cpun)
949 {
950 }
951 
952 
953 static void
954 apic_ret()
955 {
956 }
957 
958 static int
959 get_apic_cmd1()
960 {
961 	return (apicadr[APIC_INT_CMD1]);
962 }
963 
964 static int
965 get_apic_pri()
966 {
967 #if defined(__amd64)
968 	return ((int)getcr8());
969 #else
970 	return (apicadr[APIC_TASK_REG]);
971 #endif
972 }
973 
974 /*
975  * If apic_coarse_time == 1, then apic_gettime() is used instead of
976  * apic_gethrtime().  This is used for performance instead of accuracy.
977  */
978 
979 static hrtime_t
980 apic_gettime()
981 {
982 	int old_hrtime_stamp;
983 	hrtime_t temp;
984 
985 	/*
986 	 * In one-shot mode, we do not keep time, so if anyone
987 	 * calls psm_gettime() directly, we vector over to
988 	 * gethrtime().
989 	 * one-shot mode MUST NOT be enabled if this psm is the source of
990 	 * hrtime.
991 	 */
992 
993 	if (apic_oneshot)
994 		return (gethrtime());
995 
996 
997 gettime_again:
998 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
999 		apic_ret();
1000 
1001 	temp = apic_nsec_since_boot;
1002 
1003 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
1004 		goto gettime_again;
1005 	}
1006 	return (temp);
1007 }
1008 
1009 /*
1010  * Here we return the number of nanoseconds since booting.  Note every
1011  * clock interrupt increments apic_nsec_since_boot by the appropriate
1012  * amount.
1013  */
1014 static hrtime_t
1015 apic_gethrtime()
1016 {
1017 	int curr_timeval, countval, elapsed_ticks;
1018 	int old_hrtime_stamp, status;
1019 	hrtime_t temp;
1020 	uchar_t	cpun;
1021 	ulong_t oflags;
1022 
1023 	/*
1024 	 * In one-shot mode, we do not keep time, so if anyone
1025 	 * calls psm_gethrtime() directly, we vector over to
1026 	 * gethrtime().
1027 	 * one-shot mode MUST NOT be enabled if this psm is the source of
1028 	 * hrtime.
1029 	 */
1030 
1031 	if (apic_oneshot)
1032 		return (gethrtime());
1033 
1034 	oflags = intr_clear();	/* prevent migration */
1035 
1036 	cpun = (uchar_t)((uint_t)apicadr[APIC_LID_REG] >> APIC_ID_BIT_OFFSET);
1037 
1038 	lock_set(&apic_gethrtime_lock);
1039 
1040 gethrtime_again:
1041 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
1042 		apic_ret();
1043 
1044 	/*
1045 	 * Check to see which CPU we are on.  Note the time is kept on
1046 	 * the local APIC of CPU 0.  If on CPU 0, simply read the current
1047 	 * counter.  If on another CPU, issue a remote read command to CPU 0.
1048 	 */
1049 	if (cpun == apic_cpus[0].aci_local_id) {
1050 		countval = apicadr[APIC_CURR_COUNT];
1051 	} else {
1052 		while (get_apic_cmd1() & AV_PENDING)
1053 			apic_ret();
1054 
1055 		apicadr[APIC_INT_CMD2] =
1056 		    apic_cpus[0].aci_local_id << APIC_ICR_ID_BIT_OFFSET;
1057 		apicadr[APIC_INT_CMD1] = APIC_CURR_ADD|AV_REMOTE;
1058 
1059 		while ((status = get_apic_cmd1()) & AV_READ_PENDING)
1060 			apic_ret();
1061 
1062 		if (status & AV_REMOTE_STATUS)	/* 1 = valid */
1063 			countval = apicadr[APIC_REMOTE_READ];
1064 		else {	/* 0 = invalid */
1065 			apic_remote_hrterr++;
1066 			/*
1067 			 * return last hrtime right now, will need more
1068 			 * testing if change to retry
1069 			 */
1070 			temp = apic_last_hrtime;
1071 
1072 			lock_clear(&apic_gethrtime_lock);
1073 
1074 			intr_restore(oflags);
1075 
1076 			return (temp);
1077 		}
1078 	}
1079 	if (countval > last_count_read)
1080 		countval = 0;
1081 	else
1082 		last_count_read = countval;
1083 
1084 	elapsed_ticks = apic_hertz_count - countval;
1085 
1086 	curr_timeval = APIC_TICKS_TO_NSECS(elapsed_ticks);
1087 	temp = apic_nsec_since_boot + curr_timeval;
1088 
1089 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
1090 		/* we might have clobbered last_count_read. Restore it */
1091 		last_count_read = apic_hertz_count;
1092 		goto gethrtime_again;
1093 	}
1094 
1095 	if (temp < apic_last_hrtime) {
1096 		/* return last hrtime if error occurs */
1097 		apic_hrtime_error++;
1098 		temp = apic_last_hrtime;
1099 	}
1100 	else
1101 		apic_last_hrtime = temp;
1102 
1103 	lock_clear(&apic_gethrtime_lock);
1104 	intr_restore(oflags);
1105 
1106 	return (temp);
1107 }
1108 
1109 /* apic NMI handler */
1110 /*ARGSUSED*/
1111 static void
1112 apic_nmi_intr(caddr_t arg, struct regs *rp)
1113 {
1114 	if (apic_shutdown_processors) {
1115 		apic_disable_local_apic();
1116 		return;
1117 	}
1118 
1119 	apic_error |= APIC_ERR_NMI;
1120 
1121 	if (!lock_try(&apic_nmi_lock))
1122 		return;
1123 	apic_num_nmis++;
1124 
1125 	if (apic_kmdb_on_nmi && psm_debugger()) {
1126 		debug_enter("NMI received: entering kmdb\n");
1127 	} else if (apic_panic_on_nmi) {
1128 		/* Keep panic from entering kmdb. */
1129 		nopanicdebug = 1;
1130 		panic("NMI received\n");
1131 	} else {
1132 		/*
1133 		 * prom_printf is the best shot we have of something which is
1134 		 * problem free from high level/NMI type of interrupts
1135 		 */
1136 		prom_printf("NMI received\n");
1137 	}
1138 
1139 	lock_clear(&apic_nmi_lock);
1140 }
1141 
1142 /*ARGSUSED*/
1143 static int
1144 apic_addspl(int irqno, int ipl, int min_ipl, int max_ipl)
1145 {
1146 	return (apic_addspl_common(irqno, ipl, min_ipl, max_ipl));
1147 }
1148 
1149 static int
1150 apic_delspl(int irqno, int ipl, int min_ipl, int max_ipl)
1151 {
1152 	return (apic_delspl_common(irqno, ipl, min_ipl,  max_ipl));
1153 }
1154 
1155 static int
1156 apic_post_cpu_start()
1157 {
1158 	int cpun;
1159 
1160 	splx(ipltospl(LOCK_LEVEL));
1161 	apic_init_intr();
1162 
1163 	/*
1164 	 * since some systems don't enable the internal cache on the non-boot
1165 	 * cpus, so we have to enable them here
1166 	 */
1167 	setcr0(getcr0() & ~(CR0_CD | CR0_NW));
1168 
1169 	while (get_apic_cmd1() & AV_PENDING)
1170 		apic_ret();
1171 
1172 	cpun = psm_get_cpu_id();
1173 	apic_cpus[cpun].aci_status = APIC_CPU_ONLINE;
1174 
1175 	apicadr[APIC_DIVIDE_REG] = apic_divide_reg_init;
1176 	return (PSM_SUCCESS);
1177 }
1178 
1179 processorid_t
1180 apic_get_next_processorid(processorid_t cpu_id)
1181 {
1182 
1183 	int i;
1184 
1185 	if (cpu_id == -1)
1186 		return ((processorid_t)0);
1187 
1188 	for (i = cpu_id + 1; i < NCPU; i++) {
1189 		if (CPU_IN_SET(apic_cpumask, i))
1190 			return (i);
1191 	}
1192 
1193 	return ((processorid_t)-1);
1194 }
1195 
1196 
1197 /*
1198  * type == -1 indicates it is an internal request. Do not change
1199  * resv_vector for these requests
1200  */
1201 static int
1202 apic_get_ipivect(int ipl, int type)
1203 {
1204 	uchar_t vector;
1205 	int irq;
1206 
1207 	if (irq = apic_allocate_irq(APIC_VECTOR(ipl))) {
1208 		if (vector = apic_allocate_vector(ipl, irq, 1)) {
1209 			apic_irq_table[irq]->airq_mps_intr_index =
1210 			    RESERVE_INDEX;
1211 			apic_irq_table[irq]->airq_vector = vector;
1212 			if (type != -1) {
1213 				apic_resv_vector[ipl] = vector;
1214 			}
1215 			return (irq);
1216 		}
1217 	}
1218 	apic_error |= APIC_ERR_GET_IPIVECT_FAIL;
1219 	return (-1);	/* shouldn't happen */
1220 }
1221 
1222 static int
1223 apic_getclkirq(int ipl)
1224 {
1225 	int	irq;
1226 
1227 	if ((irq = apic_get_ipivect(ipl, -1)) == -1)
1228 		return (-1);
1229 	/*
1230 	 * Note the vector in apic_clkvect for per clock handling.
1231 	 */
1232 	apic_clkvect = apic_irq_table[irq]->airq_vector - APIC_BASE_VECT;
1233 	APIC_VERBOSE_IOAPIC((CE_NOTE, "get_clkirq: vector = %x\n",
1234 	    apic_clkvect));
1235 	return (irq);
1236 }
1237 
1238 
1239 /*
1240  * Return the number of APIC clock ticks elapsed for 8245 to decrement
1241  * (APIC_TIME_COUNT + pit_ticks_adj) ticks.
1242  */
1243 static uint_t
1244 apic_calibrate(volatile uint32_t *addr, uint16_t *pit_ticks_adj)
1245 {
1246 	uint8_t		pit_tick_lo;
1247 	uint16_t	pit_tick, target_pit_tick;
1248 	uint32_t	start_apic_tick, end_apic_tick;
1249 	ulong_t		iflag;
1250 
1251 	addr += APIC_CURR_COUNT;
1252 
1253 	iflag = intr_clear();
1254 
1255 	do {
1256 		pit_tick_lo = inb(PITCTR0_PORT);
1257 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1258 	} while (pit_tick < APIC_TIME_MIN ||
1259 	    pit_tick_lo <= APIC_LB_MIN || pit_tick_lo >= APIC_LB_MAX);
1260 
1261 	/*
1262 	 * Wait for the 8254 to decrement by 5 ticks to ensure
1263 	 * we didn't start in the middle of a tick.
1264 	 * Compare with 0x10 for the wrap around case.
1265 	 */
1266 	target_pit_tick = pit_tick - 5;
1267 	do {
1268 		pit_tick_lo = inb(PITCTR0_PORT);
1269 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1270 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1271 
1272 	start_apic_tick = *addr;
1273 
1274 	/*
1275 	 * Wait for the 8254 to decrement by
1276 	 * (APIC_TIME_COUNT + pit_ticks_adj) ticks
1277 	 */
1278 	target_pit_tick = pit_tick - APIC_TIME_COUNT;
1279 	do {
1280 		pit_tick_lo = inb(PITCTR0_PORT);
1281 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1282 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1283 
1284 	end_apic_tick = *addr;
1285 
1286 	*pit_ticks_adj = target_pit_tick - pit_tick;
1287 
1288 	intr_restore(iflag);
1289 
1290 	return (start_apic_tick - end_apic_tick);
1291 }
1292 
1293 /*
1294  * Initialise the APIC timer on the local APIC of CPU 0 to the desired
1295  * frequency.  Note at this stage in the boot sequence, the boot processor
1296  * is the only active processor.
1297  * hertz value of 0 indicates a one-shot mode request.  In this case
1298  * the function returns the resolution (in nanoseconds) for the hardware
1299  * timer interrupt.  If one-shot mode capability is not available,
1300  * the return value will be 0. apic_enable_oneshot is a global switch
1301  * for disabling the functionality.
1302  * A non-zero positive value for hertz indicates a periodic mode request.
1303  * In this case the hardware will be programmed to generate clock interrupts
1304  * at hertz frequency and returns the resolution of interrupts in
1305  * nanosecond.
1306  */
1307 
1308 static int
1309 apic_clkinit(int hertz)
1310 {
1311 	uint_t		apic_ticks = 0;
1312 	uint_t		pit_ticks;
1313 	int		ret;
1314 	uint16_t	pit_ticks_adj;
1315 	static int	firsttime = 1;
1316 
1317 	if (firsttime) {
1318 		/* first time calibrate on CPU0 only */
1319 
1320 		apicadr[APIC_DIVIDE_REG] = apic_divide_reg_init;
1321 		apicadr[APIC_INIT_COUNT] = APIC_MAXVAL;
1322 		apic_ticks = apic_calibrate(apicadr, &pit_ticks_adj);
1323 
1324 		/* total number of PIT ticks corresponding to apic_ticks */
1325 		pit_ticks = APIC_TIME_COUNT + pit_ticks_adj;
1326 
1327 		/*
1328 		 * Determine the number of nanoseconds per APIC clock tick
1329 		 * and then determine how many APIC ticks to interrupt at the
1330 		 * desired frequency
1331 		 * apic_ticks / (pitticks / PIT_HZ) = apic_ticks_per_s
1332 		 * (apic_ticks * PIT_HZ) / pitticks = apic_ticks_per_s
1333 		 * apic_ticks_per_ns = (apic_ticks * PIT_HZ) / (pitticks * 10^9)
1334 		 * pic_ticks_per_SFns =
1335 		 *   (SF * apic_ticks * PIT_HZ) / (pitticks * 10^9)
1336 		 */
1337 		apic_ticks_per_SFnsecs =
1338 		    ((SF * apic_ticks * PIT_HZ) /
1339 		    ((uint64_t)pit_ticks * NANOSEC));
1340 
1341 		/* the interval timer initial count is 32 bit max */
1342 		apic_nsec_max = APIC_TICKS_TO_NSECS(APIC_MAXVAL);
1343 		firsttime = 0;
1344 	}
1345 
1346 	if (hertz != 0) {
1347 		/* periodic */
1348 		apic_nsec_per_intr = NANOSEC / hertz;
1349 		apic_hertz_count = APIC_NSECS_TO_TICKS(apic_nsec_per_intr);
1350 	}
1351 
1352 	apic_int_busy_mark = (apic_int_busy_mark *
1353 	    apic_sample_factor_redistribution) / 100;
1354 	apic_int_free_mark = (apic_int_free_mark *
1355 	    apic_sample_factor_redistribution) / 100;
1356 	apic_diff_for_redistribution = (apic_diff_for_redistribution *
1357 	    apic_sample_factor_redistribution) / 100;
1358 
1359 	if (hertz == 0) {
1360 		/* requested one_shot */
1361 		if (!tsc_gethrtime_enable || !apic_oneshot_enable)
1362 			return (0);
1363 		apic_oneshot = 1;
1364 		ret = (int)APIC_TICKS_TO_NSECS(1);
1365 	} else {
1366 		/* program the local APIC to interrupt at the given frequency */
1367 		apicadr[APIC_INIT_COUNT] = apic_hertz_count;
1368 		apicadr[APIC_LOCAL_TIMER] =
1369 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME;
1370 		apic_oneshot = 0;
1371 		ret = NANOSEC / hertz;
1372 	}
1373 
1374 	return (ret);
1375 
1376 }
1377 
1378 /*
1379  * apic_preshutdown:
1380  * Called early in shutdown whilst we can still access filesystems to do
1381  * things like loading modules which will be required to complete shutdown
1382  * after filesystems are all unmounted.
1383  */
1384 static void
1385 apic_preshutdown(int cmd, int fcn)
1386 {
1387 	APIC_VERBOSE_POWEROFF(("apic_preshutdown(%d,%d); m=%d a=%d\n",
1388 	    cmd, fcn, apic_poweroff_method, apic_enable_acpi));
1389 
1390 	if ((cmd != A_SHUTDOWN) || (fcn != AD_POWEROFF)) {
1391 		return;
1392 	}
1393 }
1394 
1395 static void
1396 apic_shutdown(int cmd, int fcn)
1397 {
1398 	int restarts, attempts;
1399 	int i;
1400 	uchar_t	byte;
1401 	ulong_t iflag;
1402 
1403 	/* Send NMI to all CPUs except self to do per processor shutdown */
1404 	iflag = intr_clear();
1405 	while (get_apic_cmd1() & AV_PENDING)
1406 		apic_ret();
1407 	apic_shutdown_processors = 1;
1408 	apicadr[APIC_INT_CMD1] = AV_NMI | AV_LEVEL | AV_SH_ALL_EXCSELF;
1409 
1410 	/* restore cmos shutdown byte before reboot */
1411 	if (apic_cmos_ssb_set) {
1412 		outb(CMOS_ADDR, SSB);
1413 		outb(CMOS_DATA, 0);
1414 	}
1415 
1416 	ioapic_disable_redirection();
1417 
1418 	/*	disable apic mode if imcr present	*/
1419 	if (apic_imcrp) {
1420 		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
1421 		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_PIC);
1422 	}
1423 
1424 	apic_disable_local_apic();
1425 
1426 	intr_restore(iflag);
1427 
1428 	/* remainder of function is for shutdown cases only */
1429 	if (cmd != A_SHUTDOWN)
1430 		return;
1431 
1432 	/*
1433 	 * Switch system back into Legacy-Mode if using ACPI and
1434 	 * not powering-off.  Some BIOSes need to remain in ACPI-mode
1435 	 * for power-off to succeed (Dell Dimension 4600)
1436 	 */
1437 	if (apic_enable_acpi && (fcn != AD_POWEROFF))
1438 		(void) AcpiDisable();
1439 
1440 	/* remainder of function is for shutdown+poweroff case only */
1441 	if (fcn != AD_POWEROFF)
1442 		return;
1443 
1444 	switch (apic_poweroff_method) {
1445 		case APIC_POWEROFF_VIA_RTC:
1446 
1447 			/* select the extended NVRAM bank in the RTC */
1448 			outb(CMOS_ADDR, RTC_REGA);
1449 			byte = inb(CMOS_DATA);
1450 			outb(CMOS_DATA, (byte | EXT_BANK));
1451 
1452 			outb(CMOS_ADDR, PFR_REG);
1453 
1454 			/* for Predator must toggle the PAB bit */
1455 			byte = inb(CMOS_DATA);
1456 
1457 			/*
1458 			 * clear power active bar, wakeup alarm and
1459 			 * kickstart
1460 			 */
1461 			byte &= ~(PAB_CBIT | WF_FLAG | KS_FLAG);
1462 			outb(CMOS_DATA, byte);
1463 
1464 			/* delay before next write */
1465 			drv_usecwait(1000);
1466 
1467 			/* for S40 the following would suffice */
1468 			byte = inb(CMOS_DATA);
1469 
1470 			/* power active bar control bit */
1471 			byte |= PAB_CBIT;
1472 			outb(CMOS_DATA, byte);
1473 
1474 			break;
1475 
1476 		case APIC_POWEROFF_VIA_ASPEN_BMC:
1477 			restarts = 0;
1478 restart_aspen_bmc:
1479 			if (++restarts == 3)
1480 				break;
1481 			attempts = 0;
1482 			do {
1483 				byte = inb(MISMIC_FLAG_REGISTER);
1484 				byte &= MISMIC_BUSY_MASK;
1485 				if (byte != 0) {
1486 					drv_usecwait(1000);
1487 					if (attempts >= 3)
1488 						goto restart_aspen_bmc;
1489 					++attempts;
1490 				}
1491 			} while (byte != 0);
1492 			outb(MISMIC_CNTL_REGISTER, CC_SMS_GET_STATUS);
1493 			byte = inb(MISMIC_FLAG_REGISTER);
1494 			byte |= 0x1;
1495 			outb(MISMIC_FLAG_REGISTER, byte);
1496 			i = 0;
1497 			for (; i < (sizeof (aspen_bmc)/sizeof (aspen_bmc[0]));
1498 			    i++) {
1499 				attempts = 0;
1500 				do {
1501 					byte = inb(MISMIC_FLAG_REGISTER);
1502 					byte &= MISMIC_BUSY_MASK;
1503 					if (byte != 0) {
1504 						drv_usecwait(1000);
1505 						if (attempts >= 3)
1506 							goto restart_aspen_bmc;
1507 						++attempts;
1508 					}
1509 				} while (byte != 0);
1510 				outb(MISMIC_CNTL_REGISTER, aspen_bmc[i].cntl);
1511 				outb(MISMIC_DATA_REGISTER, aspen_bmc[i].data);
1512 				byte = inb(MISMIC_FLAG_REGISTER);
1513 				byte |= 0x1;
1514 				outb(MISMIC_FLAG_REGISTER, byte);
1515 			}
1516 			break;
1517 
1518 		case APIC_POWEROFF_VIA_SITKA_BMC:
1519 			restarts = 0;
1520 restart_sitka_bmc:
1521 			if (++restarts == 3)
1522 				break;
1523 			attempts = 0;
1524 			do {
1525 				byte = inb(SMS_STATUS_REGISTER);
1526 				byte &= SMS_STATE_MASK;
1527 				if ((byte == SMS_READ_STATE) ||
1528 				    (byte == SMS_WRITE_STATE)) {
1529 					drv_usecwait(1000);
1530 					if (attempts >= 3)
1531 						goto restart_sitka_bmc;
1532 					++attempts;
1533 				}
1534 			} while ((byte == SMS_READ_STATE) ||
1535 			    (byte == SMS_WRITE_STATE));
1536 			outb(SMS_COMMAND_REGISTER, SMS_GET_STATUS);
1537 			i = 0;
1538 			for (; i < (sizeof (sitka_bmc)/sizeof (sitka_bmc[0]));
1539 			    i++) {
1540 				attempts = 0;
1541 				do {
1542 					byte = inb(SMS_STATUS_REGISTER);
1543 					byte &= SMS_IBF_MASK;
1544 					if (byte != 0) {
1545 						drv_usecwait(1000);
1546 						if (attempts >= 3)
1547 							goto restart_sitka_bmc;
1548 						++attempts;
1549 					}
1550 				} while (byte != 0);
1551 				outb(sitka_bmc[i].port, sitka_bmc[i].data);
1552 			}
1553 			break;
1554 
1555 		case APIC_POWEROFF_NONE:
1556 
1557 			/* If no APIC direct method, we will try using ACPI */
1558 			if (apic_enable_acpi) {
1559 				if (acpi_poweroff() == 1)
1560 					return;
1561 			} else
1562 				return;
1563 
1564 			break;
1565 	}
1566 	/*
1567 	 * Wait a limited time here for power to go off.
1568 	 * If the power does not go off, then there was a
1569 	 * problem and we should continue to the halt which
1570 	 * prints a message for the user to press a key to
1571 	 * reboot.
1572 	 */
1573 	drv_usecwait(7000000); /* wait seven seconds */
1574 
1575 }
1576 
1577 /*
1578  * Try and disable all interrupts. We just assign interrupts to other
1579  * processors based on policy. If any were bound by user request, we
1580  * let them continue and return failure. We do not bother to check
1581  * for cache affinity while rebinding.
1582  */
1583 
1584 static int
1585 apic_disable_intr(processorid_t cpun)
1586 {
1587 	int bind_cpu = 0, i, hardbound = 0;
1588 	apic_irq_t *irq_ptr;
1589 	ulong_t iflag;
1590 
1591 	iflag = intr_clear();
1592 	lock_set(&apic_ioapic_lock);
1593 
1594 	for (i = 0; i <= APIC_MAX_VECTOR; i++) {
1595 		if (apic_reprogram_info[i].done == B_FALSE) {
1596 			if (apic_reprogram_info[i].bindcpu == cpun) {
1597 				/*
1598 				 * CPU is busy -- it's the target of
1599 				 * a pending reprogramming attempt
1600 				 */
1601 				lock_clear(&apic_ioapic_lock);
1602 				intr_restore(iflag);
1603 				return (PSM_FAILURE);
1604 			}
1605 		}
1606 	}
1607 
1608 	apic_cpus[cpun].aci_status &= ~APIC_CPU_INTR_ENABLE;
1609 
1610 	apic_cpus[cpun].aci_curipl = 0;
1611 
1612 	i = apic_min_device_irq;
1613 	for (; i <= apic_max_device_irq; i++) {
1614 		/*
1615 		 * If there are bound interrupts on this cpu, then
1616 		 * rebind them to other processors.
1617 		 */
1618 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1619 			ASSERT((irq_ptr->airq_temp_cpu == IRQ_UNBOUND) ||
1620 			    (irq_ptr->airq_temp_cpu == IRQ_UNINIT) ||
1621 			    ((irq_ptr->airq_temp_cpu & ~IRQ_USER_BOUND) <
1622 			    apic_nproc));
1623 
1624 			if (irq_ptr->airq_temp_cpu == (cpun | IRQ_USER_BOUND)) {
1625 				hardbound = 1;
1626 				continue;
1627 			}
1628 
1629 			if (irq_ptr->airq_temp_cpu == cpun) {
1630 				do {
1631 					bind_cpu = apic_next_bind_cpu++;
1632 					if (bind_cpu >= apic_nproc) {
1633 						apic_next_bind_cpu = 1;
1634 						bind_cpu = 0;
1635 
1636 					}
1637 				} while (apic_rebind_all(irq_ptr, bind_cpu));
1638 			}
1639 		}
1640 	}
1641 
1642 	lock_clear(&apic_ioapic_lock);
1643 	intr_restore(iflag);
1644 
1645 	if (hardbound) {
1646 		cmn_err(CE_WARN, "Could not disable interrupts on %d"
1647 		    "due to user bound interrupts", cpun);
1648 		return (PSM_FAILURE);
1649 	}
1650 	else
1651 		return (PSM_SUCCESS);
1652 }
1653 
1654 static void
1655 apic_enable_intr(processorid_t cpun)
1656 {
1657 	int	i;
1658 	apic_irq_t *irq_ptr;
1659 	ulong_t iflag;
1660 
1661 	iflag = intr_clear();
1662 	lock_set(&apic_ioapic_lock);
1663 
1664 	apic_cpus[cpun].aci_status |= APIC_CPU_INTR_ENABLE;
1665 
1666 	i = apic_min_device_irq;
1667 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
1668 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1669 			if ((irq_ptr->airq_cpu & ~IRQ_USER_BOUND) == cpun) {
1670 				(void) apic_rebind_all(irq_ptr,
1671 				    irq_ptr->airq_cpu);
1672 			}
1673 		}
1674 	}
1675 
1676 	lock_clear(&apic_ioapic_lock);
1677 	intr_restore(iflag);
1678 }
1679 
1680 
1681 /*
1682  * This function will reprogram the timer.
1683  *
1684  * When in oneshot mode the argument is the absolute time in future to
1685  * generate the interrupt at.
1686  *
1687  * When in periodic mode, the argument is the interval at which the
1688  * interrupts should be generated. There is no need to support the periodic
1689  * mode timer change at this time.
1690  */
1691 static void
1692 apic_timer_reprogram(hrtime_t time)
1693 {
1694 	hrtime_t now;
1695 	uint_t ticks;
1696 	int64_t delta;
1697 
1698 	/*
1699 	 * We should be called from high PIL context (CBE_HIGH_PIL),
1700 	 * so kpreempt is disabled.
1701 	 */
1702 
1703 	if (!apic_oneshot) {
1704 		/* time is the interval for periodic mode */
1705 		ticks = APIC_NSECS_TO_TICKS(time);
1706 	} else {
1707 		/* one shot mode */
1708 
1709 		now = gethrtime();
1710 		delta = time - now;
1711 
1712 		if (delta <= 0) {
1713 			/*
1714 			 * requested to generate an interrupt in the past
1715 			 * generate an interrupt as soon as possible
1716 			 */
1717 			ticks = apic_min_timer_ticks;
1718 		} else if (delta > apic_nsec_max) {
1719 			/*
1720 			 * requested to generate an interrupt at a time
1721 			 * further than what we are capable of. Set to max
1722 			 * the hardware can handle
1723 			 */
1724 
1725 			ticks = APIC_MAXVAL;
1726 #ifdef DEBUG
1727 			cmn_err(CE_CONT, "apic_timer_reprogram, request at"
1728 			    "  %lld  too far in future, current time"
1729 			    "  %lld \n", time, now);
1730 #endif
1731 		} else
1732 			ticks = APIC_NSECS_TO_TICKS(delta);
1733 	}
1734 
1735 	if (ticks < apic_min_timer_ticks)
1736 		ticks = apic_min_timer_ticks;
1737 
1738 	apicadr[APIC_INIT_COUNT] = ticks;
1739 
1740 }
1741 
1742 /*
1743  * This function will enable timer interrupts.
1744  */
1745 static void
1746 apic_timer_enable(void)
1747 {
1748 	/*
1749 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1750 	 * so kpreempt is disabled.
1751 	 */
1752 
1753 	if (!apic_oneshot)
1754 		apicadr[APIC_LOCAL_TIMER] =
1755 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME;
1756 	else {
1757 		/* one shot */
1758 		apicadr[APIC_LOCAL_TIMER] = (apic_clkvect + APIC_BASE_VECT);
1759 	}
1760 }
1761 
1762 /*
1763  * This function will disable timer interrupts.
1764  */
1765 static void
1766 apic_timer_disable(void)
1767 {
1768 	/*
1769 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1770 	 * so kpreempt is disabled.
1771 	 */
1772 
1773 	apicadr[APIC_LOCAL_TIMER] = (apic_clkvect + APIC_BASE_VECT) | AV_MASK;
1774 }
1775 
1776 
1777 ddi_periodic_t apic_periodic_id;
1778 
1779 /*
1780  * If this module needs a periodic handler for the interrupt distribution, it
1781  * can be added here. The argument to the periodic handler is not currently
1782  * used, but is reserved for future.
1783  */
1784 static void
1785 apic_post_cyclic_setup(void *arg)
1786 {
1787 _NOTE(ARGUNUSED(arg))
1788 	/* cpu_lock is held */
1789 	/* set up a periodic handler for intr redistribution */
1790 
1791 	/*
1792 	 * In peridoc mode intr redistribution processing is done in
1793 	 * apic_intr_enter during clk intr processing
1794 	 */
1795 	if (!apic_oneshot)
1796 		return;
1797 	/*
1798 	 * Register a periodical handler for the redistribution processing.
1799 	 * On X86, CY_LOW_LEVEL is mapped to the level 2 interrupt, so
1800 	 * DDI_IPL_2 should be passed to ddi_periodic_add() here.
1801 	 */
1802 	apic_periodic_id = ddi_periodic_add(
1803 	    (void (*)(void *))apic_redistribute_compute, NULL,
1804 	    apic_redistribute_sample_interval, DDI_IPL_2);
1805 }
1806 
1807 static void
1808 apic_redistribute_compute(void)
1809 {
1810 	int	i, j, max_busy;
1811 
1812 	if (apic_enable_dynamic_migration) {
1813 		if (++apic_nticks == apic_sample_factor_redistribution) {
1814 			/*
1815 			 * Time to call apic_intr_redistribute().
1816 			 * reset apic_nticks. This will cause max_busy
1817 			 * to be calculated below and if it is more than
1818 			 * apic_int_busy, we will do the whole thing
1819 			 */
1820 			apic_nticks = 0;
1821 		}
1822 		max_busy = 0;
1823 		for (i = 0; i < apic_nproc; i++) {
1824 
1825 			/*
1826 			 * Check if curipl is non zero & if ISR is in
1827 			 * progress
1828 			 */
1829 			if (((j = apic_cpus[i].aci_curipl) != 0) &&
1830 			    (apic_cpus[i].aci_ISR_in_progress & (1 << j))) {
1831 
1832 				int	irq;
1833 				apic_cpus[i].aci_busy++;
1834 				irq = apic_cpus[i].aci_current[j];
1835 				apic_irq_table[irq]->airq_busy++;
1836 			}
1837 
1838 			if (!apic_nticks &&
1839 			    (apic_cpus[i].aci_busy > max_busy))
1840 				max_busy = apic_cpus[i].aci_busy;
1841 		}
1842 		if (!apic_nticks) {
1843 			if (max_busy > apic_int_busy_mark) {
1844 			/*
1845 			 * We could make the following check be
1846 			 * skipped > 1 in which case, we get a
1847 			 * redistribution at half the busy mark (due to
1848 			 * double interval). Need to be able to collect
1849 			 * more empirical data to decide if that is a
1850 			 * good strategy. Punt for now.
1851 			 */
1852 				if (apic_skipped_redistribute) {
1853 					apic_cleanup_busy();
1854 					apic_skipped_redistribute = 0;
1855 				} else {
1856 					apic_intr_redistribute();
1857 				}
1858 			} else
1859 				apic_skipped_redistribute++;
1860 		}
1861 	}
1862 }
1863 
1864 
1865 /*
1866  * The following functions are in the platform specific file so that they
1867  * can be different functions depending on whether we are running on
1868  * bare metal or a hypervisor.
1869  */
1870 
1871 /*
1872  * map an apic for memory-mapped access
1873  */
1874 uint32_t *
1875 mapin_apic(uint32_t addr, size_t len, int flags)
1876 {
1877 	/*LINTED: pointer cast may result in improper alignment */
1878 	return ((uint32_t *)psm_map_phys(addr, len, flags));
1879 }
1880 
1881 uint32_t *
1882 mapin_ioapic(uint32_t addr, size_t len, int flags)
1883 {
1884 	return (mapin_apic(addr, len, flags));
1885 }
1886 
1887 /*
1888  * unmap an apic
1889  */
1890 void
1891 mapout_apic(caddr_t addr, size_t len)
1892 {
1893 	psm_unmap_phys(addr, len);
1894 }
1895 
1896 void
1897 mapout_ioapic(caddr_t addr, size_t len)
1898 {
1899 	mapout_apic(addr, len);
1900 }
1901 
1902 /*
1903  * Check to make sure there are enough irq slots
1904  */
1905 int
1906 apic_check_free_irqs(int count)
1907 {
1908 	int i, avail;
1909 
1910 	avail = 0;
1911 	for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
1912 		if ((apic_irq_table[i] == NULL) ||
1913 		    apic_irq_table[i]->airq_mps_intr_index == FREE_INDEX) {
1914 			if (++avail >= count)
1915 				return (PSM_SUCCESS);
1916 		}
1917 	}
1918 	return (PSM_FAILURE);
1919 }
1920 
1921 /*
1922  * This function allocates "count" MSI vector(s) for the given "dip/pri/type"
1923  */
1924 int
1925 apic_alloc_msi_vectors(dev_info_t *dip, int inum, int count, int pri,
1926     int behavior)
1927 {
1928 	int	rcount, i;
1929 	uchar_t	start, irqno, cpu;
1930 	major_t	major;
1931 	apic_irq_t	*irqptr;
1932 
1933 	DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: dip=0x%p "
1934 	    "inum=0x%x  pri=0x%x count=0x%x behavior=%d\n",
1935 	    (void *)dip, inum, pri, count, behavior));
1936 
1937 	if (count > 1) {
1938 		if (behavior == DDI_INTR_ALLOC_STRICT &&
1939 		    (apic_multi_msi_enable == 0 || count > apic_multi_msi_max))
1940 			return (0);
1941 
1942 		if (apic_multi_msi_enable == 0)
1943 			count = 1;
1944 		else if (count > apic_multi_msi_max)
1945 			count = apic_multi_msi_max;
1946 	}
1947 
1948 	if ((rcount = apic_navail_vector(dip, pri)) > count)
1949 		rcount = count;
1950 	else if (rcount == 0 || (rcount < count &&
1951 	    behavior == DDI_INTR_ALLOC_STRICT))
1952 		return (0);
1953 
1954 	/* if not ISP2, then round it down */
1955 	if (!ISP2(rcount))
1956 		rcount = 1 << (highbit(rcount) - 1);
1957 
1958 	mutex_enter(&airq_mutex);
1959 
1960 	for (start = 0; rcount > 0; rcount >>= 1) {
1961 		if ((start = apic_find_multi_vectors(pri, rcount)) != 0 ||
1962 		    behavior == DDI_INTR_ALLOC_STRICT)
1963 			break;
1964 	}
1965 
1966 	if (start == 0) {
1967 		/* no vector available */
1968 		mutex_exit(&airq_mutex);
1969 		return (0);
1970 	}
1971 
1972 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
1973 		/* not enough free irq slots available */
1974 		mutex_exit(&airq_mutex);
1975 		return (0);
1976 	}
1977 
1978 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
1979 	for (i = 0; i < rcount; i++) {
1980 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
1981 		    (uchar_t)-1) {
1982 			/*
1983 			 * shouldn't happen because of the
1984 			 * apic_check_free_irqs() check earlier
1985 			 */
1986 			mutex_exit(&airq_mutex);
1987 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
1988 			    "apic_allocate_irq failed\n"));
1989 			return (i);
1990 		}
1991 		apic_max_device_irq = max(irqno, apic_max_device_irq);
1992 		apic_min_device_irq = min(irqno, apic_min_device_irq);
1993 		irqptr = apic_irq_table[irqno];
1994 #ifdef	DEBUG
1995 		if (apic_vector_to_irq[start + i] != APIC_RESV_IRQ)
1996 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
1997 			    "apic_vector_to_irq is not APIC_RESV_IRQ\n"));
1998 #endif
1999 		apic_vector_to_irq[start + i] = (uchar_t)irqno;
2000 
2001 		irqptr->airq_vector = (uchar_t)(start + i);
2002 		irqptr->airq_ioapicindex = (uchar_t)inum;	/* start */
2003 		irqptr->airq_intin_no = (uchar_t)rcount;
2004 		irqptr->airq_ipl = pri;
2005 		irqptr->airq_vector = start + i;
2006 		irqptr->airq_origirq = (uchar_t)(inum + i);
2007 		irqptr->airq_share_id = 0;
2008 		irqptr->airq_mps_intr_index = MSI_INDEX;
2009 		irqptr->airq_dip = dip;
2010 		irqptr->airq_major = major;
2011 		if (i == 0) /* they all bound to the same cpu */
2012 			cpu = irqptr->airq_cpu = apic_bind_intr(dip, irqno,
2013 			    0xff, 0xff);
2014 		else
2015 			irqptr->airq_cpu = cpu;
2016 		DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: irq=0x%x "
2017 		    "dip=0x%p vector=0x%x origirq=0x%x pri=0x%x\n", irqno,
2018 		    (void *)irqptr->airq_dip, irqptr->airq_vector,
2019 		    irqptr->airq_origirq, pri));
2020 	}
2021 	mutex_exit(&airq_mutex);
2022 	return (rcount);
2023 }
2024 
2025 /*
2026  * This function allocates "count" MSI-X vector(s) for the given "dip/pri/type"
2027  */
2028 int
2029 apic_alloc_msix_vectors(dev_info_t *dip, int inum, int count, int pri,
2030     int behavior)
2031 {
2032 	int	rcount, i;
2033 	major_t	major;
2034 
2035 	if (count > 1) {
2036 		if (behavior == DDI_INTR_ALLOC_STRICT) {
2037 			if (count > apic_msix_max)
2038 				return (0);
2039 		} else if (count > apic_msix_max)
2040 			count = apic_msix_max;
2041 	}
2042 
2043 	mutex_enter(&airq_mutex);
2044 
2045 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2046 		rcount = count;
2047 	else if (rcount == 0 || (rcount < count &&
2048 	    behavior == DDI_INTR_ALLOC_STRICT)) {
2049 		rcount = 0;
2050 		goto out;
2051 	}
2052 
2053 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2054 		/* not enough free irq slots available */
2055 		rcount = 0;
2056 		goto out;
2057 	}
2058 
2059 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
2060 	for (i = 0; i < rcount; i++) {
2061 		uchar_t	vector, irqno;
2062 		apic_irq_t	*irqptr;
2063 
2064 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2065 		    (uchar_t)-1) {
2066 			/*
2067 			 * shouldn't happen because of the
2068 			 * apic_check_free_irqs() check earlier
2069 			 */
2070 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2071 			    "apic_allocate_irq failed\n"));
2072 			rcount = i;
2073 			goto out;
2074 		}
2075 		if ((vector = apic_allocate_vector(pri, irqno, 1)) == 0) {
2076 			/*
2077 			 * shouldn't happen because of the
2078 			 * apic_navail_vector() call earlier
2079 			 */
2080 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2081 			    "apic_allocate_vector failed\n"));
2082 			rcount = i;
2083 			goto out;
2084 		}
2085 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2086 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2087 		irqptr = apic_irq_table[irqno];
2088 		irqptr->airq_vector = (uchar_t)vector;
2089 		irqptr->airq_ipl = pri;
2090 		irqptr->airq_origirq = (uchar_t)(inum + i);
2091 		irqptr->airq_share_id = 0;
2092 		irqptr->airq_mps_intr_index = MSIX_INDEX;
2093 		irqptr->airq_dip = dip;
2094 		irqptr->airq_major = major;
2095 		irqptr->airq_cpu = apic_bind_intr(dip, irqno, 0xff, 0xff);
2096 	}
2097 out:
2098 	mutex_exit(&airq_mutex);
2099 	return (rcount);
2100 }
2101 
2102 /*
2103  * Allocate a free vector for irq at ipl. Takes care of merging of multiple
2104  * IPLs into a single APIC level as well as stretching some IPLs onto multiple
2105  * levels. APIC_HI_PRI_VECTS interrupts are reserved for high priority
2106  * requests and allocated only when pri is set.
2107  */
2108 uchar_t
2109 apic_allocate_vector(int ipl, int irq, int pri)
2110 {
2111 	int	lowest, highest, i;
2112 
2113 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
2114 	lowest = apic_ipltopri[ipl - 1] + APIC_VECTOR_PER_IPL;
2115 
2116 	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
2117 		lowest -= APIC_VECTOR_PER_IPL;
2118 
2119 #ifdef	DEBUG
2120 	if (apic_restrict_vector)	/* for testing shared interrupt logic */
2121 		highest = lowest + apic_restrict_vector + APIC_HI_PRI_VECTS;
2122 #endif /* DEBUG */
2123 	if (pri == 0)
2124 		highest -= APIC_HI_PRI_VECTS;
2125 
2126 	for (i = lowest; i < highest; i++) {
2127 		if (APIC_CHECK_RESERVE_VECTORS(i))
2128 			continue;
2129 		if (apic_vector_to_irq[i] == APIC_RESV_IRQ) {
2130 			apic_vector_to_irq[i] = (uchar_t)irq;
2131 			return (i);
2132 		}
2133 	}
2134 
2135 	return (0);
2136 }
2137 
2138 /* Mark vector as not being used by any irq */
2139 void
2140 apic_free_vector(uchar_t vector)
2141 {
2142 	apic_vector_to_irq[vector] = APIC_RESV_IRQ;
2143 }
2144 
2145 uint32_t
2146 ioapic_read(int ioapic_ix, uint32_t reg)
2147 {
2148 	volatile uint32_t *ioapic;
2149 
2150 	ioapic = apicioadr[ioapic_ix];
2151 	ioapic[APIC_IO_REG] = reg;
2152 	return (ioapic[APIC_IO_DATA]);
2153 }
2154 
2155 void
2156 ioapic_write(int ioapic_ix, uint32_t reg, uint32_t value)
2157 {
2158 	volatile uint32_t *ioapic;
2159 
2160 	ioapic = apicioadr[ioapic_ix];
2161 	ioapic[APIC_IO_REG] = reg;
2162 	ioapic[APIC_IO_DATA] = value;
2163 }
2164 
2165 static processorid_t
2166 apic_find_cpu(int flag)
2167 {
2168 	processorid_t acid = 0;
2169 	int i;
2170 
2171 	/* Find the first CPU with the passed-in flag set */
2172 	for (i = 0; i < apic_nproc; i++) {
2173 		if (apic_cpus[i].aci_status & flag) {
2174 			acid = i;
2175 			break;
2176 		}
2177 	}
2178 
2179 	ASSERT((apic_cpus[acid].aci_status & flag) != 0);
2180 	return (acid);
2181 }
2182 
2183 /*
2184  * Call rebind to do the actual programming.
2185  * Must be called with interrupts disabled and apic_ioapic_lock held
2186  * 'p' is polymorphic -- if this function is called to process a deferred
2187  * reprogramming, p is of type 'struct ioapic_reprogram_data *', from which
2188  * the irq pointer is retrieved.  If not doing deferred reprogramming,
2189  * p is of the type 'apic_irq_t *'.
2190  *
2191  * apic_ioapic_lock must be held across this call, as it protects apic_rebind
2192  * and it protects apic_find_cpu() from a race in which a CPU can be taken
2193  * offline after a cpu is selected, but before apic_rebind is called to
2194  * bind interrupts to it.
2195  */
2196 int
2197 apic_setup_io_intr(void *p, int irq, boolean_t deferred)
2198 {
2199 	apic_irq_t *irqptr;
2200 	struct ioapic_reprogram_data *drep = NULL;
2201 	int rv;
2202 
2203 	if (deferred) {
2204 		drep = (struct ioapic_reprogram_data *)p;
2205 		ASSERT(drep != NULL);
2206 		irqptr = drep->irqp;
2207 	} else
2208 		irqptr = (apic_irq_t *)p;
2209 
2210 	ASSERT(irqptr != NULL);
2211 
2212 	rv = apic_rebind(irqptr, apic_irq_table[irq]->airq_cpu, drep);
2213 	if (rv) {
2214 		/*
2215 		 * CPU is not up or interrupts are disabled. Fall back to
2216 		 * the first available CPU
2217 		 */
2218 		rv = apic_rebind(irqptr, apic_find_cpu(APIC_CPU_INTR_ENABLE),
2219 		    drep);
2220 	}
2221 
2222 	return (rv);
2223 }
2224 
2225 
2226 uchar_t
2227 apic_modify_vector(uchar_t vector, int irq)
2228 {
2229 	apic_vector_to_irq[vector] = (uchar_t)irq;
2230 	return (vector);
2231 }
2232 
2233 char *
2234 apic_get_apic_type()
2235 {
2236 	return (apic_psm_info.p_mach_idstring);
2237 }
2238