xref: /titanic_51/usr/src/uts/i86pc/io/pcplusmp/apic.c (revision fc80c0dfb0c877aee828d778ea32b77fcf7b1ef4)
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/note.h>
65 #include <sys/pci_intr_lib.h>
66 #include <sys/spl.h>
67 #include <sys/clock.h>
68 #include <sys/dditypes.h>
69 #include <sys/sunddi.h>
70 
71 /*
72  *	Local Function Prototypes
73  */
74 static void apic_init_intr();
75 static void apic_ret();
76 static int get_apic_cmd1();
77 static int get_apic_pri();
78 static void apic_nmi_intr(caddr_t arg, struct regs *rp);
79 
80 /*
81  *	standard MP entries
82  */
83 static int	apic_probe();
84 static int	apic_clkinit();
85 static int	apic_getclkirq(int ipl);
86 static uint_t	apic_calibrate(volatile uint32_t *addr,
87     uint16_t *pit_ticks_adj);
88 static hrtime_t apic_gettime();
89 static hrtime_t apic_gethrtime();
90 static void	apic_init();
91 static void	apic_picinit(void);
92 static int	apic_cpu_start(processorid_t, caddr_t);
93 static int	apic_post_cpu_start(void);
94 static void	apic_send_ipi(int cpun, int ipl);
95 static void	apic_set_idlecpu(processorid_t cpun);
96 static void	apic_unset_idlecpu(processorid_t cpun);
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 	(int (*)(int))NULL,		/* psm_softlvl_to_irq */
216 	(void (*)(int))NULL,		/* psm_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 	APIC_PCPLUSMP_NAME,			/* 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_picinit_called;
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_picinit_called = 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 intr_exit_fn_t
849 psm_intr_exit_fn(void)
850 {
851 	return (apic_intr_exit);
852 }
853 
854 /*
855  * Mask all interrupts below or equal to the given IPL
856  */
857 static void
858 apic_setspl(int ipl)
859 {
860 
861 #if defined(__amd64)
862 	setcr8((ulong_t)apic_cr8pri[ipl]);
863 #else
864 	apicadr[APIC_TASK_REG] = apic_ipltopri[ipl];
865 #endif
866 
867 	/* interrupts at ipl above this cannot be in progress */
868 	apic_cpus[psm_get_cpu_id()].aci_ISR_in_progress &= (2 << ipl) - 1;
869 	/*
870 	 * this is a patch fix for the ALR QSMP P5 machine, so that interrupts
871 	 * have enough time to come in before the priority is raised again
872 	 * during the idle() loop.
873 	 */
874 	if (apic_setspl_delay)
875 		(void) get_apic_pri();
876 }
877 
878 /*
879  * generates an interprocessor interrupt to another CPU
880  */
881 static void
882 apic_send_ipi(int cpun, int ipl)
883 {
884 	int vector;
885 	ulong_t flag;
886 
887 	vector = apic_resv_vector[ipl];
888 
889 	flag = intr_clear();
890 
891 	while (get_apic_cmd1() & AV_PENDING)
892 		apic_ret();
893 
894 	apicadr[APIC_INT_CMD2] =
895 	    apic_cpus[cpun].aci_local_id << APIC_ICR_ID_BIT_OFFSET;
896 	apicadr[APIC_INT_CMD1] = vector;
897 
898 	intr_restore(flag);
899 }
900 
901 
902 /*ARGSUSED*/
903 static void
904 apic_set_idlecpu(processorid_t cpun)
905 {
906 }
907 
908 /*ARGSUSED*/
909 static void
910 apic_unset_idlecpu(processorid_t cpun)
911 {
912 }
913 
914 
915 static void
916 apic_ret()
917 {
918 }
919 
920 static int
921 get_apic_cmd1()
922 {
923 	return (apicadr[APIC_INT_CMD1]);
924 }
925 
926 static int
927 get_apic_pri()
928 {
929 #if defined(__amd64)
930 	return ((int)getcr8());
931 #else
932 	return (apicadr[APIC_TASK_REG]);
933 #endif
934 }
935 
936 /*
937  * If apic_coarse_time == 1, then apic_gettime() is used instead of
938  * apic_gethrtime().  This is used for performance instead of accuracy.
939  */
940 
941 static hrtime_t
942 apic_gettime()
943 {
944 	int old_hrtime_stamp;
945 	hrtime_t temp;
946 
947 	/*
948 	 * In one-shot mode, we do not keep time, so if anyone
949 	 * calls psm_gettime() directly, we vector over to
950 	 * gethrtime().
951 	 * one-shot mode MUST NOT be enabled if this psm is the source of
952 	 * hrtime.
953 	 */
954 
955 	if (apic_oneshot)
956 		return (gethrtime());
957 
958 
959 gettime_again:
960 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
961 		apic_ret();
962 
963 	temp = apic_nsec_since_boot;
964 
965 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
966 		goto gettime_again;
967 	}
968 	return (temp);
969 }
970 
971 /*
972  * Here we return the number of nanoseconds since booting.  Note every
973  * clock interrupt increments apic_nsec_since_boot by the appropriate
974  * amount.
975  */
976 static hrtime_t
977 apic_gethrtime()
978 {
979 	int curr_timeval, countval, elapsed_ticks;
980 	int old_hrtime_stamp, status;
981 	hrtime_t temp;
982 	uchar_t	cpun;
983 	ulong_t oflags;
984 
985 	/*
986 	 * In one-shot mode, we do not keep time, so if anyone
987 	 * calls psm_gethrtime() directly, we vector over to
988 	 * gethrtime().
989 	 * one-shot mode MUST NOT be enabled if this psm is the source of
990 	 * hrtime.
991 	 */
992 
993 	if (apic_oneshot)
994 		return (gethrtime());
995 
996 	oflags = intr_clear();	/* prevent migration */
997 
998 	cpun = (uchar_t)((uint_t)apicadr[APIC_LID_REG] >> APIC_ID_BIT_OFFSET);
999 
1000 	lock_set(&apic_gethrtime_lock);
1001 
1002 gethrtime_again:
1003 	while ((old_hrtime_stamp = apic_hrtime_stamp) & 1)
1004 		apic_ret();
1005 
1006 	/*
1007 	 * Check to see which CPU we are on.  Note the time is kept on
1008 	 * the local APIC of CPU 0.  If on CPU 0, simply read the current
1009 	 * counter.  If on another CPU, issue a remote read command to CPU 0.
1010 	 */
1011 	if (cpun == apic_cpus[0].aci_local_id) {
1012 		countval = apicadr[APIC_CURR_COUNT];
1013 	} else {
1014 		while (get_apic_cmd1() & AV_PENDING)
1015 			apic_ret();
1016 
1017 		apicadr[APIC_INT_CMD2] =
1018 		    apic_cpus[0].aci_local_id << APIC_ICR_ID_BIT_OFFSET;
1019 		apicadr[APIC_INT_CMD1] = APIC_CURR_ADD|AV_REMOTE;
1020 
1021 		while ((status = get_apic_cmd1()) & AV_READ_PENDING)
1022 			apic_ret();
1023 
1024 		if (status & AV_REMOTE_STATUS)	/* 1 = valid */
1025 			countval = apicadr[APIC_REMOTE_READ];
1026 		else {	/* 0 = invalid */
1027 			apic_remote_hrterr++;
1028 			/*
1029 			 * return last hrtime right now, will need more
1030 			 * testing if change to retry
1031 			 */
1032 			temp = apic_last_hrtime;
1033 
1034 			lock_clear(&apic_gethrtime_lock);
1035 
1036 			intr_restore(oflags);
1037 
1038 			return (temp);
1039 		}
1040 	}
1041 	if (countval > last_count_read)
1042 		countval = 0;
1043 	else
1044 		last_count_read = countval;
1045 
1046 	elapsed_ticks = apic_hertz_count - countval;
1047 
1048 	curr_timeval = APIC_TICKS_TO_NSECS(elapsed_ticks);
1049 	temp = apic_nsec_since_boot + curr_timeval;
1050 
1051 	if (apic_hrtime_stamp != old_hrtime_stamp) {	/* got an interrupt */
1052 		/* we might have clobbered last_count_read. Restore it */
1053 		last_count_read = apic_hertz_count;
1054 		goto gethrtime_again;
1055 	}
1056 
1057 	if (temp < apic_last_hrtime) {
1058 		/* return last hrtime if error occurs */
1059 		apic_hrtime_error++;
1060 		temp = apic_last_hrtime;
1061 	}
1062 	else
1063 		apic_last_hrtime = temp;
1064 
1065 	lock_clear(&apic_gethrtime_lock);
1066 	intr_restore(oflags);
1067 
1068 	return (temp);
1069 }
1070 
1071 /* apic NMI handler */
1072 /*ARGSUSED*/
1073 static void
1074 apic_nmi_intr(caddr_t arg, struct regs *rp)
1075 {
1076 	if (apic_shutdown_processors) {
1077 		apic_disable_local_apic();
1078 		return;
1079 	}
1080 
1081 	apic_error |= APIC_ERR_NMI;
1082 
1083 	if (!lock_try(&apic_nmi_lock))
1084 		return;
1085 	apic_num_nmis++;
1086 
1087 	if (apic_kmdb_on_nmi && psm_debugger()) {
1088 		debug_enter("NMI received: entering kmdb\n");
1089 	} else if (apic_panic_on_nmi) {
1090 		/* Keep panic from entering kmdb. */
1091 		nopanicdebug = 1;
1092 		panic("NMI received\n");
1093 	} else {
1094 		/*
1095 		 * prom_printf is the best shot we have of something which is
1096 		 * problem free from high level/NMI type of interrupts
1097 		 */
1098 		prom_printf("NMI received\n");
1099 	}
1100 
1101 	lock_clear(&apic_nmi_lock);
1102 }
1103 
1104 /*ARGSUSED*/
1105 static int
1106 apic_addspl(int irqno, int ipl, int min_ipl, int max_ipl)
1107 {
1108 	return (apic_addspl_common(irqno, ipl, min_ipl, max_ipl));
1109 }
1110 
1111 static int
1112 apic_delspl(int irqno, int ipl, int min_ipl, int max_ipl)
1113 {
1114 	return (apic_delspl_common(irqno, ipl, min_ipl,  max_ipl));
1115 }
1116 
1117 static int
1118 apic_post_cpu_start()
1119 {
1120 	int i, cpun;
1121 	ulong_t iflag;
1122 	apic_irq_t *irq_ptr;
1123 
1124 	splx(ipltospl(LOCK_LEVEL));
1125 	apic_init_intr();
1126 
1127 	/*
1128 	 * since some systems don't enable the internal cache on the non-boot
1129 	 * cpus, so we have to enable them here
1130 	 */
1131 	setcr0(getcr0() & ~(CR0_CD | CR0_NW));
1132 
1133 	while (get_apic_cmd1() & AV_PENDING)
1134 		apic_ret();
1135 
1136 	cpun = psm_get_cpu_id();
1137 	apic_cpus[cpun].aci_status = APIC_CPU_ONLINE | APIC_CPU_INTR_ENABLE;
1138 
1139 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
1140 		irq_ptr = apic_irq_table[i];
1141 		if ((irq_ptr == NULL) ||
1142 		    ((irq_ptr->airq_cpu & ~IRQ_USER_BOUND) != cpun))
1143 			continue;
1144 
1145 		while (irq_ptr) {
1146 			if (irq_ptr->airq_temp_cpu != IRQ_UNINIT) {
1147 				iflag = intr_clear();
1148 				lock_set(&apic_ioapic_lock);
1149 
1150 				(void) apic_rebind(irq_ptr, cpun, NULL);
1151 
1152 				lock_clear(&apic_ioapic_lock);
1153 				intr_restore(iflag);
1154 			}
1155 			irq_ptr = irq_ptr->airq_next;
1156 		}
1157 	}
1158 
1159 	apicadr[APIC_DIVIDE_REG] = apic_divide_reg_init;
1160 	return (PSM_SUCCESS);
1161 }
1162 
1163 processorid_t
1164 apic_get_next_processorid(processorid_t cpu_id)
1165 {
1166 
1167 	int i;
1168 
1169 	if (cpu_id == -1)
1170 		return ((processorid_t)0);
1171 
1172 	for (i = cpu_id + 1; i < NCPU; i++) {
1173 		if (CPU_IN_SET(apic_cpumask, i))
1174 			return (i);
1175 	}
1176 
1177 	return ((processorid_t)-1);
1178 }
1179 
1180 
1181 /*
1182  * type == -1 indicates it is an internal request. Do not change
1183  * resv_vector for these requests
1184  */
1185 static int
1186 apic_get_ipivect(int ipl, int type)
1187 {
1188 	uchar_t vector;
1189 	int irq;
1190 
1191 	if (irq = apic_allocate_irq(APIC_VECTOR(ipl))) {
1192 		if (vector = apic_allocate_vector(ipl, irq, 1)) {
1193 			apic_irq_table[irq]->airq_mps_intr_index =
1194 			    RESERVE_INDEX;
1195 			apic_irq_table[irq]->airq_vector = vector;
1196 			if (type != -1) {
1197 				apic_resv_vector[ipl] = vector;
1198 			}
1199 			return (irq);
1200 		}
1201 	}
1202 	apic_error |= APIC_ERR_GET_IPIVECT_FAIL;
1203 	return (-1);	/* shouldn't happen */
1204 }
1205 
1206 static int
1207 apic_getclkirq(int ipl)
1208 {
1209 	int	irq;
1210 
1211 	if ((irq = apic_get_ipivect(ipl, -1)) == -1)
1212 		return (-1);
1213 	/*
1214 	 * Note the vector in apic_clkvect for per clock handling.
1215 	 */
1216 	apic_clkvect = apic_irq_table[irq]->airq_vector - APIC_BASE_VECT;
1217 	APIC_VERBOSE_IOAPIC((CE_NOTE, "get_clkirq: vector = %x\n",
1218 	    apic_clkvect));
1219 	return (irq);
1220 }
1221 
1222 
1223 /*
1224  * Return the number of APIC clock ticks elapsed for 8245 to decrement
1225  * (APIC_TIME_COUNT + pit_ticks_adj) ticks.
1226  */
1227 static uint_t
1228 apic_calibrate(volatile uint32_t *addr, uint16_t *pit_ticks_adj)
1229 {
1230 	uint8_t		pit_tick_lo;
1231 	uint16_t	pit_tick, target_pit_tick;
1232 	uint32_t	start_apic_tick, end_apic_tick;
1233 	ulong_t		iflag;
1234 
1235 	addr += APIC_CURR_COUNT;
1236 
1237 	iflag = intr_clear();
1238 
1239 	do {
1240 		pit_tick_lo = inb(PITCTR0_PORT);
1241 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1242 	} while (pit_tick < APIC_TIME_MIN ||
1243 	    pit_tick_lo <= APIC_LB_MIN || pit_tick_lo >= APIC_LB_MAX);
1244 
1245 	/*
1246 	 * Wait for the 8254 to decrement by 5 ticks to ensure
1247 	 * we didn't start in the middle of a tick.
1248 	 * Compare with 0x10 for the wrap around case.
1249 	 */
1250 	target_pit_tick = pit_tick - 5;
1251 	do {
1252 		pit_tick_lo = inb(PITCTR0_PORT);
1253 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1254 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1255 
1256 	start_apic_tick = *addr;
1257 
1258 	/*
1259 	 * Wait for the 8254 to decrement by
1260 	 * (APIC_TIME_COUNT + pit_ticks_adj) ticks
1261 	 */
1262 	target_pit_tick = pit_tick - APIC_TIME_COUNT;
1263 	do {
1264 		pit_tick_lo = inb(PITCTR0_PORT);
1265 		pit_tick = (inb(PITCTR0_PORT) << 8) | pit_tick_lo;
1266 	} while (pit_tick > target_pit_tick || pit_tick_lo < 0x10);
1267 
1268 	end_apic_tick = *addr;
1269 
1270 	*pit_ticks_adj = target_pit_tick - pit_tick;
1271 
1272 	intr_restore(iflag);
1273 
1274 	return (start_apic_tick - end_apic_tick);
1275 }
1276 
1277 /*
1278  * Initialise the APIC timer on the local APIC of CPU 0 to the desired
1279  * frequency.  Note at this stage in the boot sequence, the boot processor
1280  * is the only active processor.
1281  * hertz value of 0 indicates a one-shot mode request.  In this case
1282  * the function returns the resolution (in nanoseconds) for the hardware
1283  * timer interrupt.  If one-shot mode capability is not available,
1284  * the return value will be 0. apic_enable_oneshot is a global switch
1285  * for disabling the functionality.
1286  * A non-zero positive value for hertz indicates a periodic mode request.
1287  * In this case the hardware will be programmed to generate clock interrupts
1288  * at hertz frequency and returns the resolution of interrupts in
1289  * nanosecond.
1290  */
1291 
1292 static int
1293 apic_clkinit(int hertz)
1294 {
1295 	uint_t		apic_ticks = 0;
1296 	uint_t		pit_ticks;
1297 	int		ret;
1298 	uint16_t	pit_ticks_adj;
1299 	static int	firsttime = 1;
1300 
1301 	if (firsttime) {
1302 		/* first time calibrate on CPU0 only */
1303 
1304 		apicadr[APIC_DIVIDE_REG] = apic_divide_reg_init;
1305 		apicadr[APIC_INIT_COUNT] = APIC_MAXVAL;
1306 		apic_ticks = apic_calibrate(apicadr, &pit_ticks_adj);
1307 
1308 		/* total number of PIT ticks corresponding to apic_ticks */
1309 		pit_ticks = APIC_TIME_COUNT + pit_ticks_adj;
1310 
1311 		/*
1312 		 * Determine the number of nanoseconds per APIC clock tick
1313 		 * and then determine how many APIC ticks to interrupt at the
1314 		 * desired frequency
1315 		 * apic_ticks / (pitticks / PIT_HZ) = apic_ticks_per_s
1316 		 * (apic_ticks * PIT_HZ) / pitticks = apic_ticks_per_s
1317 		 * apic_ticks_per_ns = (apic_ticks * PIT_HZ) / (pitticks * 10^9)
1318 		 * pic_ticks_per_SFns =
1319 		 *   (SF * apic_ticks * PIT_HZ) / (pitticks * 10^9)
1320 		 */
1321 		apic_ticks_per_SFnsecs =
1322 		    ((SF * apic_ticks * PIT_HZ) /
1323 		    ((uint64_t)pit_ticks * NANOSEC));
1324 
1325 		/* the interval timer initial count is 32 bit max */
1326 		apic_nsec_max = APIC_TICKS_TO_NSECS(APIC_MAXVAL);
1327 		firsttime = 0;
1328 	}
1329 
1330 	if (hertz != 0) {
1331 		/* periodic */
1332 		apic_nsec_per_intr = NANOSEC / hertz;
1333 		apic_hertz_count = APIC_NSECS_TO_TICKS(apic_nsec_per_intr);
1334 	}
1335 
1336 	apic_int_busy_mark = (apic_int_busy_mark *
1337 	    apic_sample_factor_redistribution) / 100;
1338 	apic_int_free_mark = (apic_int_free_mark *
1339 	    apic_sample_factor_redistribution) / 100;
1340 	apic_diff_for_redistribution = (apic_diff_for_redistribution *
1341 	    apic_sample_factor_redistribution) / 100;
1342 
1343 	if (hertz == 0) {
1344 		/* requested one_shot */
1345 		if (!tsc_gethrtime_enable || !apic_oneshot_enable)
1346 			return (0);
1347 		apic_oneshot = 1;
1348 		ret = (int)APIC_TICKS_TO_NSECS(1);
1349 	} else {
1350 		/* program the local APIC to interrupt at the given frequency */
1351 		apicadr[APIC_INIT_COUNT] = apic_hertz_count;
1352 		apicadr[APIC_LOCAL_TIMER] =
1353 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME;
1354 		apic_oneshot = 0;
1355 		ret = NANOSEC / hertz;
1356 	}
1357 
1358 	return (ret);
1359 
1360 }
1361 
1362 /*
1363  * apic_preshutdown:
1364  * Called early in shutdown whilst we can still access filesystems to do
1365  * things like loading modules which will be required to complete shutdown
1366  * after filesystems are all unmounted.
1367  */
1368 static void
1369 apic_preshutdown(int cmd, int fcn)
1370 {
1371 	APIC_VERBOSE_POWEROFF(("apic_preshutdown(%d,%d); m=%d a=%d\n",
1372 	    cmd, fcn, apic_poweroff_method, apic_enable_acpi));
1373 
1374 }
1375 
1376 static void
1377 apic_shutdown(int cmd, int fcn)
1378 {
1379 	int restarts, attempts;
1380 	int i;
1381 	uchar_t	byte;
1382 	ulong_t iflag;
1383 
1384 	/* Send NMI to all CPUs except self to do per processor shutdown */
1385 	iflag = intr_clear();
1386 	while (get_apic_cmd1() & AV_PENDING)
1387 		apic_ret();
1388 	apic_shutdown_processors = 1;
1389 	apicadr[APIC_INT_CMD1] = AV_NMI | AV_LEVEL | AV_SH_ALL_EXCSELF;
1390 
1391 	/* restore cmos shutdown byte before reboot */
1392 	if (apic_cmos_ssb_set) {
1393 		outb(CMOS_ADDR, SSB);
1394 		outb(CMOS_DATA, 0);
1395 	}
1396 
1397 	ioapic_disable_redirection();
1398 
1399 	/*	disable apic mode if imcr present	*/
1400 	if (apic_imcrp) {
1401 		outb(APIC_IMCR_P1, (uchar_t)APIC_IMCR_SELECT);
1402 		outb(APIC_IMCR_P2, (uchar_t)APIC_IMCR_PIC);
1403 	}
1404 
1405 	apic_disable_local_apic();
1406 
1407 	intr_restore(iflag);
1408 
1409 	/* remainder of function is for shutdown cases only */
1410 	if (cmd != A_SHUTDOWN)
1411 		return;
1412 
1413 	/*
1414 	 * Switch system back into Legacy-Mode if using ACPI and
1415 	 * not powering-off.  Some BIOSes need to remain in ACPI-mode
1416 	 * for power-off to succeed (Dell Dimension 4600)
1417 	 */
1418 	if (apic_enable_acpi && (fcn != AD_POWEROFF))
1419 		(void) AcpiDisable();
1420 
1421 	/* remainder of function is for shutdown+poweroff case only */
1422 	if (fcn != AD_POWEROFF)
1423 		return;
1424 
1425 	switch (apic_poweroff_method) {
1426 		case APIC_POWEROFF_VIA_RTC:
1427 
1428 			/* select the extended NVRAM bank in the RTC */
1429 			outb(CMOS_ADDR, RTC_REGA);
1430 			byte = inb(CMOS_DATA);
1431 			outb(CMOS_DATA, (byte | EXT_BANK));
1432 
1433 			outb(CMOS_ADDR, PFR_REG);
1434 
1435 			/* for Predator must toggle the PAB bit */
1436 			byte = inb(CMOS_DATA);
1437 
1438 			/*
1439 			 * clear power active bar, wakeup alarm and
1440 			 * kickstart
1441 			 */
1442 			byte &= ~(PAB_CBIT | WF_FLAG | KS_FLAG);
1443 			outb(CMOS_DATA, byte);
1444 
1445 			/* delay before next write */
1446 			drv_usecwait(1000);
1447 
1448 			/* for S40 the following would suffice */
1449 			byte = inb(CMOS_DATA);
1450 
1451 			/* power active bar control bit */
1452 			byte |= PAB_CBIT;
1453 			outb(CMOS_DATA, byte);
1454 
1455 			break;
1456 
1457 		case APIC_POWEROFF_VIA_ASPEN_BMC:
1458 			restarts = 0;
1459 restart_aspen_bmc:
1460 			if (++restarts == 3)
1461 				break;
1462 			attempts = 0;
1463 			do {
1464 				byte = inb(MISMIC_FLAG_REGISTER);
1465 				byte &= MISMIC_BUSY_MASK;
1466 				if (byte != 0) {
1467 					drv_usecwait(1000);
1468 					if (attempts >= 3)
1469 						goto restart_aspen_bmc;
1470 					++attempts;
1471 				}
1472 			} while (byte != 0);
1473 			outb(MISMIC_CNTL_REGISTER, CC_SMS_GET_STATUS);
1474 			byte = inb(MISMIC_FLAG_REGISTER);
1475 			byte |= 0x1;
1476 			outb(MISMIC_FLAG_REGISTER, byte);
1477 			i = 0;
1478 			for (; i < (sizeof (aspen_bmc)/sizeof (aspen_bmc[0]));
1479 			    i++) {
1480 				attempts = 0;
1481 				do {
1482 					byte = inb(MISMIC_FLAG_REGISTER);
1483 					byte &= MISMIC_BUSY_MASK;
1484 					if (byte != 0) {
1485 						drv_usecwait(1000);
1486 						if (attempts >= 3)
1487 							goto restart_aspen_bmc;
1488 						++attempts;
1489 					}
1490 				} while (byte != 0);
1491 				outb(MISMIC_CNTL_REGISTER, aspen_bmc[i].cntl);
1492 				outb(MISMIC_DATA_REGISTER, aspen_bmc[i].data);
1493 				byte = inb(MISMIC_FLAG_REGISTER);
1494 				byte |= 0x1;
1495 				outb(MISMIC_FLAG_REGISTER, byte);
1496 			}
1497 			break;
1498 
1499 		case APIC_POWEROFF_VIA_SITKA_BMC:
1500 			restarts = 0;
1501 restart_sitka_bmc:
1502 			if (++restarts == 3)
1503 				break;
1504 			attempts = 0;
1505 			do {
1506 				byte = inb(SMS_STATUS_REGISTER);
1507 				byte &= SMS_STATE_MASK;
1508 				if ((byte == SMS_READ_STATE) ||
1509 				    (byte == SMS_WRITE_STATE)) {
1510 					drv_usecwait(1000);
1511 					if (attempts >= 3)
1512 						goto restart_sitka_bmc;
1513 					++attempts;
1514 				}
1515 			} while ((byte == SMS_READ_STATE) ||
1516 			    (byte == SMS_WRITE_STATE));
1517 			outb(SMS_COMMAND_REGISTER, SMS_GET_STATUS);
1518 			i = 0;
1519 			for (; i < (sizeof (sitka_bmc)/sizeof (sitka_bmc[0]));
1520 			    i++) {
1521 				attempts = 0;
1522 				do {
1523 					byte = inb(SMS_STATUS_REGISTER);
1524 					byte &= SMS_IBF_MASK;
1525 					if (byte != 0) {
1526 						drv_usecwait(1000);
1527 						if (attempts >= 3)
1528 							goto restart_sitka_bmc;
1529 						++attempts;
1530 					}
1531 				} while (byte != 0);
1532 				outb(sitka_bmc[i].port, sitka_bmc[i].data);
1533 			}
1534 			break;
1535 
1536 		case APIC_POWEROFF_NONE:
1537 
1538 			/* If no APIC direct method, we will try using ACPI */
1539 			if (apic_enable_acpi) {
1540 				if (acpi_poweroff() == 1)
1541 					return;
1542 			} else
1543 				return;
1544 
1545 			break;
1546 	}
1547 	/*
1548 	 * Wait a limited time here for power to go off.
1549 	 * If the power does not go off, then there was a
1550 	 * problem and we should continue to the halt which
1551 	 * prints a message for the user to press a key to
1552 	 * reboot.
1553 	 */
1554 	drv_usecwait(7000000); /* wait seven seconds */
1555 
1556 }
1557 
1558 /*
1559  * Try and disable all interrupts. We just assign interrupts to other
1560  * processors based on policy. If any were bound by user request, we
1561  * let them continue and return failure. We do not bother to check
1562  * for cache affinity while rebinding.
1563  */
1564 
1565 static int
1566 apic_disable_intr(processorid_t cpun)
1567 {
1568 	int bind_cpu = 0, i, hardbound = 0;
1569 	apic_irq_t *irq_ptr;
1570 	ulong_t iflag;
1571 
1572 	iflag = intr_clear();
1573 	lock_set(&apic_ioapic_lock);
1574 
1575 	for (i = 0; i <= APIC_MAX_VECTOR; i++) {
1576 		if (apic_reprogram_info[i].done == B_FALSE) {
1577 			if (apic_reprogram_info[i].bindcpu == cpun) {
1578 				/*
1579 				 * CPU is busy -- it's the target of
1580 				 * a pending reprogramming attempt
1581 				 */
1582 				lock_clear(&apic_ioapic_lock);
1583 				intr_restore(iflag);
1584 				return (PSM_FAILURE);
1585 			}
1586 		}
1587 	}
1588 
1589 	apic_cpus[cpun].aci_status &= ~APIC_CPU_INTR_ENABLE;
1590 
1591 	apic_cpus[cpun].aci_curipl = 0;
1592 
1593 	i = apic_min_device_irq;
1594 	for (; i <= apic_max_device_irq; i++) {
1595 		/*
1596 		 * If there are bound interrupts on this cpu, then
1597 		 * rebind them to other processors.
1598 		 */
1599 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1600 			ASSERT((irq_ptr->airq_temp_cpu == IRQ_UNBOUND) ||
1601 			    (irq_ptr->airq_temp_cpu == IRQ_UNINIT) ||
1602 			    ((irq_ptr->airq_temp_cpu & ~IRQ_USER_BOUND) <
1603 			    apic_nproc));
1604 
1605 			if (irq_ptr->airq_temp_cpu == (cpun | IRQ_USER_BOUND)) {
1606 				hardbound = 1;
1607 				continue;
1608 			}
1609 
1610 			if (irq_ptr->airq_temp_cpu == cpun) {
1611 				do {
1612 					bind_cpu = apic_next_bind_cpu++;
1613 					if (bind_cpu >= apic_nproc) {
1614 						apic_next_bind_cpu = 1;
1615 						bind_cpu = 0;
1616 
1617 					}
1618 				} while (apic_rebind_all(irq_ptr, bind_cpu));
1619 			}
1620 		}
1621 	}
1622 
1623 	lock_clear(&apic_ioapic_lock);
1624 	intr_restore(iflag);
1625 
1626 	if (hardbound) {
1627 		cmn_err(CE_WARN, "Could not disable interrupts on %d"
1628 		    "due to user bound interrupts", cpun);
1629 		return (PSM_FAILURE);
1630 	}
1631 	else
1632 		return (PSM_SUCCESS);
1633 }
1634 
1635 static void
1636 apic_enable_intr(processorid_t cpun)
1637 {
1638 	int	i;
1639 	apic_irq_t *irq_ptr;
1640 	ulong_t iflag;
1641 
1642 	iflag = intr_clear();
1643 	lock_set(&apic_ioapic_lock);
1644 
1645 	apic_cpus[cpun].aci_status |= APIC_CPU_INTR_ENABLE;
1646 
1647 	i = apic_min_device_irq;
1648 	for (i = apic_min_device_irq; i <= apic_max_device_irq; i++) {
1649 		if ((irq_ptr = apic_irq_table[i]) != NULL) {
1650 			if ((irq_ptr->airq_cpu & ~IRQ_USER_BOUND) == cpun) {
1651 				(void) apic_rebind_all(irq_ptr,
1652 				    irq_ptr->airq_cpu);
1653 			}
1654 		}
1655 	}
1656 
1657 	lock_clear(&apic_ioapic_lock);
1658 	intr_restore(iflag);
1659 }
1660 
1661 
1662 /*
1663  * This function will reprogram the timer.
1664  *
1665  * When in oneshot mode the argument is the absolute time in future to
1666  * generate the interrupt at.
1667  *
1668  * When in periodic mode, the argument is the interval at which the
1669  * interrupts should be generated. There is no need to support the periodic
1670  * mode timer change at this time.
1671  */
1672 static void
1673 apic_timer_reprogram(hrtime_t time)
1674 {
1675 	hrtime_t now;
1676 	uint_t ticks;
1677 	int64_t delta;
1678 
1679 	/*
1680 	 * We should be called from high PIL context (CBE_HIGH_PIL),
1681 	 * so kpreempt is disabled.
1682 	 */
1683 
1684 	if (!apic_oneshot) {
1685 		/* time is the interval for periodic mode */
1686 		ticks = APIC_NSECS_TO_TICKS(time);
1687 	} else {
1688 		/* one shot mode */
1689 
1690 		now = gethrtime();
1691 		delta = time - now;
1692 
1693 		if (delta <= 0) {
1694 			/*
1695 			 * requested to generate an interrupt in the past
1696 			 * generate an interrupt as soon as possible
1697 			 */
1698 			ticks = apic_min_timer_ticks;
1699 		} else if (delta > apic_nsec_max) {
1700 			/*
1701 			 * requested to generate an interrupt at a time
1702 			 * further than what we are capable of. Set to max
1703 			 * the hardware can handle
1704 			 */
1705 
1706 			ticks = APIC_MAXVAL;
1707 #ifdef DEBUG
1708 			cmn_err(CE_CONT, "apic_timer_reprogram, request at"
1709 			    "  %lld  too far in future, current time"
1710 			    "  %lld \n", time, now);
1711 #endif
1712 		} else
1713 			ticks = APIC_NSECS_TO_TICKS(delta);
1714 	}
1715 
1716 	if (ticks < apic_min_timer_ticks)
1717 		ticks = apic_min_timer_ticks;
1718 
1719 	apicadr[APIC_INIT_COUNT] = ticks;
1720 
1721 }
1722 
1723 /*
1724  * This function will enable timer interrupts.
1725  */
1726 static void
1727 apic_timer_enable(void)
1728 {
1729 	/*
1730 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1731 	 * so kpreempt is disabled.
1732 	 */
1733 
1734 	if (!apic_oneshot)
1735 		apicadr[APIC_LOCAL_TIMER] =
1736 		    (apic_clkvect + APIC_BASE_VECT) | AV_TIME;
1737 	else {
1738 		/* one shot */
1739 		apicadr[APIC_LOCAL_TIMER] = (apic_clkvect + APIC_BASE_VECT);
1740 	}
1741 }
1742 
1743 /*
1744  * This function will disable timer interrupts.
1745  */
1746 static void
1747 apic_timer_disable(void)
1748 {
1749 	/*
1750 	 * We should be Called from high PIL context (CBE_HIGH_PIL),
1751 	 * so kpreempt is disabled.
1752 	 */
1753 
1754 	apicadr[APIC_LOCAL_TIMER] = (apic_clkvect + APIC_BASE_VECT) | AV_MASK;
1755 }
1756 
1757 
1758 ddi_periodic_t apic_periodic_id;
1759 
1760 /*
1761  * If this module needs a periodic handler for the interrupt distribution, it
1762  * can be added here. The argument to the periodic handler is not currently
1763  * used, but is reserved for future.
1764  */
1765 static void
1766 apic_post_cyclic_setup(void *arg)
1767 {
1768 _NOTE(ARGUNUSED(arg))
1769 	/* cpu_lock is held */
1770 	/* set up a periodic handler for intr redistribution */
1771 
1772 	/*
1773 	 * In peridoc mode intr redistribution processing is done in
1774 	 * apic_intr_enter during clk intr processing
1775 	 */
1776 	if (!apic_oneshot)
1777 		return;
1778 	/*
1779 	 * Register a periodical handler for the redistribution processing.
1780 	 * On X86, CY_LOW_LEVEL is mapped to the level 2 interrupt, so
1781 	 * DDI_IPL_2 should be passed to ddi_periodic_add() here.
1782 	 */
1783 	apic_periodic_id = ddi_periodic_add(
1784 	    (void (*)(void *))apic_redistribute_compute, NULL,
1785 	    apic_redistribute_sample_interval, DDI_IPL_2);
1786 }
1787 
1788 static void
1789 apic_redistribute_compute(void)
1790 {
1791 	int	i, j, max_busy;
1792 
1793 	if (apic_enable_dynamic_migration) {
1794 		if (++apic_nticks == apic_sample_factor_redistribution) {
1795 			/*
1796 			 * Time to call apic_intr_redistribute().
1797 			 * reset apic_nticks. This will cause max_busy
1798 			 * to be calculated below and if it is more than
1799 			 * apic_int_busy, we will do the whole thing
1800 			 */
1801 			apic_nticks = 0;
1802 		}
1803 		max_busy = 0;
1804 		for (i = 0; i < apic_nproc; i++) {
1805 
1806 			/*
1807 			 * Check if curipl is non zero & if ISR is in
1808 			 * progress
1809 			 */
1810 			if (((j = apic_cpus[i].aci_curipl) != 0) &&
1811 			    (apic_cpus[i].aci_ISR_in_progress & (1 << j))) {
1812 
1813 				int	irq;
1814 				apic_cpus[i].aci_busy++;
1815 				irq = apic_cpus[i].aci_current[j];
1816 				apic_irq_table[irq]->airq_busy++;
1817 			}
1818 
1819 			if (!apic_nticks &&
1820 			    (apic_cpus[i].aci_busy > max_busy))
1821 				max_busy = apic_cpus[i].aci_busy;
1822 		}
1823 		if (!apic_nticks) {
1824 			if (max_busy > apic_int_busy_mark) {
1825 			/*
1826 			 * We could make the following check be
1827 			 * skipped > 1 in which case, we get a
1828 			 * redistribution at half the busy mark (due to
1829 			 * double interval). Need to be able to collect
1830 			 * more empirical data to decide if that is a
1831 			 * good strategy. Punt for now.
1832 			 */
1833 				if (apic_skipped_redistribute) {
1834 					apic_cleanup_busy();
1835 					apic_skipped_redistribute = 0;
1836 				} else {
1837 					apic_intr_redistribute();
1838 				}
1839 			} else
1840 				apic_skipped_redistribute++;
1841 		}
1842 	}
1843 }
1844 
1845 
1846 /*
1847  * The following functions are in the platform specific file so that they
1848  * can be different functions depending on whether we are running on
1849  * bare metal or a hypervisor.
1850  */
1851 
1852 /*
1853  * map an apic for memory-mapped access
1854  */
1855 uint32_t *
1856 mapin_apic(uint32_t addr, size_t len, int flags)
1857 {
1858 	/*LINTED: pointer cast may result in improper alignment */
1859 	return ((uint32_t *)psm_map_phys(addr, len, flags));
1860 }
1861 
1862 uint32_t *
1863 mapin_ioapic(uint32_t addr, size_t len, int flags)
1864 {
1865 	return (mapin_apic(addr, len, flags));
1866 }
1867 
1868 /*
1869  * unmap an apic
1870  */
1871 void
1872 mapout_apic(caddr_t addr, size_t len)
1873 {
1874 	psm_unmap_phys(addr, len);
1875 }
1876 
1877 void
1878 mapout_ioapic(caddr_t addr, size_t len)
1879 {
1880 	mapout_apic(addr, len);
1881 }
1882 
1883 /*
1884  * Check to make sure there are enough irq slots
1885  */
1886 int
1887 apic_check_free_irqs(int count)
1888 {
1889 	int i, avail;
1890 
1891 	avail = 0;
1892 	for (i = APIC_FIRST_FREE_IRQ; i < APIC_RESV_IRQ; i++) {
1893 		if ((apic_irq_table[i] == NULL) ||
1894 		    apic_irq_table[i]->airq_mps_intr_index == FREE_INDEX) {
1895 			if (++avail >= count)
1896 				return (PSM_SUCCESS);
1897 		}
1898 	}
1899 	return (PSM_FAILURE);
1900 }
1901 
1902 /*
1903  * This function allocates "count" MSI vector(s) for the given "dip/pri/type"
1904  */
1905 int
1906 apic_alloc_msi_vectors(dev_info_t *dip, int inum, int count, int pri,
1907     int behavior)
1908 {
1909 	int	rcount, i;
1910 	uchar_t	start, irqno, cpu;
1911 	major_t	major;
1912 	apic_irq_t	*irqptr;
1913 
1914 	DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: dip=0x%p "
1915 	    "inum=0x%x  pri=0x%x count=0x%x behavior=%d\n",
1916 	    (void *)dip, inum, pri, count, behavior));
1917 
1918 	if (count > 1) {
1919 		if (behavior == DDI_INTR_ALLOC_STRICT &&
1920 		    (apic_multi_msi_enable == 0 || count > apic_multi_msi_max))
1921 			return (0);
1922 
1923 		if (apic_multi_msi_enable == 0)
1924 			count = 1;
1925 		else if (count > apic_multi_msi_max)
1926 			count = apic_multi_msi_max;
1927 	}
1928 
1929 	if ((rcount = apic_navail_vector(dip, pri)) > count)
1930 		rcount = count;
1931 	else if (rcount == 0 || (rcount < count &&
1932 	    behavior == DDI_INTR_ALLOC_STRICT))
1933 		return (0);
1934 
1935 	/* if not ISP2, then round it down */
1936 	if (!ISP2(rcount))
1937 		rcount = 1 << (highbit(rcount) - 1);
1938 
1939 	mutex_enter(&airq_mutex);
1940 
1941 	for (start = 0; rcount > 0; rcount >>= 1) {
1942 		if ((start = apic_find_multi_vectors(pri, rcount)) != 0 ||
1943 		    behavior == DDI_INTR_ALLOC_STRICT)
1944 			break;
1945 	}
1946 
1947 	if (start == 0) {
1948 		/* no vector available */
1949 		mutex_exit(&airq_mutex);
1950 		return (0);
1951 	}
1952 
1953 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
1954 		/* not enough free irq slots available */
1955 		mutex_exit(&airq_mutex);
1956 		return (0);
1957 	}
1958 
1959 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
1960 	for (i = 0; i < rcount; i++) {
1961 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
1962 		    (uchar_t)-1) {
1963 			/*
1964 			 * shouldn't happen because of the
1965 			 * apic_check_free_irqs() check earlier
1966 			 */
1967 			mutex_exit(&airq_mutex);
1968 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
1969 			    "apic_allocate_irq failed\n"));
1970 			return (i);
1971 		}
1972 		apic_max_device_irq = max(irqno, apic_max_device_irq);
1973 		apic_min_device_irq = min(irqno, apic_min_device_irq);
1974 		irqptr = apic_irq_table[irqno];
1975 #ifdef	DEBUG
1976 		if (apic_vector_to_irq[start + i] != APIC_RESV_IRQ)
1977 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: "
1978 			    "apic_vector_to_irq is not APIC_RESV_IRQ\n"));
1979 #endif
1980 		apic_vector_to_irq[start + i] = (uchar_t)irqno;
1981 
1982 		irqptr->airq_vector = (uchar_t)(start + i);
1983 		irqptr->airq_ioapicindex = (uchar_t)inum;	/* start */
1984 		irqptr->airq_intin_no = (uchar_t)rcount;
1985 		irqptr->airq_ipl = pri;
1986 		irqptr->airq_vector = start + i;
1987 		irqptr->airq_origirq = (uchar_t)(inum + i);
1988 		irqptr->airq_share_id = 0;
1989 		irqptr->airq_mps_intr_index = MSI_INDEX;
1990 		irqptr->airq_dip = dip;
1991 		irqptr->airq_major = major;
1992 		if (i == 0) /* they all bound to the same cpu */
1993 			cpu = irqptr->airq_cpu = apic_bind_intr(dip, irqno,
1994 			    0xff, 0xff);
1995 		else
1996 			irqptr->airq_cpu = cpu;
1997 		DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msi_vectors: irq=0x%x "
1998 		    "dip=0x%p vector=0x%x origirq=0x%x pri=0x%x\n", irqno,
1999 		    (void *)irqptr->airq_dip, irqptr->airq_vector,
2000 		    irqptr->airq_origirq, pri));
2001 	}
2002 	mutex_exit(&airq_mutex);
2003 	return (rcount);
2004 }
2005 
2006 /*
2007  * This function allocates "count" MSI-X vector(s) for the given "dip/pri/type"
2008  */
2009 int
2010 apic_alloc_msix_vectors(dev_info_t *dip, int inum, int count, int pri,
2011     int behavior)
2012 {
2013 	int	rcount, i;
2014 	major_t	major;
2015 
2016 	if (count > 1) {
2017 		if (behavior == DDI_INTR_ALLOC_STRICT) {
2018 			if (count > apic_msix_max)
2019 				return (0);
2020 		} else if (count > apic_msix_max)
2021 			count = apic_msix_max;
2022 	}
2023 
2024 	mutex_enter(&airq_mutex);
2025 
2026 	if ((rcount = apic_navail_vector(dip, pri)) > count)
2027 		rcount = count;
2028 	else if (rcount == 0 || (rcount < count &&
2029 	    behavior == DDI_INTR_ALLOC_STRICT)) {
2030 		rcount = 0;
2031 		goto out;
2032 	}
2033 
2034 	if (apic_check_free_irqs(rcount) == PSM_FAILURE) {
2035 		/* not enough free irq slots available */
2036 		rcount = 0;
2037 		goto out;
2038 	}
2039 
2040 	major = (dip != NULL) ? ddi_name_to_major(ddi_get_name(dip)) : 0;
2041 	for (i = 0; i < rcount; i++) {
2042 		uchar_t	vector, irqno;
2043 		apic_irq_t	*irqptr;
2044 
2045 		if ((irqno = apic_allocate_irq(apic_first_avail_irq)) ==
2046 		    (uchar_t)-1) {
2047 			/*
2048 			 * shouldn't happen because of the
2049 			 * apic_check_free_irqs() check earlier
2050 			 */
2051 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2052 			    "apic_allocate_irq failed\n"));
2053 			rcount = i;
2054 			goto out;
2055 		}
2056 		if ((vector = apic_allocate_vector(pri, irqno, 1)) == 0) {
2057 			/*
2058 			 * shouldn't happen because of the
2059 			 * apic_navail_vector() call earlier
2060 			 */
2061 			DDI_INTR_IMPLDBG((CE_CONT, "apic_alloc_msix_vectors: "
2062 			    "apic_allocate_vector failed\n"));
2063 			rcount = i;
2064 			goto out;
2065 		}
2066 		apic_max_device_irq = max(irqno, apic_max_device_irq);
2067 		apic_min_device_irq = min(irqno, apic_min_device_irq);
2068 		irqptr = apic_irq_table[irqno];
2069 		irqptr->airq_vector = (uchar_t)vector;
2070 		irqptr->airq_ipl = pri;
2071 		irqptr->airq_origirq = (uchar_t)(inum + i);
2072 		irqptr->airq_share_id = 0;
2073 		irqptr->airq_mps_intr_index = MSIX_INDEX;
2074 		irqptr->airq_dip = dip;
2075 		irqptr->airq_major = major;
2076 		irqptr->airq_cpu = apic_bind_intr(dip, irqno, 0xff, 0xff);
2077 	}
2078 out:
2079 	mutex_exit(&airq_mutex);
2080 	return (rcount);
2081 }
2082 
2083 /*
2084  * Allocate a free vector for irq at ipl. Takes care of merging of multiple
2085  * IPLs into a single APIC level as well as stretching some IPLs onto multiple
2086  * levels. APIC_HI_PRI_VECTS interrupts are reserved for high priority
2087  * requests and allocated only when pri is set.
2088  */
2089 uchar_t
2090 apic_allocate_vector(int ipl, int irq, int pri)
2091 {
2092 	int	lowest, highest, i;
2093 
2094 	highest = apic_ipltopri[ipl] + APIC_VECTOR_MASK;
2095 	lowest = apic_ipltopri[ipl - 1] + APIC_VECTOR_PER_IPL;
2096 
2097 	if (highest < lowest) /* Both ipl and ipl - 1 map to same pri */
2098 		lowest -= APIC_VECTOR_PER_IPL;
2099 
2100 #ifdef	DEBUG
2101 	if (apic_restrict_vector)	/* for testing shared interrupt logic */
2102 		highest = lowest + apic_restrict_vector + APIC_HI_PRI_VECTS;
2103 #endif /* DEBUG */
2104 	if (pri == 0)
2105 		highest -= APIC_HI_PRI_VECTS;
2106 
2107 	for (i = lowest; i < highest; i++) {
2108 		if (APIC_CHECK_RESERVE_VECTORS(i))
2109 			continue;
2110 		if (apic_vector_to_irq[i] == APIC_RESV_IRQ) {
2111 			apic_vector_to_irq[i] = (uchar_t)irq;
2112 			return (i);
2113 		}
2114 	}
2115 
2116 	return (0);
2117 }
2118 
2119 /* Mark vector as not being used by any irq */
2120 void
2121 apic_free_vector(uchar_t vector)
2122 {
2123 	apic_vector_to_irq[vector] = APIC_RESV_IRQ;
2124 }
2125 
2126 uint32_t
2127 ioapic_read(int ioapic_ix, uint32_t reg)
2128 {
2129 	volatile uint32_t *ioapic;
2130 
2131 	ioapic = apicioadr[ioapic_ix];
2132 	ioapic[APIC_IO_REG] = reg;
2133 	return (ioapic[APIC_IO_DATA]);
2134 }
2135 
2136 void
2137 ioapic_write(int ioapic_ix, uint32_t reg, uint32_t value)
2138 {
2139 	volatile uint32_t *ioapic;
2140 
2141 	ioapic = apicioadr[ioapic_ix];
2142 	ioapic[APIC_IO_REG] = reg;
2143 	ioapic[APIC_IO_DATA] = value;
2144 }
2145 
2146 static processorid_t
2147 apic_find_cpu(int flag)
2148 {
2149 	processorid_t acid = 0;
2150 	int i;
2151 
2152 	/* Find the first CPU with the passed-in flag set */
2153 	for (i = 0; i < apic_nproc; i++) {
2154 		if (apic_cpus[i].aci_status & flag) {
2155 			acid = i;
2156 			break;
2157 		}
2158 	}
2159 
2160 	ASSERT((apic_cpus[acid].aci_status & flag) != 0);
2161 	return (acid);
2162 }
2163 
2164 /*
2165  * Call rebind to do the actual programming.
2166  * Must be called with interrupts disabled and apic_ioapic_lock held
2167  * 'p' is polymorphic -- if this function is called to process a deferred
2168  * reprogramming, p is of type 'struct ioapic_reprogram_data *', from which
2169  * the irq pointer is retrieved.  If not doing deferred reprogramming,
2170  * p is of the type 'apic_irq_t *'.
2171  *
2172  * apic_ioapic_lock must be held across this call, as it protects apic_rebind
2173  * and it protects apic_find_cpu() from a race in which a CPU can be taken
2174  * offline after a cpu is selected, but before apic_rebind is called to
2175  * bind interrupts to it.
2176  */
2177 int
2178 apic_setup_io_intr(void *p, int irq, boolean_t deferred)
2179 {
2180 	apic_irq_t *irqptr;
2181 	struct ioapic_reprogram_data *drep = NULL;
2182 	int rv;
2183 
2184 	if (deferred) {
2185 		drep = (struct ioapic_reprogram_data *)p;
2186 		ASSERT(drep != NULL);
2187 		irqptr = drep->irqp;
2188 	} else
2189 		irqptr = (apic_irq_t *)p;
2190 
2191 	ASSERT(irqptr != NULL);
2192 
2193 	rv = apic_rebind(irqptr, apic_irq_table[irq]->airq_cpu, drep);
2194 	if (rv) {
2195 		/*
2196 		 * CPU is not up or interrupts are disabled. Fall back to
2197 		 * the first available CPU
2198 		 */
2199 		rv = apic_rebind(irqptr, apic_find_cpu(APIC_CPU_INTR_ENABLE),
2200 		    drep);
2201 	}
2202 
2203 	return (rv);
2204 }
2205 
2206 
2207 uchar_t
2208 apic_modify_vector(uchar_t vector, int irq)
2209 {
2210 	apic_vector_to_irq[vector] = (uchar_t)irq;
2211 	return (vector);
2212 }
2213 
2214 char *
2215 apic_get_apic_type()
2216 {
2217 	return (apic_psm_info.p_mach_idstring);
2218 }
2219