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