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