xref: /titanic_50/usr/src/uts/i86pc/io/pcplusmp/apic.c (revision 0e7515250c8395f368aa45fb9acae7c4f8f8b786)
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 	 * initialize interrupt remapping before apic
443 	 * hardware initialization
444 	 */
445 	apic_intrr_init(apic_mode);
446 }
447 
448 /*
449  * handler for APIC Error interrupt. Just print a warning and continue
450  */
451 static int
452 apic_error_intr()
453 {
454 	uint_t	error0, error1, error;
455 	uint_t	i;
456 
457 	/*
458 	 * We need to write before read as per 7.4.17 of system prog manual.
459 	 * We do both and or the results to be safe
460 	 */
461 	error0 = apic_reg_ops->apic_read(APIC_ERROR_STATUS);
462 	apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
463 	error1 = apic_reg_ops->apic_read(APIC_ERROR_STATUS);
464 	error = error0 | error1;
465 
466 	/*
467 	 * Clear the APIC error status (do this on all cpus that enter here)
468 	 * (two writes are required due to the semantics of accessing the
469 	 * error status register.)
470 	 */
471 	apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
472 	apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
473 
474 	/*
475 	 * Prevent more than 1 CPU from handling error interrupt causing
476 	 * double printing (interleave of characters from multiple
477 	 * CPU's when using prom_printf)
478 	 */
479 	if (lock_try(&apic_error_lock) == 0)
480 		return (error ? DDI_INTR_CLAIMED : DDI_INTR_UNCLAIMED);
481 	if (error) {
482 #if	DEBUG
483 		if (apic_debug)
484 			debug_enter("pcplusmp: APIC Error interrupt received");
485 #endif /* DEBUG */
486 		if (apic_panic_on_apic_error)
487 			cmn_err(CE_PANIC,
488 			    "APIC Error interrupt on CPU %d. Status = %x\n",
489 			    psm_get_cpu_id(), error);
490 		else {
491 			if ((error & ~APIC_CS_ERRORS) == 0) {
492 				/* cksum error only */
493 				apic_error |= APIC_ERR_APIC_ERROR;
494 				apic_apic_error |= error;
495 				apic_num_apic_errors++;
496 				apic_num_cksum_errors++;
497 			} else {
498 				/*
499 				 * prom_printf is the best shot we have of
500 				 * something which is problem free from
501 				 * high level/NMI type of interrupts
502 				 */
503 				prom_printf("APIC Error interrupt on CPU %d. "
504 				    "Status 0 = %x, Status 1 = %x\n",
505 				    psm_get_cpu_id(), error0, error1);
506 				apic_error |= APIC_ERR_APIC_ERROR;
507 				apic_apic_error |= error;
508 				apic_num_apic_errors++;
509 				for (i = 0; i < apic_error_display_delay; i++) {
510 					tenmicrosec();
511 				}
512 				/*
513 				 * provide more delay next time limited to
514 				 * roughly 1 clock tick time
515 				 */
516 				if (apic_error_display_delay < 500)
517 					apic_error_display_delay *= 2;
518 			}
519 		}
520 		lock_clear(&apic_error_lock);
521 		return (DDI_INTR_CLAIMED);
522 	} else {
523 		lock_clear(&apic_error_lock);
524 		return (DDI_INTR_UNCLAIMED);
525 	}
526 	/* NOTREACHED */
527 }
528 
529 /*
530  * Turn off the mask bit in the performance counter Local Vector Table entry.
531  */
532 static void
533 apic_cpcovf_mask_clear(void)
534 {
535 	apic_reg_ops->apic_write(APIC_PCINT_VECT,
536 	    (apic_reg_ops->apic_read(APIC_PCINT_VECT) & ~APIC_LVT_MASK));
537 }
538 
539 /*ARGSUSED*/
540 static int
541 apic_cmci_enable(xc_arg_t arg1, xc_arg_t arg2, xc_arg_t arg3)
542 {
543 	apic_reg_ops->apic_write(APIC_CMCI_VECT, apic_cmci_vect);
544 	return (0);
545 }
546 
547 /*ARGSUSED*/
548 static int
549 apic_cmci_disable(xc_arg_t arg1, xc_arg_t arg2, xc_arg_t arg3)
550 {
551 	apic_reg_ops->apic_write(APIC_CMCI_VECT, apic_cmci_vect | AV_MASK);
552 	return (0);
553 }
554 
555 /*ARGSUSED*/
556 static int
557 cmci_cpu_setup(cpu_setup_t what, int cpuid, void *arg)
558 {
559 	cpuset_t	cpu_set;
560 
561 	CPUSET_ONLY(cpu_set, cpuid);
562 
563 	switch (what) {
564 		case CPU_ON:
565 			xc_call(NULL, NULL, NULL, X_CALL_HIPRI, cpu_set,
566 			    (xc_func_t)apic_cmci_enable);
567 			break;
568 
569 		case CPU_OFF:
570 			xc_call(NULL, NULL, NULL, X_CALL_HIPRI, cpu_set,
571 			    (xc_func_t)apic_cmci_disable);
572 			break;
573 
574 		default:
575 			break;
576 	}
577 
578 	return (0);
579 }
580 
581 static void
582 apic_init_intr()
583 {
584 	processorid_t	cpun = psm_get_cpu_id();
585 	uint_t nlvt;
586 	uint32_t svr = AV_UNIT_ENABLE | APIC_SPUR_INTR;
587 
588 	apic_reg_ops->apic_write_task_reg(APIC_MASK_ALL);
589 
590 	if (apic_mode == LOCAL_APIC) {
591 		/*
592 		 * We are running APIC in MMIO mode.
593 		 */
594 		if (apic_flat_model) {
595 			apic_reg_ops->apic_write(APIC_FORMAT_REG,
596 			    APIC_FLAT_MODEL);
597 		} else {
598 			apic_reg_ops->apic_write(APIC_FORMAT_REG,
599 			    APIC_CLUSTER_MODEL);
600 		}
601 
602 		apic_reg_ops->apic_write(APIC_DEST_REG,
603 		    AV_HIGH_ORDER >> cpun);
604 	}
605 
606 	if (apic_direct_EOI) {
607 		/*
608 		 * Set 12th bit in Spurious Interrupt Vector
609 		 * Register to support level triggered interrupt
610 		 * directed EOI.
611 		 */
612 		svr |= (0x1 << APIC_SVR);
613 	}
614 
615 	/* need to enable APIC before unmasking NMI */
616 	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, svr);
617 
618 	/*
619 	 * Presence of an invalid vector with delivery mode AV_FIXED can
620 	 * cause an error interrupt, even if the entry is masked...so
621 	 * write a valid vector to LVT entries along with the mask bit
622 	 */
623 
624 	/* All APICs have timer and LINT0/1 */
625 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, AV_MASK|APIC_RESV_IRQ);
626 	apic_reg_ops->apic_write(APIC_INT_VECT0, AV_MASK|APIC_RESV_IRQ);
627 	apic_reg_ops->apic_write(APIC_INT_VECT1, AV_NMI);	/* enable NMI */
628 
629 	/*
630 	 * On integrated APICs, the number of LVT entries is
631 	 * 'Max LVT entry' + 1; on 82489DX's (non-integrated
632 	 * APICs), nlvt is "3" (LINT0, LINT1, and timer)
633 	 */
634 
635 	if (apic_cpus[cpun].aci_local_ver < APIC_INTEGRATED_VERS) {
636 		nlvt = 3;
637 	} else {
638 		nlvt = ((apic_reg_ops->apic_read(APIC_VERS_REG) >> 16) &
639 		    0xFF) + 1;
640 	}
641 
642 	if (nlvt >= 5) {
643 		/* Enable performance counter overflow interrupt */
644 
645 		if ((x86_feature & X86_MSR) != X86_MSR)
646 			apic_enable_cpcovf_intr = 0;
647 		if (apic_enable_cpcovf_intr) {
648 			if (apic_cpcovf_vect == 0) {
649 				int ipl = APIC_PCINT_IPL;
650 				int irq = apic_get_ipivect(ipl, -1);
651 
652 				ASSERT(irq != -1);
653 				apic_cpcovf_vect =
654 				    apic_irq_table[irq]->airq_vector;
655 				ASSERT(apic_cpcovf_vect);
656 				(void) add_avintr(NULL, ipl,
657 				    (avfunc)kcpc_hw_overflow_intr,
658 				    "apic pcint", irq, NULL, NULL, NULL, NULL);
659 				kcpc_hw_overflow_intr_installed = 1;
660 				kcpc_hw_enable_cpc_intr =
661 				    apic_cpcovf_mask_clear;
662 			}
663 			apic_reg_ops->apic_write(APIC_PCINT_VECT,
664 			    apic_cpcovf_vect);
665 		}
666 	}
667 
668 	if (nlvt >= 6) {
669 		/* Only mask TM intr if the BIOS apparently doesn't use it */
670 
671 		uint32_t lvtval;
672 
673 		lvtval = apic_reg_ops->apic_read(APIC_THERM_VECT);
674 		if (((lvtval & AV_MASK) == AV_MASK) ||
675 		    ((lvtval & AV_DELIV_MODE) != AV_SMI)) {
676 			apic_reg_ops->apic_write(APIC_THERM_VECT,
677 			    AV_MASK|APIC_RESV_IRQ);
678 		}
679 	}
680 
681 	/* Enable error interrupt */
682 
683 	if (nlvt >= 4 && apic_enable_error_intr) {
684 		if (apic_errvect == 0) {
685 			int ipl = 0xf;	/* get highest priority intr */
686 			int irq = apic_get_ipivect(ipl, -1);
687 
688 			ASSERT(irq != -1);
689 			apic_errvect = apic_irq_table[irq]->airq_vector;
690 			ASSERT(apic_errvect);
691 			/*
692 			 * Not PSMI compliant, but we are going to merge
693 			 * with ON anyway
694 			 */
695 			(void) add_avintr((void *)NULL, ipl,
696 			    (avfunc)apic_error_intr, "apic error intr",
697 			    irq, NULL, NULL, NULL, NULL);
698 		}
699 		apic_reg_ops->apic_write(APIC_ERR_VECT, apic_errvect);
700 		apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
701 		apic_reg_ops->apic_write(APIC_ERROR_STATUS, 0);
702 	}
703 
704 	/* Enable CMCI interrupt */
705 	if (cmi_enable_cmci) {
706 
707 		mutex_enter(&cmci_cpu_setup_lock);
708 		if (cmci_cpu_setup_registered == 0) {
709 			mutex_enter(&cpu_lock);
710 			register_cpu_setup_func(cmci_cpu_setup, NULL);
711 			mutex_exit(&cpu_lock);
712 			cmci_cpu_setup_registered = 1;
713 		}
714 		mutex_exit(&cmci_cpu_setup_lock);
715 
716 		if (apic_cmci_vect == 0) {
717 			int ipl = 0x2;
718 			int irq = apic_get_ipivect(ipl, -1);
719 
720 			ASSERT(irq != -1);
721 			apic_cmci_vect = apic_irq_table[irq]->airq_vector;
722 			ASSERT(apic_cmci_vect);
723 
724 			(void) add_avintr(NULL, ipl,
725 			    (avfunc)cmi_cmci_trap,
726 			    "apic cmci intr", irq, NULL, NULL, NULL, NULL);
727 		}
728 		apic_reg_ops->apic_write(APIC_CMCI_VECT, apic_cmci_vect);
729 	}
730 }
731 
732 static void
733 apic_disable_local_apic()
734 {
735 	apic_reg_ops->apic_write_task_reg(APIC_MASK_ALL);
736 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER, AV_MASK);
737 
738 	/* local intr reg 0 */
739 	apic_reg_ops->apic_write(APIC_INT_VECT0, AV_MASK);
740 
741 	/* disable NMI */
742 	apic_reg_ops->apic_write(APIC_INT_VECT1, AV_MASK);
743 
744 	/* and error interrupt */
745 	apic_reg_ops->apic_write(APIC_ERR_VECT, AV_MASK);
746 
747 	/* and perf counter intr */
748 	apic_reg_ops->apic_write(APIC_PCINT_VECT, AV_MASK);
749 
750 	apic_reg_ops->apic_write(APIC_SPUR_INT_REG, APIC_SPUR_INTR);
751 }
752 
753 static void
754 apic_picinit(void)
755 {
756 	int i, j;
757 	uint_t isr;
758 	uint32_t ver;
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 #ifdef	DEBUG
1022 	APIC_DEBUG_BUF_PUT(vector);
1023 	APIC_DEBUG_BUF_PUT(irq);
1024 	APIC_DEBUG_BUF_PUT(nipl);
1025 	APIC_DEBUG_BUF_PUT(psm_get_cpu_id());
1026 	if ((apic_stretch_interrupts) && (apic_stretch_ISR & (1 << nipl)))
1027 		drv_usecwait(apic_stretch_interrupts);
1028 
1029 	if (apic_break_on_cpu == psm_get_cpu_id())
1030 		apic_break();
1031 #endif /* DEBUG */
1032 	return (nipl);
1033 }
1034 
1035 /*
1036  * This macro is a common code used by MMIO local apic and X2APIC
1037  * local apic.
1038  */
1039 #define	APIC_INTR_EXIT() \
1040 { \
1041 	cpu_infop = &apic_cpus[psm_get_cpu_id()]; \
1042 	if (apic_level_intr[irq]) \
1043 		apic_reg_ops->apic_send_eoi(irq); \
1044 	cpu_infop->aci_curipl = (uchar_t)prev_ipl; \
1045 	/* ISR above current pri could not be in progress */ \
1046 	cpu_infop->aci_ISR_in_progress &= (2 << prev_ipl) - 1; \
1047 }
1048 
1049 /*
1050  * Any changes made to this function must also change X2APIC
1051  * version of intr_exit.
1052  */
1053 void
1054 apic_intr_exit(int prev_ipl, int irq)
1055 {
1056 	apic_cpus_info_t *cpu_infop;
1057 
1058 #if defined(__amd64)
1059 	setcr8((ulong_t)apic_cr8pri[prev_ipl]);
1060 #else
1061 	apicadr[APIC_TASK_REG] = apic_ipltopri[prev_ipl];
1062 #endif
1063 
1064 	APIC_INTR_EXIT();
1065 }
1066 
1067 /*
1068  * Same as apic_intr_exit() except it uses MSR rather than MMIO
1069  * to access local apic registers.
1070  */
1071 void
1072 x2apic_intr_exit(int prev_ipl, int irq)
1073 {
1074 	apic_cpus_info_t *cpu_infop;
1075 
1076 	X2APIC_WRITE(APIC_TASK_REG, apic_ipltopri[prev_ipl]);
1077 	APIC_INTR_EXIT();
1078 }
1079 
1080 intr_exit_fn_t
1081 psm_intr_exit_fn(void)
1082 {
1083 	if (apic_mode == LOCAL_X2APIC)
1084 		return (x2apic_intr_exit);
1085 
1086 	return (apic_intr_exit);
1087 }
1088 
1089 /*
1090  * Mask all interrupts below or equal to the given IPL.
1091  * Any changes made to this function must also change X2APIC
1092  * version of setspl.
1093  */
1094 static void
1095 apic_setspl(int ipl)
1096 {
1097 #if defined(__amd64)
1098 	setcr8((ulong_t)apic_cr8pri[ipl]);
1099 #else
1100 	apicadr[APIC_TASK_REG] = apic_ipltopri[ipl];
1101 #endif
1102 
1103 	/* interrupts at ipl above this cannot be in progress */
1104 	apic_cpus[psm_get_cpu_id()].aci_ISR_in_progress &= (2 << ipl) - 1;
1105 	/*
1106 	 * this is a patch fix for the ALR QSMP P5 machine, so that interrupts
1107 	 * have enough time to come in before the priority is raised again
1108 	 * during the idle() loop.
1109 	 */
1110 	if (apic_setspl_delay)
1111 		(void) apic_reg_ops->apic_get_pri();
1112 }
1113 
1114 /*
1115  * X2APIC version of setspl.
1116  * Mask all interrupts below or equal to the given IPL
1117  */
1118 static void
1119 x2apic_setspl(int ipl)
1120 {
1121 	X2APIC_WRITE(APIC_TASK_REG, apic_ipltopri[ipl]);
1122 
1123 	/* interrupts at ipl above this cannot be in progress */
1124 	apic_cpus[psm_get_cpu_id()].aci_ISR_in_progress &= (2 << ipl) - 1;
1125 }
1126 
1127 /*
1128  * generates an interprocessor interrupt to another CPU. Any changes made to
1129  * this routine must be accompanied by similar changes to
1130  * apic_common_send_ipi().
1131  */
1132 static void
1133 apic_send_ipi(int cpun, int ipl)
1134 {
1135 	int vector;
1136 	ulong_t flag;
1137 
1138 	vector = apic_resv_vector[ipl];
1139 
1140 	ASSERT((vector >= APIC_BASE_VECT) && (vector <= APIC_SPUR_INTR));
1141 
1142 	flag = intr_clear();
1143 
1144 	APIC_AV_PENDING_SET();
1145 
1146 	apic_reg_ops->apic_write_int_cmd(apic_cpus[cpun].aci_local_id,
1147 	    vector);
1148 
1149 	intr_restore(flag);
1150 }
1151 
1152 
1153 /*ARGSUSED*/
1154 static void
1155 apic_set_idlecpu(processorid_t cpun)
1156 {
1157 }
1158 
1159 /*ARGSUSED*/
1160 static void
1161 apic_unset_idlecpu(processorid_t cpun)
1162 {
1163 }
1164 
1165 
1166 void
1167 apic_ret()
1168 {
1169 }
1170 
1171 /*
1172  * If apic_coarse_time == 1, then apic_gettime() is used instead of
1173  * apic_gethrtime().  This is used for performance instead of accuracy.
1174  */
1175 
1176 static hrtime_t
1177 apic_gettime()
1178 {
1179 	int old_hrtime_stamp;
1180 	hrtime_t temp;
1181 
1182 	/*
1183 	 * In one-shot mode, we do not keep time, so if anyone
1184 	 * calls psm_gettime() directly, we vector over to
1185 	 * gethrtime().
1186 	 * one-shot mode MUST NOT be enabled if this psm is the source of
1187 	 * hrtime.
1188 	 */
1189 
1190 	if (apic_oneshot)
1191 		return (gethrtime());
1192 
1193 
1194 gettime_again:
1195 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
1196 		apic_ret();
1197 
1198 	temp = apic_nsec_since_boot;
1199 
1200 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
1201 		goto gettime_again;
1202 	}
1203 	return (temp);
1204 }
1205 
1206 /*
1207  * Here we return the number of nanoseconds since booting.  Note every
1208  * clock interrupt increments apic_nsec_since_boot by the appropriate
1209  * amount.
1210  */
1211 static hrtime_t
1212 apic_gethrtime()
1213 {
1214 	int curr_timeval, countval, elapsed_ticks;
1215 	int old_hrtime_stamp, status;
1216 	hrtime_t temp;
1217 	uint32_t cpun;
1218 	ulong_t oflags;
1219 
1220 	/*
1221 	 * In one-shot mode, we do not keep time, so if anyone
1222 	 * calls psm_gethrtime() directly, we vector over to
1223 	 * gethrtime().
1224 	 * one-shot mode MUST NOT be enabled if this psm is the source of
1225 	 * hrtime.
1226 	 */
1227 
1228 	if (apic_oneshot)
1229 		return (gethrtime());
1230 
1231 	oflags = intr_clear();	/* prevent migration */
1232 
1233 	cpun = apic_reg_ops->apic_read(APIC_LID_REG);
1234 	if (apic_mode == LOCAL_APIC)
1235 		cpun >>= APIC_ID_BIT_OFFSET;
1236 
1237 	lock_set(&apic_gethrtime_lock);
1238 
1239 gethrtime_again:
1240 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
1241 		apic_ret();
1242 
1243 	/*
1244 	 * Check to see which CPU we are on.  Note the time is kept on
1245 	 * the local APIC of CPU 0.  If on CPU 0, simply read the current
1246 	 * counter.  If on another CPU, issue a remote read command to CPU 0.
1247 	 */
1248 	if (cpun == apic_cpus[0].aci_local_id) {
1249 		countval = apic_reg_ops->apic_read(APIC_CURR_COUNT);
1250 	} else {
1251 #ifdef	DEBUG
1252 		APIC_AV_PENDING_SET();
1253 #else
1254 		if (apic_mode == LOCAL_APIC)
1255 			APIC_AV_PENDING_SET();
1256 #endif /* DEBUG */
1257 
1258 		apic_reg_ops->apic_write_int_cmd(
1259 		    apic_cpus[0].aci_local_id, APIC_CURR_ADD | AV_REMOTE);
1260 
1261 		while ((status = apic_reg_ops->apic_read(APIC_INT_CMD1))
1262 		    & AV_READ_PENDING) {
1263 			apic_ret();
1264 		}
1265 
1266 		if (status & AV_REMOTE_STATUS)	/* 1 = valid */
1267 			countval = apic_reg_ops->apic_read(APIC_REMOTE_READ);
1268 		else {	/* 0 = invalid */
1269 			apic_remote_hrterr++;
1270 			/*
1271 			 * return last hrtime right now, will need more
1272 			 * testing if change to retry
1273 			 */
1274 			temp = apic_last_hrtime;
1275 
1276 			lock_clear(&apic_gethrtime_lock);
1277 
1278 			intr_restore(oflags);
1279 
1280 			return (temp);
1281 		}
1282 	}
1283 	if (countval > last_count_read)
1284 		countval = 0;
1285 	else
1286 		last_count_read = countval;
1287 
1288 	elapsed_ticks = apic_hertz_count - countval;
1289 
1290 	curr_timeval = APIC_TICKS_TO_NSECS(elapsed_ticks);
1291 	temp = apic_nsec_since_boot + curr_timeval;
1292 
1293 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
1294 		/* we might have clobbered last_count_read. Restore it */
1295 		last_count_read = apic_hertz_count;
1296 		goto gethrtime_again;
1297 	}
1298 
1299 	if (temp < apic_last_hrtime) {
1300 		/* return last hrtime if error occurs */
1301 		apic_hrtime_error++;
1302 		temp = apic_last_hrtime;
1303 	}
1304 	else
1305 		apic_last_hrtime = temp;
1306 
1307 	lock_clear(&apic_gethrtime_lock);
1308 	intr_restore(oflags);
1309 
1310 	return (temp);
1311 }
1312 
1313 /* apic NMI handler */
1314 /*ARGSUSED*/
1315 static void
1316 apic_nmi_intr(caddr_t arg, struct regs *rp)
1317 {
1318 	if (apic_shutdown_processors) {
1319 		apic_disable_local_apic();
1320 		return;
1321 	}
1322 
1323 	apic_error |= APIC_ERR_NMI;
1324 
1325 	if (!lock_try(&apic_nmi_lock))
1326 		return;
1327 	apic_num_nmis++;
1328 
1329 	if (apic_kmdb_on_nmi && psm_debugger()) {
1330 		debug_enter("NMI received: entering kmdb\n");
1331 	} else if (apic_panic_on_nmi) {
1332 		/* Keep panic from entering kmdb. */
1333 		nopanicdebug = 1;
1334 		panic("NMI received\n");
1335 	} else {
1336 		/*
1337 		 * prom_printf is the best shot we have of something which is
1338 		 * problem free from high level/NMI type of interrupts
1339 		 */
1340 		prom_printf("NMI received\n");
1341 	}
1342 
1343 	lock_clear(&apic_nmi_lock);
1344 }
1345 
1346 /*ARGSUSED*/
1347 static int
1348 apic_addspl(int irqno, int ipl, int min_ipl, int max_ipl)
1349 {
1350 	return (apic_addspl_common(irqno, ipl, min_ipl, max_ipl));
1351 }
1352 
1353 static int
1354 apic_delspl(int irqno, int ipl, int min_ipl, int max_ipl)
1355 {
1356 	return (apic_delspl_common(irqno, ipl, min_ipl,  max_ipl));
1357 }
1358 
1359 static int
1360 apic_post_cpu_start()
1361 {
1362 	int cpun;
1363 	static int cpus_started = 1;
1364 	struct psm_ops *pops = &apic_ops;
1365 
1366 	/* We know this CPU + BSP  started successfully. */
1367 	cpus_started++;
1368 
1369 	/*
1370 	 * On BSP we would have enabled X2APIC, if supported by processor,
1371 	 * in acpi_probe(), but on AP we do it here.
1372 	 *
1373 	 * We enable X2APIC mode only if BSP is running in X2APIC & the
1374 	 * local APIC mode of the current CPU is MMIO (xAPIC).
1375 	 */
1376 	if (apic_mode == LOCAL_X2APIC && apic_detect_x2apic() &&
1377 	    apic_local_mode() == LOCAL_APIC) {
1378 		apic_enable_x2apic();
1379 	}
1380 
1381 	/*
1382 	 * We change psm_send_ipi and send_dirintf only if Solaris
1383 	 * is booted in kmdb & the current CPU is the last CPU being
1384 	 * brought up. We don't need to do anything if Solaris is running
1385 	 * in MMIO mode (xAPIC).
1386 	 */
1387 	if ((boothowto & RB_DEBUG) &&
1388 	    (cpus_started == boot_ncpus || cpus_started == apic_nproc) &&
1389 	    apic_mode == LOCAL_X2APIC) {
1390 		/*
1391 		 * We no longer need help from apic_common_send_ipi()
1392 		 * since we will not start any more CPUs.
1393 		 *
1394 		 * We will need to revisit this if we start supporting
1395 		 * hot-plugging of CPUs.
1396 		 */
1397 		pops->psm_send_ipi = x2apic_send_ipi;
1398 		send_dirintf = pops->psm_send_ipi;
1399 	}
1400 
1401 	splx(ipltospl(LOCK_LEVEL));
1402 	apic_init_intr();
1403 
1404 	/*
1405 	 * since some systems don't enable the internal cache on the non-boot
1406 	 * cpus, so we have to enable them here
1407 	 */
1408 	setcr0(getcr0() & ~(CR0_CD | CR0_NW));
1409 
1410 #ifdef	DEBUG
1411 	APIC_AV_PENDING_SET();
1412 #else
1413 	if (apic_mode == LOCAL_APIC)
1414 		APIC_AV_PENDING_SET();
1415 #endif	/* DEBUG */
1416 
1417 	/*
1418 	 * We may be booting, or resuming from suspend; aci_status will
1419 	 * be APIC_CPU_INTR_ENABLE if coming from suspend, so we add the
1420 	 * APIC_CPU_ONLINE flag here rather than setting aci_status completely.
1421 	 */
1422 	cpun = psm_get_cpu_id();
1423 	apic_cpus[cpun].aci_status |= APIC_CPU_ONLINE;
1424 
1425 	apic_reg_ops->apic_write(APIC_DIVIDE_REG, apic_divide_reg_init);
1426 	return (PSM_SUCCESS);
1427 }
1428 
1429 processorid_t
1430 apic_get_next_processorid(processorid_t cpu_id)
1431 {
1432 
1433 	int i;
1434 
1435 	if (cpu_id == -1)
1436 		return ((processorid_t)0);
1437 
1438 	for (i = cpu_id + 1; i < NCPU; i++) {
1439 		if (CPU_IN_SET(apic_cpumask, i))
1440 			return (i);
1441 	}
1442 
1443 	return ((processorid_t)-1);
1444 }
1445 
1446 
1447 /*
1448  * type == -1 indicates it is an internal request. Do not change
1449  * resv_vector for these requests
1450  */
1451 static int
1452 apic_get_ipivect(int ipl, int type)
1453 {
1454 	uchar_t vector;
1455 	int irq;
1456 
1457 	if (irq = apic_allocate_irq(APIC_VECTOR(ipl))) {
1458 		if (vector = apic_allocate_vector(ipl, irq, 1)) {
1459 			apic_irq_table[irq]->airq_mps_intr_index =
1460 			    RESERVE_INDEX;
1461 			apic_irq_table[irq]->airq_vector = vector;
1462 			if (type != -1) {
1463 				apic_resv_vector[ipl] = vector;
1464 			}
1465 			return (irq);
1466 		}
1467 	}
1468 	apic_error |= APIC_ERR_GET_IPIVECT_FAIL;
1469 	return (-1);	/* shouldn't happen */
1470 }
1471 
1472 static int
1473 apic_getclkirq(int ipl)
1474 {
1475 	int	irq;
1476 
1477 	if ((irq = apic_get_ipivect(ipl, -1)) == -1)
1478 		return (-1);
1479 	/*
1480 	 * Note the vector in apic_clkvect for per clock handling.
1481 	 */
1482 	apic_clkvect = apic_irq_table[irq]->airq_vector - APIC_BASE_VECT;
1483 	APIC_VERBOSE_IOAPIC((CE_NOTE, "get_clkirq: vector = %x\n",
1484 	    apic_clkvect));
1485 	return (irq);
1486 }
1487 
1488 
1489 /*
1490  * Return the number of APIC clock ticks elapsed for 8245 to decrement
1491  * (APIC_TIME_COUNT + pit_ticks_adj) ticks.
1492  */
1493 static uint_t
1494 apic_calibrate(volatile uint32_t *addr, uint16_t *pit_ticks_adj)
1495 {
1496 	uint8_t		pit_tick_lo;
1497 	uint16_t	pit_tick, target_pit_tick;
1498 	uint32_t	start_apic_tick, end_apic_tick;
1499 	ulong_t		iflag;
1500 	uint32_t	reg;
1501 
1502 	reg = addr + APIC_CURR_COUNT - apicadr;
1503 
1504 	iflag = intr_clear();
1505 
1506 	do {
1507 		pit_tick_lo = inb(PITCTR0_PORT);
1508 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1509 	} while (pit_tick < APIC_TIME_MIN ||
1510 	    pit_tick_lo <= APIC_LB_MIN || pit_tick_lo >= APIC_LB_MAX);
1511 
1512 	/*
1513 	 * Wait for the 8254 to decrement by 5 ticks to ensure
1514 	 * we didn't start in the middle of a tick.
1515 	 * Compare with 0x10 for the wrap around case.
1516 	 */
1517 	target_pit_tick = pit_tick - 5;
1518 	do {
1519 		pit_tick_lo = inb(PITCTR0_PORT);
1520 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1521 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1522 
1523 	start_apic_tick = apic_reg_ops->apic_read(reg);
1524 
1525 	/*
1526 	 * Wait for the 8254 to decrement by
1527 	 * (APIC_TIME_COUNT + pit_ticks_adj) ticks
1528 	 */
1529 	target_pit_tick = pit_tick - APIC_TIME_COUNT;
1530 	do {
1531 		pit_tick_lo = inb(PITCTR0_PORT);
1532 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1533 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1534 
1535 	end_apic_tick = apic_reg_ops->apic_read(reg);
1536 
1537 	*pit_ticks_adj = target_pit_tick - pit_tick;
1538 
1539 	intr_restore(iflag);
1540 
1541 	return (start_apic_tick - end_apic_tick);
1542 }
1543 
1544 /*
1545  * Initialise the APIC timer on the local APIC of CPU 0 to the desired
1546  * frequency.  Note at this stage in the boot sequence, the boot processor
1547  * is the only active processor.
1548  * hertz value of 0 indicates a one-shot mode request.  In this case
1549  * the function returns the resolution (in nanoseconds) for the hardware
1550  * timer interrupt.  If one-shot mode capability is not available,
1551  * the return value will be 0. apic_enable_oneshot is a global switch
1552  * for disabling the functionality.
1553  * A non-zero positive value for hertz indicates a periodic mode request.
1554  * In this case the hardware will be programmed to generate clock interrupts
1555  * at hertz frequency and returns the resolution of interrupts in
1556  * nanosecond.
1557  */
1558 
1559 static int
1560 apic_clkinit(int hertz)
1561 {
1562 	uint_t		apic_ticks = 0;
1563 	uint_t		pit_ticks;
1564 	int		ret;
1565 	uint16_t	pit_ticks_adj;
1566 	static int	firsttime = 1;
1567 
1568 	if (firsttime) {
1569 		/* first time calibrate on CPU0 only */
1570 
1571 		apic_reg_ops->apic_write(APIC_DIVIDE_REG, apic_divide_reg_init);
1572 		apic_reg_ops->apic_write(APIC_INIT_COUNT, APIC_MAXVAL);
1573 		apic_ticks = apic_calibrate(apicadr, &pit_ticks_adj);
1574 
1575 		/* total number of PIT ticks corresponding to apic_ticks */
1576 		pit_ticks = APIC_TIME_COUNT + pit_ticks_adj;
1577 
1578 		/*
1579 		 * Determine the number of nanoseconds per APIC clock tick
1580 		 * and then determine how many APIC ticks to interrupt at the
1581 		 * desired frequency
1582 		 * apic_ticks / (pitticks / PIT_HZ) = apic_ticks_per_s
1583 		 * (apic_ticks * PIT_HZ) / pitticks = apic_ticks_per_s
1584 		 * apic_ticks_per_ns = (apic_ticks * PIT_HZ) / (pitticks * 10^9)
1585 		 * pic_ticks_per_SFns =
1586 		 *   (SF * apic_ticks * PIT_HZ) / (pitticks * 10^9)
1587 		 */
1588 		apic_ticks_per_SFnsecs =
1589 		    ((SF * apic_ticks * PIT_HZ) /
1590 		    ((uint64_t)pit_ticks * NANOSEC));
1591 
1592 		/* the interval timer initial count is 32 bit max */
1593 		apic_nsec_max = APIC_TICKS_TO_NSECS(APIC_MAXVAL);
1594 		firsttime = 0;
1595 	}
1596 
1597 	if (hertz != 0) {
1598 		/* periodic */
1599 		apic_nsec_per_intr = NANOSEC / hertz;
1600 		apic_hertz_count = APIC_NSECS_TO_TICKS(apic_nsec_per_intr);
1601 	}
1602 
1603 	apic_int_busy_mark = (apic_int_busy_mark *
1604 	    apic_sample_factor_redistribution) / 100;
1605 	apic_int_free_mark = (apic_int_free_mark *
1606 	    apic_sample_factor_redistribution) / 100;
1607 	apic_diff_for_redistribution = (apic_diff_for_redistribution *
1608 	    apic_sample_factor_redistribution) / 100;
1609 
1610 	if (hertz == 0) {
1611 		/* requested one_shot */
1612 		if (!tsc_gethrtime_enable || !apic_oneshot_enable)
1613 			return (0);
1614 		apic_oneshot = 1;
1615 		ret = (int)APIC_TICKS_TO_NSECS(1);
1616 	} else {
1617 		/* program the local APIC to interrupt at the given frequency */
1618 		apic_reg_ops->apic_write(APIC_INIT_COUNT, apic_hertz_count);
1619 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
1620 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME);
1621 		apic_oneshot = 0;
1622 		ret = NANOSEC / hertz;
1623 	}
1624 
1625 	return (ret);
1626 
1627 }
1628 
1629 /*
1630  * apic_preshutdown:
1631  * Called early in shutdown whilst we can still access filesystems to do
1632  * things like loading modules which will be required to complete shutdown
1633  * after filesystems are all unmounted.
1634  */
1635 static void
1636 apic_preshutdown(int cmd, int fcn)
1637 {
1638 	APIC_VERBOSE_POWEROFF(("apic_preshutdown(%d,%d); m=%d a=%d\n",
1639 	    cmd, fcn, apic_poweroff_method, apic_enable_acpi));
1640 
1641 	if ((cmd != A_SHUTDOWN) || (fcn != AD_POWEROFF)) {
1642 		return;
1643 	}
1644 }
1645 
1646 static void
1647 apic_shutdown(int cmd, int fcn)
1648 {
1649 	int restarts, attempts;
1650 	int i;
1651 	uchar_t	byte;
1652 	ulong_t iflag;
1653 
1654 	hpet_acpi_fini();
1655 
1656 	/* Send NMI to all CPUs except self to do per processor shutdown */
1657 	iflag = intr_clear();
1658 #ifdef	DEBUG
1659 	APIC_AV_PENDING_SET();
1660 #else
1661 	if (apic_mode == LOCAL_APIC)
1662 		APIC_AV_PENDING_SET();
1663 #endif /* DEBUG */
1664 	apic_shutdown_processors = 1;
1665 	apic_reg_ops->apic_write(APIC_INT_CMD1,
1666 	    AV_NMI | AV_LEVEL | AV_SH_ALL_EXCSELF);
1667 
1668 	/* restore cmos shutdown byte before reboot */
1669 	if (apic_cmos_ssb_set) {
1670 		outb(CMOS_ADDR, SSB);
1671 		outb(CMOS_DATA, 0);
1672 	}
1673 
1674 	ioapic_disable_redirection();
1675 
1676 	/*	disable apic mode if imcr present	*/
1677 	if (apic_imcrp) {
1678 		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
1679 		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_PIC);
1680 	}
1681 
1682 	apic_disable_local_apic();
1683 
1684 	intr_restore(iflag);
1685 
1686 	/* remainder of function is for shutdown cases only */
1687 	if (cmd != A_SHUTDOWN)
1688 		return;
1689 
1690 	/*
1691 	 * Switch system back into Legacy-Mode if using ACPI and
1692 	 * not powering-off.  Some BIOSes need to remain in ACPI-mode
1693 	 * for power-off to succeed (Dell Dimension 4600)
1694 	 * Do not disable ACPI while doing fastreboot
1695 	 */
1696 	if (apic_enable_acpi && fcn != AD_POWEROFF && fcn != AD_FASTREBOOT)
1697 		(void) AcpiDisable();
1698 
1699 	if (fcn == AD_FASTREBOOT) {
1700 		apic_reg_ops->apic_write(APIC_INT_CMD1,
1701 		    AV_ASSERT | AV_RESET | AV_SH_ALL_EXCSELF);
1702 	}
1703 
1704 	/* remainder of function is for shutdown+poweroff case only */
1705 	if (fcn != AD_POWEROFF)
1706 		return;
1707 
1708 	switch (apic_poweroff_method) {
1709 		case APIC_POWEROFF_VIA_RTC:
1710 
1711 			/* select the extended NVRAM bank in the RTC */
1712 			outb(CMOS_ADDR, RTC_REGA);
1713 			byte = inb(CMOS_DATA);
1714 			outb(CMOS_DATA, (byte | EXT_BANK));
1715 
1716 			outb(CMOS_ADDR, PFR_REG);
1717 
1718 			/* for Predator must toggle the PAB bit */
1719 			byte = inb(CMOS_DATA);
1720 
1721 			/*
1722 			 * clear power active bar, wakeup alarm and
1723 			 * kickstart
1724 			 */
1725 			byte &= ~(PAB_CBIT | WF_FLAG | KS_FLAG);
1726 			outb(CMOS_DATA, byte);
1727 
1728 			/* delay before next write */
1729 			drv_usecwait(1000);
1730 
1731 			/* for S40 the following would suffice */
1732 			byte = inb(CMOS_DATA);
1733 
1734 			/* power active bar control bit */
1735 			byte |= PAB_CBIT;
1736 			outb(CMOS_DATA, byte);
1737 
1738 			break;
1739 
1740 		case APIC_POWEROFF_VIA_ASPEN_BMC:
1741 			restarts = 0;
1742 restart_aspen_bmc:
1743 			if (++restarts == 3)
1744 				break;
1745 			attempts = 0;
1746 			do {
1747 				byte = inb(MISMIC_FLAG_REGISTER);
1748 				byte &= MISMIC_BUSY_MASK;
1749 				if (byte != 0) {
1750 					drv_usecwait(1000);
1751 					if (attempts >= 3)
1752 						goto restart_aspen_bmc;
1753 					++attempts;
1754 				}
1755 			} while (byte != 0);
1756 			outb(MISMIC_CNTL_REGISTER, CC_SMS_GET_STATUS);
1757 			byte = inb(MISMIC_FLAG_REGISTER);
1758 			byte |= 0x1;
1759 			outb(MISMIC_FLAG_REGISTER, byte);
1760 			i = 0;
1761 			for (; i < (sizeof (aspen_bmc)/sizeof (aspen_bmc[0]));
1762 			    i++) {
1763 				attempts = 0;
1764 				do {
1765 					byte = inb(MISMIC_FLAG_REGISTER);
1766 					byte &= MISMIC_BUSY_MASK;
1767 					if (byte != 0) {
1768 						drv_usecwait(1000);
1769 						if (attempts >= 3)
1770 							goto restart_aspen_bmc;
1771 						++attempts;
1772 					}
1773 				} while (byte != 0);
1774 				outb(MISMIC_CNTL_REGISTER, aspen_bmc[i].cntl);
1775 				outb(MISMIC_DATA_REGISTER, aspen_bmc[i].data);
1776 				byte = inb(MISMIC_FLAG_REGISTER);
1777 				byte |= 0x1;
1778 				outb(MISMIC_FLAG_REGISTER, byte);
1779 			}
1780 			break;
1781 
1782 		case APIC_POWEROFF_VIA_SITKA_BMC:
1783 			restarts = 0;
1784 restart_sitka_bmc:
1785 			if (++restarts == 3)
1786 				break;
1787 			attempts = 0;
1788 			do {
1789 				byte = inb(SMS_STATUS_REGISTER);
1790 				byte &= SMS_STATE_MASK;
1791 				if ((byte == SMS_READ_STATE) ||
1792 				    (byte == SMS_WRITE_STATE)) {
1793 					drv_usecwait(1000);
1794 					if (attempts >= 3)
1795 						goto restart_sitka_bmc;
1796 					++attempts;
1797 				}
1798 			} while ((byte == SMS_READ_STATE) ||
1799 			    (byte == SMS_WRITE_STATE));
1800 			outb(SMS_COMMAND_REGISTER, SMS_GET_STATUS);
1801 			i = 0;
1802 			for (; i < (sizeof (sitka_bmc)/sizeof (sitka_bmc[0]));
1803 			    i++) {
1804 				attempts = 0;
1805 				do {
1806 					byte = inb(SMS_STATUS_REGISTER);
1807 					byte &= SMS_IBF_MASK;
1808 					if (byte != 0) {
1809 						drv_usecwait(1000);
1810 						if (attempts >= 3)
1811 							goto restart_sitka_bmc;
1812 						++attempts;
1813 					}
1814 				} while (byte != 0);
1815 				outb(sitka_bmc[i].port, sitka_bmc[i].data);
1816 			}
1817 			break;
1818 
1819 		case APIC_POWEROFF_NONE:
1820 
1821 			/* If no APIC direct method, we will try using ACPI */
1822 			if (apic_enable_acpi) {
1823 				if (acpi_poweroff() == 1)
1824 					return;
1825 			} else
1826 				return;
1827 
1828 			break;
1829 	}
1830 	/*
1831 	 * Wait a limited time here for power to go off.
1832 	 * If the power does not go off, then there was a
1833 	 * problem and we should continue to the halt which
1834 	 * prints a message for the user to press a key to
1835 	 * reboot.
1836 	 */
1837 	drv_usecwait(7000000); /* wait seven seconds */
1838 
1839 }
1840 
1841 /*
1842  * Try and disable all interrupts. We just assign interrupts to other
1843  * processors based on policy. If any were bound by user request, we
1844  * let them continue and return failure. We do not bother to check
1845  * for cache affinity while rebinding.
1846  */
1847 
1848 static int
1849 apic_disable_intr(processorid_t cpun)
1850 {
1851 	int bind_cpu = 0, i, hardbound = 0;
1852 	apic_irq_t *irq_ptr;
1853 	ulong_t iflag;
1854 
1855 	iflag = intr_clear();
1856 	lock_set(&apic_ioapic_lock);
1857 
1858 	for (i = 0; i <= APIC_MAX_VECTOR; i++) {
1859 		if (apic_reprogram_info[i].done == B_FALSE) {
1860 			if (apic_reprogram_info[i].bindcpu == cpun) {
1861 				/*
1862 				 * CPU is busy -- it's the target of
1863 				 * a pending reprogramming attempt
1864 				 */
1865 				lock_clear(&apic_ioapic_lock);
1866 				intr_restore(iflag);
1867 				return (PSM_FAILURE);
1868 			}
1869 		}
1870 	}
1871 
1872 	apic_cpus[cpun].aci_status &= ~APIC_CPU_INTR_ENABLE;
1873 
1874 	apic_cpus[cpun].aci_curipl = 0;
1875 
1876 	i = apic_min_device_irq;
1877 	for (; i <= apic_max_device_irq; i++) {
1878 		/*
1879 		 * If there are bound interrupts on this cpu, then
1880 		 * rebind them to other processors.
1881 		 */
1882 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1883 			ASSERT((irq_ptr->airq_temp_cpu == IRQ_UNBOUND) ||
1884 			    (irq_ptr->airq_temp_cpu == IRQ_UNINIT) ||
1885 			    ((irq_ptr->airq_temp_cpu & ~IRQ_USER_BOUND) <
1886 			    apic_nproc));
1887 
1888 			if (irq_ptr->airq_temp_cpu == (cpun | IRQ_USER_BOUND)) {
1889 				hardbound = 1;
1890 				continue;
1891 			}
1892 
1893 			if (irq_ptr->airq_temp_cpu == cpun) {
1894 				do {
1895 					bind_cpu = apic_next_bind_cpu++;
1896 					if (bind_cpu >= apic_nproc) {
1897 						apic_next_bind_cpu = 1;
1898 						bind_cpu = 0;
1899 
1900 					}
1901 				} while (apic_rebind_all(irq_ptr, bind_cpu));
1902 			}
1903 		}
1904 	}
1905 
1906 	lock_clear(&apic_ioapic_lock);
1907 	intr_restore(iflag);
1908 
1909 	if (hardbound) {
1910 		cmn_err(CE_WARN, "Could not disable interrupts on %d"
1911 		    "due to user bound interrupts", cpun);
1912 		return (PSM_FAILURE);
1913 	}
1914 	else
1915 		return (PSM_SUCCESS);
1916 }
1917 
1918 /*
1919  * Bind interrupts to the CPU's local APIC.
1920  * Interrupts should not be bound to a CPU's local APIC until the CPU
1921  * is ready to receive interrupts.
1922  */
1923 static void
1924 apic_enable_intr(processorid_t cpun)
1925 {
1926 	int	i;
1927 	apic_irq_t *irq_ptr;
1928 	ulong_t iflag;
1929 
1930 	iflag = intr_clear();
1931 	lock_set(&apic_ioapic_lock);
1932 
1933 	apic_cpus[cpun].aci_status |= APIC_CPU_INTR_ENABLE;
1934 
1935 	i = apic_min_device_irq;
1936 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
1937 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1938 			if ((irq_ptr->airq_cpu & ~IRQ_USER_BOUND) == cpun) {
1939 				(void) apic_rebind_all(irq_ptr,
1940 				    irq_ptr->airq_cpu);
1941 			}
1942 		}
1943 	}
1944 
1945 	lock_clear(&apic_ioapic_lock);
1946 	intr_restore(iflag);
1947 }
1948 
1949 
1950 /*
1951  * This function will reprogram the timer.
1952  *
1953  * When in oneshot mode the argument is the absolute time in future to
1954  * generate the interrupt at.
1955  *
1956  * When in periodic mode, the argument is the interval at which the
1957  * interrupts should be generated. There is no need to support the periodic
1958  * mode timer change at this time.
1959  */
1960 static void
1961 apic_timer_reprogram(hrtime_t time)
1962 {
1963 	hrtime_t now;
1964 	uint_t ticks;
1965 	int64_t delta;
1966 
1967 	/*
1968 	 * We should be called from high PIL context (CBE_HIGH_PIL),
1969 	 * so kpreempt is disabled.
1970 	 */
1971 
1972 	if (!apic_oneshot) {
1973 		/* time is the interval for periodic mode */
1974 		ticks = APIC_NSECS_TO_TICKS(time);
1975 	} else {
1976 		/* one shot mode */
1977 
1978 		now = gethrtime();
1979 		delta = time - now;
1980 
1981 		if (delta <= 0) {
1982 			/*
1983 			 * requested to generate an interrupt in the past
1984 			 * generate an interrupt as soon as possible
1985 			 */
1986 			ticks = apic_min_timer_ticks;
1987 		} else if (delta > apic_nsec_max) {
1988 			/*
1989 			 * requested to generate an interrupt at a time
1990 			 * further than what we are capable of. Set to max
1991 			 * the hardware can handle
1992 			 */
1993 
1994 			ticks = APIC_MAXVAL;
1995 #ifdef DEBUG
1996 			cmn_err(CE_CONT, "apic_timer_reprogram, request at"
1997 			    "  %lld  too far in future, current time"
1998 			    "  %lld \n", time, now);
1999 #endif
2000 		} else
2001 			ticks = APIC_NSECS_TO_TICKS(delta);
2002 	}
2003 
2004 	if (ticks < apic_min_timer_ticks)
2005 		ticks = apic_min_timer_ticks;
2006 
2007 	apic_reg_ops->apic_write(APIC_INIT_COUNT, ticks);
2008 }
2009 
2010 /*
2011  * This function will enable timer interrupts.
2012  */
2013 static void
2014 apic_timer_enable(void)
2015 {
2016 	/*
2017 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
2018 	 * so kpreempt is disabled.
2019 	 */
2020 
2021 	if (!apic_oneshot) {
2022 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
2023 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME);
2024 	} else {
2025 		/* one shot */
2026 		apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
2027 		    (apic_clkvect + APIC_BASE_VECT));
2028 	}
2029 }
2030 
2031 /*
2032  * This function will disable timer interrupts.
2033  */
2034 static void
2035 apic_timer_disable(void)
2036 {
2037 	/*
2038 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
2039 	 * so kpreempt is disabled.
2040 	 */
2041 	apic_reg_ops->apic_write(APIC_LOCAL_TIMER,
2042 	    (apic_clkvect + APIC_BASE_VECT) | AV_MASK);
2043 }
2044 
2045 /*
2046  * Set timer far into the future and return timer
2047  * current Count in nanoseconds.
2048  */
2049 hrtime_t
2050 apic_timer_stop_count(void)
2051 {
2052 	hrtime_t	ns_val;
2053 	int		enable_val, count_val;
2054 
2055 	/*
2056 	 * Should be called with interrupts disabled.
2057 	 */
2058 	ASSERT(!interrupts_enabled());
2059 
2060 	enable_val = apic_reg_ops->apic_read(APIC_LOCAL_TIMER);
2061 	if ((enable_val & AV_MASK) == AV_MASK)
2062 		return ((hrtime_t)-1);		/* timer is disabled */
2063 
2064 	count_val = apic_reg_ops->apic_read(APIC_CURR_COUNT);
2065 	ns_val = APIC_TICKS_TO_NSECS(count_val);
2066 
2067 	apic_reg_ops->apic_write(APIC_INIT_COUNT, APIC_MAXVAL);
2068 
2069 	return (ns_val);
2070 }
2071 
2072 /*
2073  * Reprogram timer after Deep C-State.
2074  */
2075 void
2076 apic_timer_restart(hrtime_t time)
2077 {
2078 	apic_timer_reprogram(time);
2079 }
2080 
2081 ddi_periodic_t apic_periodic_id;
2082 
2083 /*
2084  * If this module needs a periodic handler for the interrupt distribution, it
2085  * can be added here. The argument to the periodic handler is not currently
2086  * used, but is reserved for future.
2087  */
2088 static void
2089 apic_post_cyclic_setup(void *arg)
2090 {
2091 _NOTE(ARGUNUSED(arg))
2092 	/* cpu_lock is held */
2093 	/* set up a periodic handler for intr redistribution */
2094 
2095 	/*
2096 	 * In peridoc mode intr redistribution processing is done in
2097 	 * apic_intr_enter during clk intr processing
2098 	 */
2099 	if (!apic_oneshot)
2100 		return;
2101 	/*
2102 	 * Register a periodical handler for the redistribution processing.
2103 	 * On X86, CY_LOW_LEVEL is mapped to the level 2 interrupt, so
2104 	 * DDI_IPL_2 should be passed to ddi_periodic_add() here.
2105 	 */
2106 	apic_periodic_id = ddi_periodic_add(
2107 	    (void (*)(void *))apic_redistribute_compute, NULL,
2108 	    apic_redistribute_sample_interval, DDI_IPL_2);
2109 }
2110 
2111 static void
2112 apic_redistribute_compute(void)
2113 {
2114 	int	i, j, max_busy;
2115 
2116 	if (apic_enable_dynamic_migration) {
2117 		if (++apic_nticks == apic_sample_factor_redistribution) {
2118 			/*
2119 			 * Time to call apic_intr_redistribute().
2120 			 * reset apic_nticks. This will cause max_busy
2121 			 * to be calculated below and if it is more than
2122 			 * apic_int_busy, we will do the whole thing
2123 			 */
2124 			apic_nticks = 0;
2125 		}
2126 		max_busy = 0;
2127 		for (i = 0; i < apic_nproc; i++) {
2128 
2129 			/*
2130 			 * Check if curipl is non zero & if ISR is in
2131 			 * progress
2132 			 */
2133 			if (((j = apic_cpus[i].aci_curipl) != 0) &&
2134 			    (apic_cpus[i].aci_ISR_in_progress & (1 << j))) {
2135 
2136 				int	irq;
2137 				apic_cpus[i].aci_busy++;
2138 				irq = apic_cpus[i].aci_current[j];
2139 				apic_irq_table[irq]->airq_busy++;
2140 			}
2141 
2142 			if (!apic_nticks &&
2143 			    (apic_cpus[i].aci_busy > max_busy))
2144 				max_busy = apic_cpus[i].aci_busy;
2145 		}
2146 		if (!apic_nticks) {
2147 			if (max_busy > apic_int_busy_mark) {
2148 			/*
2149 			 * We could make the following check be
2150 			 * skipped > 1 in which case, we get a
2151 			 * redistribution at half the busy mark (due to
2152 			 * double interval). Need to be able to collect
2153 			 * more empirical data to decide if that is a
2154 			 * good strategy. Punt for now.
2155 			 */
2156 				if (apic_skipped_redistribute) {
2157 					apic_cleanup_busy();
2158 					apic_skipped_redistribute = 0;
2159 				} else {
2160 					apic_intr_redistribute();
2161 				}
2162 			} else
2163 				apic_skipped_redistribute++;
2164 		}
2165 	}
2166 }
2167 
2168 
2169 /*
2170  * The following functions are in the platform specific file so that they
2171  * can be different functions depending on whether we are running on
2172  * bare metal or a hypervisor.
2173  */
2174 
2175 /*
2176  * map an apic for memory-mapped access
2177  */
2178 uint32_t *
2179 mapin_apic(uint32_t addr, size_t len, int flags)
2180 {
2181 	/*LINTED: pointer cast may result in improper alignment */
2182 	return ((uint32_t *)psm_map_phys(addr, len, flags));
2183 }
2184 
2185 uint32_t *
2186 mapin_ioapic(uint32_t addr, size_t len, int flags)
2187 {
2188 	return (mapin_apic(addr, len, flags));
2189 }
2190 
2191 /*
2192  * unmap an apic
2193  */
2194 void
2195 mapout_apic(caddr_t addr, size_t len)
2196 {
2197 	psm_unmap_phys(addr, len);
2198 }
2199 
2200 void
2201 mapout_ioapic(caddr_t addr, size_t len)
2202 {
2203 	mapout_apic(addr, len);
2204 }
2205 
2206 /*
2207  * Check to make sure there are enough irq slots
2208  */
2209 int
2210 apic_check_free_irqs(int count)
2211 {
2212 	int i, avail;
2213 
2214 	avail = 0;
2215 	for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
2216 		if ((apic_irq_table[i] == NULL) ||
2217 		    apic_irq_table[i]->airq_mps_intr_index == FREE_INDEX) {
2218 			if (++avail >= count)
2219 				return (PSM_SUCCESS);
2220 		}
2221 	}
2222 	return (PSM_FAILURE);
2223 }
2224 
2225 /*
2226  * This function allocates "count" MSI vector(s) for the given "dip/pri/type"
2227  */
2228 int
2229 apic_alloc_msi_vectors(dev_info_t *dip, int inum, int count, int pri,
2230     int behavior)
2231 {
2232 	int	rcount, i;
2233 	uchar_t	start, irqno;
2234 	uint32_t cpu;
2235 	major_t	major;
2236 	apic_irq_t	*irqptr;
2237 
2238 	DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: dip=0x%p "
2239 	    "inum=0x%x  pri=0x%x count=0x%x behavior=%d\n",
2240 	    (void *)dip, inum, pri, count, behavior));
2241 
2242 	if (count > 1) {
2243 		if (behavior == DDI_INTR_ALLOC_STRICT &&
2244 		    (apic_multi_msi_enable == 0 || count > apic_multi_msi_max))
2245 			return (0);
2246 
2247 		if (apic_multi_msi_enable == 0)
2248 			count = 1;
2249 		else if (count > apic_multi_msi_max)
2250 			count = apic_multi_msi_max;
2251 	}
2252 
2253 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2254 		rcount = count;
2255 	else if (rcount == 0 || (rcount < count &&
2256 	    behavior == DDI_INTR_ALLOC_STRICT))
2257 		return (0);
2258 
2259 	/* if not ISP2, then round it down */
2260 	if (!ISP2(rcount))
2261 		rcount = 1 << (highbit(rcount) - 1);
2262 
2263 	mutex_enter(&airq_mutex);
2264 
2265 	for (start = 0; rcount > 0; rcount >>= 1) {
2266 		if ((start = apic_find_multi_vectors(pri, rcount)) != 0 ||
2267 		    behavior == DDI_INTR_ALLOC_STRICT)
2268 			break;
2269 	}
2270 
2271 	if (start == 0) {
2272 		/* no vector available */
2273 		mutex_exit(&airq_mutex);
2274 		return (0);
2275 	}
2276 
2277 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2278 		/* not enough free irq slots available */
2279 		mutex_exit(&airq_mutex);
2280 		return (0);
2281 	}
2282 
2283 	major = (dip != NULL) ? ddi_driver_major(dip) : 0;
2284 	for (i = 0; i < rcount; i++) {
2285 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2286 		    (uchar_t)-1) {
2287 			/*
2288 			 * shouldn't happen because of the
2289 			 * apic_check_free_irqs() check earlier
2290 			 */
2291 			mutex_exit(&airq_mutex);
2292 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
2293 			    "apic_allocate_irq failed\n"));
2294 			return (i);
2295 		}
2296 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2297 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2298 		irqptr = apic_irq_table[irqno];
2299 #ifdef	DEBUG
2300 		if (apic_vector_to_irq[start + i] != APIC_RESV_IRQ)
2301 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
2302 			    "apic_vector_to_irq is not APIC_RESV_IRQ\n"));
2303 #endif
2304 		apic_vector_to_irq[start + i] = (uchar_t)irqno;
2305 
2306 		irqptr->airq_vector = (uchar_t)(start + i);
2307 		irqptr->airq_ioapicindex = (uchar_t)inum;	/* start */
2308 		irqptr->airq_intin_no = (uchar_t)rcount;
2309 		irqptr->airq_ipl = pri;
2310 		irqptr->airq_vector = start + i;
2311 		irqptr->airq_origirq = (uchar_t)(inum + i);
2312 		irqptr->airq_share_id = 0;
2313 		irqptr->airq_mps_intr_index = MSI_INDEX;
2314 		irqptr->airq_dip = dip;
2315 		irqptr->airq_major = major;
2316 		if (i == 0) /* they all bound to the same cpu */
2317 			cpu = irqptr->airq_cpu = apic_bind_intr(dip, irqno,
2318 			    0xff, 0xff);
2319 		else
2320 			irqptr->airq_cpu = cpu;
2321 		DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: irq=0x%x "
2322 		    "dip=0x%p vector=0x%x origirq=0x%x pri=0x%x\n", irqno,
2323 		    (void *)irqptr->airq_dip, irqptr->airq_vector,
2324 		    irqptr->airq_origirq, pri));
2325 	}
2326 	mutex_exit(&airq_mutex);
2327 	return (rcount);
2328 }
2329 
2330 /*
2331  * This function allocates "count" MSI-X vector(s) for the given "dip/pri/type"
2332  */
2333 int
2334 apic_alloc_msix_vectors(dev_info_t *dip, int inum, int count, int pri,
2335     int behavior)
2336 {
2337 	int	rcount, i;
2338 	major_t	major;
2339 
2340 	if (count > 1) {
2341 		if (behavior == DDI_INTR_ALLOC_STRICT) {
2342 			if (count > apic_msix_max)
2343 				return (0);
2344 		} else if (count > apic_msix_max)
2345 			count = apic_msix_max;
2346 	}
2347 
2348 	mutex_enter(&airq_mutex);
2349 
2350 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2351 		rcount = count;
2352 	else if (rcount == 0 || (rcount < count &&
2353 	    behavior == DDI_INTR_ALLOC_STRICT)) {
2354 		rcount = 0;
2355 		goto out;
2356 	}
2357 
2358 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2359 		/* not enough free irq slots available */
2360 		rcount = 0;
2361 		goto out;
2362 	}
2363 
2364 	major = (dip != NULL) ? ddi_driver_major(dip) : 0;
2365 	for (i = 0; i < rcount; i++) {
2366 		uchar_t	vector, irqno;
2367 		apic_irq_t	*irqptr;
2368 
2369 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2370 		    (uchar_t)-1) {
2371 			/*
2372 			 * shouldn't happen because of the
2373 			 * apic_check_free_irqs() check earlier
2374 			 */
2375 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2376 			    "apic_allocate_irq failed\n"));
2377 			rcount = i;
2378 			goto out;
2379 		}
2380 		if ((vector = apic_allocate_vector(pri, irqno, 1)) == 0) {
2381 			/*
2382 			 * shouldn't happen because of the
2383 			 * apic_navail_vector() call earlier
2384 			 */
2385 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2386 			    "apic_allocate_vector failed\n"));
2387 			rcount = i;
2388 			goto out;
2389 		}
2390 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2391 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2392 		irqptr = apic_irq_table[irqno];
2393 		irqptr->airq_vector = (uchar_t)vector;
2394 		irqptr->airq_ipl = pri;
2395 		irqptr->airq_origirq = (uchar_t)(inum + i);
2396 		irqptr->airq_share_id = 0;
2397 		irqptr->airq_mps_intr_index = MSIX_INDEX;
2398 		irqptr->airq_dip = dip;
2399 		irqptr->airq_major = major;
2400 		irqptr->airq_cpu = apic_bind_intr(dip, irqno, 0xff, 0xff);
2401 	}
2402 out:
2403 	mutex_exit(&airq_mutex);
2404 	return (rcount);
2405 }
2406 
2407 /*
2408  * Allocate a free vector for irq at ipl. Takes care of merging of multiple
2409  * IPLs into a single APIC level as well as stretching some IPLs onto multiple
2410  * levels. APIC_HI_PRI_VECTS interrupts are reserved for high priority
2411  * requests and allocated only when pri is set.
2412  */
2413 uchar_t
2414 apic_allocate_vector(int ipl, int irq, int pri)
2415 {
2416 	int	lowest, highest, i;
2417 
2418 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
2419 	lowest = apic_ipltopri[ipl - 1] + APIC_VECTOR_PER_IPL;
2420 
2421 	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
2422 		lowest -= APIC_VECTOR_PER_IPL;
2423 
2424 #ifdef	DEBUG
2425 	if (apic_restrict_vector)	/* for testing shared interrupt logic */
2426 		highest = lowest + apic_restrict_vector + APIC_HI_PRI_VECTS;
2427 #endif /* DEBUG */
2428 	if (pri == 0)
2429 		highest -= APIC_HI_PRI_VECTS;
2430 
2431 	for (i = lowest; i < highest; i++) {
2432 		if (APIC_CHECK_RESERVE_VECTORS(i))
2433 			continue;
2434 		if (apic_vector_to_irq[i] == APIC_RESV_IRQ) {
2435 			apic_vector_to_irq[i] = (uchar_t)irq;
2436 			return (i);
2437 		}
2438 	}
2439 
2440 	return (0);
2441 }
2442 
2443 /* Mark vector as not being used by any irq */
2444 void
2445 apic_free_vector(uchar_t vector)
2446 {
2447 	apic_vector_to_irq[vector] = APIC_RESV_IRQ;
2448 }
2449 
2450 uint32_t
2451 ioapic_read(int ioapic_ix, uint32_t reg)
2452 {
2453 	volatile uint32_t *ioapic;
2454 
2455 	ioapic = apicioadr[ioapic_ix];
2456 	ioapic[APIC_IO_REG] = reg;
2457 	return (ioapic[APIC_IO_DATA]);
2458 }
2459 
2460 void
2461 ioapic_write(int ioapic_ix, uint32_t reg, uint32_t value)
2462 {
2463 	volatile uint32_t *ioapic;
2464 
2465 	ioapic = apicioadr[ioapic_ix];
2466 	ioapic[APIC_IO_REG] = reg;
2467 	ioapic[APIC_IO_DATA] = value;
2468 }
2469 
2470 void
2471 ioapic_write_eoi(int ioapic_ix, uint32_t value)
2472 {
2473 	volatile uint32_t *ioapic;
2474 
2475 	ioapic = apicioadr[ioapic_ix];
2476 	ioapic[APIC_IO_EOI] = value;
2477 }
2478 
2479 static processorid_t
2480 apic_find_cpu(int flag)
2481 {
2482 	processorid_t acid = 0;
2483 	int i;
2484 
2485 	/* Find the first CPU with the passed-in flag set */
2486 	for (i = 0; i < apic_nproc; i++) {
2487 		if (apic_cpus[i].aci_status & flag) {
2488 			acid = i;
2489 			break;
2490 		}
2491 	}
2492 
2493 	ASSERT((apic_cpus[acid].aci_status & flag) != 0);
2494 	return (acid);
2495 }
2496 
2497 /*
2498  * Call rebind to do the actual programming.
2499  * Must be called with interrupts disabled and apic_ioapic_lock held
2500  * 'p' is polymorphic -- if this function is called to process a deferred
2501  * reprogramming, p is of type 'struct ioapic_reprogram_data *', from which
2502  * the irq pointer is retrieved.  If not doing deferred reprogramming,
2503  * p is of the type 'apic_irq_t *'.
2504  *
2505  * apic_ioapic_lock must be held across this call, as it protects apic_rebind
2506  * and it protects apic_find_cpu() from a race in which a CPU can be taken
2507  * offline after a cpu is selected, but before apic_rebind is called to
2508  * bind interrupts to it.
2509  */
2510 int
2511 apic_setup_io_intr(void *p, int irq, boolean_t deferred)
2512 {
2513 	apic_irq_t *irqptr;
2514 	struct ioapic_reprogram_data *drep = NULL;
2515 	int rv;
2516 
2517 	if (deferred) {
2518 		drep = (struct ioapic_reprogram_data *)p;
2519 		ASSERT(drep != NULL);
2520 		irqptr = drep->irqp;
2521 	} else
2522 		irqptr = (apic_irq_t *)p;
2523 
2524 	ASSERT(irqptr != NULL);
2525 
2526 	rv = apic_rebind(irqptr, apic_irq_table[irq]->airq_cpu, drep);
2527 	if (rv) {
2528 		/*
2529 		 * CPU is not up or interrupts are disabled. Fall back to
2530 		 * the first available CPU
2531 		 */
2532 		rv = apic_rebind(irqptr, apic_find_cpu(APIC_CPU_INTR_ENABLE),
2533 		    drep);
2534 	}
2535 
2536 	return (rv);
2537 }
2538 
2539 
2540 uchar_t
2541 apic_modify_vector(uchar_t vector, int irq)
2542 {
2543 	apic_vector_to_irq[vector] = (uchar_t)irq;
2544 	return (vector);
2545 }
2546 
2547 char *
2548 apic_get_apic_type()
2549 {
2550 	return (apic_psm_info.p_mach_idstring);
2551 }
2552 
2553 void
2554 x2apic_update_psm()
2555 {
2556 	struct psm_ops *pops = &apic_ops;
2557 
2558 	ASSERT(pops != NULL);
2559 
2560 	/*
2561 	 * We don't need to do any magic if one of the following
2562 	 * conditions is true :
2563 	 * - Not being run under kernel debugger.
2564 	 * - MP is not set.
2565 	 * - Booted with one CPU only.
2566 	 * - One CPU configured.
2567 	 *
2568 	 * We set apic_common_send_ipi() since kernel debuggers
2569 	 * attempt to send IPIs to other slave CPUs during
2570 	 * entry (exit) from (to) debugger.
2571 	 */
2572 	if (!(boothowto & RB_DEBUG) || use_mp == 0 ||
2573 	    apic_nproc == 1 || boot_ncpus == 1) {
2574 		pops->psm_send_ipi =  x2apic_send_ipi;
2575 	} else {
2576 		pops->psm_send_ipi =  apic_common_send_ipi;
2577 	}
2578 
2579 	pops->psm_intr_exit = x2apic_intr_exit;
2580 	pops->psm_setspl = x2apic_setspl;
2581 
2582 	send_dirintf = pops->psm_send_ipi;
2583 
2584 	apic_mode = LOCAL_X2APIC;
2585 	apic_change_ops();
2586 }
2587 
2588 static void
2589 apic_intrr_init(int apic_mode)
2590 {
2591 	if (psm_vt_ops != NULL) {
2592 		if (((apic_intrr_ops_t *)psm_vt_ops)->apic_intrr_init(apic_mode)
2593 		    == DDI_SUCCESS) {
2594 			apic_vt_ops = psm_vt_ops;
2595 			apic_vt_ops->apic_intrr_enable();
2596 		}
2597 	}
2598 }
2599 
2600 /*ARGSUSED*/
2601 static void
2602 apic_record_ioapic_rdt(apic_irq_t *irq_ptr, ioapic_rdt_t *irdt)
2603 {
2604 	irdt->ir_hi <<= APIC_ID_BIT_OFFSET;
2605 }
2606 
2607 /*ARGSUSED*/
2608 static void
2609 apic_record_msi(apic_irq_t *irq_ptr, msi_regs_t *mregs)
2610 {
2611 	mregs->mr_addr = MSI_ADDR_HDR |
2612 	    (MSI_ADDR_RH_FIXED << MSI_ADDR_RH_SHIFT) |
2613 	    (MSI_ADDR_DM_PHYSICAL << MSI_ADDR_DM_SHIFT) |
2614 	    (mregs->mr_addr << MSI_ADDR_DEST_SHIFT);
2615 	mregs->mr_data = (MSI_DATA_TM_EDGE << MSI_DATA_TM_SHIFT) |
2616 	    mregs->mr_data;
2617 }
2618