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