xref: /titanic_51/usr/src/uts/i86pc/io/pcplusmp/apic.c (revision 628e3cbed6489fa1db545d8524a06cd6535af456)
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 	apic_reg_ops->apic_write_task_reg(APIC_MASK_ALL);
565 
566 	if (apic_mode == LOCAL_APIC) {
567 		/*
568 		 * We are running APIC in MMIO mode.
569 		 */
570 		if (apic_flat_model) {
571 			apic_reg_ops->apic_write(APIC_FORMAT_REG,
572 			    APIC_FLAT_MODEL);
573 		} else {
574 			apic_reg_ops->apic_write(APIC_FORMAT_REG,
575 			    APIC_CLUSTER_MODEL);
576 		}
577 
578 		apic_reg_ops->apic_write(APIC_DEST_REG,
579 		    AV_HIGH_ORDER >> cpun);
580 	}
581 
582 	if (apic_direct_EOI) {
583 		/*
584 		 * Set 12th bit in Spurious Interrupt Vector
585 		 * Register to support level triggered interrupt
586 		 * directed EOI.
587 		 */
588 		svr |= (0x1 << APIC_SVR);
589 	}
590 
591 	/* need to enable APIC before unmasking NMI */
592 	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, svr);
593 
594 	/*
595 	 * Presence of an invalid vector with delivery mode AV_FIXED can
596 	 * cause an error interrupt, even if the entry is masked...so
597 	 * write a valid vector to LVT entries along with the mask bit
598 	 */
599 
600 	/* All APICs have timer and LINT0/1 */
601 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, AV_MASK|APIC_RESV_IRQ);
602 	apic_reg_ops->apic_write(APIC_INT_VECT0, AV_MASK|APIC_RESV_IRQ);
603 	apic_reg_ops->apic_write(APIC_INT_VECT1, AV_NMI);	/* enable NMI */
604 
605 	/*
606 	 * On integrated APICs, the number of LVT entries is
607 	 * 'Max LVT entry' + 1; on 82489DX's (non-integrated
608 	 * APICs), nlvt is "3" (LINT0, LINT1, and timer)
609 	 */
610 
611 	if (apic_cpus[cpun].aci_local_ver < APIC_INTEGRATED_VERS) {
612 		nlvt = 3;
613 	} else {
614 		nlvt = ((apicadr[APIC_VERS_REG] >> 16) & 0xFF) + 1;
615 	}
616 
617 	if (nlvt >= 5) {
618 		/* Enable performance counter overflow interrupt */
619 
620 		if ((x86_feature & X86_MSR) != X86_MSR)
621 			apic_enable_cpcovf_intr = 0;
622 		if (apic_enable_cpcovf_intr) {
623 			if (apic_cpcovf_vect == 0) {
624 				int ipl = APIC_PCINT_IPL;
625 				int irq = apic_get_ipivect(ipl, -1);
626 
627 				ASSERT(irq != -1);
628 				apic_cpcovf_vect =
629 				    apic_irq_table[irq]->airq_vector;
630 				ASSERT(apic_cpcovf_vect);
631 				(void) add_avintr(NULL, ipl,
632 				    (avfunc)kcpc_hw_overflow_intr,
633 				    "apic pcint", irq, NULL, NULL, NULL, NULL);
634 				kcpc_hw_overflow_intr_installed = 1;
635 				kcpc_hw_enable_cpc_intr =
636 				    apic_cpcovf_mask_clear;
637 			}
638 			apic_reg_ops->apic_write(APIC_PCINT_VECT,
639 			    apic_cpcovf_vect);
640 		}
641 	}
642 
643 	if (nlvt >= 6) {
644 		/* Only mask TM intr if the BIOS apparently doesn't use it */
645 
646 		uint32_t lvtval;
647 
648 		lvtval = apic_reg_ops->apic_read(APIC_THERM_VECT);
649 		if (((lvtval & AV_MASK) == AV_MASK) ||
650 		    ((lvtval & AV_DELIV_MODE) != AV_SMI)) {
651 			apic_reg_ops->apic_write(APIC_THERM_VECT,
652 			    AV_MASK|APIC_RESV_IRQ);
653 		}
654 	}
655 
656 	/* Enable error interrupt */
657 
658 	if (nlvt >= 4 && apic_enable_error_intr) {
659 		if (apic_errvect == 0) {
660 			int ipl = 0xf;	/* get highest priority intr */
661 			int irq = apic_get_ipivect(ipl, -1);
662 
663 			ASSERT(irq != -1);
664 			apic_errvect = apic_irq_table[irq]->airq_vector;
665 			ASSERT(apic_errvect);
666 			/*
667 			 * Not PSMI compliant, but we are going to merge
668 			 * with ON anyway
669 			 */
670 			(void) add_avintr((void *)NULL, ipl,
671 			    (avfunc)apic_error_intr, "apic error intr",
672 			    irq, NULL, NULL, NULL, NULL);
673 		}
674 		apic_reg_ops->apic_write(APIC_ERR_VECT, apic_errvect);
675 		apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
676 		apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
677 	}
678 
679 	/* Enable CMCI interrupt */
680 	if (cmi_enable_cmci) {
681 
682 		mutex_enter(&cmci_cpu_setup_lock);
683 		if (cmci_cpu_setup_registered == 0) {
684 			mutex_enter(&cpu_lock);
685 			register_cpu_setup_func(cmci_cpu_setup, NULL);
686 			mutex_exit(&cpu_lock);
687 			cmci_cpu_setup_registered = 1;
688 		}
689 		mutex_exit(&cmci_cpu_setup_lock);
690 
691 		if (apic_cmci_vect == 0) {
692 			int ipl = 0x2;
693 			int irq = apic_get_ipivect(ipl, -1);
694 
695 			ASSERT(irq != -1);
696 			apic_cmci_vect = apic_irq_table[irq]->airq_vector;
697 			ASSERT(apic_cmci_vect);
698 
699 			(void) add_avintr(NULL, ipl,
700 			    (avfunc)cmi_cmci_trap,
701 			    "apic cmci intr", irq, NULL, NULL, NULL, NULL);
702 		}
703 		apic_reg_ops->apic_write(APIC_CMCI_VECT, apic_cmci_vect);
704 	}
705 
706 }
707 
708 static void
709 apic_disable_local_apic()
710 {
711 	apic_reg_ops->apic_write_task_reg(APIC_MASK_ALL);
712 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, AV_MASK);
713 
714 	/* local intr reg 0 */
715 	apic_reg_ops->apic_write(APIC_INT_VECT0, AV_MASK);
716 
717 	/* disable NMI */
718 	apic_reg_ops->apic_write(APIC_INT_VECT1, AV_MASK);
719 
720 	/* and error interrupt */
721 	apic_reg_ops->apic_write(APIC_ERR_VECT, AV_MASK);
722 
723 	/* and perf counter intr */
724 	apic_reg_ops->apic_write(APIC_PCINT_VECT, AV_MASK);
725 
726 	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, APIC_SPUR_INTR);
727 }
728 
729 static void
730 apic_picinit(void)
731 {
732 	int i, j;
733 	uint_t isr;
734 	uint32_t ver;
735 
736 	/*
737 	 * On UniSys Model 6520, the BIOS leaves vector 0x20 isr
738 	 * bit on without clearing it with EOI.  Since softint
739 	 * uses vector 0x20 to interrupt itself, so softint will
740 	 * not work on this machine.  In order to fix this problem
741 	 * a check is made to verify all the isr bits are clear.
742 	 * If not, EOIs are issued to clear the bits.
743 	 */
744 	for (i = 7; i >= 1; i--) {
745 		isr = apic_reg_ops->apic_read(APIC_ISR_REG + (i * 4));
746 		if (isr != 0)
747 			for (j = 0; ((j < 32) && (isr != 0)); j++)
748 				if (isr & (1 << j)) {
749 					apic_reg_ops->apic_write(
750 					    APIC_EOI_REG, 0);
751 					isr &= ~(1 << j);
752 					apic_error |= APIC_ERR_BOOT_EOI;
753 				}
754 	}
755 
756 	/* set a flag so we know we have run apic_picinit() */
757 	apic_picinit_called = 1;
758 	LOCK_INIT_CLEAR(&apic_gethrtime_lock);
759 	LOCK_INIT_CLEAR(&apic_ioapic_lock);
760 	LOCK_INIT_CLEAR(&apic_error_lock);
761 
762 	picsetup();	 /* initialise the 8259 */
763 
764 	/* add nmi handler - least priority nmi handler */
765 	LOCK_INIT_CLEAR(&apic_nmi_lock);
766 
767 	if (!psm_add_nmintr(0, (avfunc) apic_nmi_intr,
768 	    "pcplusmp NMI handler", (caddr_t)NULL))
769 		cmn_err(CE_WARN, "pcplusmp: Unable to add nmi handler");
770 
771 	ver = apic_reg_ops->apic_read(APIC_VERS_REG);
772 	/*
773 	 * In order to determine support for Directed EOI capability,
774 	 * we check for 24th bit in Local APIC Version Register.
775 	 */
776 	if (ver & (0x1 << APIC_DIRECTED_EOI)) {
777 		apic_direct_EOI = 1;
778 		apic_change_eoi();
779 	}
780 
781 	apic_init_intr();
782 
783 	/* enable apic mode if imcr present */
784 	if (apic_imcrp) {
785 		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
786 		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_APIC);
787 	}
788 
789 	ioapic_init_intr(IOAPIC_MASK);
790 }
791 
792 
793 /*ARGSUSED1*/
794 static int
795 apic_cpu_start(processorid_t cpun, caddr_t arg)
796 {
797 	int		loop_count;
798 	uint32_t	vector;
799 	uint_t		cpu_id;
800 	ulong_t		iflag;
801 
802 	cpu_id =  apic_cpus[cpun].aci_local_id;
803 
804 	apic_cmos_ssb_set = 1;
805 
806 	/*
807 	 * Interrupts on BSP cpu will be disabled during these startup
808 	 * steps in order to avoid unwanted side effects from
809 	 * executing interrupt handlers on a problematic BIOS.
810 	 */
811 
812 	iflag = intr_clear();
813 	outb(CMOS_ADDR, SSB);
814 	outb(CMOS_DATA, BIOS_SHUTDOWN);
815 
816 	/*
817 	 * According to x2APIC specification in section '2.3.5.1' of
818 	 * Interrupt Command Register Semantics, the semantics of
819 	 * programming the Interrupt Command Register to dispatch an interrupt
820 	 * is simplified. A single MSR write to the 64-bit ICR is required
821 	 * for dispatching an interrupt. Specifically, with the 64-bit MSR
822 	 * interface to ICR, system software is not required to check the
823 	 * status of the delivery status bit prior to writing to the ICR
824 	 * to send an IPI. With the removal of the Delivery Status bit,
825 	 * system software no longer has a reason to read the ICR. It remains
826 	 * readable only to aid in debugging.
827 	 */
828 #ifdef	DEBUG
829 	APIC_AV_PENDING_SET();
830 #else
831 	if (apic_mode == LOCAL_APIC) {
832 		APIC_AV_PENDING_SET();
833 	}
834 #endif /* DEBUG */
835 
836 	/* for integrated - make sure there is one INIT IPI in buffer */
837 	/* for external - it will wake up the cpu */
838 	apic_reg_ops->apic_write_int_cmd(cpu_id, AV_ASSERT | AV_RESET);
839 
840 	/* If only 1 CPU is installed, PENDING bit will not go low */
841 	for (loop_count = 0x1000; loop_count; loop_count--) {
842 		if (apic_mode == LOCAL_APIC &&
843 		    apic_reg_ops->apic_read(APIC_INT_CMD1) & AV_PENDING)
844 			apic_ret();
845 		else
846 			break;
847 	}
848 
849 	apic_reg_ops->apic_write_int_cmd(cpu_id, AV_DEASSERT | AV_RESET);
850 
851 	drv_usecwait(20000);		/* 20 milli sec */
852 
853 	if (apic_cpus[cpun].aci_local_ver >= APIC_INTEGRATED_VERS) {
854 		/* integrated apic */
855 
856 		vector = (rm_platter_pa >> MMU_PAGESHIFT) &
857 		    (APIC_VECTOR_MASK | APIC_IPL_MASK);
858 
859 		/* to offset the INIT IPI queue up in the buffer */
860 		apic_reg_ops->apic_write_int_cmd(cpu_id, vector | AV_STARTUP);
861 
862 		drv_usecwait(200);		/* 20 micro sec */
863 
864 		apic_reg_ops->apic_write_int_cmd(cpu_id, vector | AV_STARTUP);
865 
866 		drv_usecwait(200);		/* 20 micro sec */
867 	}
868 	intr_restore(iflag);
869 	return (0);
870 }
871 
872 
873 #ifdef	DEBUG
874 int	apic_break_on_cpu = 9;
875 int	apic_stretch_interrupts = 0;
876 int	apic_stretch_ISR = 1 << 3;	/* IPL of 3 matches nothing now */
877 
878 void
879 apic_break()
880 {
881 }
882 #endif /* DEBUG */
883 
884 /*
885  * platform_intr_enter
886  *
887  *	Called at the beginning of the interrupt service routine to
888  *	mask all level equal to and below the interrupt priority
889  *	of the interrupting vector.  An EOI should be given to
890  *	the interrupt controller to enable other HW interrupts.
891  *
892  *	Return -1 for spurious interrupts
893  *
894  */
895 /*ARGSUSED*/
896 static int
897 apic_intr_enter(int ipl, int *vectorp)
898 {
899 	uchar_t vector;
900 	int nipl;
901 	int irq;
902 	ulong_t iflag;
903 	apic_cpus_info_t *cpu_infop;
904 
905 	/*
906 	 * The real vector delivered is (*vectorp + 0x20), but our caller
907 	 * subtracts 0x20 from the vector before passing it to us.
908 	 * (That's why APIC_BASE_VECT is 0x20.)
909 	 */
910 	vector = (uchar_t)*vectorp;
911 
912 	/* if interrupted by the clock, increment apic_nsec_since_boot */
913 	if (vector == apic_clkvect) {
914 		if (!apic_oneshot) {
915 			/* NOTE: this is not MT aware */
916 			apic_hrtime_stamp++;
917 			apic_nsec_since_boot += apic_nsec_per_intr;
918 			apic_hrtime_stamp++;
919 			last_count_read = apic_hertz_count;
920 			apic_redistribute_compute();
921 		}
922 
923 		/* We will avoid all the book keeping overhead for clock */
924 		nipl = apic_ipls[vector];
925 
926 		*vectorp = apic_vector_to_irq[vector + APIC_BASE_VECT];
927 		if (apic_mode == LOCAL_APIC) {
928 #if defined(__amd64)
929 			setcr8((ulong_t)(apic_ipltopri[nipl] >>
930 			    APIC_IPL_SHIFT));
931 #else
932 			LOCAL_APIC_WRITE_REG(APIC_TASK_REG,
933 			    (uint32_t)apic_ipltopri[nipl]);
934 #endif
935 			LOCAL_APIC_WRITE_REG(APIC_EOI_REG, 0);
936 		} else {
937 			X2APIC_WRITE(APIC_TASK_REG, apic_ipltopri[nipl]);
938 			X2APIC_WRITE(APIC_EOI_REG, 0);
939 		}
940 
941 		return (nipl);
942 	}
943 
944 	cpu_infop = &apic_cpus[psm_get_cpu_id()];
945 
946 	if (vector == (APIC_SPUR_INTR - APIC_BASE_VECT)) {
947 		cpu_infop->aci_spur_cnt++;
948 		return (APIC_INT_SPURIOUS);
949 	}
950 
951 	/* Check if the vector we got is really what we need */
952 	if (apic_revector_pending) {
953 		/*
954 		 * Disable interrupts for the duration of
955 		 * the vector translation to prevent a self-race for
956 		 * the apic_revector_lock.  This cannot be done
957 		 * in apic_xlate_vector because it is recursive and
958 		 * we want the vector translation to be atomic with
959 		 * respect to other (higher-priority) interrupts.
960 		 */
961 		iflag = intr_clear();
962 		vector = apic_xlate_vector(vector + APIC_BASE_VECT) -
963 		    APIC_BASE_VECT;
964 		intr_restore(iflag);
965 	}
966 
967 	nipl = apic_ipls[vector];
968 	*vectorp = irq = apic_vector_to_irq[vector + APIC_BASE_VECT];
969 
970 	if (apic_mode == LOCAL_APIC) {
971 #if defined(__amd64)
972 		setcr8((ulong_t)(apic_ipltopri[nipl] >> APIC_IPL_SHIFT));
973 #else
974 		LOCAL_APIC_WRITE_REG(APIC_TASK_REG,
975 		    (uint32_t)apic_ipltopri[nipl]);
976 #endif
977 	} else {
978 		X2APIC_WRITE(APIC_TASK_REG, apic_ipltopri[nipl]);
979 	}
980 
981 	cpu_infop->aci_current[nipl] = (uchar_t)irq;
982 	cpu_infop->aci_curipl = (uchar_t)nipl;
983 	cpu_infop->aci_ISR_in_progress |= 1 << nipl;
984 
985 	/*
986 	 * apic_level_intr could have been assimilated into the irq struct.
987 	 * but, having it as a character array is more efficient in terms of
988 	 * cache usage. So, we leave it as is.
989 	 */
990 	if (!apic_level_intr[irq]) {
991 		if (apic_mode == LOCAL_APIC)
992 			LOCAL_APIC_WRITE_REG(APIC_EOI_REG, 0);
993 		else
994 			X2APIC_WRITE(APIC_EOI_REG, 0);
995 	}
996 
997 #ifdef	DEBUG
998 	APIC_DEBUG_BUF_PUT(vector);
999 	APIC_DEBUG_BUF_PUT(irq);
1000 	APIC_DEBUG_BUF_PUT(nipl);
1001 	APIC_DEBUG_BUF_PUT(psm_get_cpu_id());
1002 	if ((apic_stretch_interrupts) && (apic_stretch_ISR & (1 << nipl)))
1003 		drv_usecwait(apic_stretch_interrupts);
1004 
1005 	if (apic_break_on_cpu == psm_get_cpu_id())
1006 		apic_break();
1007 #endif /* DEBUG */
1008 	return (nipl);
1009 }
1010 
1011 /*
1012  * This macro is a common code used by MMIO local apic and x2apic
1013  * local apic.
1014  */
1015 #define	APIC_INTR_EXIT() \
1016 { \
1017 	cpu_infop = &apic_cpus[psm_get_cpu_id()]; \
1018 	if (apic_level_intr[irq]) \
1019 		apic_reg_ops->apic_send_eoi(irq); \
1020 	cpu_infop->aci_curipl = (uchar_t)prev_ipl; \
1021 	/* ISR above current pri could not be in progress */ \
1022 	cpu_infop->aci_ISR_in_progress &= (2 << prev_ipl) - 1; \
1023 }
1024 
1025 /*
1026  * Any changes made to this function must also change x2apic
1027  * version of intr_exit.
1028  */
1029 void
1030 apic_intr_exit(int prev_ipl, int irq)
1031 {
1032 	apic_cpus_info_t *cpu_infop;
1033 
1034 #if defined(__amd64)
1035 	setcr8((ulong_t)apic_cr8pri[prev_ipl]);
1036 #else
1037 	apicadr[APIC_TASK_REG] = apic_ipltopri[prev_ipl];
1038 #endif
1039 
1040 	APIC_INTR_EXIT();
1041 }
1042 
1043 /*
1044  * Same as apic_intr_exit() except it uses MSR rather than MMIO
1045  * to access local apic registers.
1046  */
1047 void
1048 x2apic_intr_exit(int prev_ipl, int irq)
1049 {
1050 	apic_cpus_info_t *cpu_infop;
1051 
1052 	X2APIC_WRITE(APIC_TASK_REG, apic_ipltopri[prev_ipl]);
1053 	APIC_INTR_EXIT();
1054 }
1055 
1056 intr_exit_fn_t
1057 psm_intr_exit_fn(void)
1058 {
1059 	if (apic_mode == LOCAL_X2APIC)
1060 		return (x2apic_intr_exit);
1061 
1062 	return (apic_intr_exit);
1063 }
1064 
1065 /*
1066  * Mask all interrupts below or equal to the given IPL.
1067  * Any changes made to this function must also change x2apic
1068  * version of setspl.
1069  */
1070 static void
1071 apic_setspl(int ipl)
1072 {
1073 
1074 #if defined(__amd64)
1075 	setcr8((ulong_t)apic_cr8pri[ipl]);
1076 #else
1077 	apicadr[APIC_TASK_REG] = apic_ipltopri[ipl];
1078 #endif
1079 
1080 	/* interrupts at ipl above this cannot be in progress */
1081 	apic_cpus[psm_get_cpu_id()].aci_ISR_in_progress &= (2 << ipl) - 1;
1082 	/*
1083 	 * this is a patch fix for the ALR QSMP P5 machine, so that interrupts
1084 	 * have enough time to come in before the priority is raised again
1085 	 * during the idle() loop.
1086 	 */
1087 	if (apic_setspl_delay)
1088 		(void) apic_reg_ops->apic_get_pri();
1089 }
1090 
1091 /*
1092  * x2apic version of setspl.
1093  * Mask all interrupts below or equal to the given IPL
1094  */
1095 static void
1096 x2apic_setspl(int ipl)
1097 {
1098 	X2APIC_WRITE(APIC_TASK_REG, apic_ipltopri[ipl]);
1099 
1100 	/* interrupts at ipl above this cannot be in progress */
1101 	apic_cpus[psm_get_cpu_id()].aci_ISR_in_progress &= (2 << ipl) - 1;
1102 }
1103 
1104 /*
1105  * generates an interprocessor interrupt to another CPU
1106  */
1107 static void
1108 apic_send_ipi(int cpun, int ipl)
1109 {
1110 	int vector;
1111 	ulong_t flag;
1112 
1113 	vector = apic_resv_vector[ipl];
1114 
1115 	ASSERT((vector >= APIC_BASE_VECT) && (vector <= APIC_SPUR_INTR));
1116 
1117 	flag = intr_clear();
1118 
1119 	APIC_AV_PENDING_SET();
1120 
1121 	apic_reg_ops->apic_write_int_cmd(apic_cpus[cpun].aci_local_id,
1122 	    vector);
1123 
1124 	intr_restore(flag);
1125 }
1126 
1127 
1128 /*ARGSUSED*/
1129 static void
1130 apic_set_idlecpu(processorid_t cpun)
1131 {
1132 }
1133 
1134 /*ARGSUSED*/
1135 static void
1136 apic_unset_idlecpu(processorid_t cpun)
1137 {
1138 }
1139 
1140 
1141 void
1142 apic_ret()
1143 {
1144 }
1145 
1146 /*
1147  * If apic_coarse_time == 1, then apic_gettime() is used instead of
1148  * apic_gethrtime().  This is used for performance instead of accuracy.
1149  */
1150 
1151 static hrtime_t
1152 apic_gettime()
1153 {
1154 	int old_hrtime_stamp;
1155 	hrtime_t temp;
1156 
1157 	/*
1158 	 * In one-shot mode, we do not keep time, so if anyone
1159 	 * calls psm_gettime() directly, we vector over to
1160 	 * gethrtime().
1161 	 * one-shot mode MUST NOT be enabled if this psm is the source of
1162 	 * hrtime.
1163 	 */
1164 
1165 	if (apic_oneshot)
1166 		return (gethrtime());
1167 
1168 
1169 gettime_again:
1170 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
1171 		apic_ret();
1172 
1173 	temp = apic_nsec_since_boot;
1174 
1175 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
1176 		goto gettime_again;
1177 	}
1178 	return (temp);
1179 }
1180 
1181 /*
1182  * Here we return the number of nanoseconds since booting.  Note every
1183  * clock interrupt increments apic_nsec_since_boot by the appropriate
1184  * amount.
1185  */
1186 static hrtime_t
1187 apic_gethrtime()
1188 {
1189 	int curr_timeval, countval, elapsed_ticks;
1190 	int old_hrtime_stamp, status;
1191 	hrtime_t temp;
1192 	uint32_t cpun;
1193 	ulong_t oflags;
1194 
1195 	/*
1196 	 * In one-shot mode, we do not keep time, so if anyone
1197 	 * calls psm_gethrtime() directly, we vector over to
1198 	 * gethrtime().
1199 	 * one-shot mode MUST NOT be enabled if this psm is the source of
1200 	 * hrtime.
1201 	 */
1202 
1203 	if (apic_oneshot)
1204 		return (gethrtime());
1205 
1206 	oflags = intr_clear();	/* prevent migration */
1207 
1208 	cpun = apic_reg_ops->apic_read(APIC_LID_REG);
1209 	if (apic_mode == LOCAL_APIC)
1210 		cpun >>= APIC_ID_BIT_OFFSET;
1211 
1212 	lock_set(&apic_gethrtime_lock);
1213 
1214 gethrtime_again:
1215 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
1216 		apic_ret();
1217 
1218 	/*
1219 	 * Check to see which CPU we are on.  Note the time is kept on
1220 	 * the local APIC of CPU 0.  If on CPU 0, simply read the current
1221 	 * counter.  If on another CPU, issue a remote read command to CPU 0.
1222 	 */
1223 	if (cpun == apic_cpus[0].aci_local_id) {
1224 		countval = apic_reg_ops->apic_read(APIC_CURR_COUNT);
1225 	} else {
1226 #ifdef	DEBUG
1227 		APIC_AV_PENDING_SET();
1228 #else
1229 		if (apic_mode == LOCAL_APIC)
1230 			APIC_AV_PENDING_SET();
1231 #endif /* DEBUG */
1232 
1233 		apic_reg_ops->apic_write_int_cmd(
1234 		    apic_cpus[0].aci_local_id, APIC_CURR_ADD | AV_REMOTE);
1235 
1236 		while ((status = apic_reg_ops->apic_read(APIC_INT_CMD1))
1237 		    & AV_READ_PENDING) {
1238 			apic_ret();
1239 		}
1240 
1241 		if (status & AV_REMOTE_STATUS)	/* 1 = valid */
1242 			countval = apic_reg_ops->apic_read(APIC_REMOTE_READ);
1243 		else {	/* 0 = invalid */
1244 			apic_remote_hrterr++;
1245 			/*
1246 			 * return last hrtime right now, will need more
1247 			 * testing if change to retry
1248 			 */
1249 			temp = apic_last_hrtime;
1250 
1251 			lock_clear(&apic_gethrtime_lock);
1252 
1253 			intr_restore(oflags);
1254 
1255 			return (temp);
1256 		}
1257 	}
1258 	if (countval > last_count_read)
1259 		countval = 0;
1260 	else
1261 		last_count_read = countval;
1262 
1263 	elapsed_ticks = apic_hertz_count - countval;
1264 
1265 	curr_timeval = APIC_TICKS_TO_NSECS(elapsed_ticks);
1266 	temp = apic_nsec_since_boot + curr_timeval;
1267 
1268 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
1269 		/* we might have clobbered last_count_read. Restore it */
1270 		last_count_read = apic_hertz_count;
1271 		goto gethrtime_again;
1272 	}
1273 
1274 	if (temp < apic_last_hrtime) {
1275 		/* return last hrtime if error occurs */
1276 		apic_hrtime_error++;
1277 		temp = apic_last_hrtime;
1278 	}
1279 	else
1280 		apic_last_hrtime = temp;
1281 
1282 	lock_clear(&apic_gethrtime_lock);
1283 	intr_restore(oflags);
1284 
1285 	return (temp);
1286 }
1287 
1288 /* apic NMI handler */
1289 /*ARGSUSED*/
1290 static void
1291 apic_nmi_intr(caddr_t arg, struct regs *rp)
1292 {
1293 	if (apic_shutdown_processors) {
1294 		apic_disable_local_apic();
1295 		return;
1296 	}
1297 
1298 	apic_error |= APIC_ERR_NMI;
1299 
1300 	if (!lock_try(&apic_nmi_lock))
1301 		return;
1302 	apic_num_nmis++;
1303 
1304 	if (apic_kmdb_on_nmi && psm_debugger()) {
1305 		debug_enter("NMI received: entering kmdb\n");
1306 	} else if (apic_panic_on_nmi) {
1307 		/* Keep panic from entering kmdb. */
1308 		nopanicdebug = 1;
1309 		panic("NMI received\n");
1310 	} else {
1311 		/*
1312 		 * prom_printf is the best shot we have of something which is
1313 		 * problem free from high level/NMI type of interrupts
1314 		 */
1315 		prom_printf("NMI received\n");
1316 	}
1317 
1318 	lock_clear(&apic_nmi_lock);
1319 }
1320 
1321 /*ARGSUSED*/
1322 static int
1323 apic_addspl(int irqno, int ipl, int min_ipl, int max_ipl)
1324 {
1325 	return (apic_addspl_common(irqno, ipl, min_ipl, max_ipl));
1326 }
1327 
1328 static int
1329 apic_delspl(int irqno, int ipl, int min_ipl, int max_ipl)
1330 {
1331 	return (apic_delspl_common(irqno, ipl, min_ipl,  max_ipl));
1332 }
1333 
1334 static int
1335 apic_post_cpu_start()
1336 {
1337 	int cpun;
1338 
1339 	/*
1340 	 * On BSP we would have enabled X2APIC, if supported by processor,
1341 	 * in acpi_probe(), but on AP we do it here.
1342 	 */
1343 	if (apic_detect_x2apic()) {
1344 		apic_enable_x2apic();
1345 	}
1346 
1347 	splx(ipltospl(LOCK_LEVEL));
1348 	apic_init_intr();
1349 
1350 	/*
1351 	 * since some systems don't enable the internal cache on the non-boot
1352 	 * cpus, so we have to enable them here
1353 	 */
1354 	setcr0(getcr0() & ~(CR0_CD | CR0_NW));
1355 
1356 #ifdef	DEBUG
1357 	APIC_AV_PENDING_SET();
1358 #else
1359 	if (apic_mode == LOCAL_APIC)
1360 		APIC_AV_PENDING_SET();
1361 #endif	/* DEBUG */
1362 
1363 	/*
1364 	 * We may be booting, or resuming from suspend; aci_status will
1365 	 * be APIC_CPU_INTR_ENABLE if coming from suspend, so we add the
1366 	 * APIC_CPU_ONLINE flag here rather than setting aci_status completely.
1367 	 */
1368 	cpun = psm_get_cpu_id();
1369 	apic_cpus[cpun].aci_status |= APIC_CPU_ONLINE;
1370 
1371 	apic_reg_ops->apic_write(APIC_DIVIDE_REG, apic_divide_reg_init);
1372 	return (PSM_SUCCESS);
1373 }
1374 
1375 processorid_t
1376 apic_get_next_processorid(processorid_t cpu_id)
1377 {
1378 
1379 	int i;
1380 
1381 	if (cpu_id == -1)
1382 		return ((processorid_t)0);
1383 
1384 	for (i = cpu_id + 1; i < NCPU; i++) {
1385 		if (CPU_IN_SET(apic_cpumask, i))
1386 			return (i);
1387 	}
1388 
1389 	return ((processorid_t)-1);
1390 }
1391 
1392 
1393 /*
1394  * type == -1 indicates it is an internal request. Do not change
1395  * resv_vector for these requests
1396  */
1397 static int
1398 apic_get_ipivect(int ipl, int type)
1399 {
1400 	uchar_t vector;
1401 	int irq;
1402 
1403 	if (irq = apic_allocate_irq(APIC_VECTOR(ipl))) {
1404 		if (vector = apic_allocate_vector(ipl, irq, 1)) {
1405 			apic_irq_table[irq]->airq_mps_intr_index =
1406 			    RESERVE_INDEX;
1407 			apic_irq_table[irq]->airq_vector = vector;
1408 			if (type != -1) {
1409 				apic_resv_vector[ipl] = vector;
1410 			}
1411 			return (irq);
1412 		}
1413 	}
1414 	apic_error |= APIC_ERR_GET_IPIVECT_FAIL;
1415 	return (-1);	/* shouldn't happen */
1416 }
1417 
1418 static int
1419 apic_getclkirq(int ipl)
1420 {
1421 	int	irq;
1422 
1423 	if ((irq = apic_get_ipivect(ipl, -1)) == -1)
1424 		return (-1);
1425 	/*
1426 	 * Note the vector in apic_clkvect for per clock handling.
1427 	 */
1428 	apic_clkvect = apic_irq_table[irq]->airq_vector - APIC_BASE_VECT;
1429 	APIC_VERBOSE_IOAPIC((CE_NOTE, "get_clkirq: vector = %x\n",
1430 	    apic_clkvect));
1431 	return (irq);
1432 }
1433 
1434 
1435 /*
1436  * Return the number of APIC clock ticks elapsed for 8245 to decrement
1437  * (APIC_TIME_COUNT + pit_ticks_adj) ticks.
1438  */
1439 static uint_t
1440 apic_calibrate(volatile uint32_t *addr, uint16_t *pit_ticks_adj)
1441 {
1442 	uint8_t		pit_tick_lo;
1443 	uint16_t	pit_tick, target_pit_tick;
1444 	uint32_t	start_apic_tick, end_apic_tick;
1445 	ulong_t		iflag;
1446 	uint32_t	reg;
1447 
1448 	reg = addr + APIC_CURR_COUNT - apicadr;
1449 
1450 	iflag = intr_clear();
1451 
1452 	do {
1453 		pit_tick_lo = inb(PITCTR0_PORT);
1454 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1455 	} while (pit_tick < APIC_TIME_MIN ||
1456 	    pit_tick_lo <= APIC_LB_MIN || pit_tick_lo >= APIC_LB_MAX);
1457 
1458 	/*
1459 	 * Wait for the 8254 to decrement by 5 ticks to ensure
1460 	 * we didn't start in the middle of a tick.
1461 	 * Compare with 0x10 for the wrap around case.
1462 	 */
1463 	target_pit_tick = pit_tick - 5;
1464 	do {
1465 		pit_tick_lo = inb(PITCTR0_PORT);
1466 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1467 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1468 
1469 	start_apic_tick = apic_reg_ops->apic_read(reg);
1470 
1471 	/*
1472 	 * Wait for the 8254 to decrement by
1473 	 * (APIC_TIME_COUNT + pit_ticks_adj) ticks
1474 	 */
1475 	target_pit_tick = pit_tick - APIC_TIME_COUNT;
1476 	do {
1477 		pit_tick_lo = inb(PITCTR0_PORT);
1478 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1479 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1480 
1481 	end_apic_tick = apic_reg_ops->apic_read(reg);
1482 
1483 	*pit_ticks_adj = target_pit_tick - pit_tick;
1484 
1485 	intr_restore(iflag);
1486 
1487 	return (start_apic_tick - end_apic_tick);
1488 }
1489 
1490 /*
1491  * Initialise the APIC timer on the local APIC of CPU 0 to the desired
1492  * frequency.  Note at this stage in the boot sequence, the boot processor
1493  * is the only active processor.
1494  * hertz value of 0 indicates a one-shot mode request.  In this case
1495  * the function returns the resolution (in nanoseconds) for the hardware
1496  * timer interrupt.  If one-shot mode capability is not available,
1497  * the return value will be 0. apic_enable_oneshot is a global switch
1498  * for disabling the functionality.
1499  * A non-zero positive value for hertz indicates a periodic mode request.
1500  * In this case the hardware will be programmed to generate clock interrupts
1501  * at hertz frequency and returns the resolution of interrupts in
1502  * nanosecond.
1503  */
1504 
1505 static int
1506 apic_clkinit(int hertz)
1507 {
1508 	uint_t		apic_ticks = 0;
1509 	uint_t		pit_ticks;
1510 	int		ret;
1511 	uint16_t	pit_ticks_adj;
1512 	static int	firsttime = 1;
1513 
1514 	if (firsttime) {
1515 		/* first time calibrate on CPU0 only */
1516 
1517 		apic_reg_ops->apic_write(APIC_DIVIDE_REG, apic_divide_reg_init);
1518 		apic_reg_ops->apic_write(APIC_INIT_COUNT, APIC_MAXVAL);
1519 		apic_ticks = apic_calibrate(apicadr, &pit_ticks_adj);
1520 
1521 		/* total number of PIT ticks corresponding to apic_ticks */
1522 		pit_ticks = APIC_TIME_COUNT + pit_ticks_adj;
1523 
1524 		/*
1525 		 * Determine the number of nanoseconds per APIC clock tick
1526 		 * and then determine how many APIC ticks to interrupt at the
1527 		 * desired frequency
1528 		 * apic_ticks / (pitticks / PIT_HZ) = apic_ticks_per_s
1529 		 * (apic_ticks * PIT_HZ) / pitticks = apic_ticks_per_s
1530 		 * apic_ticks_per_ns = (apic_ticks * PIT_HZ) / (pitticks * 10^9)
1531 		 * pic_ticks_per_SFns =
1532 		 *   (SF * apic_ticks * PIT_HZ) / (pitticks * 10^9)
1533 		 */
1534 		apic_ticks_per_SFnsecs =
1535 		    ((SF * apic_ticks * PIT_HZ) /
1536 		    ((uint64_t)pit_ticks * NANOSEC));
1537 
1538 		/* the interval timer initial count is 32 bit max */
1539 		apic_nsec_max = APIC_TICKS_TO_NSECS(APIC_MAXVAL);
1540 		firsttime = 0;
1541 	}
1542 
1543 	if (hertz != 0) {
1544 		/* periodic */
1545 		apic_nsec_per_intr = NANOSEC / hertz;
1546 		apic_hertz_count = APIC_NSECS_TO_TICKS(apic_nsec_per_intr);
1547 	}
1548 
1549 	apic_int_busy_mark = (apic_int_busy_mark *
1550 	    apic_sample_factor_redistribution) / 100;
1551 	apic_int_free_mark = (apic_int_free_mark *
1552 	    apic_sample_factor_redistribution) / 100;
1553 	apic_diff_for_redistribution = (apic_diff_for_redistribution *
1554 	    apic_sample_factor_redistribution) / 100;
1555 
1556 	if (hertz == 0) {
1557 		/* requested one_shot */
1558 		if (!tsc_gethrtime_enable || !apic_oneshot_enable)
1559 			return (0);
1560 		apic_oneshot = 1;
1561 		ret = (int)APIC_TICKS_TO_NSECS(1);
1562 	} else {
1563 		/* program the local APIC to interrupt at the given frequency */
1564 		apic_reg_ops->apic_write(APIC_INIT_COUNT, apic_hertz_count);
1565 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1566 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME);
1567 		apic_oneshot = 0;
1568 		ret = NANOSEC / hertz;
1569 	}
1570 
1571 	return (ret);
1572 
1573 }
1574 
1575 /*
1576  * apic_preshutdown:
1577  * Called early in shutdown whilst we can still access filesystems to do
1578  * things like loading modules which will be required to complete shutdown
1579  * after filesystems are all unmounted.
1580  */
1581 static void
1582 apic_preshutdown(int cmd, int fcn)
1583 {
1584 	APIC_VERBOSE_POWEROFF(("apic_preshutdown(%d,%d); m=%d a=%d\n",
1585 	    cmd, fcn, apic_poweroff_method, apic_enable_acpi));
1586 
1587 	if ((cmd != A_SHUTDOWN) || (fcn != AD_POWEROFF)) {
1588 		return;
1589 	}
1590 }
1591 
1592 static void
1593 apic_shutdown(int cmd, int fcn)
1594 {
1595 	int restarts, attempts;
1596 	int i;
1597 	uchar_t	byte;
1598 	ulong_t iflag;
1599 
1600 	/* Send NMI to all CPUs except self to do per processor shutdown */
1601 	iflag = intr_clear();
1602 #ifdef	DEBUG
1603 	APIC_AV_PENDING_SET();
1604 #else
1605 	if (apic_mode == LOCAL_APIC)
1606 		APIC_AV_PENDING_SET();
1607 #endif /* DEBUG */
1608 	apic_shutdown_processors = 1;
1609 	apic_reg_ops->apic_write(APIC_INT_CMD1,
1610 	    AV_NMI | AV_LEVEL | AV_SH_ALL_EXCSELF);
1611 
1612 	/* restore cmos shutdown byte before reboot */
1613 	if (apic_cmos_ssb_set) {
1614 		outb(CMOS_ADDR, SSB);
1615 		outb(CMOS_DATA, 0);
1616 	}
1617 
1618 	ioapic_disable_redirection();
1619 
1620 	/*	disable apic mode if imcr present	*/
1621 	if (apic_imcrp) {
1622 		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
1623 		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_PIC);
1624 	}
1625 
1626 	apic_disable_local_apic();
1627 
1628 	intr_restore(iflag);
1629 
1630 	/* remainder of function is for shutdown cases only */
1631 	if (cmd != A_SHUTDOWN)
1632 		return;
1633 
1634 	/*
1635 	 * Switch system back into Legacy-Mode if using ACPI and
1636 	 * not powering-off.  Some BIOSes need to remain in ACPI-mode
1637 	 * for power-off to succeed (Dell Dimension 4600)
1638 	 * Do not disable ACPI while doing fastreboot
1639 	 */
1640 	if (apic_enable_acpi && fcn != AD_POWEROFF && fcn != AD_FASTREBOOT)
1641 		(void) AcpiDisable();
1642 
1643 	if (fcn == AD_FASTREBOOT) {
1644 		apicadr[APIC_INT_CMD1] = AV_ASSERT | AV_RESET |
1645 		    AV_SH_ALL_EXCSELF;
1646 	}
1647 
1648 	/* remainder of function is for shutdown+poweroff case only */
1649 	if (fcn != AD_POWEROFF)
1650 		return;
1651 
1652 	switch (apic_poweroff_method) {
1653 		case APIC_POWEROFF_VIA_RTC:
1654 
1655 			/* select the extended NVRAM bank in the RTC */
1656 			outb(CMOS_ADDR, RTC_REGA);
1657 			byte = inb(CMOS_DATA);
1658 			outb(CMOS_DATA, (byte | EXT_BANK));
1659 
1660 			outb(CMOS_ADDR, PFR_REG);
1661 
1662 			/* for Predator must toggle the PAB bit */
1663 			byte = inb(CMOS_DATA);
1664 
1665 			/*
1666 			 * clear power active bar, wakeup alarm and
1667 			 * kickstart
1668 			 */
1669 			byte &= ~(PAB_CBIT | WF_FLAG | KS_FLAG);
1670 			outb(CMOS_DATA, byte);
1671 
1672 			/* delay before next write */
1673 			drv_usecwait(1000);
1674 
1675 			/* for S40 the following would suffice */
1676 			byte = inb(CMOS_DATA);
1677 
1678 			/* power active bar control bit */
1679 			byte |= PAB_CBIT;
1680 			outb(CMOS_DATA, byte);
1681 
1682 			break;
1683 
1684 		case APIC_POWEROFF_VIA_ASPEN_BMC:
1685 			restarts = 0;
1686 restart_aspen_bmc:
1687 			if (++restarts == 3)
1688 				break;
1689 			attempts = 0;
1690 			do {
1691 				byte = inb(MISMIC_FLAG_REGISTER);
1692 				byte &= MISMIC_BUSY_MASK;
1693 				if (byte != 0) {
1694 					drv_usecwait(1000);
1695 					if (attempts >= 3)
1696 						goto restart_aspen_bmc;
1697 					++attempts;
1698 				}
1699 			} while (byte != 0);
1700 			outb(MISMIC_CNTL_REGISTER, CC_SMS_GET_STATUS);
1701 			byte = inb(MISMIC_FLAG_REGISTER);
1702 			byte |= 0x1;
1703 			outb(MISMIC_FLAG_REGISTER, byte);
1704 			i = 0;
1705 			for (; i < (sizeof (aspen_bmc)/sizeof (aspen_bmc[0]));
1706 			    i++) {
1707 				attempts = 0;
1708 				do {
1709 					byte = inb(MISMIC_FLAG_REGISTER);
1710 					byte &= MISMIC_BUSY_MASK;
1711 					if (byte != 0) {
1712 						drv_usecwait(1000);
1713 						if (attempts >= 3)
1714 							goto restart_aspen_bmc;
1715 						++attempts;
1716 					}
1717 				} while (byte != 0);
1718 				outb(MISMIC_CNTL_REGISTER, aspen_bmc[i].cntl);
1719 				outb(MISMIC_DATA_REGISTER, aspen_bmc[i].data);
1720 				byte = inb(MISMIC_FLAG_REGISTER);
1721 				byte |= 0x1;
1722 				outb(MISMIC_FLAG_REGISTER, byte);
1723 			}
1724 			break;
1725 
1726 		case APIC_POWEROFF_VIA_SITKA_BMC:
1727 			restarts = 0;
1728 restart_sitka_bmc:
1729 			if (++restarts == 3)
1730 				break;
1731 			attempts = 0;
1732 			do {
1733 				byte = inb(SMS_STATUS_REGISTER);
1734 				byte &= SMS_STATE_MASK;
1735 				if ((byte == SMS_READ_STATE) ||
1736 				    (byte == SMS_WRITE_STATE)) {
1737 					drv_usecwait(1000);
1738 					if (attempts >= 3)
1739 						goto restart_sitka_bmc;
1740 					++attempts;
1741 				}
1742 			} while ((byte == SMS_READ_STATE) ||
1743 			    (byte == SMS_WRITE_STATE));
1744 			outb(SMS_COMMAND_REGISTER, SMS_GET_STATUS);
1745 			i = 0;
1746 			for (; i < (sizeof (sitka_bmc)/sizeof (sitka_bmc[0]));
1747 			    i++) {
1748 				attempts = 0;
1749 				do {
1750 					byte = inb(SMS_STATUS_REGISTER);
1751 					byte &= SMS_IBF_MASK;
1752 					if (byte != 0) {
1753 						drv_usecwait(1000);
1754 						if (attempts >= 3)
1755 							goto restart_sitka_bmc;
1756 						++attempts;
1757 					}
1758 				} while (byte != 0);
1759 				outb(sitka_bmc[i].port, sitka_bmc[i].data);
1760 			}
1761 			break;
1762 
1763 		case APIC_POWEROFF_NONE:
1764 
1765 			/* If no APIC direct method, we will try using ACPI */
1766 			if (apic_enable_acpi) {
1767 				if (acpi_poweroff() == 1)
1768 					return;
1769 			} else
1770 				return;
1771 
1772 			break;
1773 	}
1774 	/*
1775 	 * Wait a limited time here for power to go off.
1776 	 * If the power does not go off, then there was a
1777 	 * problem and we should continue to the halt which
1778 	 * prints a message for the user to press a key to
1779 	 * reboot.
1780 	 */
1781 	drv_usecwait(7000000); /* wait seven seconds */
1782 
1783 }
1784 
1785 /*
1786  * Try and disable all interrupts. We just assign interrupts to other
1787  * processors based on policy. If any were bound by user request, we
1788  * let them continue and return failure. We do not bother to check
1789  * for cache affinity while rebinding.
1790  */
1791 
1792 static int
1793 apic_disable_intr(processorid_t cpun)
1794 {
1795 	int bind_cpu = 0, i, hardbound = 0;
1796 	apic_irq_t *irq_ptr;
1797 	ulong_t iflag;
1798 
1799 	iflag = intr_clear();
1800 	lock_set(&apic_ioapic_lock);
1801 
1802 	for (i = 0; i <= APIC_MAX_VECTOR; i++) {
1803 		if (apic_reprogram_info[i].done == B_FALSE) {
1804 			if (apic_reprogram_info[i].bindcpu == cpun) {
1805 				/*
1806 				 * CPU is busy -- it's the target of
1807 				 * a pending reprogramming attempt
1808 				 */
1809 				lock_clear(&apic_ioapic_lock);
1810 				intr_restore(iflag);
1811 				return (PSM_FAILURE);
1812 			}
1813 		}
1814 	}
1815 
1816 	apic_cpus[cpun].aci_status &= ~APIC_CPU_INTR_ENABLE;
1817 
1818 	apic_cpus[cpun].aci_curipl = 0;
1819 
1820 	i = apic_min_device_irq;
1821 	for (; i <= apic_max_device_irq; i++) {
1822 		/*
1823 		 * If there are bound interrupts on this cpu, then
1824 		 * rebind them to other processors.
1825 		 */
1826 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1827 			ASSERT((irq_ptr->airq_temp_cpu == IRQ_UNBOUND) ||
1828 			    (irq_ptr->airq_temp_cpu == IRQ_UNINIT) ||
1829 			    ((irq_ptr->airq_temp_cpu & ~IRQ_USER_BOUND) <
1830 			    apic_nproc));
1831 
1832 			if (irq_ptr->airq_temp_cpu == (cpun | IRQ_USER_BOUND)) {
1833 				hardbound = 1;
1834 				continue;
1835 			}
1836 
1837 			if (irq_ptr->airq_temp_cpu == cpun) {
1838 				do {
1839 					bind_cpu = apic_next_bind_cpu++;
1840 					if (bind_cpu >= apic_nproc) {
1841 						apic_next_bind_cpu = 1;
1842 						bind_cpu = 0;
1843 
1844 					}
1845 				} while (apic_rebind_all(irq_ptr, bind_cpu));
1846 			}
1847 		}
1848 	}
1849 
1850 	lock_clear(&apic_ioapic_lock);
1851 	intr_restore(iflag);
1852 
1853 	if (hardbound) {
1854 		cmn_err(CE_WARN, "Could not disable interrupts on %d"
1855 		    "due to user bound interrupts", cpun);
1856 		return (PSM_FAILURE);
1857 	}
1858 	else
1859 		return (PSM_SUCCESS);
1860 }
1861 
1862 /*
1863  * Bind interrupts to the CPU's local APIC.
1864  * Interrupts should not be bound to a CPU's local APIC until the CPU
1865  * is ready to receive interrupts.
1866  */
1867 static void
1868 apic_enable_intr(processorid_t cpun)
1869 {
1870 	int	i;
1871 	apic_irq_t *irq_ptr;
1872 	ulong_t iflag;
1873 
1874 	iflag = intr_clear();
1875 	lock_set(&apic_ioapic_lock);
1876 
1877 	apic_cpus[cpun].aci_status |= APIC_CPU_INTR_ENABLE;
1878 
1879 	i = apic_min_device_irq;
1880 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
1881 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1882 			if ((irq_ptr->airq_cpu & ~IRQ_USER_BOUND) == cpun) {
1883 				(void) apic_rebind_all(irq_ptr,
1884 				    irq_ptr->airq_cpu);
1885 			}
1886 		}
1887 	}
1888 
1889 	lock_clear(&apic_ioapic_lock);
1890 	intr_restore(iflag);
1891 }
1892 
1893 
1894 /*
1895  * This function will reprogram the timer.
1896  *
1897  * When in oneshot mode the argument is the absolute time in future to
1898  * generate the interrupt at.
1899  *
1900  * When in periodic mode, the argument is the interval at which the
1901  * interrupts should be generated. There is no need to support the periodic
1902  * mode timer change at this time.
1903  */
1904 static void
1905 apic_timer_reprogram(hrtime_t time)
1906 {
1907 	hrtime_t now;
1908 	uint_t ticks;
1909 	int64_t delta;
1910 
1911 	/*
1912 	 * We should be called from high PIL context (CBE_HIGH_PIL),
1913 	 * so kpreempt is disabled.
1914 	 */
1915 
1916 	if (!apic_oneshot) {
1917 		/* time is the interval for periodic mode */
1918 		ticks = APIC_NSECS_TO_TICKS(time);
1919 	} else {
1920 		/* one shot mode */
1921 
1922 		now = gethrtime();
1923 		delta = time - now;
1924 
1925 		if (delta <= 0) {
1926 			/*
1927 			 * requested to generate an interrupt in the past
1928 			 * generate an interrupt as soon as possible
1929 			 */
1930 			ticks = apic_min_timer_ticks;
1931 		} else if (delta > apic_nsec_max) {
1932 			/*
1933 			 * requested to generate an interrupt at a time
1934 			 * further than what we are capable of. Set to max
1935 			 * the hardware can handle
1936 			 */
1937 
1938 			ticks = APIC_MAXVAL;
1939 #ifdef DEBUG
1940 			cmn_err(CE_CONT, "apic_timer_reprogram, request at"
1941 			    "  %lld  too far in future, current time"
1942 			    "  %lld \n", time, now);
1943 #endif
1944 		} else
1945 			ticks = APIC_NSECS_TO_TICKS(delta);
1946 	}
1947 
1948 	if (ticks < apic_min_timer_ticks)
1949 		ticks = apic_min_timer_ticks;
1950 
1951 	apic_reg_ops->apic_write(APIC_INIT_COUNT, ticks);
1952 }
1953 
1954 /*
1955  * This function will enable timer interrupts.
1956  */
1957 static void
1958 apic_timer_enable(void)
1959 {
1960 	/*
1961 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1962 	 * so kpreempt is disabled.
1963 	 */
1964 
1965 	if (!apic_oneshot) {
1966 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1967 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME);
1968 	} else {
1969 		/* one shot */
1970 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1971 		    (apic_clkvect + APIC_BASE_VECT));
1972 	}
1973 }
1974 
1975 /*
1976  * This function will disable timer interrupts.
1977  */
1978 static void
1979 apic_timer_disable(void)
1980 {
1981 	/*
1982 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1983 	 * so kpreempt is disabled.
1984 	 */
1985 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1986 	    (apic_clkvect + APIC_BASE_VECT) | AV_MASK);
1987 }
1988 
1989 
1990 ddi_periodic_t apic_periodic_id;
1991 
1992 /*
1993  * If this module needs a periodic handler for the interrupt distribution, it
1994  * can be added here. The argument to the periodic handler is not currently
1995  * used, but is reserved for future.
1996  */
1997 static void
1998 apic_post_cyclic_setup(void *arg)
1999 {
2000 _NOTE(ARGUNUSED(arg))
2001 	/* cpu_lock is held */
2002 	/* set up a periodic handler for intr redistribution */
2003 
2004 	/*
2005 	 * In peridoc mode intr redistribution processing is done in
2006 	 * apic_intr_enter during clk intr processing
2007 	 */
2008 	if (!apic_oneshot)
2009 		return;
2010 	/*
2011 	 * Register a periodical handler for the redistribution processing.
2012 	 * On X86, CY_LOW_LEVEL is mapped to the level 2 interrupt, so
2013 	 * DDI_IPL_2 should be passed to ddi_periodic_add() here.
2014 	 */
2015 	apic_periodic_id = ddi_periodic_add(
2016 	    (void (*)(void *))apic_redistribute_compute, NULL,
2017 	    apic_redistribute_sample_interval, DDI_IPL_2);
2018 }
2019 
2020 static void
2021 apic_redistribute_compute(void)
2022 {
2023 	int	i, j, max_busy;
2024 
2025 	if (apic_enable_dynamic_migration) {
2026 		if (++apic_nticks == apic_sample_factor_redistribution) {
2027 			/*
2028 			 * Time to call apic_intr_redistribute().
2029 			 * reset apic_nticks. This will cause max_busy
2030 			 * to be calculated below and if it is more than
2031 			 * apic_int_busy, we will do the whole thing
2032 			 */
2033 			apic_nticks = 0;
2034 		}
2035 		max_busy = 0;
2036 		for (i = 0; i < apic_nproc; i++) {
2037 
2038 			/*
2039 			 * Check if curipl is non zero & if ISR is in
2040 			 * progress
2041 			 */
2042 			if (((j = apic_cpus[i].aci_curipl) != 0) &&
2043 			    (apic_cpus[i].aci_ISR_in_progress & (1 << j))) {
2044 
2045 				int	irq;
2046 				apic_cpus[i].aci_busy++;
2047 				irq = apic_cpus[i].aci_current[j];
2048 				apic_irq_table[irq]->airq_busy++;
2049 			}
2050 
2051 			if (!apic_nticks &&
2052 			    (apic_cpus[i].aci_busy > max_busy))
2053 				max_busy = apic_cpus[i].aci_busy;
2054 		}
2055 		if (!apic_nticks) {
2056 			if (max_busy > apic_int_busy_mark) {
2057 			/*
2058 			 * We could make the following check be
2059 			 * skipped > 1 in which case, we get a
2060 			 * redistribution at half the busy mark (due to
2061 			 * double interval). Need to be able to collect
2062 			 * more empirical data to decide if that is a
2063 			 * good strategy. Punt for now.
2064 			 */
2065 				if (apic_skipped_redistribute) {
2066 					apic_cleanup_busy();
2067 					apic_skipped_redistribute = 0;
2068 				} else {
2069 					apic_intr_redistribute();
2070 				}
2071 			} else
2072 				apic_skipped_redistribute++;
2073 		}
2074 	}
2075 }
2076 
2077 
2078 /*
2079  * The following functions are in the platform specific file so that they
2080  * can be different functions depending on whether we are running on
2081  * bare metal or a hypervisor.
2082  */
2083 
2084 /*
2085  * map an apic for memory-mapped access
2086  */
2087 uint32_t *
2088 mapin_apic(uint32_t addr, size_t len, int flags)
2089 {
2090 	/*LINTED: pointer cast may result in improper alignment */
2091 	return ((uint32_t *)psm_map_phys(addr, len, flags));
2092 }
2093 
2094 uint32_t *
2095 mapin_ioapic(uint32_t addr, size_t len, int flags)
2096 {
2097 	return (mapin_apic(addr, len, flags));
2098 }
2099 
2100 /*
2101  * unmap an apic
2102  */
2103 void
2104 mapout_apic(caddr_t addr, size_t len)
2105 {
2106 	psm_unmap_phys(addr, len);
2107 }
2108 
2109 void
2110 mapout_ioapic(caddr_t addr, size_t len)
2111 {
2112 	mapout_apic(addr, len);
2113 }
2114 
2115 /*
2116  * Check to make sure there are enough irq slots
2117  */
2118 int
2119 apic_check_free_irqs(int count)
2120 {
2121 	int i, avail;
2122 
2123 	avail = 0;
2124 	for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
2125 		if ((apic_irq_table[i] == NULL) ||
2126 		    apic_irq_table[i]->airq_mps_intr_index == FREE_INDEX) {
2127 			if (++avail >= count)
2128 				return (PSM_SUCCESS);
2129 		}
2130 	}
2131 	return (PSM_FAILURE);
2132 }
2133 
2134 /*
2135  * This function allocates "count" MSI vector(s) for the given "dip/pri/type"
2136  */
2137 int
2138 apic_alloc_msi_vectors(dev_info_t *dip, int inum, int count, int pri,
2139     int behavior)
2140 {
2141 	int	rcount, i;
2142 	uchar_t	start, irqno;
2143 	uint32_t cpu;
2144 	major_t	major;
2145 	apic_irq_t	*irqptr;
2146 
2147 	DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: dip=0x%p "
2148 	    "inum=0x%x  pri=0x%x count=0x%x behavior=%d\n",
2149 	    (void *)dip, inum, pri, count, behavior));
2150 
2151 	if (count > 1) {
2152 		if (behavior == DDI_INTR_ALLOC_STRICT &&
2153 		    (apic_multi_msi_enable == 0 || count > apic_multi_msi_max))
2154 			return (0);
2155 
2156 		if (apic_multi_msi_enable == 0)
2157 			count = 1;
2158 		else if (count > apic_multi_msi_max)
2159 			count = apic_multi_msi_max;
2160 	}
2161 
2162 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2163 		rcount = count;
2164 	else if (rcount == 0 || (rcount < count &&
2165 	    behavior == DDI_INTR_ALLOC_STRICT))
2166 		return (0);
2167 
2168 	/* if not ISP2, then round it down */
2169 	if (!ISP2(rcount))
2170 		rcount = 1 << (highbit(rcount) - 1);
2171 
2172 	mutex_enter(&airq_mutex);
2173 
2174 	for (start = 0; rcount > 0; rcount >>= 1) {
2175 		if ((start = apic_find_multi_vectors(pri, rcount)) != 0 ||
2176 		    behavior == DDI_INTR_ALLOC_STRICT)
2177 			break;
2178 	}
2179 
2180 	if (start == 0) {
2181 		/* no vector available */
2182 		mutex_exit(&airq_mutex);
2183 		return (0);
2184 	}
2185 
2186 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2187 		/* not enough free irq slots available */
2188 		mutex_exit(&airq_mutex);
2189 		return (0);
2190 	}
2191 
2192 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
2193 	for (i = 0; i < rcount; i++) {
2194 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2195 		    (uchar_t)-1) {
2196 			/*
2197 			 * shouldn't happen because of the
2198 			 * apic_check_free_irqs() check earlier
2199 			 */
2200 			mutex_exit(&airq_mutex);
2201 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
2202 			    "apic_allocate_irq failed\n"));
2203 			return (i);
2204 		}
2205 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2206 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2207 		irqptr = apic_irq_table[irqno];
2208 #ifdef	DEBUG
2209 		if (apic_vector_to_irq[start + i] != APIC_RESV_IRQ)
2210 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
2211 			    "apic_vector_to_irq is not APIC_RESV_IRQ\n"));
2212 #endif
2213 		apic_vector_to_irq[start + i] = (uchar_t)irqno;
2214 
2215 		irqptr->airq_vector = (uchar_t)(start + i);
2216 		irqptr->airq_ioapicindex = (uchar_t)inum;	/* start */
2217 		irqptr->airq_intin_no = (uchar_t)rcount;
2218 		irqptr->airq_ipl = pri;
2219 		irqptr->airq_vector = start + i;
2220 		irqptr->airq_origirq = (uchar_t)(inum + i);
2221 		irqptr->airq_share_id = 0;
2222 		irqptr->airq_mps_intr_index = MSI_INDEX;
2223 		irqptr->airq_dip = dip;
2224 		irqptr->airq_major = major;
2225 		if (i == 0) /* they all bound to the same cpu */
2226 			cpu = irqptr->airq_cpu = apic_bind_intr(dip, irqno,
2227 			    0xff, 0xff);
2228 		else
2229 			irqptr->airq_cpu = cpu;
2230 		DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: irq=0x%x "
2231 		    "dip=0x%p vector=0x%x origirq=0x%x pri=0x%x\n", irqno,
2232 		    (void *)irqptr->airq_dip, irqptr->airq_vector,
2233 		    irqptr->airq_origirq, pri));
2234 	}
2235 	mutex_exit(&airq_mutex);
2236 	return (rcount);
2237 }
2238 
2239 /*
2240  * This function allocates "count" MSI-X vector(s) for the given "dip/pri/type"
2241  */
2242 int
2243 apic_alloc_msix_vectors(dev_info_t *dip, int inum, int count, int pri,
2244     int behavior)
2245 {
2246 	int	rcount, i;
2247 	major_t	major;
2248 
2249 	if (count > 1) {
2250 		if (behavior == DDI_INTR_ALLOC_STRICT) {
2251 			if (count > apic_msix_max)
2252 				return (0);
2253 		} else if (count > apic_msix_max)
2254 			count = apic_msix_max;
2255 	}
2256 
2257 	mutex_enter(&airq_mutex);
2258 
2259 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2260 		rcount = count;
2261 	else if (rcount == 0 || (rcount < count &&
2262 	    behavior == DDI_INTR_ALLOC_STRICT)) {
2263 		rcount = 0;
2264 		goto out;
2265 	}
2266 
2267 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2268 		/* not enough free irq slots available */
2269 		rcount = 0;
2270 		goto out;
2271 	}
2272 
2273 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
2274 	for (i = 0; i < rcount; i++) {
2275 		uchar_t	vector, irqno;
2276 		apic_irq_t	*irqptr;
2277 
2278 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2279 		    (uchar_t)-1) {
2280 			/*
2281 			 * shouldn't happen because of the
2282 			 * apic_check_free_irqs() check earlier
2283 			 */
2284 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2285 			    "apic_allocate_irq failed\n"));
2286 			rcount = i;
2287 			goto out;
2288 		}
2289 		if ((vector = apic_allocate_vector(pri, irqno, 1)) == 0) {
2290 			/*
2291 			 * shouldn't happen because of the
2292 			 * apic_navail_vector() call earlier
2293 			 */
2294 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2295 			    "apic_allocate_vector failed\n"));
2296 			rcount = i;
2297 			goto out;
2298 		}
2299 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2300 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2301 		irqptr = apic_irq_table[irqno];
2302 		irqptr->airq_vector = (uchar_t)vector;
2303 		irqptr->airq_ipl = pri;
2304 		irqptr->airq_origirq = (uchar_t)(inum + i);
2305 		irqptr->airq_share_id = 0;
2306 		irqptr->airq_mps_intr_index = MSIX_INDEX;
2307 		irqptr->airq_dip = dip;
2308 		irqptr->airq_major = major;
2309 		irqptr->airq_cpu = apic_bind_intr(dip, irqno, 0xff, 0xff);
2310 	}
2311 out:
2312 	mutex_exit(&airq_mutex);
2313 	return (rcount);
2314 }
2315 
2316 /*
2317  * Allocate a free vector for irq at ipl. Takes care of merging of multiple
2318  * IPLs into a single APIC level as well as stretching some IPLs onto multiple
2319  * levels. APIC_HI_PRI_VECTS interrupts are reserved for high priority
2320  * requests and allocated only when pri is set.
2321  */
2322 uchar_t
2323 apic_allocate_vector(int ipl, int irq, int pri)
2324 {
2325 	int	lowest, highest, i;
2326 
2327 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
2328 	lowest = apic_ipltopri[ipl - 1] + APIC_VECTOR_PER_IPL;
2329 
2330 	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
2331 		lowest -= APIC_VECTOR_PER_IPL;
2332 
2333 #ifdef	DEBUG
2334 	if (apic_restrict_vector)	/* for testing shared interrupt logic */
2335 		highest = lowest + apic_restrict_vector + APIC_HI_PRI_VECTS;
2336 #endif /* DEBUG */
2337 	if (pri == 0)
2338 		highest -= APIC_HI_PRI_VECTS;
2339 
2340 	for (i = lowest; i < highest; i++) {
2341 		if (APIC_CHECK_RESERVE_VECTORS(i))
2342 			continue;
2343 		if (apic_vector_to_irq[i] == APIC_RESV_IRQ) {
2344 			apic_vector_to_irq[i] = (uchar_t)irq;
2345 			return (i);
2346 		}
2347 	}
2348 
2349 	return (0);
2350 }
2351 
2352 /* Mark vector as not being used by any irq */
2353 void
2354 apic_free_vector(uchar_t vector)
2355 {
2356 	apic_vector_to_irq[vector] = APIC_RESV_IRQ;
2357 }
2358 
2359 uint32_t
2360 ioapic_read(int ioapic_ix, uint32_t reg)
2361 {
2362 	volatile uint32_t *ioapic;
2363 
2364 	ioapic = apicioadr[ioapic_ix];
2365 	ioapic[APIC_IO_REG] = reg;
2366 	return (ioapic[APIC_IO_DATA]);
2367 }
2368 
2369 void
2370 ioapic_write(int ioapic_ix, uint32_t reg, uint32_t value)
2371 {
2372 	volatile uint32_t *ioapic;
2373 
2374 	ioapic = apicioadr[ioapic_ix];
2375 	ioapic[APIC_IO_REG] = reg;
2376 	ioapic[APIC_IO_DATA] = value;
2377 }
2378 
2379 void
2380 ioapic_write_eoi(int ioapic_ix, uint32_t value)
2381 {
2382 	volatile uint32_t *ioapic;
2383 
2384 	ioapic = apicioadr[ioapic_ix];
2385 	ioapic[APIC_IO_EOI] = value;
2386 }
2387 
2388 static processorid_t
2389 apic_find_cpu(int flag)
2390 {
2391 	processorid_t acid = 0;
2392 	int i;
2393 
2394 	/* Find the first CPU with the passed-in flag set */
2395 	for (i = 0; i < apic_nproc; i++) {
2396 		if (apic_cpus[i].aci_status & flag) {
2397 			acid = i;
2398 			break;
2399 		}
2400 	}
2401 
2402 	ASSERT((apic_cpus[acid].aci_status & flag) != 0);
2403 	return (acid);
2404 }
2405 
2406 /*
2407  * Call rebind to do the actual programming.
2408  * Must be called with interrupts disabled and apic_ioapic_lock held
2409  * 'p' is polymorphic -- if this function is called to process a deferred
2410  * reprogramming, p is of type 'struct ioapic_reprogram_data *', from which
2411  * the irq pointer is retrieved.  If not doing deferred reprogramming,
2412  * p is of the type 'apic_irq_t *'.
2413  *
2414  * apic_ioapic_lock must be held across this call, as it protects apic_rebind
2415  * and it protects apic_find_cpu() from a race in which a CPU can be taken
2416  * offline after a cpu is selected, but before apic_rebind is called to
2417  * bind interrupts to it.
2418  */
2419 int
2420 apic_setup_io_intr(void *p, int irq, boolean_t deferred)
2421 {
2422 	apic_irq_t *irqptr;
2423 	struct ioapic_reprogram_data *drep = NULL;
2424 	int rv;
2425 
2426 	if (deferred) {
2427 		drep = (struct ioapic_reprogram_data *)p;
2428 		ASSERT(drep != NULL);
2429 		irqptr = drep->irqp;
2430 	} else
2431 		irqptr = (apic_irq_t *)p;
2432 
2433 	ASSERT(irqptr != NULL);
2434 
2435 	rv = apic_rebind(irqptr, apic_irq_table[irq]->airq_cpu, drep);
2436 	if (rv) {
2437 		/*
2438 		 * CPU is not up or interrupts are disabled. Fall back to
2439 		 * the first available CPU
2440 		 */
2441 		rv = apic_rebind(irqptr, apic_find_cpu(APIC_CPU_INTR_ENABLE),
2442 		    drep);
2443 	}
2444 
2445 	return (rv);
2446 }
2447 
2448 
2449 uchar_t
2450 apic_modify_vector(uchar_t vector, int irq)
2451 {
2452 	apic_vector_to_irq[vector] = (uchar_t)irq;
2453 	return (vector);
2454 }
2455 
2456 char *
2457 apic_get_apic_type()
2458 {
2459 	return (apic_psm_info.p_mach_idstring);
2460 }
2461 
2462 void
2463 x2apic_update_psm()
2464 {
2465 	struct psm_ops *pops = &apic_ops;
2466 
2467 	ASSERT(pops != NULL);
2468 
2469 	pops->psm_send_ipi =  x2apic_send_ipi;
2470 	pops->psm_intr_exit = x2apic_intr_exit;
2471 	pops->psm_setspl = x2apic_setspl;
2472 
2473 	/* global functions */
2474 	send_dirintf = pops->psm_send_ipi;
2475 }
2476