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