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