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