xref: /illumos-gate/usr/src/uts/i86pc/os/mp_machdep.c (revision 46b592853d0f4f11781b6b0a7533f267c6aee132)
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  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /*
26  * Copyright (c) 2009, Intel Corporation.
27  * All rights reserved.
28  */
29 
30 #define	PSMI_1_6
31 #include <sys/smp_impldefs.h>
32 #include <sys/psm.h>
33 #include <sys/psm_modctl.h>
34 #include <sys/pit.h>
35 #include <sys/cmn_err.h>
36 #include <sys/strlog.h>
37 #include <sys/clock.h>
38 #include <sys/debug.h>
39 #include <sys/rtc.h>
40 #include <sys/x86_archext.h>
41 #include <sys/cpupart.h>
42 #include <sys/cpuvar.h>
43 #include <sys/cpu_event.h>
44 #include <sys/cmt.h>
45 #include <sys/cpu.h>
46 #include <sys/disp.h>
47 #include <sys/archsystm.h>
48 #include <sys/machsystm.h>
49 #include <sys/sysmacros.h>
50 #include <sys/memlist.h>
51 #include <sys/param.h>
52 #include <sys/promif.h>
53 #include <sys/cpu_pm.h>
54 #if defined(__xpv)
55 #include <sys/hypervisor.h>
56 #endif
57 #include <sys/mach_intr.h>
58 #include <vm/hat_i86.h>
59 #include <sys/kdi_machimpl.h>
60 #include <sys/sdt.h>
61 #include <sys/hpet.h>
62 #include <sys/sunddi.h>
63 #include <sys/sunndi.h>
64 
65 #define	OFFSETOF(s, m)		(size_t)(&(((s *)0)->m))
66 
67 /*
68  *	Local function prototypes
69  */
70 static int mp_disable_intr(processorid_t cpun);
71 static void mp_enable_intr(processorid_t cpun);
72 static void mach_init();
73 static void mach_picinit();
74 static int machhztomhz(uint64_t cpu_freq_hz);
75 static uint64_t mach_getcpufreq(void);
76 static void mach_fixcpufreq(void);
77 static int mach_clkinit(int, int *);
78 static void mach_smpinit(void);
79 static int mach_softlvl_to_vect(int ipl);
80 static void mach_get_platform(int owner);
81 static void mach_construct_info();
82 static int mach_translate_irq(dev_info_t *dip, int irqno);
83 static int mach_intr_ops(dev_info_t *, ddi_intr_handle_impl_t *,
84     psm_intr_op_t, int *);
85 static void mach_notify_error(int level, char *errmsg);
86 static hrtime_t dummy_hrtime(void);
87 static void dummy_scalehrtime(hrtime_t *);
88 static uint64_t dummy_unscalehrtime(hrtime_t);
89 void cpu_idle(void);
90 static void cpu_wakeup(cpu_t *, int);
91 #ifndef __xpv
92 void cpu_idle_mwait(void);
93 static void cpu_wakeup_mwait(cpu_t *, int);
94 #endif
95 static int mach_cpu_create_devinfo(cpu_t *cp, dev_info_t **dipp);
96 
97 /*
98  *	External reference functions
99  */
100 extern void return_instr();
101 extern uint64_t freq_tsc(uint32_t *);
102 #if defined(__i386)
103 extern uint64_t freq_notsc(uint32_t *);
104 #endif
105 extern void pc_gethrestime(timestruc_t *);
106 extern int cpuid_get_coreid(cpu_t *);
107 extern int cpuid_get_chipid(cpu_t *);
108 
109 /*
110  *	PSM functions initialization
111  */
112 void (*psm_shutdownf)(int, int)	= (void (*)(int, int))return_instr;
113 void (*psm_preshutdownf)(int, int) = (void (*)(int, int))return_instr;
114 void (*psm_notifyf)(int)	= (void (*)(int))return_instr;
115 void (*psm_set_idle_cpuf)(int)	= (void (*)(int))return_instr;
116 void (*psm_unset_idle_cpuf)(int) = (void (*)(int))return_instr;
117 void (*psminitf)()		= mach_init;
118 void (*picinitf)() 		= return_instr;
119 int (*clkinitf)(int, int *) 	= (int (*)(int, int *))return_instr;
120 int (*ap_mlsetup)() 		= (int (*)(void))return_instr;
121 void (*send_dirintf)() 		= return_instr;
122 void (*setspl)(int)		= (void (*)(int))return_instr;
123 int (*addspl)(int, int, int, int) = (int (*)(int, int, int, int))return_instr;
124 int (*delspl)(int, int, int, int) = (int (*)(int, int, int, int))return_instr;
125 void (*kdisetsoftint)(int, struct av_softinfo *)=
126 	(void (*)(int, struct av_softinfo *))return_instr;
127 void (*setsoftint)(int, struct av_softinfo *)=
128 	(void (*)(int, struct av_softinfo *))return_instr;
129 int (*slvltovect)(int)		= (int (*)(int))return_instr;
130 int (*setlvl)(int, int *)	= (int (*)(int, int *))return_instr;
131 void (*setlvlx)(int, int)	= (void (*)(int, int))return_instr;
132 int (*psm_disable_intr)(int)	= mp_disable_intr;
133 void (*psm_enable_intr)(int)	= mp_enable_intr;
134 hrtime_t (*gethrtimef)(void)	= dummy_hrtime;
135 hrtime_t (*gethrtimeunscaledf)(void)	= dummy_hrtime;
136 void (*scalehrtimef)(hrtime_t *)	= dummy_scalehrtime;
137 uint64_t (*unscalehrtimef)(hrtime_t)	= dummy_unscalehrtime;
138 int (*psm_translate_irq)(dev_info_t *, int) = mach_translate_irq;
139 void (*gethrestimef)(timestruc_t *) = pc_gethrestime;
140 void (*psm_notify_error)(int, char *) = (void (*)(int, char *))NULL;
141 int (*psm_get_clockirq)(int) = NULL;
142 int (*psm_get_ipivect)(int, int) = NULL;
143 
144 int (*psm_clkinit)(int) = NULL;
145 void (*psm_timer_reprogram)(hrtime_t) = NULL;
146 void (*psm_timer_enable)(void) = NULL;
147 void (*psm_timer_disable)(void) = NULL;
148 void (*psm_post_cyclic_setup)(void *arg) = NULL;
149 int (*psm_intr_ops)(dev_info_t *, ddi_intr_handle_impl_t *, psm_intr_op_t,
150     int *) = mach_intr_ops;
151 int (*psm_state)(psm_state_request_t *) = (int (*)(psm_state_request_t *))
152     return_instr;
153 
154 void (*notify_error)(int, char *) = (void (*)(int, char *))return_instr;
155 void (*hrtime_tick)(void)	= return_instr;
156 
157 int (*psm_cpu_create_devinfo)(cpu_t *, dev_info_t **) = mach_cpu_create_devinfo;
158 
159 /*
160  * True if the generic TSC code is our source of hrtime, rather than whatever
161  * the PSM can provide.
162  */
163 #ifdef __xpv
164 int tsc_gethrtime_enable = 0;
165 #else
166 int tsc_gethrtime_enable = 1;
167 #endif
168 int tsc_gethrtime_initted = 0;
169 
170 /*
171  * True if the hrtime implementation is "hires"; namely, better than microdata.
172  */
173 int gethrtime_hires = 0;
174 
175 /*
176  * Local Static Data
177  */
178 static struct psm_ops mach_ops;
179 static struct psm_ops *mach_set[4] = {&mach_ops, NULL, NULL, NULL};
180 static ushort_t mach_ver[4] = {0, 0, 0, 0};
181 
182 /*
183  * virtualization support for psm
184  */
185 void *psm_vt_ops = NULL;
186 /*
187  * If non-zero, idle cpus will become "halted" when there's
188  * no work to do.
189  */
190 int	idle_cpu_use_hlt = 1;
191 
192 #ifndef __xpv
193 /*
194  * If non-zero, idle cpus will use mwait if available to halt instead of hlt.
195  */
196 int	idle_cpu_prefer_mwait = 1;
197 /*
198  * Set to 0 to avoid MONITOR+CLFLUSH assertion.
199  */
200 int	idle_cpu_assert_cflush_monitor = 1;
201 
202 /*
203  * If non-zero, idle cpus will not use power saving Deep C-States idle loop.
204  */
205 int	idle_cpu_no_deep_c = 0;
206 /*
207  * Non-power saving idle loop and wakeup pointers.
208  * Allows user to toggle Deep Idle power saving feature on/off.
209  */
210 void	(*non_deep_idle_cpu)() = cpu_idle;
211 void	(*non_deep_idle_disp_enq_thread)(cpu_t *, int);
212 
213 /*
214  * Object for the kernel to access the HPET.
215  */
216 hpet_t hpet;
217 
218 #endif	/* ifndef __xpv */
219 
220 /*ARGSUSED*/
221 int
222 pg_plat_hw_shared(cpu_t *cp, pghw_type_t hw)
223 {
224 	switch (hw) {
225 	case PGHW_IPIPE:
226 		if (x86_feature & (X86_HTT)) {
227 			/*
228 			 * Hyper-threading is SMT
229 			 */
230 			return (1);
231 		} else {
232 			return (0);
233 		}
234 	case PGHW_CHIP:
235 		if (x86_feature & (X86_CMP|X86_HTT))
236 			return (1);
237 		else
238 			return (0);
239 	case PGHW_CACHE:
240 		if (cpuid_get_ncpu_sharing_last_cache(cp) > 1)
241 			return (1);
242 		else
243 			return (0);
244 	case PGHW_POW_ACTIVE:
245 		if (cpupm_domain_id(cp, CPUPM_DTYPE_ACTIVE) != (id_t)-1)
246 			return (1);
247 		else
248 			return (0);
249 	case PGHW_POW_IDLE:
250 		if (cpupm_domain_id(cp, CPUPM_DTYPE_IDLE) != (id_t)-1)
251 			return (1);
252 		else
253 			return (0);
254 	default:
255 		return (0);
256 	}
257 }
258 
259 /*
260  * Compare two CPUs and see if they have a pghw_type_t sharing relationship
261  * If pghw_type_t is an unsupported hardware type, then return -1
262  */
263 int
264 pg_plat_cpus_share(cpu_t *cpu_a, cpu_t *cpu_b, pghw_type_t hw)
265 {
266 	id_t pgp_a, pgp_b;
267 
268 	pgp_a = pg_plat_hw_instance_id(cpu_a, hw);
269 	pgp_b = pg_plat_hw_instance_id(cpu_b, hw);
270 
271 	if (pgp_a == -1 || pgp_b == -1)
272 		return (-1);
273 
274 	return (pgp_a == pgp_b);
275 }
276 
277 /*
278  * Return a physical instance identifier for known hardware sharing
279  * relationships
280  */
281 id_t
282 pg_plat_hw_instance_id(cpu_t *cpu, pghw_type_t hw)
283 {
284 	switch (hw) {
285 	case PGHW_IPIPE:
286 		return (cpuid_get_coreid(cpu));
287 	case PGHW_CACHE:
288 		return (cpuid_get_last_lvl_cacheid(cpu));
289 	case PGHW_CHIP:
290 		return (cpuid_get_chipid(cpu));
291 	case PGHW_POW_ACTIVE:
292 		return (cpupm_domain_id(cpu, CPUPM_DTYPE_ACTIVE));
293 	case PGHW_POW_IDLE:
294 		return (cpupm_domain_id(cpu, CPUPM_DTYPE_IDLE));
295 	default:
296 		return (-1);
297 	}
298 }
299 
300 /*
301  * Express preference for optimizing for sharing relationship
302  * hw1 vs hw2
303  */
304 pghw_type_t
305 pg_plat_hw_rank(pghw_type_t hw1, pghw_type_t hw2)
306 {
307 	int i, rank1, rank2;
308 
309 	static pghw_type_t hw_hier[] = {
310 		PGHW_IPIPE,
311 		PGHW_CACHE,
312 		PGHW_CHIP,
313 		PGHW_POW_IDLE,
314 		PGHW_POW_ACTIVE,
315 		PGHW_NUM_COMPONENTS
316 	};
317 
318 	for (i = 0; hw_hier[i] != PGHW_NUM_COMPONENTS; i++) {
319 		if (hw_hier[i] == hw1)
320 			rank1 = i;
321 		if (hw_hier[i] == hw2)
322 			rank2 = i;
323 	}
324 
325 	if (rank1 > rank2)
326 		return (hw1);
327 	else
328 		return (hw2);
329 }
330 
331 /*
332  * Override the default CMT dispatcher policy for the specified
333  * hardware sharing relationship
334  */
335 pg_cmt_policy_t
336 pg_plat_cmt_policy(pghw_type_t hw)
337 {
338 	/*
339 	 * For shared caches, also load balance across them to
340 	 * maximize aggregate cache capacity
341 	 */
342 	switch (hw) {
343 	case PGHW_CACHE:
344 		return (CMT_BALANCE|CMT_AFFINITY);
345 	default:
346 		return (CMT_NO_POLICY);
347 	}
348 }
349 
350 id_t
351 pg_plat_get_core_id(cpu_t *cpu)
352 {
353 	return ((id_t)cpuid_get_coreid(cpu));
354 }
355 
356 void
357 cmp_set_nosteal_interval(void)
358 {
359 	/* Set the nosteal interval (used by disp_getbest()) to 100us */
360 	nosteal_nsec = 100000UL;
361 }
362 
363 /*
364  * Routine to ensure initial callers to hrtime gets 0 as return
365  */
366 static hrtime_t
367 dummy_hrtime(void)
368 {
369 	return (0);
370 }
371 
372 /* ARGSUSED */
373 static void
374 dummy_scalehrtime(hrtime_t *ticks)
375 {}
376 
377 static uint64_t
378 dummy_unscalehrtime(hrtime_t nsecs)
379 {
380 	return ((uint64_t)nsecs);
381 }
382 
383 /*
384  * Supports Deep C-State power saving idle loop.
385  */
386 void
387 cpu_idle_adaptive(void)
388 {
389 	(*CPU->cpu_m.mcpu_idle_cpu)();
390 }
391 
392 /*
393  * Function called by CPU idle notification framework to check whether CPU
394  * has been awakened. It will be called with interrupt disabled.
395  * If CPU has been awakened, call cpu_idle_exit() to notify CPU idle
396  * notification framework.
397  */
398 /*ARGSUSED*/
399 static void
400 cpu_idle_check_wakeup(void *arg)
401 {
402 	/*
403 	 * Toggle interrupt flag to detect pending interrupts.
404 	 * If interrupt happened, do_interrupt() will notify CPU idle
405 	 * notification framework so no need to call cpu_idle_exit() here.
406 	 */
407 	sti();
408 	SMT_PAUSE();
409 	cli();
410 }
411 
412 /*
413  * Idle the present CPU until wakened via an interrupt
414  */
415 void
416 cpu_idle(void)
417 {
418 	cpu_t		*cpup = CPU;
419 	processorid_t	cpu_sid = cpup->cpu_seqid;
420 	cpupart_t	*cp = cpup->cpu_part;
421 	int		hset_update = 1;
422 
423 	/*
424 	 * If this CPU is online, and there's multiple CPUs
425 	 * in the system, then we should notate our halting
426 	 * by adding ourselves to the partition's halted CPU
427 	 * bitmap. This allows other CPUs to find/awaken us when
428 	 * work becomes available.
429 	 */
430 	if (cpup->cpu_flags & CPU_OFFLINE || ncpus == 1)
431 		hset_update = 0;
432 
433 	/*
434 	 * Add ourselves to the partition's halted CPUs bitmap
435 	 * and set our HALTED flag, if necessary.
436 	 *
437 	 * When a thread becomes runnable, it is placed on the queue
438 	 * and then the halted CPU bitmap is checked to determine who
439 	 * (if anyone) should be awakened. We therefore need to first
440 	 * add ourselves to the bitmap, and and then check if there
441 	 * is any work available. The order is important to prevent a race
442 	 * that can lead to work languishing on a run queue somewhere while
443 	 * this CPU remains halted.
444 	 *
445 	 * Either the producing CPU will see we're halted and will awaken us,
446 	 * or this CPU will see the work available in disp_anywork().
447 	 *
448 	 * Note that memory barriers after updating the HALTED flag
449 	 * are not necessary since an atomic operation (updating the bitset)
450 	 * immediately follows. On x86 the atomic operation acts as a
451 	 * memory barrier for the update of cpu_disp_flags.
452 	 */
453 	if (hset_update) {
454 		cpup->cpu_disp_flags |= CPU_DISP_HALTED;
455 		bitset_atomic_add(&cp->cp_haltset, cpu_sid);
456 	}
457 
458 	/*
459 	 * Check to make sure there's really nothing to do.
460 	 * Work destined for this CPU may become available after
461 	 * this check. We'll be notified through the clearing of our
462 	 * bit in the halted CPU bitmap, and a poke.
463 	 */
464 	if (disp_anywork()) {
465 		if (hset_update) {
466 			cpup->cpu_disp_flags &= ~CPU_DISP_HALTED;
467 			bitset_atomic_del(&cp->cp_haltset, cpu_sid);
468 		}
469 		return;
470 	}
471 
472 	/*
473 	 * We're on our way to being halted.
474 	 *
475 	 * Disable interrupts now, so that we'll awaken immediately
476 	 * after halting if someone tries to poke us between now and
477 	 * the time we actually halt.
478 	 *
479 	 * We check for the presence of our bit after disabling interrupts.
480 	 * If it's cleared, we'll return. If the bit is cleared after
481 	 * we check then the poke will pop us out of the halted state.
482 	 *
483 	 * This means that the ordering of the poke and the clearing
484 	 * of the bit by cpu_wakeup is important.
485 	 * cpu_wakeup() must clear, then poke.
486 	 * cpu_idle() must disable interrupts, then check for the bit.
487 	 */
488 	cli();
489 
490 	if (hset_update && bitset_in_set(&cp->cp_haltset, cpu_sid) == 0) {
491 		cpup->cpu_disp_flags &= ~CPU_DISP_HALTED;
492 		sti();
493 		return;
494 	}
495 
496 	/*
497 	 * The check for anything locally runnable is here for performance
498 	 * and isn't needed for correctness. disp_nrunnable ought to be
499 	 * in our cache still, so it's inexpensive to check, and if there
500 	 * is anything runnable we won't have to wait for the poke.
501 	 */
502 	if (cpup->cpu_disp->disp_nrunnable != 0) {
503 		if (hset_update) {
504 			cpup->cpu_disp_flags &= ~CPU_DISP_HALTED;
505 			bitset_atomic_del(&cp->cp_haltset, cpu_sid);
506 		}
507 		sti();
508 		return;
509 	}
510 
511 	if (cpu_idle_enter(IDLE_STATE_C1, 0,
512 	    cpu_idle_check_wakeup, NULL) == 0) {
513 		mach_cpu_idle();
514 		cpu_idle_exit(CPU_IDLE_CB_FLAG_IDLE);
515 	}
516 
517 	/*
518 	 * We're no longer halted
519 	 */
520 	if (hset_update) {
521 		cpup->cpu_disp_flags &= ~CPU_DISP_HALTED;
522 		bitset_atomic_del(&cp->cp_haltset, cpu_sid);
523 	}
524 }
525 
526 
527 /*
528  * If "cpu" is halted, then wake it up clearing its halted bit in advance.
529  * Otherwise, see if other CPUs in the cpu partition are halted and need to
530  * be woken up so that they can steal the thread we placed on this CPU.
531  * This function is only used on MP systems.
532  */
533 static void
534 cpu_wakeup(cpu_t *cpu, int bound)
535 {
536 	uint_t		cpu_found;
537 	processorid_t	cpu_sid;
538 	cpupart_t	*cp;
539 
540 	cp = cpu->cpu_part;
541 	cpu_sid = cpu->cpu_seqid;
542 	if (bitset_in_set(&cp->cp_haltset, cpu_sid)) {
543 		/*
544 		 * Clear the halted bit for that CPU since it will be
545 		 * poked in a moment.
546 		 */
547 		bitset_atomic_del(&cp->cp_haltset, cpu_sid);
548 		/*
549 		 * We may find the current CPU present in the halted cpuset
550 		 * if we're in the context of an interrupt that occurred
551 		 * before we had a chance to clear our bit in cpu_idle().
552 		 * Poking ourself is obviously unnecessary, since if
553 		 * we're here, we're not halted.
554 		 */
555 		if (cpu != CPU)
556 			poke_cpu(cpu->cpu_id);
557 		return;
558 	} else {
559 		/*
560 		 * This cpu isn't halted, but it's idle or undergoing a
561 		 * context switch. No need to awaken anyone else.
562 		 */
563 		if (cpu->cpu_thread == cpu->cpu_idle_thread ||
564 		    cpu->cpu_disp_flags & CPU_DISP_DONTSTEAL)
565 			return;
566 	}
567 
568 	/*
569 	 * No need to wake up other CPUs if this is for a bound thread.
570 	 */
571 	if (bound)
572 		return;
573 
574 	/*
575 	 * The CPU specified for wakeup isn't currently halted, so check
576 	 * to see if there are any other halted CPUs in the partition,
577 	 * and if there are then awaken one.
578 	 */
579 	do {
580 		cpu_found = bitset_find(&cp->cp_haltset);
581 		if (cpu_found == (uint_t)-1)
582 			return;
583 	} while (bitset_atomic_test_and_del(&cp->cp_haltset, cpu_found) < 0);
584 
585 	if (cpu_found != CPU->cpu_seqid) {
586 		poke_cpu(cpu_seq[cpu_found]->cpu_id);
587 	}
588 }
589 
590 #ifndef __xpv
591 /*
592  * Function called by CPU idle notification framework to check whether CPU
593  * has been awakened. It will be called with interrupt disabled.
594  * If CPU has been awakened, call cpu_idle_exit() to notify CPU idle
595  * notification framework.
596  */
597 static void
598 cpu_idle_mwait_check_wakeup(void *arg)
599 {
600 	volatile uint32_t *mcpu_mwait = (volatile uint32_t *)arg;
601 
602 	ASSERT(arg != NULL);
603 	if (*mcpu_mwait != MWAIT_HALTED) {
604 		/*
605 		 * CPU has been awakened, notify CPU idle notification system.
606 		 */
607 		cpu_idle_exit(CPU_IDLE_CB_FLAG_IDLE);
608 	} else {
609 		/*
610 		 * Toggle interrupt flag to detect pending interrupts.
611 		 * If interrupt happened, do_interrupt() will notify CPU idle
612 		 * notification framework so no need to call cpu_idle_exit()
613 		 * here.
614 		 */
615 		sti();
616 		SMT_PAUSE();
617 		cli();
618 	}
619 }
620 
621 /*
622  * Idle the present CPU until awakened via touching its monitored line
623  */
624 void
625 cpu_idle_mwait(void)
626 {
627 	volatile uint32_t	*mcpu_mwait = CPU->cpu_m.mcpu_mwait;
628 	cpu_t			*cpup = CPU;
629 	processorid_t		cpu_sid = cpup->cpu_seqid;
630 	cpupart_t		*cp = cpup->cpu_part;
631 	int			hset_update = 1;
632 
633 	/*
634 	 * Set our mcpu_mwait here, so we can tell if anyone tries to
635 	 * wake us between now and when we call mwait.  No other cpu will
636 	 * attempt to set our mcpu_mwait until we add ourself to the halted
637 	 * CPU bitmap.
638 	 */
639 	*mcpu_mwait = MWAIT_HALTED;
640 
641 	/*
642 	 * If this CPU is online, and there's multiple CPUs
643 	 * in the system, then we should note our halting
644 	 * by adding ourselves to the partition's halted CPU
645 	 * bitmap. This allows other CPUs to find/awaken us when
646 	 * work becomes available.
647 	 */
648 	if (cpup->cpu_flags & CPU_OFFLINE || ncpus == 1)
649 		hset_update = 0;
650 
651 	/*
652 	 * Add ourselves to the partition's halted CPUs bitmap
653 	 * and set our HALTED flag, if necessary.
654 	 *
655 	 * When a thread becomes runnable, it is placed on the queue
656 	 * and then the halted CPU bitmap is checked to determine who
657 	 * (if anyone) should be awakened. We therefore need to first
658 	 * add ourselves to the bitmap, and and then check if there
659 	 * is any work available.
660 	 *
661 	 * Note that memory barriers after updating the HALTED flag
662 	 * are not necessary since an atomic operation (updating the bitmap)
663 	 * immediately follows. On x86 the atomic operation acts as a
664 	 * memory barrier for the update of cpu_disp_flags.
665 	 */
666 	if (hset_update) {
667 		cpup->cpu_disp_flags |= CPU_DISP_HALTED;
668 		bitset_atomic_add(&cp->cp_haltset, cpu_sid);
669 	}
670 
671 	/*
672 	 * Check to make sure there's really nothing to do.
673 	 * Work destined for this CPU may become available after
674 	 * this check. We'll be notified through the clearing of our
675 	 * bit in the halted CPU bitmap, and a write to our mcpu_mwait.
676 	 *
677 	 * disp_anywork() checks disp_nrunnable, so we do not have to later.
678 	 */
679 	if (disp_anywork()) {
680 		if (hset_update) {
681 			cpup->cpu_disp_flags &= ~CPU_DISP_HALTED;
682 			bitset_atomic_del(&cp->cp_haltset, cpu_sid);
683 		}
684 		return;
685 	}
686 
687 	/*
688 	 * We're on our way to being halted.
689 	 * To avoid a lost wakeup, arm the monitor before checking if another
690 	 * cpu wrote to mcpu_mwait to wake us up.
691 	 */
692 	i86_monitor(mcpu_mwait, 0, 0);
693 	if (*mcpu_mwait == MWAIT_HALTED) {
694 		if (cpu_idle_enter(IDLE_STATE_C1, 0,
695 		    cpu_idle_mwait_check_wakeup, (void *)mcpu_mwait) == 0) {
696 			if (*mcpu_mwait == MWAIT_HALTED) {
697 				i86_mwait(0, 0);
698 			}
699 			cpu_idle_exit(CPU_IDLE_CB_FLAG_IDLE);
700 		}
701 	}
702 
703 	/*
704 	 * We're no longer halted
705 	 */
706 	if (hset_update) {
707 		cpup->cpu_disp_flags &= ~CPU_DISP_HALTED;
708 		bitset_atomic_del(&cp->cp_haltset, cpu_sid);
709 	}
710 }
711 
712 /*
713  * If "cpu" is halted in mwait, then wake it up clearing its halted bit in
714  * advance.  Otherwise, see if other CPUs in the cpu partition are halted and
715  * need to be woken up so that they can steal the thread we placed on this CPU.
716  * This function is only used on MP systems.
717  */
718 static void
719 cpu_wakeup_mwait(cpu_t *cp, int bound)
720 {
721 	cpupart_t	*cpu_part;
722 	uint_t		cpu_found;
723 	processorid_t	cpu_sid;
724 
725 	cpu_part = cp->cpu_part;
726 	cpu_sid = cp->cpu_seqid;
727 
728 	/*
729 	 * Clear the halted bit for that CPU since it will be woken up
730 	 * in a moment.
731 	 */
732 	if (bitset_in_set(&cpu_part->cp_haltset, cpu_sid)) {
733 		/*
734 		 * Clear the halted bit for that CPU since it will be
735 		 * poked in a moment.
736 		 */
737 		bitset_atomic_del(&cpu_part->cp_haltset, cpu_sid);
738 		/*
739 		 * We may find the current CPU present in the halted cpuset
740 		 * if we're in the context of an interrupt that occurred
741 		 * before we had a chance to clear our bit in cpu_idle().
742 		 * Waking ourself is obviously unnecessary, since if
743 		 * we're here, we're not halted.
744 		 *
745 		 * monitor/mwait wakeup via writing to our cache line is
746 		 * harmless and less expensive than always checking if we
747 		 * are waking ourself which is an uncommon case.
748 		 */
749 		MWAIT_WAKEUP(cp);	/* write to monitored line */
750 		return;
751 	} else {
752 		/*
753 		 * This cpu isn't halted, but it's idle or undergoing a
754 		 * context switch. No need to awaken anyone else.
755 		 */
756 		if (cp->cpu_thread == cp->cpu_idle_thread ||
757 		    cp->cpu_disp_flags & CPU_DISP_DONTSTEAL)
758 			return;
759 	}
760 
761 	/*
762 	 * No need to wake up other CPUs if the thread we just enqueued
763 	 * is bound.
764 	 */
765 	if (bound || ncpus == 1)
766 		return;
767 
768 	/*
769 	 * See if there's any other halted CPUs. If there are, then
770 	 * select one, and awaken it.
771 	 * It's possible that after we find a CPU, somebody else
772 	 * will awaken it before we get the chance.
773 	 * In that case, look again.
774 	 */
775 	do {
776 		cpu_found = bitset_find(&cpu_part->cp_haltset);
777 		if (cpu_found == (uint_t)-1)
778 			return;
779 	} while (bitset_atomic_test_and_del(&cpu_part->cp_haltset,
780 	    cpu_found) < 0);
781 
782 	/*
783 	 * Do not check if cpu_found is ourself as monitor/mwait
784 	 * wakeup is cheap.
785 	 */
786 	MWAIT_WAKEUP(cpu_seq[cpu_found]); /* write to monitored line */
787 }
788 
789 #endif
790 
791 void (*cpu_pause_handler)(volatile char *) = NULL;
792 
793 static int
794 mp_disable_intr(int cpun)
795 {
796 	/*
797 	 * switch to the offline cpu
798 	 */
799 	affinity_set(cpun);
800 	/*
801 	 * raise ipl to just below cross call
802 	 */
803 	splx(XC_SYS_PIL - 1);
804 	/*
805 	 *	set base spl to prevent the next swtch to idle from
806 	 *	lowering back to ipl 0
807 	 */
808 	CPU->cpu_intr_actv |= (1 << (XC_SYS_PIL - 1));
809 	set_base_spl();
810 	affinity_clear();
811 	return (DDI_SUCCESS);
812 }
813 
814 static void
815 mp_enable_intr(int cpun)
816 {
817 	/*
818 	 * switch to the online cpu
819 	 */
820 	affinity_set(cpun);
821 	/*
822 	 * clear the interrupt active mask
823 	 */
824 	CPU->cpu_intr_actv &= ~(1 << (XC_SYS_PIL - 1));
825 	set_base_spl();
826 	(void) spl0();
827 	affinity_clear();
828 }
829 
830 static void
831 mach_get_platform(int owner)
832 {
833 	void		**srv_opsp;
834 	void		**clt_opsp;
835 	int		i;
836 	int		total_ops;
837 
838 	/* fix up psm ops */
839 	srv_opsp = (void **)mach_set[0];
840 	clt_opsp = (void **)mach_set[owner];
841 	if (mach_ver[owner] == (ushort_t)PSM_INFO_VER01)
842 		total_ops = sizeof (struct psm_ops_ver01) /
843 		    sizeof (void (*)(void));
844 	else if (mach_ver[owner] == (ushort_t)PSM_INFO_VER01_1)
845 		/* no psm_notify_func */
846 		total_ops = OFFSETOF(struct psm_ops, psm_notify_func) /
847 		    sizeof (void (*)(void));
848 	else if (mach_ver[owner] == (ushort_t)PSM_INFO_VER01_2)
849 		/* no psm_timer funcs */
850 		total_ops = OFFSETOF(struct psm_ops, psm_timer_reprogram) /
851 		    sizeof (void (*)(void));
852 	else if (mach_ver[owner] == (ushort_t)PSM_INFO_VER01_3)
853 		/* no psm_preshutdown function */
854 		total_ops = OFFSETOF(struct psm_ops, psm_preshutdown) /
855 		    sizeof (void (*)(void));
856 	else if (mach_ver[owner] == (ushort_t)PSM_INFO_VER01_4)
857 		/* no psm_preshutdown function */
858 		total_ops = OFFSETOF(struct psm_ops, psm_intr_ops) /
859 		    sizeof (void (*)(void));
860 	else
861 		total_ops = sizeof (struct psm_ops) / sizeof (void (*)(void));
862 
863 	/*
864 	 * Save the version of the PSM module, in case we need to
865 	 * behave differently based on version.
866 	 */
867 	mach_ver[0] = mach_ver[owner];
868 
869 	for (i = 0; i < total_ops; i++)
870 		if (clt_opsp[i] != NULL)
871 			srv_opsp[i] = clt_opsp[i];
872 }
873 
874 static void
875 mach_construct_info()
876 {
877 	struct psm_sw *swp;
878 	int	mach_cnt[PSM_OWN_OVERRIDE+1] = {0};
879 	int	conflict_owner = 0;
880 
881 	if (psmsw->psw_forw == psmsw)
882 		panic("No valid PSM modules found");
883 	mutex_enter(&psmsw_lock);
884 	for (swp = psmsw->psw_forw; swp != psmsw; swp = swp->psw_forw) {
885 		if (!(swp->psw_flag & PSM_MOD_IDENTIFY))
886 			continue;
887 		mach_set[swp->psw_infop->p_owner] = swp->psw_infop->p_ops;
888 		mach_ver[swp->psw_infop->p_owner] = swp->psw_infop->p_version;
889 		mach_cnt[swp->psw_infop->p_owner]++;
890 	}
891 	mutex_exit(&psmsw_lock);
892 
893 	mach_get_platform(PSM_OWN_SYS_DEFAULT);
894 
895 	/* check to see are there any conflicts */
896 	if (mach_cnt[PSM_OWN_EXCLUSIVE] > 1)
897 		conflict_owner = PSM_OWN_EXCLUSIVE;
898 	if (mach_cnt[PSM_OWN_OVERRIDE] > 1)
899 		conflict_owner = PSM_OWN_OVERRIDE;
900 	if (conflict_owner) {
901 		/* remove all psm modules except uppc */
902 		cmn_err(CE_WARN,
903 		    "Conflicts detected on the following PSM modules:");
904 		mutex_enter(&psmsw_lock);
905 		for (swp = psmsw->psw_forw; swp != psmsw; swp = swp->psw_forw) {
906 			if (swp->psw_infop->p_owner == conflict_owner)
907 				cmn_err(CE_WARN, "%s ",
908 				    swp->psw_infop->p_mach_idstring);
909 		}
910 		mutex_exit(&psmsw_lock);
911 		cmn_err(CE_WARN,
912 		    "Setting the system back to SINGLE processor mode!");
913 		cmn_err(CE_WARN,
914 		    "Please edit /etc/mach to remove the invalid PSM module.");
915 		return;
916 	}
917 
918 	if (mach_set[PSM_OWN_EXCLUSIVE])
919 		mach_get_platform(PSM_OWN_EXCLUSIVE);
920 
921 	if (mach_set[PSM_OWN_OVERRIDE])
922 		mach_get_platform(PSM_OWN_OVERRIDE);
923 }
924 
925 static void
926 mach_init()
927 {
928 	struct psm_ops  *pops;
929 
930 	mach_construct_info();
931 
932 	pops = mach_set[0];
933 
934 	/* register the interrupt and clock initialization rotuines */
935 	picinitf = mach_picinit;
936 	clkinitf = mach_clkinit;
937 	psm_get_clockirq = pops->psm_get_clockirq;
938 
939 	/* register the interrupt setup code */
940 	slvltovect = mach_softlvl_to_vect;
941 	addspl	= pops->psm_addspl;
942 	delspl	= pops->psm_delspl;
943 
944 	if (pops->psm_translate_irq)
945 		psm_translate_irq = pops->psm_translate_irq;
946 	if (pops->psm_intr_ops)
947 		psm_intr_ops = pops->psm_intr_ops;
948 
949 #if defined(PSMI_1_2) || defined(PSMI_1_3) || defined(PSMI_1_4)
950 	/*
951 	 * Time-of-day functionality now handled in TOD modules.
952 	 * (Warn about PSM modules that think that we're going to use
953 	 * their ops vectors.)
954 	 */
955 	if (pops->psm_tod_get)
956 		cmn_err(CE_WARN, "obsolete psm_tod_get op %p",
957 		    (void *)pops->psm_tod_get);
958 
959 	if (pops->psm_tod_set)
960 		cmn_err(CE_WARN, "obsolete psm_tod_set op %p",
961 		    (void *)pops->psm_tod_set);
962 #endif
963 
964 	if (pops->psm_notify_error) {
965 		psm_notify_error = mach_notify_error;
966 		notify_error = pops->psm_notify_error;
967 	}
968 
969 	(*pops->psm_softinit)();
970 
971 	/*
972 	 * Initialize the dispatcher's function hooks to enable CPU halting
973 	 * when idle.  Set both the deep-idle and non-deep-idle hooks.
974 	 *
975 	 * Assume we can use power saving deep-idle loop cpu_idle_adaptive.
976 	 * Platform deep-idle driver will reset our idle loop to
977 	 * non_deep_idle_cpu if power saving deep-idle feature is not available.
978 	 *
979 	 * Do not use monitor/mwait if idle_cpu_use_hlt is not set(spin idle)
980 	 * or idle_cpu_prefer_mwait is not set.
981 	 * Allocate monitor/mwait buffer for cpu0.
982 	 */
983 #ifndef __xpv
984 	non_deep_idle_disp_enq_thread = disp_enq_thread;
985 #endif
986 	if (idle_cpu_use_hlt) {
987 		idle_cpu = cpu_idle_adaptive;
988 		CPU->cpu_m.mcpu_idle_cpu = cpu_idle;
989 #ifndef __xpv
990 		if ((x86_feature & X86_MWAIT) && idle_cpu_prefer_mwait) {
991 			CPU->cpu_m.mcpu_mwait = cpuid_mwait_alloc(CPU);
992 			/*
993 			 * Protect ourself from insane mwait size.
994 			 */
995 			if (CPU->cpu_m.mcpu_mwait == NULL) {
996 #ifdef DEBUG
997 				cmn_err(CE_NOTE, "Using hlt idle.  Cannot "
998 				    "handle cpu 0 mwait size.");
999 #endif
1000 				idle_cpu_prefer_mwait = 0;
1001 				CPU->cpu_m.mcpu_idle_cpu = cpu_idle;
1002 			} else {
1003 				CPU->cpu_m.mcpu_idle_cpu = cpu_idle_mwait;
1004 			}
1005 		} else {
1006 			CPU->cpu_m.mcpu_idle_cpu = cpu_idle;
1007 		}
1008 		non_deep_idle_cpu = CPU->cpu_m.mcpu_idle_cpu;
1009 
1010 		/*
1011 		 * Disable power saving deep idle loop?
1012 		 */
1013 		if (idle_cpu_no_deep_c) {
1014 			idle_cpu = non_deep_idle_cpu;
1015 		}
1016 #endif
1017 	}
1018 
1019 	mach_smpinit();
1020 }
1021 
1022 static void
1023 mach_smpinit(void)
1024 {
1025 	struct psm_ops  *pops;
1026 	processorid_t cpu_id;
1027 	int cnt;
1028 	cpuset_t cpumask;
1029 
1030 	pops = mach_set[0];
1031 	CPUSET_ZERO(cpumask);
1032 
1033 	cpu_id = -1;
1034 	cpu_id = (*pops->psm_get_next_processorid)(cpu_id);
1035 	for (cnt = 0; cpu_id != -1; cnt++) {
1036 		CPUSET_ADD(cpumask, cpu_id);
1037 		cpu_id = (*pops->psm_get_next_processorid)(cpu_id);
1038 	}
1039 
1040 	mp_cpus = cpumask;
1041 
1042 	/* MP related routines */
1043 	ap_mlsetup = pops->psm_post_cpu_start;
1044 	send_dirintf = pops->psm_send_ipi;
1045 
1046 	/* optional MP related routines */
1047 	if (pops->psm_shutdown)
1048 		psm_shutdownf = pops->psm_shutdown;
1049 	if (pops->psm_preshutdown)
1050 		psm_preshutdownf = pops->psm_preshutdown;
1051 	if (pops->psm_notify_func)
1052 		psm_notifyf = pops->psm_notify_func;
1053 	if (pops->psm_set_idlecpu)
1054 		psm_set_idle_cpuf = pops->psm_set_idlecpu;
1055 	if (pops->psm_unset_idlecpu)
1056 		psm_unset_idle_cpuf = pops->psm_unset_idlecpu;
1057 
1058 	psm_clkinit = pops->psm_clkinit;
1059 
1060 	if (pops->psm_timer_reprogram)
1061 		psm_timer_reprogram = pops->psm_timer_reprogram;
1062 
1063 	if (pops->psm_timer_enable)
1064 		psm_timer_enable = pops->psm_timer_enable;
1065 
1066 	if (pops->psm_timer_disable)
1067 		psm_timer_disable = pops->psm_timer_disable;
1068 
1069 	if (pops->psm_post_cyclic_setup)
1070 		psm_post_cyclic_setup = pops->psm_post_cyclic_setup;
1071 
1072 	if (pops->psm_state)
1073 		psm_state = pops->psm_state;
1074 
1075 	/*
1076 	 * Set these vectors here so they can be used by Suspend/Resume
1077 	 * on UP machines.
1078 	 */
1079 	if (pops->psm_disable_intr)
1080 		psm_disable_intr = pops->psm_disable_intr;
1081 	if (pops->psm_enable_intr)
1082 		psm_enable_intr  = pops->psm_enable_intr;
1083 
1084 	/* check for multiple CPUs */
1085 	if (cnt < 2)
1086 		return;
1087 
1088 	/* check for MP platforms */
1089 	if (pops->psm_cpu_start == NULL)
1090 		return;
1091 
1092 	/*
1093 	 * Set the dispatcher hook to enable cpu "wake up"
1094 	 * when a thread becomes runnable.
1095 	 */
1096 	if (idle_cpu_use_hlt) {
1097 		disp_enq_thread = cpu_wakeup;
1098 #ifndef __xpv
1099 		if ((x86_feature & X86_MWAIT) && idle_cpu_prefer_mwait)
1100 			disp_enq_thread = cpu_wakeup_mwait;
1101 		non_deep_idle_disp_enq_thread = disp_enq_thread;
1102 #endif
1103 	}
1104 
1105 	psm_get_ipivect = pops->psm_get_ipivect;
1106 
1107 	(void) add_avintr((void *)NULL, XC_HI_PIL, xc_serv, "xc_intr",
1108 	    (*pops->psm_get_ipivect)(XC_HI_PIL, PSM_INTR_IPI_HI),
1109 	    NULL, NULL, NULL, NULL);
1110 
1111 	(void) (*pops->psm_get_ipivect)(XC_CPUPOKE_PIL, PSM_INTR_POKE);
1112 }
1113 
1114 static void
1115 mach_picinit()
1116 {
1117 	struct psm_ops  *pops;
1118 
1119 	pops = mach_set[0];
1120 
1121 	/* register the interrupt handlers */
1122 	setlvl = pops->psm_intr_enter;
1123 	setlvlx = pops->psm_intr_exit;
1124 
1125 	/* initialize the interrupt hardware */
1126 	(*pops->psm_picinit)();
1127 
1128 	/* set interrupt mask for current ipl */
1129 	setspl = pops->psm_setspl;
1130 	cli();
1131 	setspl(CPU->cpu_pri);
1132 }
1133 
1134 uint_t	cpu_freq;	/* MHz */
1135 uint64_t cpu_freq_hz;	/* measured (in hertz) */
1136 
1137 #define	MEGA_HZ		1000000
1138 
1139 #ifdef __xpv
1140 
1141 int xpv_cpufreq_workaround = 1;
1142 int xpv_cpufreq_verbose = 0;
1143 
1144 #else	/* __xpv */
1145 
1146 static uint64_t
1147 mach_calchz(uint32_t pit_counter, uint64_t *processor_clks)
1148 {
1149 	uint64_t cpu_hz;
1150 
1151 	if ((pit_counter == 0) || (*processor_clks == 0) ||
1152 	    (*processor_clks > (((uint64_t)-1) / PIT_HZ)))
1153 		return (0);
1154 
1155 	cpu_hz = ((uint64_t)PIT_HZ * *processor_clks) / pit_counter;
1156 
1157 	return (cpu_hz);
1158 }
1159 
1160 #endif	/* __xpv */
1161 
1162 static uint64_t
1163 mach_getcpufreq(void)
1164 {
1165 #if defined(__xpv)
1166 	vcpu_time_info_t *vti = &CPU->cpu_m.mcpu_vcpu_info->time;
1167 	uint64_t cpu_hz;
1168 
1169 	/*
1170 	 * During dom0 bringup, it was noted that on at least one older
1171 	 * Intel HT machine, the hypervisor initially gives a tsc_to_system_mul
1172 	 * value that is quite wrong (the 3.06GHz clock was reported
1173 	 * as 4.77GHz)
1174 	 *
1175 	 * The curious thing is, that if you stop the kernel at entry,
1176 	 * breakpoint here and inspect the value with kmdb, the value
1177 	 * is correct - but if you don't stop and simply enable the
1178 	 * printf statement (below), you can see the bad value printed
1179 	 * here.  Almost as if something kmdb did caused the hypervisor to
1180 	 * figure it out correctly.  And, note that the hypervisor
1181 	 * eventually -does- figure it out correctly ... if you look at
1182 	 * the field later in the life of dom0, it is correct.
1183 	 *
1184 	 * For now, on dom0, we employ a slightly cheesy workaround of
1185 	 * using the DOM0_PHYSINFO hypercall.
1186 	 */
1187 	if (DOMAIN_IS_INITDOMAIN(xen_info) && xpv_cpufreq_workaround) {
1188 		cpu_hz = 1000 * xpv_cpu_khz();
1189 	} else {
1190 		cpu_hz = (UINT64_C(1000000000) << 32) / vti->tsc_to_system_mul;
1191 
1192 		if (vti->tsc_shift < 0)
1193 			cpu_hz <<= -vti->tsc_shift;
1194 		else
1195 			cpu_hz >>= vti->tsc_shift;
1196 	}
1197 
1198 	if (xpv_cpufreq_verbose)
1199 		printf("mach_getcpufreq: system_mul 0x%x, shift %d, "
1200 		    "cpu_hz %" PRId64 "Hz\n",
1201 		    vti->tsc_to_system_mul, vti->tsc_shift, cpu_hz);
1202 
1203 	return (cpu_hz);
1204 #else	/* __xpv */
1205 	uint32_t pit_counter;
1206 	uint64_t processor_clks;
1207 
1208 	if (x86_feature & X86_TSC) {
1209 		/*
1210 		 * We have a TSC. freq_tsc() knows how to measure the number
1211 		 * of clock cycles sampled against the PIT.
1212 		 */
1213 		ulong_t flags = clear_int_flag();
1214 		processor_clks = freq_tsc(&pit_counter);
1215 		restore_int_flag(flags);
1216 		return (mach_calchz(pit_counter, &processor_clks));
1217 	} else if (x86_vendor == X86_VENDOR_Cyrix || x86_type == X86_TYPE_P5) {
1218 #if defined(__amd64)
1219 		panic("mach_getcpufreq: no TSC!");
1220 #elif defined(__i386)
1221 		/*
1222 		 * We are a Cyrix based on a 6x86 core or an Intel Pentium
1223 		 * for which freq_notsc() knows how to measure the number of
1224 		 * elapsed clock cycles sampled against the PIT
1225 		 */
1226 		ulong_t flags = clear_int_flag();
1227 		processor_clks = freq_notsc(&pit_counter);
1228 		restore_int_flag(flags);
1229 		return (mach_calchz(pit_counter, &processor_clks));
1230 #endif	/* __i386 */
1231 	}
1232 
1233 	/* We do not know how to calculate cpu frequency for this cpu. */
1234 	return (0);
1235 #endif	/* __xpv */
1236 }
1237 
1238 /*
1239  * If the clock speed of a cpu is found to be reported incorrectly, do not add
1240  * to this array, instead improve the accuracy of the algorithm that determines
1241  * the clock speed of the processor or extend the implementation to support the
1242  * vendor as appropriate. This is here only to support adjusting the speed on
1243  * older slower processors that mach_fixcpufreq() would not be able to account
1244  * for otherwise.
1245  */
1246 static int x86_cpu_freq[] = { 60, 75, 80, 90, 120, 160, 166, 175, 180, 233 };
1247 
1248 /*
1249  * On fast processors the clock frequency that is measured may be off by
1250  * a few MHz from the value printed on the part. This is a combination of
1251  * the factors that for such fast parts being off by this much is within
1252  * the tolerances for manufacture and because of the difficulties in the
1253  * measurement that can lead to small error. This function uses some
1254  * heuristics in order to tweak the value that was measured to match what
1255  * is most likely printed on the part.
1256  *
1257  * Some examples:
1258  * 	AMD Athlon 1000 mhz measured as 998 mhz
1259  * 	Intel Pentium III Xeon 733 mhz measured as 731 mhz
1260  * 	Intel Pentium IV 1500 mhz measured as 1495mhz
1261  *
1262  * If in the future this function is no longer sufficient to correct
1263  * for the error in the measurement, then the algorithm used to perform
1264  * the measurement will have to be improved in order to increase accuracy
1265  * rather than adding horrible and questionable kludges here.
1266  *
1267  * This is called after the cyclics subsystem because of the potential
1268  * that the heuristics within may give a worse estimate of the clock
1269  * frequency than the value that was measured.
1270  */
1271 static void
1272 mach_fixcpufreq(void)
1273 {
1274 	uint32_t freq, mul, near66, delta66, near50, delta50, fixed, delta, i;
1275 
1276 	freq = (uint32_t)cpu_freq;
1277 
1278 	/*
1279 	 * Find the nearest integer multiple of 200/3 (about 66) MHz to the
1280 	 * measured speed taking into account that the 667 MHz parts were
1281 	 * the first to round-up.
1282 	 */
1283 	mul = (uint32_t)((3 * (uint64_t)freq + 100) / 200);
1284 	near66 = (uint32_t)((200 * (uint64_t)mul + ((mul >= 10) ? 1 : 0)) / 3);
1285 	delta66 = (near66 > freq) ? (near66 - freq) : (freq - near66);
1286 
1287 	/* Find the nearest integer multiple of 50 MHz to the measured speed */
1288 	mul = (freq + 25) / 50;
1289 	near50 = mul * 50;
1290 	delta50 = (near50 > freq) ? (near50 - freq) : (freq - near50);
1291 
1292 	/* Find the closer of the two */
1293 	if (delta66 < delta50) {
1294 		fixed = near66;
1295 		delta = delta66;
1296 	} else {
1297 		fixed = near50;
1298 		delta = delta50;
1299 	}
1300 
1301 	if (fixed > INT_MAX)
1302 		return;
1303 
1304 	/*
1305 	 * Some older parts have a core clock frequency that is not an
1306 	 * integral multiple of 50 or 66 MHz. Check if one of the old
1307 	 * clock frequencies is closer to the measured value than any
1308 	 * of the integral multiples of 50 an 66, and if so set fixed
1309 	 * and delta appropriately to represent the closest value.
1310 	 */
1311 	i = sizeof (x86_cpu_freq) / sizeof (int);
1312 	while (i > 0) {
1313 		i--;
1314 
1315 		if (x86_cpu_freq[i] <= freq) {
1316 			mul = freq - x86_cpu_freq[i];
1317 
1318 			if (mul < delta) {
1319 				fixed = x86_cpu_freq[i];
1320 				delta = mul;
1321 			}
1322 
1323 			break;
1324 		}
1325 
1326 		mul = x86_cpu_freq[i] - freq;
1327 
1328 		if (mul < delta) {
1329 			fixed = x86_cpu_freq[i];
1330 			delta = mul;
1331 		}
1332 	}
1333 
1334 	/*
1335 	 * Set a reasonable maximum for how much to correct the measured
1336 	 * result by. This check is here to prevent the adjustment made
1337 	 * by this function from being more harm than good. It is entirely
1338 	 * possible that in the future parts will be made that are not
1339 	 * integral multiples of 66 or 50 in clock frequency or that
1340 	 * someone may overclock a part to some odd frequency. If the
1341 	 * measured value is farther from the corrected value than
1342 	 * allowed, then assume the corrected value is in error and use
1343 	 * the measured value.
1344 	 */
1345 	if (6 < delta)
1346 		return;
1347 
1348 	cpu_freq = (int)fixed;
1349 }
1350 
1351 
1352 static int
1353 machhztomhz(uint64_t cpu_freq_hz)
1354 {
1355 	uint64_t cpu_mhz;
1356 
1357 	/* Round to nearest MHZ */
1358 	cpu_mhz = (cpu_freq_hz + (MEGA_HZ / 2)) / MEGA_HZ;
1359 
1360 	if (cpu_mhz > INT_MAX)
1361 		return (0);
1362 
1363 	return ((int)cpu_mhz);
1364 
1365 }
1366 
1367 
1368 static int
1369 mach_clkinit(int preferred_mode, int *set_mode)
1370 {
1371 	struct psm_ops  *pops;
1372 	int resolution;
1373 
1374 	pops = mach_set[0];
1375 
1376 	cpu_freq_hz = mach_getcpufreq();
1377 
1378 	cpu_freq = machhztomhz(cpu_freq_hz);
1379 
1380 	if (!(x86_feature & X86_TSC) || (cpu_freq == 0))
1381 		tsc_gethrtime_enable = 0;
1382 
1383 #ifndef __xpv
1384 	if (tsc_gethrtime_enable) {
1385 		tsc_hrtimeinit(cpu_freq_hz);
1386 	} else
1387 #endif
1388 	{
1389 		if (pops->psm_hrtimeinit)
1390 			(*pops->psm_hrtimeinit)();
1391 		gethrtimef = pops->psm_gethrtime;
1392 		gethrtimeunscaledf = gethrtimef;
1393 		/* scalehrtimef will remain dummy */
1394 	}
1395 
1396 	mach_fixcpufreq();
1397 
1398 	if (mach_ver[0] >= PSM_INFO_VER01_3) {
1399 		if (preferred_mode == TIMER_ONESHOT) {
1400 
1401 			resolution = (*pops->psm_clkinit)(0);
1402 			if (resolution != 0)  {
1403 				*set_mode = TIMER_ONESHOT;
1404 				return (resolution);
1405 			}
1406 		}
1407 
1408 		/*
1409 		 * either periodic mode was requested or could not set to
1410 		 * one-shot mode
1411 		 */
1412 		resolution = (*pops->psm_clkinit)(hz);
1413 		/*
1414 		 * psm should be able to do periodic, so we do not check
1415 		 * for return value of psm_clkinit here.
1416 		 */
1417 		*set_mode = TIMER_PERIODIC;
1418 		return (resolution);
1419 	} else {
1420 		/*
1421 		 * PSMI interface prior to PSMI_3 does not define a return
1422 		 * value for psm_clkinit, so the return value is ignored.
1423 		 */
1424 		(void) (*pops->psm_clkinit)(hz);
1425 		*set_mode = TIMER_PERIODIC;
1426 		return (nsec_per_tick);
1427 	}
1428 }
1429 
1430 
1431 /*ARGSUSED*/
1432 static int
1433 mach_softlvl_to_vect(int ipl)
1434 {
1435 	setsoftint = av_set_softint_pending;
1436 	kdisetsoftint = kdi_av_set_softint_pending;
1437 
1438 	return (PSM_SV_SOFTWARE);
1439 }
1440 
1441 #ifdef DEBUG
1442 /*
1443  * This is here to allow us to simulate cpus that refuse to start.
1444  */
1445 cpuset_t cpufailset;
1446 #endif
1447 
1448 int
1449 mach_cpu_start(struct cpu *cp, void *ctx)
1450 {
1451 	struct psm_ops *pops = mach_set[0];
1452 	processorid_t id = cp->cpu_id;
1453 
1454 #ifdef DEBUG
1455 	if (CPU_IN_SET(cpufailset, id))
1456 		return (0);
1457 #endif
1458 	return ((*pops->psm_cpu_start)(id, ctx));
1459 }
1460 
1461 int
1462 mach_cpuid_start(processorid_t id, void *ctx)
1463 {
1464 	struct psm_ops *pops = mach_set[0];
1465 
1466 #ifdef DEBUG
1467 	if (CPU_IN_SET(cpufailset, id))
1468 		return (0);
1469 #endif
1470 	return ((*pops->psm_cpu_start)(id, ctx));
1471 }
1472 
1473 /*
1474  * Default handler to create device node for CPU.
1475  * One reference count will be held on created device node.
1476  */
1477 static int
1478 mach_cpu_create_devinfo(cpu_t *cp, dev_info_t **dipp)
1479 {
1480 	int rv, circ;
1481 	dev_info_t *dip;
1482 	static kmutex_t cpu_node_lock;
1483 	static dev_info_t *cpu_nex_devi = NULL;
1484 
1485 	ASSERT(cp != NULL);
1486 	ASSERT(dipp != NULL);
1487 	*dipp = NULL;
1488 
1489 	if (cpu_nex_devi == NULL) {
1490 		mutex_enter(&cpu_node_lock);
1491 		/* First check whether cpus exists. */
1492 		cpu_nex_devi = ddi_find_devinfo("cpus", -1, 0);
1493 		/* Create cpus if it doesn't exist. */
1494 		if (cpu_nex_devi == NULL) {
1495 			ndi_devi_enter(ddi_root_node(), &circ);
1496 			rv = ndi_devi_alloc(ddi_root_node(), "cpus",
1497 			    (pnode_t)DEVI_SID_NODEID, &dip);
1498 			if (rv != NDI_SUCCESS) {
1499 				mutex_exit(&cpu_node_lock);
1500 				cmn_err(CE_CONT,
1501 				    "?failed to create cpu nexus device.\n");
1502 				return (PSM_FAILURE);
1503 			}
1504 			ASSERT(dip != NULL);
1505 			(void) ndi_devi_online(dip, 0);
1506 			ndi_devi_exit(ddi_root_node(), circ);
1507 			cpu_nex_devi = dip;
1508 		}
1509 		mutex_exit(&cpu_node_lock);
1510 	}
1511 
1512 	/*
1513 	 * create a child node for cpu identified as 'cpu_id'
1514 	 */
1515 	ndi_devi_enter(cpu_nex_devi, &circ);
1516 	dip = ddi_add_child(cpu_nex_devi, "cpu", DEVI_SID_NODEID, -1);
1517 	if (dip == NULL) {
1518 		cmn_err(CE_CONT,
1519 		    "?failed to create device node for cpu%d.\n", cp->cpu_id);
1520 		rv = PSM_FAILURE;
1521 	} else {
1522 		*dipp = dip;
1523 		(void) ndi_hold_devi(dip);
1524 		rv = PSM_SUCCESS;
1525 	}
1526 	ndi_devi_exit(cpu_nex_devi, circ);
1527 
1528 	return (rv);
1529 }
1530 
1531 /*
1532  * Create cpu device node in device tree and online it.
1533  * Return created dip with reference count held if requested.
1534  */
1535 int
1536 mach_cpu_create_device_node(struct cpu *cp, dev_info_t **dipp)
1537 {
1538 	int rv;
1539 	dev_info_t *dip = NULL;
1540 
1541 	ASSERT(psm_cpu_create_devinfo != NULL);
1542 	rv = psm_cpu_create_devinfo(cp, &dip);
1543 	if (rv == PSM_SUCCESS) {
1544 		cpuid_set_cpu_properties(dip, cp->cpu_id, cp->cpu_m.mcpu_cpi);
1545 		/* Recursively attach driver for parent nexus device. */
1546 		if (i_ddi_attach_node_hierarchy(ddi_get_parent(dip)) ==
1547 		    DDI_SUCCESS) {
1548 			/* Configure cpu itself and descendants. */
1549 			(void) ndi_devi_online(dip,
1550 			    NDI_ONLINE_ATTACH | NDI_CONFIG);
1551 		}
1552 		if (dipp != NULL) {
1553 			*dipp = dip;
1554 		} else {
1555 			(void) ndi_rele_devi(dip);
1556 		}
1557 	}
1558 
1559 	return (rv);
1560 }
1561 
1562 /*ARGSUSED*/
1563 static int
1564 mach_translate_irq(dev_info_t *dip, int irqno)
1565 {
1566 	return (irqno);	/* default to NO translation */
1567 }
1568 
1569 static void
1570 mach_notify_error(int level, char *errmsg)
1571 {
1572 	/*
1573 	 * SL_FATAL is pass in once panicstr is set, deliver it
1574 	 * as CE_PANIC.  Also, translate SL_ codes back to CE_
1575 	 * codes for the psmi handler
1576 	 */
1577 	if (level & SL_FATAL)
1578 		(*notify_error)(CE_PANIC, errmsg);
1579 	else if (level & SL_WARN)
1580 		(*notify_error)(CE_WARN, errmsg);
1581 	else if (level & SL_NOTE)
1582 		(*notify_error)(CE_NOTE, errmsg);
1583 	else if (level & SL_CONSOLE)
1584 		(*notify_error)(CE_CONT, errmsg);
1585 }
1586 
1587 /*
1588  * It provides the default basic intr_ops interface for the new DDI
1589  * interrupt framework if the PSM doesn't have one.
1590  *
1591  * Input:
1592  * dip     - pointer to the dev_info structure of the requested device
1593  * hdlp    - pointer to the internal interrupt handle structure for the
1594  *	     requested interrupt
1595  * intr_op - opcode for this call
1596  * result  - pointer to the integer that will hold the result to be
1597  *	     passed back if return value is PSM_SUCCESS
1598  *
1599  * Output:
1600  * return value is either PSM_SUCCESS or PSM_FAILURE
1601  */
1602 static int
1603 mach_intr_ops(dev_info_t *dip, ddi_intr_handle_impl_t *hdlp,
1604     psm_intr_op_t intr_op, int *result)
1605 {
1606 	struct intrspec *ispec;
1607 
1608 	switch (intr_op) {
1609 	case PSM_INTR_OP_CHECK_MSI:
1610 		*result = hdlp->ih_type & ~(DDI_INTR_TYPE_MSI |
1611 		    DDI_INTR_TYPE_MSIX);
1612 		break;
1613 	case PSM_INTR_OP_ALLOC_VECTORS:
1614 		if (hdlp->ih_type == DDI_INTR_TYPE_FIXED)
1615 			*result = 1;
1616 		else
1617 			*result = 0;
1618 		break;
1619 	case PSM_INTR_OP_FREE_VECTORS:
1620 		break;
1621 	case PSM_INTR_OP_NAVAIL_VECTORS:
1622 		if (hdlp->ih_type == DDI_INTR_TYPE_FIXED)
1623 			*result = 1;
1624 		else
1625 			*result = 0;
1626 		break;
1627 	case PSM_INTR_OP_XLATE_VECTOR:
1628 		ispec = ((ihdl_plat_t *)hdlp->ih_private)->ip_ispecp;
1629 		*result = psm_translate_irq(dip, ispec->intrspec_vec);
1630 		break;
1631 	case PSM_INTR_OP_GET_CAP:
1632 		*result = 0;
1633 		break;
1634 	case PSM_INTR_OP_GET_PENDING:
1635 	case PSM_INTR_OP_CLEAR_MASK:
1636 	case PSM_INTR_OP_SET_MASK:
1637 	case PSM_INTR_OP_GET_SHARED:
1638 	case PSM_INTR_OP_SET_PRI:
1639 	case PSM_INTR_OP_SET_CAP:
1640 	case PSM_INTR_OP_SET_CPU:
1641 	case PSM_INTR_OP_GET_INTR:
1642 	default:
1643 		return (PSM_FAILURE);
1644 	}
1645 	return (PSM_SUCCESS);
1646 }
1647 /*
1648  * Return 1 if CMT load balancing policies should be
1649  * implemented across instances of the specified hardware
1650  * sharing relationship.
1651  */
1652 int
1653 pg_cmt_load_bal_hw(pghw_type_t hw)
1654 {
1655 	if (hw == PGHW_IPIPE ||
1656 	    hw == PGHW_FPU ||
1657 	    hw == PGHW_CHIP)
1658 		return (1);
1659 	else
1660 		return (0);
1661 }
1662 /*
1663  * Return 1 if thread affinity polices should be implemented
1664  * for instances of the specifed hardware sharing relationship.
1665  */
1666 int
1667 pg_cmt_affinity_hw(pghw_type_t hw)
1668 {
1669 	if (hw == PGHW_CACHE)
1670 		return (1);
1671 	else
1672 		return (0);
1673 }
1674