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