tsc.c revision 276070
1295367Sdes/*-
276259Sgreen * Copyright (c) 1998-2003 Poul-Henning Kamp
365668Skris * All rights reserved.
465668Skris *
565668Skris * Redistribution and use in source and binary forms, with or without
665668Skris * modification, are permitted provided that the following conditions
765668Skris * are met:
865668Skris * 1. Redistributions of source code must retain the above copyright
965668Skris *    notice, this list of conditions and the following disclaimer.
1065668Skris * 2. Redistributions in binary form must reproduce the above copyright
1165668Skris *    notice, this list of conditions and the following disclaimer in the
1265668Skris *    documentation and/or other materials provided with the distribution.
1365668Skris *
1458582Skris * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1558582Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1658582Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1758582Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18204917Sdes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1958582Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2076259Sgreen * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21221420Sdes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22221420Sdes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23221420Sdes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24221420Sdes * SUCH DAMAGE.
25221420Sdes */
26221420Sdes
27221420Sdes#include <sys/cdefs.h>
28221420Sdes__FBSDID("$FreeBSD: stable/10/sys/x86/x86/tsc.c 276070 2014-12-22 18:40:59Z jhb $");
29295367Sdes
30221420Sdes#include "opt_compat.h"
31221420Sdes#include "opt_clock.h"
32221420Sdes
33221420Sdes#include <sys/param.h>
34221420Sdes#include <sys/bus.h>
35221420Sdes#include <sys/cpu.h>
36221420Sdes#include <sys/limits.h>
37221420Sdes#include <sys/malloc.h>
38295367Sdes#include <sys/systm.h>
39221420Sdes#include <sys/sysctl.h>
40221420Sdes#include <sys/time.h>
41221420Sdes#include <sys/timetc.h>
42221420Sdes#include <sys/kernel.h>
43295367Sdes#include <sys/power.h>
44295367Sdes#include <sys/smp.h>
45295367Sdes#include <sys/vdso.h>
4658582Skris#include <machine/clock.h>
47295367Sdes#include <machine/cputypes.h>
48295367Sdes#include <machine/md_var.h>
49295367Sdes#include <machine/specialreg.h>
50295367Sdes
51146998Sdes#include "cpufreq_if.h"
52146998Sdes
53146998Sdesuint64_t	tsc_freq;
54204917Sdesint		tsc_is_invariant;
55204917Sdesint		tsc_perf_stat;
56204917Sdes
57146998Sdesstatic eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
58146998Sdes
59295367SdesSYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
60295367Sdes    &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
61295367SdesTUNABLE_INT("kern.timecounter.invariant_tsc", &tsc_is_invariant);
62295367Sdes
63295367Sdes#ifdef SMP
64295367Sdesint	smp_tsc;
65295367SdesSYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
66295367Sdes    "Indicates whether the TSC is safe to use in SMP mode");
67295367SdesTUNABLE_INT("kern.timecounter.smp_tsc", &smp_tsc);
68295367Sdes
69295367Sdesint	smp_tsc_adjust = 0;
70295367SdesSYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
71295367Sdes    &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
72295367SdesTUNABLE_INT("kern.timecounter.smp_tsc_adjust", &smp_tsc_adjust);
73295367Sdes#endif
74295367Sdes
75295367Sdesstatic int	tsc_shift = 1;
76295367SdesSYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
77295367Sdes    &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
78295367SdesTUNABLE_INT("kern.timecounter.tsc_shift", &tsc_shift);
79295367Sdes
80295367Sdesstatic int	tsc_disabled;
81295367SdesSYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
82295367Sdes    "Disable x86 Time Stamp Counter");
83295367SdesTUNABLE_INT("machdep.disable_tsc", &tsc_disabled);
84295367Sdes
85295367Sdesstatic int	tsc_skip_calibration;
86295367SdesSYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
87295367Sdes    &tsc_skip_calibration, 0, "Disable TSC frequency calibration");
88295367SdesTUNABLE_INT("machdep.disable_tsc_calibration", &tsc_skip_calibration);
89295367Sdes
90295367Sdesstatic void tsc_freq_changed(void *arg, const struct cf_level *level,
91295367Sdes    int status);
92295367Sdesstatic void tsc_freq_changing(void *arg, const struct cf_level *level,
93295367Sdes    int *status);
94295367Sdesstatic unsigned tsc_get_timecount(struct timecounter *tc);
95295367Sdesstatic inline unsigned tsc_get_timecount_low(struct timecounter *tc);
96295367Sdesstatic unsigned tsc_get_timecount_lfence(struct timecounter *tc);
97295367Sdesstatic unsigned tsc_get_timecount_low_lfence(struct timecounter *tc);
98295367Sdesstatic unsigned tsc_get_timecount_mfence(struct timecounter *tc);
99295367Sdesstatic unsigned tsc_get_timecount_low_mfence(struct timecounter *tc);
100295367Sdesstatic void tsc_levels_changed(void *arg, int unit);
101295367Sdes
102295367Sdesstatic struct timecounter tsc_timecounter = {
103295367Sdes	tsc_get_timecount,	/* get_timecount */
104295367Sdes	0,			/* no poll_pps */
105295367Sdes	~0u,			/* counter_mask */
106295367Sdes	0,			/* frequency */
107295367Sdes	"TSC",			/* name */
10858582Skris	800,			/* quality (adjusted in code) */
109};
110
111#define	VMW_HVMAGIC		0x564d5868
112#define	VMW_HVPORT		0x5658
113#define	VMW_HVCMD_GETVERSION	10
114#define	VMW_HVCMD_GETHZ		45
115
116static __inline void
117vmware_hvcall(u_int cmd, u_int *p)
118{
119
120	__asm __volatile("inl %w3, %0"
121	: "=a" (p[0]), "=b" (p[1]), "=c" (p[2]), "=d" (p[3])
122	: "0" (VMW_HVMAGIC), "1" (UINT_MAX), "2" (cmd), "3" (VMW_HVPORT)
123	: "memory");
124}
125
126static int
127tsc_freq_vmware(void)
128{
129	char hv_sig[13];
130	u_int regs[4];
131	char *p;
132	u_int hv_high;
133	int i;
134
135	/*
136	 * [RFC] CPUID usage for interaction between Hypervisors and Linux.
137	 * http://lkml.org/lkml/2008/10/1/246
138	 *
139	 * KB1009458: Mechanisms to determine if software is running in
140	 * a VMware virtual machine
141	 * http://kb.vmware.com/kb/1009458
142	 */
143	hv_high = 0;
144	if ((cpu_feature2 & CPUID2_HV) != 0) {
145		do_cpuid(0x40000000, regs);
146		hv_high = regs[0];
147		for (i = 1, p = hv_sig; i < 4; i++, p += sizeof(regs) / 4)
148			memcpy(p, &regs[i], sizeof(regs[i]));
149		*p = '\0';
150		if (bootverbose) {
151			/*
152			 * HV vendor	ID string
153			 * ------------+--------------
154			 * KVM		"KVMKVMKVM"
155			 * Microsoft	"Microsoft Hv"
156			 * VMware	"VMwareVMware"
157			 * Xen		"XenVMMXenVMM"
158			 */
159			printf("Hypervisor: Origin = \"%s\"\n", hv_sig);
160		}
161		if (strncmp(hv_sig, "VMwareVMware", 12) != 0)
162			return (0);
163	} else {
164		p = getenv("smbios.system.serial");
165		if (p == NULL)
166			return (0);
167		if (strncmp(p, "VMware-", 7) != 0 &&
168		    strncmp(p, "VMW", 3) != 0) {
169			freeenv(p);
170			return (0);
171		}
172		freeenv(p);
173		vmware_hvcall(VMW_HVCMD_GETVERSION, regs);
174		if (regs[1] != VMW_HVMAGIC)
175			return (0);
176	}
177	if (hv_high >= 0x40000010) {
178		do_cpuid(0x40000010, regs);
179		tsc_freq = regs[0] * 1000;
180	} else {
181		vmware_hvcall(VMW_HVCMD_GETHZ, regs);
182		if (regs[1] != UINT_MAX)
183			tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
184	}
185	tsc_is_invariant = 1;
186	return (1);
187}
188
189static void
190tsc_freq_intel(void)
191{
192	char brand[48];
193	u_int regs[4];
194	uint64_t freq;
195	char *p;
196	u_int i;
197
198	/*
199	 * Intel Processor Identification and the CPUID Instruction
200	 * Application Note 485.
201	 * http://www.intel.com/assets/pdf/appnote/241618.pdf
202	 */
203	if (cpu_exthigh >= 0x80000004) {
204		p = brand;
205		for (i = 0x80000002; i < 0x80000005; i++) {
206			do_cpuid(i, regs);
207			memcpy(p, regs, sizeof(regs));
208			p += sizeof(regs);
209		}
210		p = NULL;
211		for (i = 0; i < sizeof(brand) - 1; i++)
212			if (brand[i] == 'H' && brand[i + 1] == 'z')
213				p = brand + i;
214		if (p != NULL) {
215			p -= 5;
216			switch (p[4]) {
217			case 'M':
218				i = 1;
219				break;
220			case 'G':
221				i = 1000;
222				break;
223			case 'T':
224				i = 1000000;
225				break;
226			default:
227				return;
228			}
229#define	C2D(c)	((c) - '0')
230			if (p[1] == '.') {
231				freq = C2D(p[0]) * 1000;
232				freq += C2D(p[2]) * 100;
233				freq += C2D(p[3]) * 10;
234				freq *= i * 1000;
235			} else {
236				freq = C2D(p[0]) * 1000;
237				freq += C2D(p[1]) * 100;
238				freq += C2D(p[2]) * 10;
239				freq += C2D(p[3]);
240				freq *= i * 1000000;
241			}
242#undef C2D
243			tsc_freq = freq;
244		}
245	}
246}
247
248static void
249probe_tsc_freq(void)
250{
251	u_int regs[4];
252	uint64_t tsc1, tsc2;
253
254	if (cpu_high >= 6) {
255		do_cpuid(6, regs);
256		if ((regs[2] & CPUID_PERF_STAT) != 0) {
257			/*
258			 * XXX Some emulators expose host CPUID without actual
259			 * support for these MSRs.  We must test whether they
260			 * really work.
261			 */
262			wrmsr(MSR_MPERF, 0);
263			wrmsr(MSR_APERF, 0);
264			DELAY(10);
265			if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
266				tsc_perf_stat = 1;
267		}
268	}
269
270	if (tsc_freq_vmware())
271		return;
272
273	switch (cpu_vendor_id) {
274	case CPU_VENDOR_AMD:
275		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
276		    (vm_guest == VM_GUEST_NO &&
277		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
278			tsc_is_invariant = 1;
279		if (cpu_feature & CPUID_SSE2) {
280			tsc_timecounter.tc_get_timecount =
281			    tsc_get_timecount_mfence;
282		}
283		break;
284	case CPU_VENDOR_INTEL:
285		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
286		    (vm_guest == VM_GUEST_NO &&
287		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
288		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
289		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
290		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
291			tsc_is_invariant = 1;
292		if (cpu_feature & CPUID_SSE2) {
293			tsc_timecounter.tc_get_timecount =
294			    tsc_get_timecount_lfence;
295		}
296		break;
297	case CPU_VENDOR_CENTAUR:
298		if (vm_guest == VM_GUEST_NO &&
299		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
300		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
301		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
302			tsc_is_invariant = 1;
303		if (cpu_feature & CPUID_SSE2) {
304			tsc_timecounter.tc_get_timecount =
305			    tsc_get_timecount_lfence;
306		}
307		break;
308	}
309
310	if (tsc_skip_calibration) {
311		if (cpu_vendor_id == CPU_VENDOR_INTEL)
312			tsc_freq_intel();
313		return;
314	}
315
316	if (bootverbose)
317	        printf("Calibrating TSC clock ... ");
318	tsc1 = rdtsc();
319	DELAY(1000000);
320	tsc2 = rdtsc();
321	tsc_freq = tsc2 - tsc1;
322	if (bootverbose)
323		printf("TSC clock: %ju Hz\n", (intmax_t)tsc_freq);
324}
325
326void
327init_TSC(void)
328{
329
330	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
331		return;
332
333#ifdef __i386__
334	/* The TSC is known to be broken on certain CPUs. */
335	switch (cpu_vendor_id) {
336	case CPU_VENDOR_AMD:
337		switch (cpu_id & 0xFF0) {
338		case 0x500:
339			/* K5 Model 0 */
340			return;
341		}
342		break;
343	case CPU_VENDOR_CENTAUR:
344		switch (cpu_id & 0xff0) {
345		case 0x540:
346			/*
347			 * http://www.centtech.com/c6_data_sheet.pdf
348			 *
349			 * I-12 RDTSC may return incoherent values in EDX:EAX
350			 * I-13 RDTSC hangs when certain event counters are used
351			 */
352			return;
353		}
354		break;
355	case CPU_VENDOR_NSC:
356		switch (cpu_id & 0xff0) {
357		case 0x540:
358			if ((cpu_id & CPUID_STEPPING) == 0)
359				return;
360			break;
361		}
362		break;
363	}
364#endif
365
366	probe_tsc_freq();
367
368	/*
369	 * Inform CPU accounting about our boot-time clock rate.  This will
370	 * be updated if someone loads a cpufreq driver after boot that
371	 * discovers a new max frequency.
372	 */
373	if (tsc_freq != 0)
374		set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
375
376	if (tsc_is_invariant)
377		return;
378
379	/* Register to find out about changes in CPU frequency. */
380	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
381	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
382	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
383	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
384	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
385	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
386}
387
388#ifdef SMP
389
390/*
391 * RDTSC is not a serializing instruction, and does not drain
392 * instruction stream, so we need to drain the stream before executing
393 * it.  It could be fixed by use of RDTSCP, except the instruction is
394 * not available everywhere.
395 *
396 * Use CPUID for draining in the boot-time SMP constistency test.  The
397 * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
398 * and VIA) when SSE2 is present, and nothing on older machines which
399 * also do not issue RDTSC prematurely.  There, testing for SSE2 and
400 * vendor is too cumbersome, and we learn about TSC presence from CPUID.
401 *
402 * Do not use do_cpuid(), since we do not need CPUID results, which
403 * have to be written into memory with do_cpuid().
404 */
405#define	TSC_READ(x)							\
406static void								\
407tsc_read_##x(void *arg)							\
408{									\
409	uint64_t *tsc = arg;						\
410	u_int cpu = PCPU_GET(cpuid);					\
411									\
412	__asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");	\
413	tsc[cpu * 3 + x] = rdtsc();					\
414}
415TSC_READ(0)
416TSC_READ(1)
417TSC_READ(2)
418#undef TSC_READ
419
420#define	N	1000
421
422static void
423comp_smp_tsc(void *arg)
424{
425	uint64_t *tsc;
426	int64_t d1, d2;
427	u_int cpu = PCPU_GET(cpuid);
428	u_int i, j, size;
429
430	size = (mp_maxid + 1) * 3;
431	for (i = 0, tsc = arg; i < N; i++, tsc += size)
432		CPU_FOREACH(j) {
433			if (j == cpu)
434				continue;
435			d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
436			d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
437			if (d1 <= 0 || d2 <= 0) {
438				smp_tsc = 0;
439				return;
440			}
441		}
442}
443
444static void
445adj_smp_tsc(void *arg)
446{
447	uint64_t *tsc;
448	int64_t d, min, max;
449	u_int cpu = PCPU_GET(cpuid);
450	u_int first, i, size;
451
452	first = CPU_FIRST();
453	if (cpu == first)
454		return;
455	min = INT64_MIN;
456	max = INT64_MAX;
457	size = (mp_maxid + 1) * 3;
458	for (i = 0, tsc = arg; i < N; i++, tsc += size) {
459		d = tsc[first * 3] - tsc[cpu * 3 + 1];
460		if (d > min)
461			min = d;
462		d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
463		if (d > min)
464			min = d;
465		d = tsc[first * 3 + 1] - tsc[cpu * 3];
466		if (d < max)
467			max = d;
468		d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
469		if (d < max)
470			max = d;
471	}
472	if (min > max)
473		return;
474	d = min / 2 + max / 2;
475	__asm __volatile (
476		"movl $0x10, %%ecx\n\t"
477		"rdmsr\n\t"
478		"addl %%edi, %%eax\n\t"
479		"adcl %%esi, %%edx\n\t"
480		"wrmsr\n"
481		: /* No output */
482		: "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
483		: "ax", "cx", "dx", "cc"
484	);
485}
486
487static int
488test_tsc(void)
489{
490	uint64_t *data, *tsc;
491	u_int i, size, adj;
492
493	if ((!smp_tsc && !tsc_is_invariant) || vm_guest)
494		return (-100);
495	size = (mp_maxid + 1) * 3;
496	data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
497	adj = 0;
498retry:
499	for (i = 0, tsc = data; i < N; i++, tsc += size)
500		smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
501	smp_tsc = 1;	/* XXX */
502	smp_rendezvous(smp_no_rendevous_barrier, comp_smp_tsc,
503	    smp_no_rendevous_barrier, data);
504	if (!smp_tsc && adj < smp_tsc_adjust) {
505		adj++;
506		smp_rendezvous(smp_no_rendevous_barrier, adj_smp_tsc,
507		    smp_no_rendevous_barrier, data);
508		goto retry;
509	}
510	free(data, M_TEMP);
511	if (bootverbose)
512		printf("SMP: %sed TSC synchronization test%s\n",
513		    smp_tsc ? "pass" : "fail",
514		    adj > 0 ? " after adjustment" : "");
515	if (smp_tsc && tsc_is_invariant) {
516		switch (cpu_vendor_id) {
517		case CPU_VENDOR_AMD:
518			/*
519			 * Starting with Family 15h processors, TSC clock
520			 * source is in the north bridge.  Check whether
521			 * we have a single-socket/multi-core platform.
522			 * XXX Need more work for complex cases.
523			 */
524			if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
525			    (amd_feature2 & AMDID2_CMP) == 0 ||
526			    smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
527				break;
528			return (1000);
529		case CPU_VENDOR_INTEL:
530			/*
531			 * XXX Assume Intel platforms have synchronized TSCs.
532			 */
533			return (1000);
534		}
535		return (800);
536	}
537	return (-100);
538}
539
540#undef N
541
542#else
543
544/*
545 * The function is not called, it is provided to avoid linking failure
546 * on uniprocessor kernel.
547 */
548static int
549test_tsc(void)
550{
551
552	return (0);
553}
554
555#endif /* SMP */
556
557static void
558init_TSC_tc(void)
559{
560	uint64_t max_freq;
561	int shift;
562
563	if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
564		return;
565
566	/*
567	 * Limit timecounter frequency to fit in an int and prevent it from
568	 * overflowing too fast.
569	 */
570	max_freq = UINT_MAX;
571
572	/*
573	 * We can not use the TSC if we support APM.  Precise timekeeping
574	 * on an APM'ed machine is at best a fools pursuit, since
575	 * any and all of the time spent in various SMM code can't
576	 * be reliably accounted for.  Reading the RTC is your only
577	 * source of reliable time info.  The i8254 loses too, of course,
578	 * but we need to have some kind of time...
579	 * We don't know at this point whether APM is going to be used
580	 * or not, nor when it might be activated.  Play it safe.
581	 */
582	if (power_pm_get_type() == POWER_PM_TYPE_APM) {
583		tsc_timecounter.tc_quality = -1000;
584		if (bootverbose)
585			printf("TSC timecounter disabled: APM enabled.\n");
586		goto init;
587	}
588
589	/*
590	 * We cannot use the TSC if it stops incrementing in deep sleep.
591	 * Currently only Intel CPUs are known for this problem unless
592	 * the invariant TSC bit is set.
593	 */
594	if (cpu_can_deep_sleep && cpu_vendor_id == CPU_VENDOR_INTEL &&
595	    (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
596		tsc_timecounter.tc_quality = -1000;
597		tsc_timecounter.tc_flags |= TC_FLAGS_C3STOP;
598		if (bootverbose)
599			printf("TSC timecounter disabled: C3 enabled.\n");
600		goto init;
601	}
602
603	/*
604	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
605	 * are synchronized.  If the user is sure that the system has
606	 * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
607	 * non-zero value.  The TSC seems unreliable in virtualized SMP
608	 * environments, so it is set to a negative quality in those cases.
609	 */
610	if (mp_ncpus > 1)
611		tsc_timecounter.tc_quality = test_tsc();
612	else if (tsc_is_invariant)
613		tsc_timecounter.tc_quality = 1000;
614	max_freq >>= tsc_shift;
615
616init:
617	for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
618		;
619	if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
620		if (cpu_vendor_id == CPU_VENDOR_AMD) {
621			tsc_timecounter.tc_get_timecount = shift > 0 ?
622			    tsc_get_timecount_low_mfence :
623			    tsc_get_timecount_mfence;
624		} else {
625			tsc_timecounter.tc_get_timecount = shift > 0 ?
626			    tsc_get_timecount_low_lfence :
627			    tsc_get_timecount_lfence;
628		}
629	} else {
630		tsc_timecounter.tc_get_timecount = shift > 0 ?
631		    tsc_get_timecount_low : tsc_get_timecount;
632	}
633	if (shift > 0) {
634		tsc_timecounter.tc_name = "TSC-low";
635		if (bootverbose)
636			printf("TSC timecounter discards lower %d bit(s)\n",
637			    shift);
638	}
639	if (tsc_freq != 0) {
640		tsc_timecounter.tc_frequency = tsc_freq >> shift;
641		tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
642		tc_init(&tsc_timecounter);
643	}
644}
645SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
646
647/*
648 * When cpufreq levels change, find out about the (new) max frequency.  We
649 * use this to update CPU accounting in case it got a lower estimate at boot.
650 */
651static void
652tsc_levels_changed(void *arg, int unit)
653{
654	device_t cf_dev;
655	struct cf_level *levels;
656	int count, error;
657	uint64_t max_freq;
658
659	/* Only use values from the first CPU, assuming all are equal. */
660	if (unit != 0)
661		return;
662
663	/* Find the appropriate cpufreq device instance. */
664	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
665	if (cf_dev == NULL) {
666		printf("tsc_levels_changed() called but no cpufreq device?\n");
667		return;
668	}
669
670	/* Get settings from the device and find the max frequency. */
671	count = 64;
672	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
673	if (levels == NULL)
674		return;
675	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
676	if (error == 0 && count != 0) {
677		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
678		set_cputicker(rdtsc, max_freq, 1);
679	} else
680		printf("tsc_levels_changed: no max freq found\n");
681	free(levels, M_TEMP);
682}
683
684/*
685 * If the TSC timecounter is in use, veto the pending change.  It may be
686 * possible in the future to handle a dynamically-changing timecounter rate.
687 */
688static void
689tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
690{
691
692	if (*status != 0 || timecounter != &tsc_timecounter)
693		return;
694
695	printf("timecounter TSC must not be in use when "
696	    "changing frequencies; change denied\n");
697	*status = EBUSY;
698}
699
700/* Update TSC freq with the value indicated by the caller. */
701static void
702tsc_freq_changed(void *arg, const struct cf_level *level, int status)
703{
704	uint64_t freq;
705
706	/* If there was an error during the transition, don't do anything. */
707	if (tsc_disabled || status != 0)
708		return;
709
710	/* Total setting for this level gives the new frequency in MHz. */
711	freq = (uint64_t)level->total_set.freq * 1000000;
712	atomic_store_rel_64(&tsc_freq, freq);
713	tsc_timecounter.tc_frequency =
714	    freq >> (int)(intptr_t)tsc_timecounter.tc_priv;
715}
716
717static int
718sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
719{
720	int error;
721	uint64_t freq;
722
723	freq = atomic_load_acq_64(&tsc_freq);
724	if (freq == 0)
725		return (EOPNOTSUPP);
726	error = sysctl_handle_64(oidp, &freq, 0, req);
727	if (error == 0 && req->newptr != NULL) {
728		atomic_store_rel_64(&tsc_freq, freq);
729		atomic_store_rel_64(&tsc_timecounter.tc_frequency,
730		    freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
731	}
732	return (error);
733}
734
735SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_U64 | CTLFLAG_RW,
736    0, 0, sysctl_machdep_tsc_freq, "QU", "Time Stamp Counter frequency");
737
738static u_int
739tsc_get_timecount(struct timecounter *tc __unused)
740{
741
742	return (rdtsc32());
743}
744
745static inline u_int
746tsc_get_timecount_low(struct timecounter *tc)
747{
748	uint32_t rv;
749
750	__asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
751	    : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
752	return (rv);
753}
754
755static u_int
756tsc_get_timecount_lfence(struct timecounter *tc __unused)
757{
758
759	lfence();
760	return (rdtsc32());
761}
762
763static u_int
764tsc_get_timecount_low_lfence(struct timecounter *tc)
765{
766
767	lfence();
768	return (tsc_get_timecount_low(tc));
769}
770
771static u_int
772tsc_get_timecount_mfence(struct timecounter *tc __unused)
773{
774
775	mfence();
776	return (rdtsc32());
777}
778
779static u_int
780tsc_get_timecount_low_mfence(struct timecounter *tc)
781{
782
783	mfence();
784	return (tsc_get_timecount_low(tc));
785}
786
787uint32_t
788cpu_fill_vdso_timehands(struct vdso_timehands *vdso_th)
789{
790
791	vdso_th->th_x86_shift = (int)(intptr_t)timecounter->tc_priv;
792	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
793	return (timecounter == &tsc_timecounter);
794}
795
796#ifdef COMPAT_FREEBSD32
797uint32_t
798cpu_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
799{
800
801	vdso_th32->th_x86_shift = (int)(intptr_t)timecounter->tc_priv;
802	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
803	return (timecounter == &tsc_timecounter);
804}
805#endif
806