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