xref: /freebsd/sys/x86/x86/tsc.c (revision 50dad48bb740a8e56d185d9e8c165e0758f46e25)
1 /*-
2  * Copyright (c) 1998-2003 Poul-Henning Kamp
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_clock.h"
31 
32 #include <sys/param.h>
33 #include <sys/bus.h>
34 #include <sys/cpu.h>
35 #include <sys/malloc.h>
36 #include <sys/systm.h>
37 #include <sys/sysctl.h>
38 #include <sys/time.h>
39 #include <sys/timetc.h>
40 #include <sys/kernel.h>
41 #include <sys/power.h>
42 #include <sys/smp.h>
43 #include <machine/clock.h>
44 #include <machine/cputypes.h>
45 #include <machine/md_var.h>
46 #include <machine/specialreg.h>
47 
48 #include "cpufreq_if.h"
49 
50 uint64_t	tsc_freq;
51 int		tsc_is_invariant;
52 int		tsc_present;
53 static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
54 
55 SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
56     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
57 TUNABLE_INT("kern.timecounter.invariant_tsc", &tsc_is_invariant);
58 
59 #ifdef SMP
60 static int	smp_tsc;
61 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
62     "Indicates whether the TSC is safe to use in SMP mode");
63 TUNABLE_INT("kern.timecounter.smp_tsc", &smp_tsc);
64 #endif
65 
66 static int	tsc_disabled;
67 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
68     "Disable x86 Time Stamp Counter");
69 TUNABLE_INT("machdep.disable_tsc", &tsc_disabled);
70 
71 static void tsc_freq_changed(void *arg, const struct cf_level *level,
72     int status);
73 static void tsc_freq_changing(void *arg, const struct cf_level *level,
74     int *status);
75 static	unsigned tsc_get_timecount(struct timecounter *tc);
76 static void tsc_levels_changed(void *arg, int unit);
77 
78 static struct timecounter tsc_timecounter = {
79 	tsc_get_timecount,	/* get_timecount */
80 	0,			/* no poll_pps */
81 	~0u,			/* counter_mask */
82 	0,			/* frequency */
83 	"TSC",			/* name */
84 	800,			/* quality (adjusted in code) */
85 };
86 
87 void
88 init_TSC(void)
89 {
90 	u_int64_t tscval[2];
91 
92 	if ((cpu_feature & CPUID_TSC) == 0)
93 		return;
94 	tsc_present = 1;
95 
96 	if (tsc_disabled)
97 		return;
98 
99 	if (bootverbose)
100 	        printf("Calibrating TSC clock ... ");
101 
102 	tscval[0] = rdtsc();
103 	DELAY(1000000);
104 	tscval[1] = rdtsc();
105 
106 	tsc_freq = tscval[1] - tscval[0];
107 	if (bootverbose)
108 		printf("TSC clock: %ju Hz\n", (intmax_t)tsc_freq);
109 
110 	switch (cpu_vendor_id) {
111 	case CPU_VENDOR_AMD:
112 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
113 		    (vm_guest == VM_GUEST_NO &&
114 		    CPUID_TO_FAMILY(cpu_id) >= 0x10))
115 			tsc_is_invariant = 1;
116 		break;
117 	case CPU_VENDOR_INTEL:
118 		if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
119 		    (vm_guest == VM_GUEST_NO &&
120 		    ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
121 		    CPUID_TO_MODEL(cpu_id) >= 0xe) ||
122 		    (CPUID_TO_FAMILY(cpu_id) == 0xf &&
123 		    CPUID_TO_MODEL(cpu_id) >= 0x3))))
124 			tsc_is_invariant = 1;
125 		break;
126 	case CPU_VENDOR_CENTAUR:
127 		if (vm_guest == VM_GUEST_NO &&
128 		    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
129 		    CPUID_TO_MODEL(cpu_id) >= 0xf &&
130 		    (rdmsr(0x1203) & 0x100000000ULL) == 0)
131 			tsc_is_invariant = 1;
132 		break;
133 	}
134 
135 	/*
136 	 * Inform CPU accounting about our boot-time clock rate.  This will
137 	 * be updated if someone loads a cpufreq driver after boot that
138 	 * discovers a new max frequency.
139 	 */
140 	set_cputicker(rdtsc, tsc_freq, 1);
141 
142 	if (tsc_is_invariant)
143 		return;
144 
145 	/* Register to find out about changes in CPU frequency. */
146 	tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
147 	    tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
148 	tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
149 	    tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
150 	tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
151 	    tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
152 }
153 
154 void
155 init_TSC_tc(void)
156 {
157 
158 	if (!tsc_present || tsc_disabled)
159 		return;
160 
161 	/*
162 	 * We can not use the TSC if we support APM.  Precise timekeeping
163 	 * on an APM'ed machine is at best a fools pursuit, since
164 	 * any and all of the time spent in various SMM code can't
165 	 * be reliably accounted for.  Reading the RTC is your only
166 	 * source of reliable time info.  The i8254 loses too, of course,
167 	 * but we need to have some kind of time...
168 	 * We don't know at this point whether APM is going to be used
169 	 * or not, nor when it might be activated.  Play it safe.
170 	 */
171 	if (power_pm_get_type() == POWER_PM_TYPE_APM) {
172 		tsc_timecounter.tc_quality = -1000;
173 		if (bootverbose)
174 			printf("TSC timecounter disabled: APM enabled.\n");
175 	}
176 
177 #ifdef SMP
178 	/*
179 	 * We can not use the TSC in SMP mode unless the TSCs on all CPUs
180 	 * are somehow synchronized.  Some hardware configurations do
181 	 * this, but we have no way of determining whether this is the
182 	 * case, so we do not use the TSC in multi-processor systems
183 	 * unless the user indicated (by setting kern.timecounter.smp_tsc
184 	 * to 1) that he believes that his TSCs are synchronized.
185 	 */
186 	if (mp_ncpus > 1 && !smp_tsc)
187 		tsc_timecounter.tc_quality = -100;
188 #endif
189 
190 	if (tsc_freq != 0) {
191 		tsc_timecounter.tc_frequency = tsc_freq;
192 		tc_init(&tsc_timecounter);
193 	}
194 }
195 
196 /*
197  * When cpufreq levels change, find out about the (new) max frequency.  We
198  * use this to update CPU accounting in case it got a lower estimate at boot.
199  */
200 static void
201 tsc_levels_changed(void *arg, int unit)
202 {
203 	device_t cf_dev;
204 	struct cf_level *levels;
205 	int count, error;
206 	uint64_t max_freq;
207 
208 	/* Only use values from the first CPU, assuming all are equal. */
209 	if (unit != 0)
210 		return;
211 
212 	/* Find the appropriate cpufreq device instance. */
213 	cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
214 	if (cf_dev == NULL) {
215 		printf("tsc_levels_changed() called but no cpufreq device?\n");
216 		return;
217 	}
218 
219 	/* Get settings from the device and find the max frequency. */
220 	count = 64;
221 	levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
222 	if (levels == NULL)
223 		return;
224 	error = CPUFREQ_LEVELS(cf_dev, levels, &count);
225 	if (error == 0 && count != 0) {
226 		max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
227 		set_cputicker(rdtsc, max_freq, 1);
228 	} else
229 		printf("tsc_levels_changed: no max freq found\n");
230 	free(levels, M_TEMP);
231 }
232 
233 /*
234  * If the TSC timecounter is in use, veto the pending change.  It may be
235  * possible in the future to handle a dynamically-changing timecounter rate.
236  */
237 static void
238 tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
239 {
240 
241 	if (*status != 0 || timecounter != &tsc_timecounter)
242 		return;
243 
244 	printf("timecounter TSC must not be in use when "
245 	    "changing frequencies; change denied\n");
246 	*status = EBUSY;
247 }
248 
249 /* Update TSC freq with the value indicated by the caller. */
250 static void
251 tsc_freq_changed(void *arg, const struct cf_level *level, int status)
252 {
253 
254 	/* If there was an error during the transition, don't do anything. */
255 	if (tsc_disabled || status != 0)
256 		return;
257 
258 	/* Total setting for this level gives the new frequency in MHz. */
259 	tsc_freq = (uint64_t)level->total_set.freq * 1000000;
260 	tsc_timecounter.tc_frequency = tsc_freq;
261 }
262 
263 static int
264 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
265 {
266 	int error;
267 	uint64_t freq;
268 
269 	if (tsc_timecounter.tc_frequency == 0)
270 		return (EOPNOTSUPP);
271 	freq = tsc_freq;
272 	error = sysctl_handle_64(oidp, &freq, 0, req);
273 	if (error == 0 && req->newptr != NULL) {
274 		tsc_freq = freq;
275 		tsc_timecounter.tc_frequency = tsc_freq;
276 	}
277 	return (error);
278 }
279 
280 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq, CTLTYPE_U64 | CTLFLAG_RW,
281     0, 0, sysctl_machdep_tsc_freq, "QU", "");
282 
283 static unsigned
284 tsc_get_timecount(struct timecounter *tc)
285 {
286 	return (rdtsc());
287 }
288