]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/x86/tsc.c
TSC: Use 0x40000010 CPUID leaf for all VM types
[FreeBSD/FreeBSD.git] / sys / x86 / x86 / tsc.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1998-2003 Poul-Henning Kamp
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_clock.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/bus.h>
37 #include <sys/cpu.h>
38 #include <sys/eventhandler.h>
39 #include <sys/limits.h>
40 #include <sys/malloc.h>
41 #include <sys/proc.h>
42 #include <sys/sched.h>
43 #include <sys/sysctl.h>
44 #include <sys/time.h>
45 #include <sys/timetc.h>
46 #include <sys/kernel.h>
47 #include <sys/smp.h>
48 #include <sys/vdso.h>
49 #include <machine/clock.h>
50 #include <machine/cputypes.h>
51 #include <machine/fpu.h>
52 #include <machine/md_var.h>
53 #include <machine/specialreg.h>
54 #include <x86/vmware.h>
55 #include <dev/acpica/acpi_hpet.h>
56 #include <contrib/dev/acpica/include/acpi.h>
57
58 #include "cpufreq_if.h"
59
60 uint64_t        tsc_freq;
61 int             tsc_is_invariant;
62 int             tsc_perf_stat;
63 static int      tsc_early_calib_exact;
64
65 static eventhandler_tag tsc_levels_tag, tsc_pre_tag, tsc_post_tag;
66
67 SYSCTL_INT(_kern_timecounter, OID_AUTO, invariant_tsc, CTLFLAG_RDTUN,
68     &tsc_is_invariant, 0, "Indicates whether the TSC is P-state invariant");
69
70 #ifdef SMP
71 int     smp_tsc;
72 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc, CTLFLAG_RDTUN, &smp_tsc, 0,
73     "Indicates whether the TSC is safe to use in SMP mode");
74
75 int     smp_tsc_adjust = 0;
76 SYSCTL_INT(_kern_timecounter, OID_AUTO, smp_tsc_adjust, CTLFLAG_RDTUN,
77     &smp_tsc_adjust, 0, "Try to adjust TSC on APs to match BSP");
78 #endif
79
80 static int      tsc_shift = 1;
81 SYSCTL_INT(_kern_timecounter, OID_AUTO, tsc_shift, CTLFLAG_RDTUN,
82     &tsc_shift, 0, "Shift to pre-apply for the maximum TSC frequency");
83
84 static int      tsc_disabled;
85 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc, CTLFLAG_RDTUN, &tsc_disabled, 0,
86     "Disable x86 Time Stamp Counter");
87
88 static int      tsc_skip_calibration;
89 SYSCTL_INT(_machdep, OID_AUTO, disable_tsc_calibration, CTLFLAG_RDTUN,
90     &tsc_skip_calibration, 0,
91     "Disable early TSC frequency calibration");
92
93 static void tsc_freq_changed(void *arg, const struct cf_level *level,
94     int status);
95 static void tsc_freq_changing(void *arg, const struct cf_level *level,
96     int *status);
97 static u_int tsc_get_timecount(struct timecounter *tc);
98 static inline u_int tsc_get_timecount_low(struct timecounter *tc);
99 static u_int tsc_get_timecount_lfence(struct timecounter *tc);
100 static u_int tsc_get_timecount_low_lfence(struct timecounter *tc);
101 static u_int tsc_get_timecount_mfence(struct timecounter *tc);
102 static u_int tsc_get_timecount_low_mfence(struct timecounter *tc);
103 static u_int tscp_get_timecount(struct timecounter *tc);
104 static u_int tscp_get_timecount_low(struct timecounter *tc);
105 static void tsc_levels_changed(void *arg, int unit);
106 static uint32_t x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th,
107     struct timecounter *tc);
108 #ifdef COMPAT_FREEBSD32
109 static uint32_t x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
110     struct timecounter *tc);
111 #endif
112
113 static struct timecounter tsc_timecounter = {
114         .tc_get_timecount =             tsc_get_timecount,
115         .tc_counter_mask =              ~0u,
116         .tc_name =                      "TSC",
117         .tc_quality =                   800,    /* adjusted in code */
118         .tc_fill_vdso_timehands =       x86_tsc_vdso_timehands,
119 #ifdef COMPAT_FREEBSD32
120         .tc_fill_vdso_timehands32 =     x86_tsc_vdso_timehands32,
121 #endif
122 };
123
124 static int
125 tsc_freq_cpuid_vm(void)
126 {
127         u_int regs[4];
128
129         if (vm_guest == VM_GUEST_NO)
130                 return (false);
131         if (hv_high < 0x40000010)
132                 return (false);
133         do_cpuid(0x40000010, regs);
134         tsc_freq = (uint64_t)(regs[0]) * 1000;
135         tsc_early_calib_exact = 1;
136         return (true);
137 }
138
139 static void
140 tsc_freq_vmware(void)
141 {
142         u_int regs[4];
143
144         vmware_hvcall(VMW_HVCMD_GETHZ, regs);
145         if (regs[1] != UINT_MAX)
146                 tsc_freq = regs[0] | ((uint64_t)regs[1] << 32);
147         tsc_early_calib_exact = 1;
148 }
149
150 /*
151  * Calculate TSC frequency using information from the CPUID leaf 0x15 'Time
152  * Stamp Counter and Nominal Core Crystal Clock'.  If leaf 0x15 is not
153  * functional, as it is on Skylake/Kabylake, try 0x16 'Processor Frequency
154  * Information'.  Leaf 0x16 is described in the SDM as informational only, but
155  * we can use this value until late calibration is complete.
156  */
157 static bool
158 tsc_freq_cpuid(uint64_t *res)
159 {
160         u_int regs[4];
161
162         if (cpu_high < 0x15)
163                 return (false);
164         do_cpuid(0x15, regs);
165         if (regs[0] != 0 && regs[1] != 0 && regs[2] != 0) {
166                 *res = (uint64_t)regs[2] * regs[1] / regs[0];
167                 return (true);
168         }
169
170         if (cpu_high < 0x16)
171                 return (false);
172         do_cpuid(0x16, regs);
173         if (regs[0] != 0) {
174                 *res = (uint64_t)regs[0] * 1000000;
175                 return (true);
176         }
177
178         return (false);
179 }
180
181 static bool
182 tsc_freq_intel_brand(uint64_t *res)
183 {
184         char brand[48];
185         u_int regs[4];
186         uint64_t freq;
187         char *p;
188         u_int i;
189
190         /*
191          * Intel Processor Identification and the CPUID Instruction
192          * Application Note 485.
193          * http://www.intel.com/assets/pdf/appnote/241618.pdf
194          */
195         if (cpu_exthigh >= 0x80000004) {
196                 p = brand;
197                 for (i = 0x80000002; i < 0x80000005; i++) {
198                         do_cpuid(i, regs);
199                         memcpy(p, regs, sizeof(regs));
200                         p += sizeof(regs);
201                 }
202                 p = NULL;
203                 for (i = 0; i < sizeof(brand) - 1; i++)
204                         if (brand[i] == 'H' && brand[i + 1] == 'z')
205                                 p = brand + i;
206                 if (p != NULL) {
207                         p -= 5;
208                         switch (p[4]) {
209                         case 'M':
210                                 i = 1;
211                                 break;
212                         case 'G':
213                                 i = 1000;
214                                 break;
215                         case 'T':
216                                 i = 1000000;
217                                 break;
218                         default:
219                                 return (false);
220                         }
221 #define C2D(c)  ((c) - '0')
222                         if (p[1] == '.') {
223                                 freq = C2D(p[0]) * 1000;
224                                 freq += C2D(p[2]) * 100;
225                                 freq += C2D(p[3]) * 10;
226                                 freq *= i * 1000;
227                         } else {
228                                 freq = C2D(p[0]) * 1000;
229                                 freq += C2D(p[1]) * 100;
230                                 freq += C2D(p[2]) * 10;
231                                 freq += C2D(p[3]);
232                                 freq *= i * 1000000;
233                         }
234 #undef C2D
235                         *res = freq;
236                         return (true);
237                 }
238         }
239         return (false);
240 }
241
242 static void
243 tsc_freq_8254(uint64_t *res)
244 {
245         uint64_t tsc1, tsc2;
246         int64_t overhead;
247         int count, i;
248
249         overhead = 0;
250         for (i = 0, count = 8; i < count; i++) {
251                 tsc1 = rdtsc_ordered();
252                 DELAY(0);
253                 tsc2 = rdtsc_ordered();
254                 if (i > 0)
255                         overhead += tsc2 - tsc1;
256         }
257         overhead /= count;
258
259         tsc1 = rdtsc_ordered();
260         DELAY(100000);
261         tsc2 = rdtsc_ordered();
262         tsc_freq = (tsc2 - tsc1 - overhead) * 10;
263 }
264
265 static void
266 probe_tsc_freq(void)
267 {
268         if (cpu_power_ecx & CPUID_PERF_STAT) {
269                 /*
270                  * XXX Some emulators expose host CPUID without actual support
271                  * for these MSRs.  We must test whether they really work.
272                  */
273                 wrmsr(MSR_MPERF, 0);
274                 wrmsr(MSR_APERF, 0);
275                 DELAY(10);
276                 if (rdmsr(MSR_MPERF) > 0 && rdmsr(MSR_APERF) > 0)
277                         tsc_perf_stat = 1;
278         }
279
280         switch (cpu_vendor_id) {
281         case CPU_VENDOR_AMD:
282         case CPU_VENDOR_HYGON:
283                 if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
284                     (vm_guest == VM_GUEST_NO &&
285                     CPUID_TO_FAMILY(cpu_id) >= 0x10))
286                         tsc_is_invariant = 1;
287                 if (cpu_feature & CPUID_SSE2) {
288                         tsc_timecounter.tc_get_timecount =
289                             tsc_get_timecount_mfence;
290                 }
291                 break;
292         case CPU_VENDOR_INTEL:
293                 if ((amd_pminfo & AMDPM_TSC_INVARIANT) != 0 ||
294                     (vm_guest == VM_GUEST_NO &&
295                     ((CPUID_TO_FAMILY(cpu_id) == 0x6 &&
296                     CPUID_TO_MODEL(cpu_id) >= 0xe) ||
297                     (CPUID_TO_FAMILY(cpu_id) == 0xf &&
298                     CPUID_TO_MODEL(cpu_id) >= 0x3))))
299                         tsc_is_invariant = 1;
300                 if (cpu_feature & CPUID_SSE2) {
301                         tsc_timecounter.tc_get_timecount =
302                             tsc_get_timecount_lfence;
303                 }
304                 break;
305         case CPU_VENDOR_CENTAUR:
306                 if (vm_guest == VM_GUEST_NO &&
307                     CPUID_TO_FAMILY(cpu_id) == 0x6 &&
308                     CPUID_TO_MODEL(cpu_id) >= 0xf &&
309                     (rdmsr(0x1203) & 0x100000000ULL) == 0)
310                         tsc_is_invariant = 1;
311                 if (cpu_feature & CPUID_SSE2) {
312                         tsc_timecounter.tc_get_timecount =
313                             tsc_get_timecount_lfence;
314                 }
315                 break;
316         }
317
318         if (tsc_freq_cpuid_vm())
319                 return;
320
321         if (vm_guest == VM_GUEST_VMWARE) {
322                 tsc_freq_vmware();
323                 return;
324         }
325
326         if (tsc_freq_cpuid(&tsc_freq)) {
327                 /*
328                  * If possible, use the value obtained from CPUID as the initial
329                  * frequency.  This will be refined later during boot but is
330                  * good enough for now.  The 8254 PIT is not functional on some
331                  * newer platforms anyway, so don't delay our boot for what
332                  * might be a garbage result.  Late calibration is required if
333                  * the initial frequency was obtained from CPUID.16H, as the
334                  * derived value may be off by as much as 1%.
335                  */
336                 if (bootverbose)
337                         printf("Early TSC frequency %juHz derived from CPUID\n",
338                             (uintmax_t)tsc_freq);
339         } else if (tsc_skip_calibration) {
340                 /*
341                  * Try to parse the brand string to obtain the nominal TSC
342                  * frequency.
343                  */
344                 if (cpu_vendor_id == CPU_VENDOR_INTEL &&
345                     tsc_freq_intel_brand(&tsc_freq)) {
346                         if (bootverbose)
347                                 printf(
348                     "Early TSC frequency %juHz derived from brand string\n",
349                                     (uintmax_t)tsc_freq);
350                 } else {
351                         tsc_disabled = 1;
352                 }
353         } else {
354                 /*
355                  * Calibrate against the 8254 PIT.  This estimate will be
356                  * refined later in tsc_calib().
357                  */
358                 tsc_freq_8254(&tsc_freq);
359                 if (bootverbose)
360                         printf(
361                     "Early TSC frequency %juHz calibrated from 8254 PIT\n",
362                             (uintmax_t)tsc_freq);
363         }
364 }
365
366 void
367 init_TSC(void)
368 {
369
370         if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
371                 return;
372
373 #ifdef __i386__
374         /* The TSC is known to be broken on certain CPUs. */
375         switch (cpu_vendor_id) {
376         case CPU_VENDOR_AMD:
377                 switch (cpu_id & 0xFF0) {
378                 case 0x500:
379                         /* K5 Model 0 */
380                         return;
381                 }
382                 break;
383         case CPU_VENDOR_CENTAUR:
384                 switch (cpu_id & 0xff0) {
385                 case 0x540:
386                         /*
387                          * http://www.centtech.com/c6_data_sheet.pdf
388                          *
389                          * I-12 RDTSC may return incoherent values in EDX:EAX
390                          * I-13 RDTSC hangs when certain event counters are used
391                          */
392                         return;
393                 }
394                 break;
395         case CPU_VENDOR_NSC:
396                 switch (cpu_id & 0xff0) {
397                 case 0x540:
398                         if ((cpu_id & CPUID_STEPPING) == 0)
399                                 return;
400                         break;
401                 }
402                 break;
403         }
404 #endif
405
406         probe_tsc_freq();
407
408         /*
409          * Inform CPU accounting about our boot-time clock rate.  This will
410          * be updated if someone loads a cpufreq driver after boot that
411          * discovers a new max frequency.
412          *
413          * The frequency may also be updated after late calibration is complete;
414          * however, we register the TSC as the ticker now to avoid switching
415          * counters after much of the kernel has already booted and potentially
416          * sampled the CPU clock.
417          */
418         if (tsc_freq != 0)
419                 set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
420
421         if (tsc_is_invariant)
422                 return;
423
424         /* Register to find out about changes in CPU frequency. */
425         tsc_pre_tag = EVENTHANDLER_REGISTER(cpufreq_pre_change,
426             tsc_freq_changing, NULL, EVENTHANDLER_PRI_FIRST);
427         tsc_post_tag = EVENTHANDLER_REGISTER(cpufreq_post_change,
428             tsc_freq_changed, NULL, EVENTHANDLER_PRI_FIRST);
429         tsc_levels_tag = EVENTHANDLER_REGISTER(cpufreq_levels_changed,
430             tsc_levels_changed, NULL, EVENTHANDLER_PRI_ANY);
431 }
432
433 #ifdef SMP
434
435 /*
436  * RDTSC is not a serializing instruction, and does not drain
437  * instruction stream, so we need to drain the stream before executing
438  * it.  It could be fixed by use of RDTSCP, except the instruction is
439  * not available everywhere.
440  *
441  * Use CPUID for draining in the boot-time SMP constistency test.  The
442  * timecounters use MFENCE for AMD CPUs, and LFENCE for others (Intel
443  * and VIA) when SSE2 is present, and nothing on older machines which
444  * also do not issue RDTSC prematurely.  There, testing for SSE2 and
445  * vendor is too cumbersome, and we learn about TSC presence from CPUID.
446  *
447  * Do not use do_cpuid(), since we do not need CPUID results, which
448  * have to be written into memory with do_cpuid().
449  */
450 #define TSC_READ(x)                                                     \
451 static void                                                             \
452 tsc_read_##x(void *arg)                                                 \
453 {                                                                       \
454         uint64_t *tsc = arg;                                            \
455         u_int cpu = PCPU_GET(cpuid);                                    \
456                                                                         \
457         __asm __volatile("cpuid" : : : "eax", "ebx", "ecx", "edx");     \
458         tsc[cpu * 3 + x] = rdtsc();                                     \
459 }
460 TSC_READ(0)
461 TSC_READ(1)
462 TSC_READ(2)
463 #undef TSC_READ
464
465 #define N       1000
466
467 static void
468 comp_smp_tsc(void *arg)
469 {
470         uint64_t *tsc;
471         int64_t d1, d2;
472         u_int cpu = PCPU_GET(cpuid);
473         u_int i, j, size;
474
475         size = (mp_maxid + 1) * 3;
476         for (i = 0, tsc = arg; i < N; i++, tsc += size)
477                 CPU_FOREACH(j) {
478                         if (j == cpu)
479                                 continue;
480                         d1 = tsc[cpu * 3 + 1] - tsc[j * 3];
481                         d2 = tsc[cpu * 3 + 2] - tsc[j * 3 + 1];
482                         if (d1 <= 0 || d2 <= 0) {
483                                 smp_tsc = 0;
484                                 return;
485                         }
486                 }
487 }
488
489 static void
490 adj_smp_tsc(void *arg)
491 {
492         uint64_t *tsc;
493         int64_t d, min, max;
494         u_int cpu = PCPU_GET(cpuid);
495         u_int first, i, size;
496
497         first = CPU_FIRST();
498         if (cpu == first)
499                 return;
500         min = INT64_MIN;
501         max = INT64_MAX;
502         size = (mp_maxid + 1) * 3;
503         for (i = 0, tsc = arg; i < N; i++, tsc += size) {
504                 d = tsc[first * 3] - tsc[cpu * 3 + 1];
505                 if (d > min)
506                         min = d;
507                 d = tsc[first * 3 + 1] - tsc[cpu * 3 + 2];
508                 if (d > min)
509                         min = d;
510                 d = tsc[first * 3 + 1] - tsc[cpu * 3];
511                 if (d < max)
512                         max = d;
513                 d = tsc[first * 3 + 2] - tsc[cpu * 3 + 1];
514                 if (d < max)
515                         max = d;
516         }
517         if (min > max)
518                 return;
519         d = min / 2 + max / 2;
520         __asm __volatile (
521                 "movl $0x10, %%ecx\n\t"
522                 "rdmsr\n\t"
523                 "addl %%edi, %%eax\n\t"
524                 "adcl %%esi, %%edx\n\t"
525                 "wrmsr\n"
526                 : /* No output */
527                 : "D" ((uint32_t)d), "S" ((uint32_t)(d >> 32))
528                 : "ax", "cx", "dx", "cc"
529         );
530 }
531
532 static int
533 test_tsc(int adj_max_count)
534 {
535         uint64_t *data, *tsc;
536         u_int i, size, adj;
537
538         if ((!smp_tsc && !tsc_is_invariant))
539                 return (-100);
540         /*
541          * Misbehavior of TSC under VirtualBox has been observed.  In
542          * particular, threads doing small (~1 second) sleeps may miss their
543          * wakeup and hang around in sleep state, causing hangs on shutdown.
544          */
545         if (vm_guest == VM_GUEST_VBOX)
546                 return (0);
547
548         size = (mp_maxid + 1) * 3;
549         data = malloc(sizeof(*data) * size * N, M_TEMP, M_WAITOK);
550         adj = 0;
551 retry:
552         for (i = 0, tsc = data; i < N; i++, tsc += size)
553                 smp_rendezvous(tsc_read_0, tsc_read_1, tsc_read_2, tsc);
554         smp_tsc = 1;    /* XXX */
555         smp_rendezvous(smp_no_rendezvous_barrier, comp_smp_tsc,
556             smp_no_rendezvous_barrier, data);
557         if (!smp_tsc && adj < adj_max_count) {
558                 adj++;
559                 smp_rendezvous(smp_no_rendezvous_barrier, adj_smp_tsc,
560                     smp_no_rendezvous_barrier, data);
561                 goto retry;
562         }
563         free(data, M_TEMP);
564         if (bootverbose)
565                 printf("SMP: %sed TSC synchronization test%s\n",
566                     smp_tsc ? "pass" : "fail", 
567                     adj > 0 ? " after adjustment" : "");
568         if (smp_tsc && tsc_is_invariant) {
569                 switch (cpu_vendor_id) {
570                 case CPU_VENDOR_AMD:
571                 case CPU_VENDOR_HYGON:
572                         /*
573                          * Processor Programming Reference (PPR) for AMD
574                          * Family 17h states that the TSC uses a common
575                          * reference for all sockets, cores and threads.
576                          */
577                         if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
578                                 return (1000);
579                         /*
580                          * Starting with Family 15h processors, TSC clock
581                          * source is in the north bridge.  Check whether
582                          * we have a single-socket/multi-core platform.
583                          * XXX Need more work for complex cases.
584                          */
585                         if (CPUID_TO_FAMILY(cpu_id) < 0x15 ||
586                             (amd_feature2 & AMDID2_CMP) == 0 ||
587                             smp_cpus > (cpu_procinfo2 & AMDID_CMP_CORES) + 1)
588                                 break;
589                         return (1000);
590                 case CPU_VENDOR_INTEL:
591                         /*
592                          * XXX Assume Intel platforms have synchronized TSCs.
593                          */
594                         return (1000);
595                 }
596                 return (800);
597         }
598         return (-100);
599 }
600
601 #undef N
602
603 #endif /* SMP */
604
605 static void
606 init_TSC_tc(void)
607 {
608         uint64_t max_freq;
609         int shift;
610
611         if ((cpu_feature & CPUID_TSC) == 0 || tsc_disabled)
612                 return;
613
614         /*
615          * Limit timecounter frequency to fit in an int and prevent it from
616          * overflowing too fast.
617          */
618         max_freq = UINT_MAX;
619
620         /*
621          * Intel CPUs without a C-state invariant TSC can stop the TSC
622          * in either C2 or C3.  Disable use of C2 and C3 while using
623          * the TSC as the timecounter.  The timecounter can be changed
624          * to enable C2 and C3.
625          *
626          * Note that the TSC is used as the cputicker for computing
627          * thread runtime regardless of the timecounter setting, so
628          * using an alternate timecounter and enabling C2 or C3 can
629          * result incorrect runtimes for kernel idle threads (but not
630          * for any non-idle threads).
631          */
632         if (cpu_vendor_id == CPU_VENDOR_INTEL &&
633             (amd_pminfo & AMDPM_TSC_INVARIANT) == 0) {
634                 tsc_timecounter.tc_flags |= TC_FLAGS_C2STOP;
635                 if (bootverbose)
636                         printf("TSC timecounter disables C2 and C3.\n");
637         }
638
639         /*
640          * We can not use the TSC in SMP mode unless the TSCs on all CPUs
641          * are synchronized.  If the user is sure that the system has
642          * synchronized TSCs, set kern.timecounter.smp_tsc tunable to a
643          * non-zero value.  The TSC seems unreliable in virtualized SMP
644          * environments, so it is set to a negative quality in those cases.
645          */
646 #ifdef SMP
647         if (mp_ncpus > 1)
648                 tsc_timecounter.tc_quality = test_tsc(smp_tsc_adjust);
649         else
650 #endif /* SMP */
651         if (tsc_is_invariant)
652                 tsc_timecounter.tc_quality = 1000;
653         max_freq >>= tsc_shift;
654
655         for (shift = 0; shift <= 31 && (tsc_freq >> shift) > max_freq; shift++)
656                 ;
657
658         /*
659          * Timecounter implementation selection, top to bottom:
660          * - If RDTSCP is available, use RDTSCP.
661          * - If fence instructions are provided (SSE2), use LFENCE;RDTSC
662          *   on Intel, and MFENCE;RDTSC on AMD.
663          * - For really old CPUs, just use RDTSC.
664          */
665         if ((amd_feature & AMDID_RDTSCP) != 0) {
666                 tsc_timecounter.tc_get_timecount = shift > 0 ?
667                     tscp_get_timecount_low : tscp_get_timecount;
668         } else if ((cpu_feature & CPUID_SSE2) != 0 && mp_ncpus > 1) {
669                 if (cpu_vendor_id == CPU_VENDOR_AMD ||
670                     cpu_vendor_id == CPU_VENDOR_HYGON) {
671                         tsc_timecounter.tc_get_timecount = shift > 0 ?
672                             tsc_get_timecount_low_mfence :
673                             tsc_get_timecount_mfence;
674                 } else {
675                         tsc_timecounter.tc_get_timecount = shift > 0 ?
676                             tsc_get_timecount_low_lfence :
677                             tsc_get_timecount_lfence;
678                 }
679         } else {
680                 tsc_timecounter.tc_get_timecount = shift > 0 ?
681                     tsc_get_timecount_low : tsc_get_timecount;
682         }
683         if (shift > 0) {
684                 tsc_timecounter.tc_name = "TSC-low";
685                 if (bootverbose)
686                         printf("TSC timecounter discards lower %d bit(s)\n",
687                             shift);
688         }
689         if (tsc_freq != 0) {
690                 tsc_timecounter.tc_frequency = tsc_freq >> shift;
691                 tsc_timecounter.tc_priv = (void *)(intptr_t)shift;
692
693                 /*
694                  * Timecounter registration is deferred until after late
695                  * calibration is finished.
696                  */
697         }
698 }
699 SYSINIT(tsc_tc, SI_SUB_SMP, SI_ORDER_ANY, init_TSC_tc, NULL);
700
701 static void
702 tsc_update_freq(uint64_t new_freq)
703 {
704         atomic_store_rel_64(&tsc_freq, new_freq);
705         atomic_store_rel_64(&tsc_timecounter.tc_frequency,
706             new_freq >> (int)(intptr_t)tsc_timecounter.tc_priv);
707 }
708
709 /*
710  * Perform late calibration of the TSC frequency once ACPI-based timecounters
711  * are available.  At this point timehands are not set up, so we read the
712  * highest-quality timecounter directly rather than using (s)binuptime().
713  */
714 void
715 tsc_calibrate(void)
716 {
717         uint64_t freq;
718
719         if (tsc_disabled)
720                 return;
721         if (tsc_early_calib_exact)
722                 goto calibrated;
723
724         fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
725         freq = clockcalib(rdtsc_ordered, "TSC");
726         fpu_kern_leave(curthread, NULL);
727         tsc_update_freq(freq);
728
729 calibrated:
730         tc_init(&tsc_timecounter);
731         set_cputicker(rdtsc, tsc_freq, !tsc_is_invariant);
732 }
733
734 void
735 resume_TSC(void)
736 {
737 #ifdef SMP
738         int quality;
739
740         /* If TSC was not good on boot, it is unlikely to become good now. */
741         if (tsc_timecounter.tc_quality < 0)
742                 return;
743         /* Nothing to do with UP. */
744         if (mp_ncpus < 2)
745                 return;
746
747         /*
748          * If TSC was good, a single synchronization should be enough,
749          * but honour smp_tsc_adjust if it's set.
750          */
751         quality = test_tsc(MAX(smp_tsc_adjust, 1));
752         if (quality != tsc_timecounter.tc_quality) {
753                 printf("TSC timecounter quality changed: %d -> %d\n",
754                     tsc_timecounter.tc_quality, quality);
755                 tsc_timecounter.tc_quality = quality;
756         }
757 #endif /* SMP */
758 }
759
760 /*
761  * When cpufreq levels change, find out about the (new) max frequency.  We
762  * use this to update CPU accounting in case it got a lower estimate at boot.
763  */
764 static void
765 tsc_levels_changed(void *arg, int unit)
766 {
767         device_t cf_dev;
768         struct cf_level *levels;
769         int count, error;
770         uint64_t max_freq;
771
772         /* Only use values from the first CPU, assuming all are equal. */
773         if (unit != 0)
774                 return;
775
776         /* Find the appropriate cpufreq device instance. */
777         cf_dev = devclass_get_device(devclass_find("cpufreq"), unit);
778         if (cf_dev == NULL) {
779                 printf("tsc_levels_changed() called but no cpufreq device?\n");
780                 return;
781         }
782
783         /* Get settings from the device and find the max frequency. */
784         count = 64;
785         levels = malloc(count * sizeof(*levels), M_TEMP, M_NOWAIT);
786         if (levels == NULL)
787                 return;
788         error = CPUFREQ_LEVELS(cf_dev, levels, &count);
789         if (error == 0 && count != 0) {
790                 max_freq = (uint64_t)levels[0].total_set.freq * 1000000;
791                 set_cputicker(rdtsc, max_freq, 1);
792         } else
793                 printf("tsc_levels_changed: no max freq found\n");
794         free(levels, M_TEMP);
795 }
796
797 /*
798  * If the TSC timecounter is in use, veto the pending change.  It may be
799  * possible in the future to handle a dynamically-changing timecounter rate.
800  */
801 static void
802 tsc_freq_changing(void *arg, const struct cf_level *level, int *status)
803 {
804
805         if (*status != 0 || timecounter != &tsc_timecounter)
806                 return;
807
808         printf("timecounter TSC must not be in use when "
809             "changing frequencies; change denied\n");
810         *status = EBUSY;
811 }
812
813 /* Update TSC freq with the value indicated by the caller. */
814 static void
815 tsc_freq_changed(void *arg, const struct cf_level *level, int status)
816 {
817         uint64_t freq;
818
819         /* If there was an error during the transition, don't do anything. */
820         if (tsc_disabled || status != 0)
821                 return;
822
823         /* Total setting for this level gives the new frequency in MHz. */
824         freq = (uint64_t)level->total_set.freq * 1000000;
825         tsc_update_freq(freq);
826 }
827
828 static int
829 sysctl_machdep_tsc_freq(SYSCTL_HANDLER_ARGS)
830 {
831         int error;
832         uint64_t freq;
833
834         freq = atomic_load_acq_64(&tsc_freq);
835         if (freq == 0)
836                 return (EOPNOTSUPP);
837         error = sysctl_handle_64(oidp, &freq, 0, req);
838         if (error == 0 && req->newptr != NULL)
839                 tsc_update_freq(freq);
840         return (error);
841 }
842 SYSCTL_PROC(_machdep, OID_AUTO, tsc_freq,
843     CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
844     0, 0, sysctl_machdep_tsc_freq, "QU",
845     "Time Stamp Counter frequency");
846
847 static u_int
848 tsc_get_timecount(struct timecounter *tc __unused)
849 {
850
851         return (rdtsc32());
852 }
853
854 static u_int
855 tscp_get_timecount(struct timecounter *tc __unused)
856 {
857
858         return (rdtscp32());
859 }
860
861 static inline u_int
862 tsc_get_timecount_low(struct timecounter *tc)
863 {
864         uint32_t rv;
865
866         __asm __volatile("rdtsc; shrd %%cl, %%edx, %0"
867             : "=a" (rv) : "c" ((int)(intptr_t)tc->tc_priv) : "edx");
868         return (rv);
869 }
870
871 static u_int
872 tscp_get_timecount_low(struct timecounter *tc)
873 {
874         uint32_t rv;
875
876         __asm __volatile("rdtscp; movl %1, %%ecx; shrd %%cl, %%edx, %0"
877             : "=&a" (rv) : "m" (tc->tc_priv) : "ecx", "edx");
878         return (rv);
879 }
880
881 static u_int
882 tsc_get_timecount_lfence(struct timecounter *tc __unused)
883 {
884
885         lfence();
886         return (rdtsc32());
887 }
888
889 static u_int
890 tsc_get_timecount_low_lfence(struct timecounter *tc)
891 {
892
893         lfence();
894         return (tsc_get_timecount_low(tc));
895 }
896
897 static u_int
898 tsc_get_timecount_mfence(struct timecounter *tc __unused)
899 {
900
901         mfence();
902         return (rdtsc32());
903 }
904
905 static u_int
906 tsc_get_timecount_low_mfence(struct timecounter *tc)
907 {
908
909         mfence();
910         return (tsc_get_timecount_low(tc));
911 }
912
913 static uint32_t
914 x86_tsc_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
915 {
916
917         vdso_th->th_algo = VDSO_TH_ALGO_X86_TSC;
918         vdso_th->th_x86_shift = (int)(intptr_t)tc->tc_priv;
919         vdso_th->th_x86_hpet_idx = 0xffffffff;
920         vdso_th->th_x86_pvc_last_systime = 0;
921         vdso_th->th_x86_pvc_stable_mask = 0;
922         bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
923         return (1);
924 }
925
926 #ifdef COMPAT_FREEBSD32
927 static uint32_t
928 x86_tsc_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
929     struct timecounter *tc)
930 {
931
932         vdso_th32->th_algo = VDSO_TH_ALGO_X86_TSC;
933         vdso_th32->th_x86_shift = (int)(intptr_t)tc->tc_priv;
934         vdso_th32->th_x86_hpet_idx = 0xffffffff;
935         vdso_th32->th_x86_pvc_last_systime = 0;
936         vdso_th32->th_x86_pvc_stable_mask = 0;
937         bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
938         return (1);
939 }
940 #endif