xref: /titanic_41/usr/src/uts/i86pc/io/pcplusmp/apic.c (revision ed5289f91b9bf164dccd6c75398362be77a4478d)
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 	 * Do not disable ACPI while doing fastreboot
1608 	 */
1609 	if (apic_enable_acpi && fcn != AD_POWEROFF && fcn != AD_FASTREBOOT)
1610 		(void) AcpiDisable();
1611 
1612 	if (fcn == AD_FASTREBOOT) {
1613 		apicadr[APIC_INT_CMD1] = AV_ASSERT | AV_RESET |
1614 		    AV_SH_ALL_EXCSELF;
1615 	}
1616 
1617 	/* remainder of function is for shutdown+poweroff case only */
1618 	if (fcn != AD_POWEROFF)
1619 		return;
1620 
1621 	switch (apic_poweroff_method) {
1622 		case APIC_POWEROFF_VIA_RTC:
1623 
1624 			/* select the extended NVRAM bank in the RTC */
1625 			outb(CMOS_ADDR, RTC_REGA);
1626 			byte = inb(CMOS_DATA);
1627 			outb(CMOS_DATA, (byte | EXT_BANK));
1628 
1629 			outb(CMOS_ADDR, PFR_REG);
1630 
1631 			/* for Predator must toggle the PAB bit */
1632 			byte = inb(CMOS_DATA);
1633 
1634 			/*
1635 			 * clear power active bar, wakeup alarm and
1636 			 * kickstart
1637 			 */
1638 			byte &= ~(PAB_CBIT | WF_FLAG | KS_FLAG);
1639 			outb(CMOS_DATA, byte);
1640 
1641 			/* delay before next write */
1642 			drv_usecwait(1000);
1643 
1644 			/* for S40 the following would suffice */
1645 			byte = inb(CMOS_DATA);
1646 
1647 			/* power active bar control bit */
1648 			byte |= PAB_CBIT;
1649 			outb(CMOS_DATA, byte);
1650 
1651 			break;
1652 
1653 		case APIC_POWEROFF_VIA_ASPEN_BMC:
1654 			restarts = 0;
1655 restart_aspen_bmc:
1656 			if (++restarts == 3)
1657 				break;
1658 			attempts = 0;
1659 			do {
1660 				byte = inb(MISMIC_FLAG_REGISTER);
1661 				byte &= MISMIC_BUSY_MASK;
1662 				if (byte != 0) {
1663 					drv_usecwait(1000);
1664 					if (attempts >= 3)
1665 						goto restart_aspen_bmc;
1666 					++attempts;
1667 				}
1668 			} while (byte != 0);
1669 			outb(MISMIC_CNTL_REGISTER, CC_SMS_GET_STATUS);
1670 			byte = inb(MISMIC_FLAG_REGISTER);
1671 			byte |= 0x1;
1672 			outb(MISMIC_FLAG_REGISTER, byte);
1673 			i = 0;
1674 			for (; i < (sizeof (aspen_bmc)/sizeof (aspen_bmc[0]));
1675 			    i++) {
1676 				attempts = 0;
1677 				do {
1678 					byte = inb(MISMIC_FLAG_REGISTER);
1679 					byte &= MISMIC_BUSY_MASK;
1680 					if (byte != 0) {
1681 						drv_usecwait(1000);
1682 						if (attempts >= 3)
1683 							goto restart_aspen_bmc;
1684 						++attempts;
1685 					}
1686 				} while (byte != 0);
1687 				outb(MISMIC_CNTL_REGISTER, aspen_bmc[i].cntl);
1688 				outb(MISMIC_DATA_REGISTER, aspen_bmc[i].data);
1689 				byte = inb(MISMIC_FLAG_REGISTER);
1690 				byte |= 0x1;
1691 				outb(MISMIC_FLAG_REGISTER, byte);
1692 			}
1693 			break;
1694 
1695 		case APIC_POWEROFF_VIA_SITKA_BMC:
1696 			restarts = 0;
1697 restart_sitka_bmc:
1698 			if (++restarts == 3)
1699 				break;
1700 			attempts = 0;
1701 			do {
1702 				byte = inb(SMS_STATUS_REGISTER);
1703 				byte &= SMS_STATE_MASK;
1704 				if ((byte == SMS_READ_STATE) ||
1705 				    (byte == SMS_WRITE_STATE)) {
1706 					drv_usecwait(1000);
1707 					if (attempts >= 3)
1708 						goto restart_sitka_bmc;
1709 					++attempts;
1710 				}
1711 			} while ((byte == SMS_READ_STATE) ||
1712 			    (byte == SMS_WRITE_STATE));
1713 			outb(SMS_COMMAND_REGISTER, SMS_GET_STATUS);
1714 			i = 0;
1715 			for (; i < (sizeof (sitka_bmc)/sizeof (sitka_bmc[0]));
1716 			    i++) {
1717 				attempts = 0;
1718 				do {
1719 					byte = inb(SMS_STATUS_REGISTER);
1720 					byte &= SMS_IBF_MASK;
1721 					if (byte != 0) {
1722 						drv_usecwait(1000);
1723 						if (attempts >= 3)
1724 							goto restart_sitka_bmc;
1725 						++attempts;
1726 					}
1727 				} while (byte != 0);
1728 				outb(sitka_bmc[i].port, sitka_bmc[i].data);
1729 			}
1730 			break;
1731 
1732 		case APIC_POWEROFF_NONE:
1733 
1734 			/* If no APIC direct method, we will try using ACPI */
1735 			if (apic_enable_acpi) {
1736 				if (acpi_poweroff() == 1)
1737 					return;
1738 			} else
1739 				return;
1740 
1741 			break;
1742 	}
1743 	/*
1744 	 * Wait a limited time here for power to go off.
1745 	 * If the power does not go off, then there was a
1746 	 * problem and we should continue to the halt which
1747 	 * prints a message for the user to press a key to
1748 	 * reboot.
1749 	 */
1750 	drv_usecwait(7000000); /* wait seven seconds */
1751 
1752 }
1753 
1754 /*
1755  * Try and disable all interrupts. We just assign interrupts to other
1756  * processors based on policy. If any were bound by user request, we
1757  * let them continue and return failure. We do not bother to check
1758  * for cache affinity while rebinding.
1759  */
1760 
1761 static int
1762 apic_disable_intr(processorid_t cpun)
1763 {
1764 	int bind_cpu = 0, i, hardbound = 0;
1765 	apic_irq_t *irq_ptr;
1766 	ulong_t iflag;
1767 
1768 	iflag = intr_clear();
1769 	lock_set(&apic_ioapic_lock);
1770 
1771 	for (i = 0; i <= APIC_MAX_VECTOR; i++) {
1772 		if (apic_reprogram_info[i].done == B_FALSE) {
1773 			if (apic_reprogram_info[i].bindcpu == cpun) {
1774 				/*
1775 				 * CPU is busy -- it's the target of
1776 				 * a pending reprogramming attempt
1777 				 */
1778 				lock_clear(&apic_ioapic_lock);
1779 				intr_restore(iflag);
1780 				return (PSM_FAILURE);
1781 			}
1782 		}
1783 	}
1784 
1785 	apic_cpus[cpun].aci_status &= ~APIC_CPU_INTR_ENABLE;
1786 
1787 	apic_cpus[cpun].aci_curipl = 0;
1788 
1789 	i = apic_min_device_irq;
1790 	for (; i <= apic_max_device_irq; i++) {
1791 		/*
1792 		 * If there are bound interrupts on this cpu, then
1793 		 * rebind them to other processors.
1794 		 */
1795 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1796 			ASSERT((irq_ptr->airq_temp_cpu == IRQ_UNBOUND) ||
1797 			    (irq_ptr->airq_temp_cpu == IRQ_UNINIT) ||
1798 			    ((irq_ptr->airq_temp_cpu & ~IRQ_USER_BOUND) <
1799 			    apic_nproc));
1800 
1801 			if (irq_ptr->airq_temp_cpu == (cpun | IRQ_USER_BOUND)) {
1802 				hardbound = 1;
1803 				continue;
1804 			}
1805 
1806 			if (irq_ptr->airq_temp_cpu == cpun) {
1807 				do {
1808 					bind_cpu = apic_next_bind_cpu++;
1809 					if (bind_cpu >= apic_nproc) {
1810 						apic_next_bind_cpu = 1;
1811 						bind_cpu = 0;
1812 
1813 					}
1814 				} while (apic_rebind_all(irq_ptr, bind_cpu));
1815 			}
1816 		}
1817 	}
1818 
1819 	lock_clear(&apic_ioapic_lock);
1820 	intr_restore(iflag);
1821 
1822 	if (hardbound) {
1823 		cmn_err(CE_WARN, "Could not disable interrupts on %d"
1824 		    "due to user bound interrupts", cpun);
1825 		return (PSM_FAILURE);
1826 	}
1827 	else
1828 		return (PSM_SUCCESS);
1829 }
1830 
1831 /*
1832  * Bind interrupts to the CPU's local APIC.
1833  * Interrupts should not be bound to a CPU's local APIC until the CPU
1834  * is ready to receive interrupts.
1835  */
1836 static void
1837 apic_enable_intr(processorid_t cpun)
1838 {
1839 	int	i;
1840 	apic_irq_t *irq_ptr;
1841 	ulong_t iflag;
1842 
1843 	iflag = intr_clear();
1844 	lock_set(&apic_ioapic_lock);
1845 
1846 	apic_cpus[cpun].aci_status |= APIC_CPU_INTR_ENABLE;
1847 
1848 	i = apic_min_device_irq;
1849 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
1850 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1851 			if ((irq_ptr->airq_cpu & ~IRQ_USER_BOUND) == cpun) {
1852 				(void) apic_rebind_all(irq_ptr,
1853 				    irq_ptr->airq_cpu);
1854 			}
1855 		}
1856 	}
1857 
1858 	lock_clear(&apic_ioapic_lock);
1859 	intr_restore(iflag);
1860 }
1861 
1862 
1863 /*
1864  * This function will reprogram the timer.
1865  *
1866  * When in oneshot mode the argument is the absolute time in future to
1867  * generate the interrupt at.
1868  *
1869  * When in periodic mode, the argument is the interval at which the
1870  * interrupts should be generated. There is no need to support the periodic
1871  * mode timer change at this time.
1872  */
1873 static void
1874 apic_timer_reprogram(hrtime_t time)
1875 {
1876 	hrtime_t now;
1877 	uint_t ticks;
1878 	int64_t delta;
1879 
1880 	/*
1881 	 * We should be called from high PIL context (CBE_HIGH_PIL),
1882 	 * so kpreempt is disabled.
1883 	 */
1884 
1885 	if (!apic_oneshot) {
1886 		/* time is the interval for periodic mode */
1887 		ticks = APIC_NSECS_TO_TICKS(time);
1888 	} else {
1889 		/* one shot mode */
1890 
1891 		now = gethrtime();
1892 		delta = time - now;
1893 
1894 		if (delta <= 0) {
1895 			/*
1896 			 * requested to generate an interrupt in the past
1897 			 * generate an interrupt as soon as possible
1898 			 */
1899 			ticks = apic_min_timer_ticks;
1900 		} else if (delta > apic_nsec_max) {
1901 			/*
1902 			 * requested to generate an interrupt at a time
1903 			 * further than what we are capable of. Set to max
1904 			 * the hardware can handle
1905 			 */
1906 
1907 			ticks = APIC_MAXVAL;
1908 #ifdef DEBUG
1909 			cmn_err(CE_CONT, "apic_timer_reprogram, request at"
1910 			    "  %lld  too far in future, current time"
1911 			    "  %lld \n", time, now);
1912 #endif
1913 		} else
1914 			ticks = APIC_NSECS_TO_TICKS(delta);
1915 	}
1916 
1917 	if (ticks < apic_min_timer_ticks)
1918 		ticks = apic_min_timer_ticks;
1919 
1920 	apic_reg_ops->apic_write(APIC_INIT_COUNT, ticks);
1921 }
1922 
1923 /*
1924  * This function will enable timer interrupts.
1925  */
1926 static void
1927 apic_timer_enable(void)
1928 {
1929 	/*
1930 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1931 	 * so kpreempt is disabled.
1932 	 */
1933 
1934 	if (!apic_oneshot) {
1935 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1936 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME);
1937 	} else {
1938 		/* one shot */
1939 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1940 		    (apic_clkvect + APIC_BASE_VECT));
1941 	}
1942 }
1943 
1944 /*
1945  * This function will disable timer interrupts.
1946  */
1947 static void
1948 apic_timer_disable(void)
1949 {
1950 	/*
1951 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1952 	 * so kpreempt is disabled.
1953 	 */
1954 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1955 	    (apic_clkvect + APIC_BASE_VECT) | AV_MASK);
1956 }
1957 
1958 
1959 ddi_periodic_t apic_periodic_id;
1960 
1961 /*
1962  * If this module needs a periodic handler for the interrupt distribution, it
1963  * can be added here. The argument to the periodic handler is not currently
1964  * used, but is reserved for future.
1965  */
1966 static void
1967 apic_post_cyclic_setup(void *arg)
1968 {
1969 _NOTE(ARGUNUSED(arg))
1970 	/* cpu_lock is held */
1971 	/* set up a periodic handler for intr redistribution */
1972 
1973 	/*
1974 	 * In peridoc mode intr redistribution processing is done in
1975 	 * apic_intr_enter during clk intr processing
1976 	 */
1977 	if (!apic_oneshot)
1978 		return;
1979 	/*
1980 	 * Register a periodical handler for the redistribution processing.
1981 	 * On X86, CY_LOW_LEVEL is mapped to the level 2 interrupt, so
1982 	 * DDI_IPL_2 should be passed to ddi_periodic_add() here.
1983 	 */
1984 	apic_periodic_id = ddi_periodic_add(
1985 	    (void (*)(void *))apic_redistribute_compute, NULL,
1986 	    apic_redistribute_sample_interval, DDI_IPL_2);
1987 }
1988 
1989 static void
1990 apic_redistribute_compute(void)
1991 {
1992 	int	i, j, max_busy;
1993 
1994 	if (apic_enable_dynamic_migration) {
1995 		if (++apic_nticks == apic_sample_factor_redistribution) {
1996 			/*
1997 			 * Time to call apic_intr_redistribute().
1998 			 * reset apic_nticks. This will cause max_busy
1999 			 * to be calculated below and if it is more than
2000 			 * apic_int_busy, we will do the whole thing
2001 			 */
2002 			apic_nticks = 0;
2003 		}
2004 		max_busy = 0;
2005 		for (i = 0; i < apic_nproc; i++) {
2006 
2007 			/*
2008 			 * Check if curipl is non zero & if ISR is in
2009 			 * progress
2010 			 */
2011 			if (((j = apic_cpus[i].aci_curipl) != 0) &&
2012 			    (apic_cpus[i].aci_ISR_in_progress & (1 << j))) {
2013 
2014 				int	irq;
2015 				apic_cpus[i].aci_busy++;
2016 				irq = apic_cpus[i].aci_current[j];
2017 				apic_irq_table[irq]->airq_busy++;
2018 			}
2019 
2020 			if (!apic_nticks &&
2021 			    (apic_cpus[i].aci_busy > max_busy))
2022 				max_busy = apic_cpus[i].aci_busy;
2023 		}
2024 		if (!apic_nticks) {
2025 			if (max_busy > apic_int_busy_mark) {
2026 			/*
2027 			 * We could make the following check be
2028 			 * skipped > 1 in which case, we get a
2029 			 * redistribution at half the busy mark (due to
2030 			 * double interval). Need to be able to collect
2031 			 * more empirical data to decide if that is a
2032 			 * good strategy. Punt for now.
2033 			 */
2034 				if (apic_skipped_redistribute) {
2035 					apic_cleanup_busy();
2036 					apic_skipped_redistribute = 0;
2037 				} else {
2038 					apic_intr_redistribute();
2039 				}
2040 			} else
2041 				apic_skipped_redistribute++;
2042 		}
2043 	}
2044 }
2045 
2046 
2047 /*
2048  * The following functions are in the platform specific file so that they
2049  * can be different functions depending on whether we are running on
2050  * bare metal or a hypervisor.
2051  */
2052 
2053 /*
2054  * map an apic for memory-mapped access
2055  */
2056 uint32_t *
2057 mapin_apic(uint32_t addr, size_t len, int flags)
2058 {
2059 	/*LINTED: pointer cast may result in improper alignment */
2060 	return ((uint32_t *)psm_map_phys(addr, len, flags));
2061 }
2062 
2063 uint32_t *
2064 mapin_ioapic(uint32_t addr, size_t len, int flags)
2065 {
2066 	return (mapin_apic(addr, len, flags));
2067 }
2068 
2069 /*
2070  * unmap an apic
2071  */
2072 void
2073 mapout_apic(caddr_t addr, size_t len)
2074 {
2075 	psm_unmap_phys(addr, len);
2076 }
2077 
2078 void
2079 mapout_ioapic(caddr_t addr, size_t len)
2080 {
2081 	mapout_apic(addr, len);
2082 }
2083 
2084 /*
2085  * Check to make sure there are enough irq slots
2086  */
2087 int
2088 apic_check_free_irqs(int count)
2089 {
2090 	int i, avail;
2091 
2092 	avail = 0;
2093 	for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
2094 		if ((apic_irq_table[i] == NULL) ||
2095 		    apic_irq_table[i]->airq_mps_intr_index == FREE_INDEX) {
2096 			if (++avail >= count)
2097 				return (PSM_SUCCESS);
2098 		}
2099 	}
2100 	return (PSM_FAILURE);
2101 }
2102 
2103 /*
2104  * This function allocates "count" MSI vector(s) for the given "dip/pri/type"
2105  */
2106 int
2107 apic_alloc_msi_vectors(dev_info_t *dip, int inum, int count, int pri,
2108     int behavior)
2109 {
2110 	int	rcount, i;
2111 	uchar_t	start, irqno;
2112 	uint32_t cpu;
2113 	major_t	major;
2114 	apic_irq_t	*irqptr;
2115 
2116 	DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: dip=0x%p "
2117 	    "inum=0x%x  pri=0x%x count=0x%x behavior=%d\n",
2118 	    (void *)dip, inum, pri, count, behavior));
2119 
2120 	if (count > 1) {
2121 		if (behavior == DDI_INTR_ALLOC_STRICT &&
2122 		    (apic_multi_msi_enable == 0 || count > apic_multi_msi_max))
2123 			return (0);
2124 
2125 		if (apic_multi_msi_enable == 0)
2126 			count = 1;
2127 		else if (count > apic_multi_msi_max)
2128 			count = apic_multi_msi_max;
2129 	}
2130 
2131 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2132 		rcount = count;
2133 	else if (rcount == 0 || (rcount < count &&
2134 	    behavior == DDI_INTR_ALLOC_STRICT))
2135 		return (0);
2136 
2137 	/* if not ISP2, then round it down */
2138 	if (!ISP2(rcount))
2139 		rcount = 1 << (highbit(rcount) - 1);
2140 
2141 	mutex_enter(&airq_mutex);
2142 
2143 	for (start = 0; rcount > 0; rcount >>= 1) {
2144 		if ((start = apic_find_multi_vectors(pri, rcount)) != 0 ||
2145 		    behavior == DDI_INTR_ALLOC_STRICT)
2146 			break;
2147 	}
2148 
2149 	if (start == 0) {
2150 		/* no vector available */
2151 		mutex_exit(&airq_mutex);
2152 		return (0);
2153 	}
2154 
2155 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2156 		/* not enough free irq slots available */
2157 		mutex_exit(&airq_mutex);
2158 		return (0);
2159 	}
2160 
2161 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
2162 	for (i = 0; i < rcount; i++) {
2163 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2164 		    (uchar_t)-1) {
2165 			/*
2166 			 * shouldn't happen because of the
2167 			 * apic_check_free_irqs() check earlier
2168 			 */
2169 			mutex_exit(&airq_mutex);
2170 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
2171 			    "apic_allocate_irq failed\n"));
2172 			return (i);
2173 		}
2174 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2175 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2176 		irqptr = apic_irq_table[irqno];
2177 #ifdef	DEBUG
2178 		if (apic_vector_to_irq[start + i] != APIC_RESV_IRQ)
2179 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
2180 			    "apic_vector_to_irq is not APIC_RESV_IRQ\n"));
2181 #endif
2182 		apic_vector_to_irq[start + i] = (uchar_t)irqno;
2183 
2184 		irqptr->airq_vector = (uchar_t)(start + i);
2185 		irqptr->airq_ioapicindex = (uchar_t)inum;	/* start */
2186 		irqptr->airq_intin_no = (uchar_t)rcount;
2187 		irqptr->airq_ipl = pri;
2188 		irqptr->airq_vector = start + i;
2189 		irqptr->airq_origirq = (uchar_t)(inum + i);
2190 		irqptr->airq_share_id = 0;
2191 		irqptr->airq_mps_intr_index = MSI_INDEX;
2192 		irqptr->airq_dip = dip;
2193 		irqptr->airq_major = major;
2194 		if (i == 0) /* they all bound to the same cpu */
2195 			cpu = irqptr->airq_cpu = apic_bind_intr(dip, irqno,
2196 			    0xff, 0xff);
2197 		else
2198 			irqptr->airq_cpu = cpu;
2199 		DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: irq=0x%x "
2200 		    "dip=0x%p vector=0x%x origirq=0x%x pri=0x%x\n", irqno,
2201 		    (void *)irqptr->airq_dip, irqptr->airq_vector,
2202 		    irqptr->airq_origirq, pri));
2203 	}
2204 	mutex_exit(&airq_mutex);
2205 	return (rcount);
2206 }
2207 
2208 /*
2209  * This function allocates "count" MSI-X vector(s) for the given "dip/pri/type"
2210  */
2211 int
2212 apic_alloc_msix_vectors(dev_info_t *dip, int inum, int count, int pri,
2213     int behavior)
2214 {
2215 	int	rcount, i;
2216 	major_t	major;
2217 
2218 	if (count > 1) {
2219 		if (behavior == DDI_INTR_ALLOC_STRICT) {
2220 			if (count > apic_msix_max)
2221 				return (0);
2222 		} else if (count > apic_msix_max)
2223 			count = apic_msix_max;
2224 	}
2225 
2226 	mutex_enter(&airq_mutex);
2227 
2228 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2229 		rcount = count;
2230 	else if (rcount == 0 || (rcount < count &&
2231 	    behavior == DDI_INTR_ALLOC_STRICT)) {
2232 		rcount = 0;
2233 		goto out;
2234 	}
2235 
2236 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2237 		/* not enough free irq slots available */
2238 		rcount = 0;
2239 		goto out;
2240 	}
2241 
2242 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
2243 	for (i = 0; i < rcount; i++) {
2244 		uchar_t	vector, irqno;
2245 		apic_irq_t	*irqptr;
2246 
2247 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2248 		    (uchar_t)-1) {
2249 			/*
2250 			 * shouldn't happen because of the
2251 			 * apic_check_free_irqs() check earlier
2252 			 */
2253 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2254 			    "apic_allocate_irq failed\n"));
2255 			rcount = i;
2256 			goto out;
2257 		}
2258 		if ((vector = apic_allocate_vector(pri, irqno, 1)) == 0) {
2259 			/*
2260 			 * shouldn't happen because of the
2261 			 * apic_navail_vector() call earlier
2262 			 */
2263 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2264 			    "apic_allocate_vector failed\n"));
2265 			rcount = i;
2266 			goto out;
2267 		}
2268 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2269 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2270 		irqptr = apic_irq_table[irqno];
2271 		irqptr->airq_vector = (uchar_t)vector;
2272 		irqptr->airq_ipl = pri;
2273 		irqptr->airq_origirq = (uchar_t)(inum + i);
2274 		irqptr->airq_share_id = 0;
2275 		irqptr->airq_mps_intr_index = MSIX_INDEX;
2276 		irqptr->airq_dip = dip;
2277 		irqptr->airq_major = major;
2278 		irqptr->airq_cpu = apic_bind_intr(dip, irqno, 0xff, 0xff);
2279 	}
2280 out:
2281 	mutex_exit(&airq_mutex);
2282 	return (rcount);
2283 }
2284 
2285 /*
2286  * Allocate a free vector for irq at ipl. Takes care of merging of multiple
2287  * IPLs into a single APIC level as well as stretching some IPLs onto multiple
2288  * levels. APIC_HI_PRI_VECTS interrupts are reserved for high priority
2289  * requests and allocated only when pri is set.
2290  */
2291 uchar_t
2292 apic_allocate_vector(int ipl, int irq, int pri)
2293 {
2294 	int	lowest, highest, i;
2295 
2296 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
2297 	lowest = apic_ipltopri[ipl - 1] + APIC_VECTOR_PER_IPL;
2298 
2299 	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
2300 		lowest -= APIC_VECTOR_PER_IPL;
2301 
2302 #ifdef	DEBUG
2303 	if (apic_restrict_vector)	/* for testing shared interrupt logic */
2304 		highest = lowest + apic_restrict_vector + APIC_HI_PRI_VECTS;
2305 #endif /* DEBUG */
2306 	if (pri == 0)
2307 		highest -= APIC_HI_PRI_VECTS;
2308 
2309 	for (i = lowest; i < highest; i++) {
2310 		if (APIC_CHECK_RESERVE_VECTORS(i))
2311 			continue;
2312 		if (apic_vector_to_irq[i] == APIC_RESV_IRQ) {
2313 			apic_vector_to_irq[i] = (uchar_t)irq;
2314 			return (i);
2315 		}
2316 	}
2317 
2318 	return (0);
2319 }
2320 
2321 /* Mark vector as not being used by any irq */
2322 void
2323 apic_free_vector(uchar_t vector)
2324 {
2325 	apic_vector_to_irq[vector] = APIC_RESV_IRQ;
2326 }
2327 
2328 uint32_t
2329 ioapic_read(int ioapic_ix, uint32_t reg)
2330 {
2331 	volatile uint32_t *ioapic;
2332 
2333 	ioapic = apicioadr[ioapic_ix];
2334 	ioapic[APIC_IO_REG] = reg;
2335 	return (ioapic[APIC_IO_DATA]);
2336 }
2337 
2338 void
2339 ioapic_write(int ioapic_ix, uint32_t reg, uint32_t value)
2340 {
2341 	volatile uint32_t *ioapic;
2342 
2343 	ioapic = apicioadr[ioapic_ix];
2344 	ioapic[APIC_IO_REG] = reg;
2345 	ioapic[APIC_IO_DATA] = value;
2346 }
2347 
2348 void
2349 ioapic_write_eoi(int ioapic_ix, uint32_t value)
2350 {
2351 	volatile uint32_t *ioapic;
2352 
2353 	ioapic = apicioadr[ioapic_ix];
2354 	ioapic[APIC_IO_EOI] = value;
2355 }
2356 
2357 static processorid_t
2358 apic_find_cpu(int flag)
2359 {
2360 	processorid_t acid = 0;
2361 	int i;
2362 
2363 	/* Find the first CPU with the passed-in flag set */
2364 	for (i = 0; i < apic_nproc; i++) {
2365 		if (apic_cpus[i].aci_status & flag) {
2366 			acid = i;
2367 			break;
2368 		}
2369 	}
2370 
2371 	ASSERT((apic_cpus[acid].aci_status & flag) != 0);
2372 	return (acid);
2373 }
2374 
2375 /*
2376  * Call rebind to do the actual programming.
2377  * Must be called with interrupts disabled and apic_ioapic_lock held
2378  * 'p' is polymorphic -- if this function is called to process a deferred
2379  * reprogramming, p is of type 'struct ioapic_reprogram_data *', from which
2380  * the irq pointer is retrieved.  If not doing deferred reprogramming,
2381  * p is of the type 'apic_irq_t *'.
2382  *
2383  * apic_ioapic_lock must be held across this call, as it protects apic_rebind
2384  * and it protects apic_find_cpu() from a race in which a CPU can be taken
2385  * offline after a cpu is selected, but before apic_rebind is called to
2386  * bind interrupts to it.
2387  */
2388 int
2389 apic_setup_io_intr(void *p, int irq, boolean_t deferred)
2390 {
2391 	apic_irq_t *irqptr;
2392 	struct ioapic_reprogram_data *drep = NULL;
2393 	int rv;
2394 
2395 	if (deferred) {
2396 		drep = (struct ioapic_reprogram_data *)p;
2397 		ASSERT(drep != NULL);
2398 		irqptr = drep->irqp;
2399 	} else
2400 		irqptr = (apic_irq_t *)p;
2401 
2402 	ASSERT(irqptr != NULL);
2403 
2404 	rv = apic_rebind(irqptr, apic_irq_table[irq]->airq_cpu, drep);
2405 	if (rv) {
2406 		/*
2407 		 * CPU is not up or interrupts are disabled. Fall back to
2408 		 * the first available CPU
2409 		 */
2410 		rv = apic_rebind(irqptr, apic_find_cpu(APIC_CPU_INTR_ENABLE),
2411 		    drep);
2412 	}
2413 
2414 	return (rv);
2415 }
2416 
2417 
2418 uchar_t
2419 apic_modify_vector(uchar_t vector, int irq)
2420 {
2421 	apic_vector_to_irq[vector] = (uchar_t)irq;
2422 	return (vector);
2423 }
2424 
2425 char *
2426 apic_get_apic_type()
2427 {
2428 	return (apic_psm_info.p_mach_idstring);
2429 }
2430 
2431 void
2432 x2apic_update_psm()
2433 {
2434 	struct psm_ops *pops = &apic_ops;
2435 
2436 	ASSERT(pops != NULL);
2437 
2438 	pops->psm_send_ipi =  x2apic_send_ipi;
2439 	pops->psm_intr_exit = x2apic_intr_exit;
2440 	pops->psm_setspl = x2apic_setspl;
2441 
2442 	/* global functions */
2443 	send_dirintf = pops->psm_send_ipi;
2444 }
2445