blob: 2e076a459a0c084aa279f32f3fc644604713e595 [file] [log] [blame]
Thomas Gleixner457c8992019-05-19 13:08:55 +01001// SPDX-License-Identifier: GPL-2.0-only
Joe Perchesc767a542012-05-21 19:50:07 -07002#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3
Alok Katariabfc0f592008-07-01 11:43:24 -07004#include <linux/kernel.h>
Alok Kataria0ef95532008-07-01 11:43:18 -07005#include <linux/sched.h>
Ingo Molnare6017572017-02-01 16:36:40 +01006#include <linux/sched/clock.h>
Alok Kataria0ef95532008-07-01 11:43:18 -07007#include <linux/init.h>
Paul Gortmaker186f4362016-07-13 20:18:56 -04008#include <linux/export.h>
Alok Kataria0ef95532008-07-01 11:43:18 -07009#include <linux/timer.h>
Alok Katariabfc0f592008-07-01 11:43:24 -070010#include <linux/acpi_pmtmr.h>
Alok Kataria2dbe06f2008-07-01 11:43:31 -070011#include <linux/cpufreq.h>
Alok Kataria8fbbc4b2008-07-01 11:43:34 -070012#include <linux/delay.h>
13#include <linux/clocksource.h>
14#include <linux/percpu.h>
Arnd Bergmann08604bd2009-06-16 15:31:12 -070015#include <linux/timex.h>
Peter Zijlstra10b033d2013-11-28 19:01:40 +010016#include <linux/static_key.h>
Juergen Grossa0e2bf72021-03-11 15:23:09 +010017#include <linux/static_call.h>
Alok Katariabfc0f592008-07-01 11:43:24 -070018
19#include <asm/hpet.h>
Alok Kataria8fbbc4b2008-07-01 11:43:34 -070020#include <asm/timer.h>
21#include <asm/vgtod.h>
22#include <asm/time.h>
23#include <asm/delay.h>
Alok Kataria88b094f2008-10-27 10:41:46 -070024#include <asm/hypervisor.h>
Thomas Gleixner08047c42009-08-20 16:27:41 +020025#include <asm/nmi.h>
Thomas Gleixner2d826402009-08-20 17:06:25 +020026#include <asm/x86_init.h>
David Woodhouse03da3ff2015-09-16 14:10:03 +010027#include <asm/geode.h>
Nicolai Stange6731b0d2016-07-14 17:22:55 +020028#include <asm/apic.h>
Prarit Bhargava655e52d2016-09-19 08:51:40 -040029#include <asm/intel-family.h>
Peter Zijlstra30c7e5b2017-12-22 10:20:11 +010030#include <asm/i8259.h>
Mike Travis2647c432018-10-02 13:01:46 -050031#include <asm/uv/uv.h>
Alok Kataria0ef95532008-07-01 11:43:18 -070032
Ingo Molnarf24ade3a2009-03-10 19:02:30 +010033unsigned int __read_mostly cpu_khz; /* TSC clocks / usec, not used here */
Alok Kataria0ef95532008-07-01 11:43:18 -070034EXPORT_SYMBOL(cpu_khz);
Ingo Molnarf24ade3a2009-03-10 19:02:30 +010035
36unsigned int __read_mostly tsc_khz;
Alok Kataria0ef95532008-07-01 11:43:18 -070037EXPORT_SYMBOL(tsc_khz);
38
Pavel Tatashincf7a63e2018-07-19 16:55:38 -040039#define KHZ 1000
40
Alok Kataria0ef95532008-07-01 11:43:18 -070041/*
42 * TSC can be unstable due to cpufreq or due to unsynced TSCs
43 */
Ingo Molnarf24ade3a2009-03-10 19:02:30 +010044static int __read_mostly tsc_unstable;
Krzysztof Piecuchbd35c772020-01-23 16:09:26 +000045static unsigned int __initdata tsc_early_khz;
Alok Kataria0ef95532008-07-01 11:43:18 -070046
Peter Zijlstra3bbfafb2015-07-24 16:34:32 +020047static DEFINE_STATIC_KEY_FALSE(__use_tsc);
Peter Zijlstra10b033d2013-11-28 19:01:40 +010048
Suresh Siddha28a00182011-11-04 15:42:17 -070049int tsc_clocksource_reliable;
Peter Zijlstra57c67da2013-11-29 15:39:25 +010050
Christopher S. Hallf9677e02016-02-29 06:33:47 -080051static u32 art_to_tsc_numerator;
52static u32 art_to_tsc_denominator;
53static u64 art_to_tsc_offset;
54struct clocksource *art_related_clocksource;
55
Peter Zijlstra20d1c862013-11-29 15:40:29 +010056struct cyc2ns {
Peter Zijlstra59eaef72017-05-02 13:22:07 +020057 struct cyc2ns_data data[2]; /* 0 + 2*16 = 32 */
Ahmed S. Darwisha1f10662020-08-27 13:40:42 +020058 seqcount_latch_t seq; /* 32 + 4 = 36 */
Peter Zijlstra59eaef72017-05-02 13:22:07 +020059
60}; /* fits one cacheline */
Peter Zijlstra20d1c862013-11-29 15:40:29 +010061
62static DEFINE_PER_CPU_ALIGNED(struct cyc2ns, cyc2ns);
63
Krzysztof Piecuchbd35c772020-01-23 16:09:26 +000064static int __init tsc_early_khz_setup(char *buf)
65{
66 return kstrtouint(buf, 0, &tsc_early_khz);
67}
68early_param("tsc_early_khz", tsc_early_khz_setup);
69
Mathieu Malaterre83e83722019-05-24 12:32:51 +020070__always_inline void cyc2ns_read_begin(struct cyc2ns_data *data)
Peter Zijlstra20d1c862013-11-29 15:40:29 +010071{
Peter Zijlstra59eaef72017-05-02 13:22:07 +020072 int seq, idx;
Peter Zijlstra20d1c862013-11-29 15:40:29 +010073
Peter Zijlstra59eaef72017-05-02 13:22:07 +020074 preempt_disable_notrace();
Peter Zijlstra20d1c862013-11-29 15:40:29 +010075
Peter Zijlstra59eaef72017-05-02 13:22:07 +020076 do {
Ahmed S. Darwisha1f10662020-08-27 13:40:42 +020077 seq = this_cpu_read(cyc2ns.seq.seqcount.sequence);
Peter Zijlstra59eaef72017-05-02 13:22:07 +020078 idx = seq & 1;
Peter Zijlstra20d1c862013-11-29 15:40:29 +010079
Peter Zijlstra59eaef72017-05-02 13:22:07 +020080 data->cyc2ns_offset = this_cpu_read(cyc2ns.data[idx].cyc2ns_offset);
81 data->cyc2ns_mul = this_cpu_read(cyc2ns.data[idx].cyc2ns_mul);
82 data->cyc2ns_shift = this_cpu_read(cyc2ns.data[idx].cyc2ns_shift);
83
Ahmed S. Darwisha1f10662020-08-27 13:40:42 +020084 } while (unlikely(seq != this_cpu_read(cyc2ns.seq.seqcount.sequence)));
Peter Zijlstra20d1c862013-11-29 15:40:29 +010085}
86
Mathieu Malaterre83e83722019-05-24 12:32:51 +020087__always_inline void cyc2ns_read_end(void)
Peter Zijlstra20d1c862013-11-29 15:40:29 +010088{
Peter Zijlstra59eaef72017-05-02 13:22:07 +020089 preempt_enable_notrace();
Peter Zijlstra20d1c862013-11-29 15:40:29 +010090}
91
92/*
93 * Accelerators for sched_clock()
Peter Zijlstra57c67da2013-11-29 15:39:25 +010094 * convert from cycles(64bits) => nanoseconds (64bits)
95 * basic equation:
96 * ns = cycles / (freq / ns_per_sec)
97 * ns = cycles * (ns_per_sec / freq)
98 * ns = cycles * (10^9 / (cpu_khz * 10^3))
99 * ns = cycles * (10^6 / cpu_khz)
100 *
101 * Then we use scaling math (suggested by george@mvista.com) to get:
102 * ns = cycles * (10^6 * SC / cpu_khz) / SC
103 * ns = cycles * cyc2ns_scale / SC
104 *
105 * And since SC is a constant power of two, we can convert the div
Adrian Hunterb20112e2015-08-21 12:05:18 +0300106 * into a shift. The larger SC is, the more accurate the conversion, but
107 * cyc2ns_scale needs to be a 32-bit value so that 32-bit multiplication
108 * (64-bit result) can be used.
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100109 *
Adrian Hunterb20112e2015-08-21 12:05:18 +0300110 * We can use khz divisor instead of mhz to keep a better precision.
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100111 * (mathieu.desnoyers@polymtl.ca)
112 *
113 * -johnstul@us.ibm.com "math is hard, lets go shopping!"
114 */
115
Peter Zijlstra4907c682018-10-11 12:38:26 +0200116static __always_inline unsigned long long cycles_2_ns(unsigned long long cyc)
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100117{
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200118 struct cyc2ns_data data;
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100119 unsigned long long ns;
120
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200121 cyc2ns_read_begin(&data);
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100122
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200123 ns = data.cyc2ns_offset;
124 ns += mul_u64_u32_shr(cyc, data.cyc2ns_mul, data.cyc2ns_shift);
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100125
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200126 cyc2ns_read_end();
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100127
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100128 return ns;
129}
130
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400131static void __set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long tsc_now)
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100132{
Peter Zijlstra615cd032017-05-05 09:55:01 +0200133 unsigned long long ns_now;
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200134 struct cyc2ns_data data;
135 struct cyc2ns *c2n;
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100136
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100137 ns_now = cycles_2_ns(tsc_now);
138
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100139 /*
140 * Compute a new multiplier as per the above comment and ensure our
141 * time function is continuous; see the comment near struct
142 * cyc2ns_data.
143 */
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200144 clocks_calc_mult_shift(&data.cyc2ns_mul, &data.cyc2ns_shift, khz,
Adrian Hunterb20112e2015-08-21 12:05:18 +0300145 NSEC_PER_MSEC, 0);
146
Adrian Hunterb9511cd2015-10-16 16:24:05 +0300147 /*
148 * cyc2ns_shift is exported via arch_perf_update_userpage() where it is
149 * not expected to be greater than 31 due to the original published
150 * conversion algorithm shifting a 32-bit value (now specifies a 64-bit
151 * value) - refer perf_event_mmap_page documentation in perf_event.h.
152 */
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200153 if (data.cyc2ns_shift == 32) {
154 data.cyc2ns_shift = 31;
155 data.cyc2ns_mul >>= 1;
Adrian Hunterb9511cd2015-10-16 16:24:05 +0300156 }
157
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200158 data.cyc2ns_offset = ns_now -
159 mul_u64_u32_shr(tsc_now, data.cyc2ns_mul, data.cyc2ns_shift);
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100160
Peter Zijlstra59eaef72017-05-02 13:22:07 +0200161 c2n = per_cpu_ptr(&cyc2ns, cpu);
162
163 raw_write_seqcount_latch(&c2n->seq);
164 c2n->data[0] = data;
165 raw_write_seqcount_latch(&c2n->seq);
166 c2n->data[1] = data;
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400167}
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100168
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400169static void set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long tsc_now)
170{
171 unsigned long flags;
172
173 local_irq_save(flags);
174 sched_clock_idle_sleep_event();
175
176 if (khz)
177 __set_cyc2ns_scale(khz, cpu, tsc_now);
178
Peter Zijlstraac1e8432017-04-21 12:26:23 +0200179 sched_clock_idle_wakeup_event();
Peter Zijlstra57c67da2013-11-29 15:39:25 +0100180 local_irq_restore(flags);
181}
Peter Zijlstra615cd032017-05-05 09:55:01 +0200182
Alok Kataria0ef95532008-07-01 11:43:18 -0700183/*
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400184 * Initialize cyc2ns for boot cpu
185 */
186static void __init cyc2ns_init_boot_cpu(void)
187{
188 struct cyc2ns *c2n = this_cpu_ptr(&cyc2ns);
189
Ahmed S. Darwisha1f10662020-08-27 13:40:42 +0200190 seqcount_latch_init(&c2n->seq);
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400191 __set_cyc2ns_scale(tsc_khz, smp_processor_id(), rdtsc());
192}
193
194/*
Dou Liyang608008a2018-07-30 15:54:20 +0800195 * Secondary CPUs do not run through tsc_init(), so set up
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400196 * all the scale factors for all CPUs, assuming the same
Rafael J. Wysockic208ac82019-04-18 16:11:37 +0200197 * speed as the bootup CPU.
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400198 */
199static void __init cyc2ns_init_secondary_cpus(void)
200{
201 unsigned int cpu, this_cpu = smp_processor_id();
202 struct cyc2ns *c2n = this_cpu_ptr(&cyc2ns);
203 struct cyc2ns_data *data = c2n->data;
204
205 for_each_possible_cpu(cpu) {
206 if (cpu != this_cpu) {
Ahmed S. Darwisha1f10662020-08-27 13:40:42 +0200207 seqcount_latch_init(&c2n->seq);
Pavel Tatashine2a9ca22018-07-19 16:55:39 -0400208 c2n = per_cpu_ptr(&cyc2ns, cpu);
209 c2n->data[0] = data[0];
210 c2n->data[1] = data[1];
211 }
212 }
213}
214
215/*
Alok Kataria0ef95532008-07-01 11:43:18 -0700216 * Scheduler clock - returns current time in nanosec units.
217 */
218u64 native_sched_clock(void)
219{
Peter Zijlstra3bbfafb2015-07-24 16:34:32 +0200220 if (static_branch_likely(&__use_tsc)) {
221 u64 tsc_now = rdtsc();
222
223 /* return the value in ns */
224 return cycles_2_ns(tsc_now);
225 }
Alok Kataria0ef95532008-07-01 11:43:18 -0700226
227 /*
228 * Fall back to jiffies if there's no TSC available:
229 * ( But note that we still use it if the TSC is marked
230 * unstable. We do this because unlike Time Of Day,
231 * the scheduler clock tolerates small errors and it's
232 * very important for it to be as fast as the platform
Daniel Mack3ad2f3fb2010-02-03 08:01:28 +0800233 * can achieve it. )
Alok Kataria0ef95532008-07-01 11:43:18 -0700234 */
Alok Kataria0ef95532008-07-01 11:43:18 -0700235
Peter Zijlstra3bbfafb2015-07-24 16:34:32 +0200236 /* No locking but a rare wrong value is not a big deal: */
237 return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
Alok Kataria0ef95532008-07-01 11:43:18 -0700238}
239
Andi Kleena94cab22015-05-10 12:22:39 -0700240/*
241 * Generate a sched_clock if you already have a TSC value.
242 */
243u64 native_sched_clock_from_tsc(u64 tsc)
244{
245 return cycles_2_ns(tsc);
246}
247
Alok Kataria0ef95532008-07-01 11:43:18 -0700248/* We need to define a real function for sched_clock, to override the
249 weak default version */
250#ifdef CONFIG_PARAVIRT
251unsigned long long sched_clock(void)
252{
253 return paravirt_sched_clock();
254}
Peter Zijlstraf94c8d12017-03-01 15:53:38 +0100255
Peter Zijlstra698eff62017-03-17 12:48:18 +0100256bool using_native_sched_clock(void)
Peter Zijlstraf94c8d12017-03-01 15:53:38 +0100257{
Juergen Grossa0e2bf72021-03-11 15:23:09 +0100258 return static_call_query(pv_sched_clock) == native_sched_clock;
Peter Zijlstraf94c8d12017-03-01 15:53:38 +0100259}
Alok Kataria0ef95532008-07-01 11:43:18 -0700260#else
261unsigned long long
262sched_clock(void) __attribute__((alias("native_sched_clock")));
Peter Zijlstraf94c8d12017-03-01 15:53:38 +0100263
Peter Zijlstra698eff62017-03-17 12:48:18 +0100264bool using_native_sched_clock(void) { return true; }
Alok Kataria0ef95532008-07-01 11:43:18 -0700265#endif
266
267int check_tsc_unstable(void)
268{
269 return tsc_unstable;
270}
271EXPORT_SYMBOL_GPL(check_tsc_unstable);
272
273#ifdef CONFIG_X86_TSC
274int __init notsc_setup(char *str)
275{
Pavel Tatashinfe9af812018-07-19 16:55:30 -0400276 mark_tsc_unstable("boot parameter notsc");
Alok Kataria0ef95532008-07-01 11:43:18 -0700277 return 1;
278}
279#else
280/*
281 * disable flag for tsc. Takes effect by clearing the TSC cpu flag
282 * in cpu/common.c
283 */
284int __init notsc_setup(char *str)
285{
286 setup_clear_cpu_cap(X86_FEATURE_TSC);
287 return 1;
288}
289#endif
290
291__setup("notsc", notsc_setup);
Alok Katariabfc0f592008-07-01 11:43:24 -0700292
Venkatesh Pallipadie82b8e42010-10-04 17:03:20 -0700293static int no_sched_irq_time;
Juri Lelli0f0b7e1c2019-03-07 13:09:13 +0100294static int no_tsc_watchdog;
Venkatesh Pallipadie82b8e42010-10-04 17:03:20 -0700295
Alok Kataria395628e2008-10-24 17:22:01 -0700296static int __init tsc_setup(char *str)
297{
298 if (!strcmp(str, "reliable"))
299 tsc_clocksource_reliable = 1;
Venkatesh Pallipadie82b8e42010-10-04 17:03:20 -0700300 if (!strncmp(str, "noirqtime", 9))
301 no_sched_irq_time = 1;
Peter Zijlstra8309f862017-04-13 14:56:44 +0200302 if (!strcmp(str, "unstable"))
303 mark_tsc_unstable("boot parameter");
Juri Lelli0f0b7e1c2019-03-07 13:09:13 +0100304 if (!strcmp(str, "nowatchdog"))
305 no_tsc_watchdog = 1;
Alok Kataria395628e2008-10-24 17:22:01 -0700306 return 1;
307}
308
309__setup("tsc=", tsc_setup);
310
Daniel Vaceka786ef12018-11-05 18:10:40 +0100311#define MAX_RETRIES 5
312#define TSC_DEFAULT_THRESHOLD 0x20000
Alok Katariabfc0f592008-07-01 11:43:24 -0700313
314/*
Daniel Vaceka786ef12018-11-05 18:10:40 +0100315 * Read TSC and the reference counters. Take care of any disturbances
Alok Katariabfc0f592008-07-01 11:43:24 -0700316 */
Thomas Gleixner827014b2008-09-04 15:18:53 +0000317static u64 tsc_read_refs(u64 *p, int hpet)
Alok Katariabfc0f592008-07-01 11:43:24 -0700318{
319 u64 t1, t2;
Daniel Vaceka786ef12018-11-05 18:10:40 +0100320 u64 thresh = tsc_khz ? tsc_khz >> 5 : TSC_DEFAULT_THRESHOLD;
Alok Katariabfc0f592008-07-01 11:43:24 -0700321 int i;
322
323 for (i = 0; i < MAX_RETRIES; i++) {
324 t1 = get_cycles();
325 if (hpet)
Thomas Gleixner827014b2008-09-04 15:18:53 +0000326 *p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
Alok Katariabfc0f592008-07-01 11:43:24 -0700327 else
Thomas Gleixner827014b2008-09-04 15:18:53 +0000328 *p = acpi_pm_read_early();
Alok Katariabfc0f592008-07-01 11:43:24 -0700329 t2 = get_cycles();
Daniel Vaceka786ef12018-11-05 18:10:40 +0100330 if ((t2 - t1) < thresh)
Alok Katariabfc0f592008-07-01 11:43:24 -0700331 return t2;
332 }
333 return ULLONG_MAX;
334}
335
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700336/*
Thomas Gleixnerd683ef72008-09-04 15:18:48 +0000337 * Calculate the TSC frequency from HPET reference
338 */
339static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
340{
341 u64 tmp;
342
343 if (hpet2 < hpet1)
344 hpet2 += 0x100000000ULL;
345 hpet2 -= hpet1;
346 tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
347 do_div(tmp, 1000000);
Xiaoming Gaod3878e162018-04-13 17:48:08 +0800348 deltatsc = div64_u64(deltatsc, tmp);
Thomas Gleixnerd683ef72008-09-04 15:18:48 +0000349
350 return (unsigned long) deltatsc;
351}
352
353/*
354 * Calculate the TSC frequency from PMTimer reference
355 */
356static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
357{
358 u64 tmp;
359
360 if (!pm1 && !pm2)
361 return ULONG_MAX;
362
363 if (pm2 < pm1)
364 pm2 += (u64)ACPI_PM_OVRRUN;
365 pm2 -= pm1;
366 tmp = pm2 * 1000000000LL;
367 do_div(tmp, PMTMR_TICKS_PER_SEC);
368 do_div(deltatsc, tmp);
369
370 return (unsigned long) deltatsc;
371}
372
Thomas Gleixnera977c402008-09-04 15:18:59 +0000373#define CAL_MS 10
Deepak Saxenab7743972011-11-01 14:25:07 -0700374#define CAL_LATCH (PIT_TICK_RATE / (1000 / CAL_MS))
Thomas Gleixnera977c402008-09-04 15:18:59 +0000375#define CAL_PIT_LOOPS 1000
376
377#define CAL2_MS 50
Deepak Saxenab7743972011-11-01 14:25:07 -0700378#define CAL2_LATCH (PIT_TICK_RATE / (1000 / CAL2_MS))
Thomas Gleixnera977c402008-09-04 15:18:59 +0000379#define CAL2_PIT_LOOPS 5000
380
Thomas Gleixnercce3e052008-09-04 15:18:44 +0000381
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700382/*
383 * Try to calibrate the TSC against the Programmable
384 * Interrupt Timer and return the frequency of the TSC
385 * in kHz.
386 *
387 * Return ULONG_MAX on failure to calibrate.
388 */
Thomas Gleixnera977c402008-09-04 15:18:59 +0000389static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700390{
391 u64 tsc, t1, t2, delta;
392 unsigned long tscmin, tscmax;
393 int pitcnt;
394
Peter Zijlstra30c7e5b2017-12-22 10:20:11 +0100395 if (!has_legacy_pic()) {
396 /*
397 * Relies on tsc_early_delay_calibrate() to have given us semi
398 * usable udelay(), wait for the same 50ms we would have with
399 * the PIT loop below.
400 */
401 udelay(10 * USEC_PER_MSEC);
402 udelay(10 * USEC_PER_MSEC);
403 udelay(10 * USEC_PER_MSEC);
404 udelay(10 * USEC_PER_MSEC);
405 udelay(10 * USEC_PER_MSEC);
406 return ULONG_MAX;
407 }
408
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700409 /* Set the Gate high, disable speaker */
410 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
411
412 /*
413 * Setup CTC channel 2* for mode 0, (interrupt on terminal
414 * count mode), binary count. Set the latch register to 50ms
415 * (LSB then MSB) to begin countdown.
416 */
417 outb(0xb0, 0x43);
Thomas Gleixnera977c402008-09-04 15:18:59 +0000418 outb(latch & 0xff, 0x42);
419 outb(latch >> 8, 0x42);
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700420
421 tsc = t1 = t2 = get_cycles();
422
423 pitcnt = 0;
424 tscmax = 0;
425 tscmin = ULONG_MAX;
426 while ((inb(0x61) & 0x20) == 0) {
427 t2 = get_cycles();
428 delta = t2 - tsc;
429 tsc = t2;
430 if ((unsigned long) delta < tscmin)
431 tscmin = (unsigned int) delta;
432 if ((unsigned long) delta > tscmax)
433 tscmax = (unsigned int) delta;
434 pitcnt++;
435 }
436
437 /*
438 * Sanity checks:
439 *
Thomas Gleixnera977c402008-09-04 15:18:59 +0000440 * If we were not able to read the PIT more than loopmin
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700441 * times, then we have been hit by a massive SMI
442 *
443 * If the maximum is 10 times larger than the minimum,
444 * then we got hit by an SMI as well.
445 */
Thomas Gleixnera977c402008-09-04 15:18:59 +0000446 if (pitcnt < loopmin || tscmax > 10 * tscmin)
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700447 return ULONG_MAX;
448
449 /* Calculate the PIT value */
450 delta = t2 - t1;
Thomas Gleixnera977c402008-09-04 15:18:59 +0000451 do_div(delta, ms);
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700452 return delta;
453}
454
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700455/*
456 * This reads the current MSB of the PIT counter, and
457 * checks if we are running on sufficiently fast and
458 * non-virtualized hardware.
459 *
460 * Our expectations are:
461 *
462 * - the PIT is running at roughly 1.19MHz
463 *
464 * - each IO is going to take about 1us on real hardware,
465 * but we allow it to be much faster (by a factor of 10) or
466 * _slightly_ slower (ie we allow up to a 2us read+counter
467 * update - anything else implies a unacceptably slow CPU
468 * or PIT for the fast calibration to work.
469 *
470 * - with 256 PIT ticks to read the value, we have 214us to
471 * see the same MSB (and overhead like doing a single TSC
472 * read per MSB value etc).
473 *
474 * - We're doing 2 reads per loop (LSB, MSB), and we expect
475 * them each to take about a microsecond on real hardware.
476 * So we expect a count value of around 100. But we'll be
477 * generous, and accept anything over 50.
478 *
479 * - if the PIT is stuck, and we see *many* more reads, we
480 * return early (and the next caller of pit_expect_msb()
481 * then consider it a failure when they don't see the
482 * next expected value).
483 *
484 * These expectations mean that we know that we have seen the
485 * transition from one expected value to another with a fairly
486 * high accuracy, and we didn't miss any events. We can thus
487 * use the TSC value at the transitions to calculate a pretty
Martin Molnar4d1d0972020-02-16 16:17:39 +0100488 * good value for the TSC frequency.
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700489 */
Linus Torvaldsb6e61ee2009-07-31 12:45:41 -0700490static inline int pit_verify_msb(unsigned char val)
491{
492 /* Ignore LSB */
493 inb(0x42);
494 return inb(0x42) == val;
495}
496
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700497static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700498{
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700499 int count;
Linus Torvalds68f30fb2012-01-17 15:35:37 -0800500 u64 tsc = 0, prev_tsc = 0;
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700501
502 for (count = 0; count < 50000; count++) {
Linus Torvaldsb6e61ee2009-07-31 12:45:41 -0700503 if (!pit_verify_msb(val))
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700504 break;
Linus Torvalds68f30fb2012-01-17 15:35:37 -0800505 prev_tsc = tsc;
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700506 tsc = get_cycles();
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700507 }
Linus Torvalds68f30fb2012-01-17 15:35:37 -0800508 *deltap = get_cycles() - prev_tsc;
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700509 *tscp = tsc;
510
511 /*
512 * We require _some_ success, but the quality control
513 * will be based on the error terms on the TSC values.
514 */
515 return count > 5;
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700516}
517
518/*
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700519 * How many MSB values do we want to see? We aim for
520 * a maximum error rate of 500ppm (in practice the
521 * real error is much smaller), but refuse to spend
Linus Torvalds68f30fb2012-01-17 15:35:37 -0800522 * more than 50ms on it.
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700523 */
Linus Torvalds68f30fb2012-01-17 15:35:37 -0800524#define MAX_QUICK_PIT_MS 50
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700525#define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700526
527static unsigned long quick_pit_calibrate(void)
528{
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700529 int i;
530 u64 tsc, delta;
531 unsigned long d1, d2;
532
Peter Zijlstra30c7e5b2017-12-22 10:20:11 +0100533 if (!has_legacy_pic())
534 return 0;
535
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700536 /* Set the Gate high, disable speaker */
537 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
538
539 /*
540 * Counter 2, mode 0 (one-shot), binary count
541 *
542 * NOTE! Mode 2 decrements by two (and then the
543 * output is flipped each time, giving the same
544 * final output frequency as a decrement-by-one),
545 * so mode 0 is much better when looking at the
546 * individual counts.
547 */
548 outb(0xb0, 0x43);
549
550 /* Start at 0xffff */
551 outb(0xff, 0x42);
552 outb(0xff, 0x42);
553
Linus Torvaldsa6a80e12009-03-17 07:58:26 -0700554 /*
555 * The PIT starts counting at the next edge, so we
556 * need to delay for a microsecond. The easiest way
557 * to do that is to just read back the 16-bit counter
558 * once from the PIT.
559 */
Linus Torvaldsb6e61ee2009-07-31 12:45:41 -0700560 pit_verify_msb(0);
Linus Torvaldsa6a80e12009-03-17 07:58:26 -0700561
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700562 if (pit_expect_msb(0xff, &tsc, &d1)) {
563 for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
564 if (!pit_expect_msb(0xff-i, &delta, &d2))
565 break;
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700566
Adrian Hunter5aac6442015-06-03 10:39:46 +0300567 delta -= tsc;
568
569 /*
570 * Extrapolate the error and fail fast if the error will
571 * never be below 500 ppm.
572 */
573 if (i == 1 &&
574 d1 + d2 >= (delta * MAX_QUICK_PIT_ITERATIONS) >> 11)
575 return 0;
576
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700577 /*
578 * Iterate until the error is less than 500 ppm
579 */
Linus Torvaldsb6e61ee2009-07-31 12:45:41 -0700580 if (d1+d2 >= delta >> 11)
581 continue;
582
583 /*
584 * Check the PIT one more time to verify that
585 * all TSC reads were stable wrt the PIT.
586 *
587 * This also guarantees serialization of the
588 * last cycle read ('d2') in pit_expect_msb.
589 */
590 if (!pit_verify_msb(0xfe - i))
591 break;
592 goto success;
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700593 }
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700594 }
Alexandre Demers52045212014-12-09 01:27:50 -0500595 pr_info("Fast TSC calibration failed\n");
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700596 return 0;
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700597
598success:
599 /*
600 * Ok, if we get here, then we've seen the
601 * MSB of the PIT decrement 'i' times, and the
602 * error has shrunk to less than 500 ppm.
603 *
604 * As a result, we can depend on there not being
605 * any odd delays anywhere, and the TSC reads are
Linus Torvalds68f30fb2012-01-17 15:35:37 -0800606 * reliable (within the error).
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700607 *
608 * kHz = ticks / time-in-seconds / 1000;
609 * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
610 * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
611 */
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700612 delta *= PIT_TICK_RATE;
613 do_div(delta, i*256*1000);
Joe Perchesc767a542012-05-21 19:50:07 -0700614 pr_info("Fast TSC calibration using PIT\n");
Linus Torvalds9e8912e2009-03-17 08:13:17 -0700615 return delta;
Linus Torvalds6ac40ed2008-09-04 10:41:22 -0700616}
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700617
Alok Katariabfc0f592008-07-01 11:43:24 -0700618/**
Len Brownaa297292016-06-17 01:22:51 -0400619 * native_calibrate_tsc
620 * Determine TSC frequency via CPUID, else return 0.
Alok Katariabfc0f592008-07-01 11:43:24 -0700621 */
Alok Katariae93ef942008-07-01 11:43:36 -0700622unsigned long native_calibrate_tsc(void)
Alok Katariabfc0f592008-07-01 11:43:24 -0700623{
Len Brownaa297292016-06-17 01:22:51 -0400624 unsigned int eax_denominator, ebx_numerator, ecx_hz, edx;
625 unsigned int crystal_khz;
626
627 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
628 return 0;
629
630 if (boot_cpu_data.cpuid_level < 0x15)
631 return 0;
632
633 eax_denominator = ebx_numerator = ecx_hz = edx = 0;
634
635 /* CPUID 15H TSC/Crystal ratio, plus optionally Crystal Hz */
636 cpuid(0x15, &eax_denominator, &ebx_numerator, &ecx_hz, &edx);
637
638 if (ebx_numerator == 0 || eax_denominator == 0)
639 return 0;
640
641 crystal_khz = ecx_hz / 1000;
642
Daniel Drake604dc912019-05-09 13:54:15 +0800643 /*
644 * Denverton SoCs don't report crystal clock, and also don't support
645 * CPUID.0x16 for the calculation below, so hardcode the 25MHz crystal
646 * clock.
647 */
648 if (crystal_khz == 0 &&
Peter Zijlstra5ebb34e2019-08-27 21:48:24 +0200649 boot_cpu_data.x86_model == INTEL_FAM6_ATOM_GOLDMONT_D)
Daniel Drake604dc912019-05-09 13:54:15 +0800650 crystal_khz = 25000;
651
652 /*
653 * TSC frequency reported directly by CPUID is a "hardware reported"
654 * frequency and is the most accurate one so far we have. This
655 * is considered a known frequency.
656 */
657 if (crystal_khz != 0)
658 setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ);
659
660 /*
661 * Some Intel SoCs like Skylake and Kabylake don't report the crystal
662 * clock, but we can easily calculate it to a high degree of accuracy
663 * by considering the crystal ratio and the CPU speed.
664 */
665 if (crystal_khz == 0 && boot_cpu_data.cpuid_level >= 0x16) {
666 unsigned int eax_base_mhz, ebx, ecx, edx;
667
668 cpuid(0x16, &eax_base_mhz, &ebx, &ecx, &edx);
669 crystal_khz = eax_base_mhz * 1000 *
670 eax_denominator / ebx_numerator;
Len Brownaa297292016-06-17 01:22:51 -0400671 }
672
Len Brownda4ae6c2017-12-22 00:27:54 -0500673 if (crystal_khz == 0)
674 return 0;
Bin Gao4ca4df02016-11-15 12:27:22 -0800675
Bin Gao4635fdc2016-11-15 12:27:23 -0800676 /*
677 * For Atom SoCs TSC is the only reliable clocksource.
678 * Mark TSC reliable so no watchdog on it.
679 */
680 if (boot_cpu_data.x86_model == INTEL_FAM6_ATOM_GOLDMONT)
681 setup_force_cpu_cap(X86_FEATURE_TSC_RELIABLE);
682
Daniel Drake2420a0b2019-05-09 13:54:17 +0800683#ifdef CONFIG_X86_LOCAL_APIC
684 /*
685 * The local APIC appears to be fed by the core crystal clock
686 * (which sounds entirely sensible). We can set the global
687 * lapic_timer_period here to avoid having to calibrate the APIC
688 * timer later.
689 */
690 lapic_timer_period = crystal_khz * 1000 / HZ;
691#endif
692
Len Brownaa297292016-06-17 01:22:51 -0400693 return crystal_khz * ebx_numerator / eax_denominator;
694}
695
696static unsigned long cpu_khz_from_cpuid(void)
697{
698 unsigned int eax_base_mhz, ebx_max_mhz, ecx_bus_mhz, edx;
699
700 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
701 return 0;
702
703 if (boot_cpu_data.cpuid_level < 0x16)
704 return 0;
705
706 eax_base_mhz = ebx_max_mhz = ecx_bus_mhz = edx = 0;
707
708 cpuid(0x16, &eax_base_mhz, &ebx_max_mhz, &ecx_bus_mhz, &edx);
709
710 return eax_base_mhz * 1000;
711}
712
Pavel Tatashin03821f42018-07-19 16:55:44 -0400713/*
714 * calibrate cpu using pit, hpet, and ptimer methods. They are available
715 * later in boot after acpi is initialized.
Len Brownaa297292016-06-17 01:22:51 -0400716 */
Pavel Tatashin03821f42018-07-19 16:55:44 -0400717static unsigned long pit_hpet_ptimer_calibrate_cpu(void)
Len Brownaa297292016-06-17 01:22:51 -0400718{
Thomas Gleixner827014b2008-09-04 15:18:53 +0000719 u64 tsc1, tsc2, delta, ref1, ref2;
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200720 unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
Pavel Tatashin03821f42018-07-19 16:55:44 -0400721 unsigned long flags, latch, ms;
Thomas Gleixnera977c402008-09-04 15:18:59 +0000722 int hpet = is_hpet_enabled(), i, loopmin;
Alok Katariabfc0f592008-07-01 11:43:24 -0700723
Alok Katariabfc0f592008-07-01 11:43:24 -0700724 /*
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200725 * Run 5 calibration loops to get the lowest frequency value
726 * (the best estimate). We use two different calibration modes
727 * here:
728 *
729 * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
730 * load a timeout of 50ms. We read the time right after we
731 * started the timer and wait until the PIT count down reaches
732 * zero. In each wait loop iteration we read the TSC and check
733 * the delta to the previous read. We keep track of the min
734 * and max values of that delta. The delta is mostly defined
Daniel Vaceka786ef12018-11-05 18:10:40 +0100735 * by the IO time of the PIT access, so we can detect when
736 * any disturbance happened between the two reads. If the
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200737 * maximum time is significantly larger than the minimum time,
738 * then we discard the result and have another try.
739 *
740 * 2) Reference counter. If available we use the HPET or the
741 * PMTIMER as a reference to check the sanity of that value.
742 * We use separate TSC readouts and check inside of the
Ingo Molnard9f6e122021-03-18 15:28:01 +0100743 * reference read for any possible disturbance. We discard
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200744 * disturbed values here as well. We do that around the PIT
745 * calibration delay loop as we have to wait for a certain
746 * amount of time anyway.
Alok Katariabfc0f592008-07-01 11:43:24 -0700747 */
Alok Katariabfc0f592008-07-01 11:43:24 -0700748
Thomas Gleixnera977c402008-09-04 15:18:59 +0000749 /* Preset PIT loop values */
750 latch = CAL_LATCH;
751 ms = CAL_MS;
752 loopmin = CAL_PIT_LOOPS;
753
754 for (i = 0; i < 3; i++) {
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700755 unsigned long tsc_pit_khz;
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200756
757 /*
758 * Read the start value and the reference count of
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700759 * hpet/pmtimer when available. Then do the PIT
760 * calibration, which will take at least 50ms, and
761 * read the end value.
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200762 */
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700763 local_irq_save(flags);
Thomas Gleixner827014b2008-09-04 15:18:53 +0000764 tsc1 = tsc_read_refs(&ref1, hpet);
Thomas Gleixnera977c402008-09-04 15:18:59 +0000765 tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
Thomas Gleixner827014b2008-09-04 15:18:53 +0000766 tsc2 = tsc_read_refs(&ref2, hpet);
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200767 local_irq_restore(flags);
768
Linus Torvaldsec0c15a2008-09-03 07:30:13 -0700769 /* Pick the lowest PIT TSC calibration so far */
770 tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200771
772 /* hpet or pmtimer available ? */
John Stultz62627be2011-01-14 09:06:28 -0800773 if (ref1 == ref2)
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200774 continue;
775
Daniel Vaceka786ef12018-11-05 18:10:40 +0100776 /* Check, whether the sampling was disturbed */
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200777 if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
778 continue;
779
780 tsc2 = (tsc2 - tsc1) * 1000000LL;
Thomas Gleixnerd683ef72008-09-04 15:18:48 +0000781 if (hpet)
Thomas Gleixner827014b2008-09-04 15:18:53 +0000782 tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
Thomas Gleixnerd683ef72008-09-04 15:18:48 +0000783 else
Thomas Gleixner827014b2008-09-04 15:18:53 +0000784 tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200785
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200786 tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
Thomas Gleixnera977c402008-09-04 15:18:59 +0000787
788 /* Check the reference deviation */
789 delta = ((u64) tsc_pit_min) * 100;
790 do_div(delta, tsc_ref_min);
791
792 /*
793 * If both calibration results are inside a 10% window
794 * then we can be sure, that the calibration
795 * succeeded. We break out of the loop right away. We
796 * use the reference value, as it is more precise.
797 */
798 if (delta >= 90 && delta <= 110) {
Joe Perchesc767a542012-05-21 19:50:07 -0700799 pr_info("PIT calibration matches %s. %d loops\n",
800 hpet ? "HPET" : "PMTIMER", i + 1);
Thomas Gleixnera977c402008-09-04 15:18:59 +0000801 return tsc_ref_min;
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200802 }
803
Thomas Gleixnera977c402008-09-04 15:18:59 +0000804 /*
805 * Check whether PIT failed more than once. This
806 * happens in virtualized environments. We need to
807 * give the virtual PC a slightly longer timeframe for
808 * the HPET/PMTIMER to make the result precise.
809 */
810 if (i == 1 && tsc_pit_min == ULONG_MAX) {
811 latch = CAL2_LATCH;
812 ms = CAL2_MS;
813 loopmin = CAL2_PIT_LOOPS;
814 }
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200815 }
816
817 /*
818 * Now check the results.
819 */
820 if (tsc_pit_min == ULONG_MAX) {
821 /* PIT gave no useful value */
Joe Perchesc767a542012-05-21 19:50:07 -0700822 pr_warn("Unable to calibrate against PIT\n");
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200823
824 /* We don't have an alternative source, disable TSC */
Thomas Gleixner827014b2008-09-04 15:18:53 +0000825 if (!hpet && !ref1 && !ref2) {
Joe Perchesc767a542012-05-21 19:50:07 -0700826 pr_notice("No reference (HPET/PMTIMER) available\n");
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200827 return 0;
828 }
829
830 /* The alternative source failed as well, disable TSC */
831 if (tsc_ref_min == ULONG_MAX) {
Joe Perchesc767a542012-05-21 19:50:07 -0700832 pr_warn("HPET/PMTIMER calibration failed\n");
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200833 return 0;
834 }
835
836 /* Use the alternative source */
Joe Perchesc767a542012-05-21 19:50:07 -0700837 pr_info("using %s reference calibration\n",
838 hpet ? "HPET" : "PMTIMER");
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200839
840 return tsc_ref_min;
841 }
842
843 /* We don't have an alternative source, use the PIT calibration value */
Thomas Gleixner827014b2008-09-04 15:18:53 +0000844 if (!hpet && !ref1 && !ref2) {
Joe Perchesc767a542012-05-21 19:50:07 -0700845 pr_info("Using PIT calibration value\n");
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200846 return tsc_pit_min;
Alok Katariabfc0f592008-07-01 11:43:24 -0700847 }
848
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200849 /* The alternative source failed, use the PIT calibration value */
850 if (tsc_ref_min == ULONG_MAX) {
Joe Perchesc767a542012-05-21 19:50:07 -0700851 pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200852 return tsc_pit_min;
Alok Katariabfc0f592008-07-01 11:43:24 -0700853 }
854
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200855 /*
856 * The calibration values differ too much. In doubt, we use
857 * the PIT value as we know that there are PMTIMERs around
Thomas Gleixnera977c402008-09-04 15:18:59 +0000858 * running at double speed. At least we let the user know:
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200859 */
Joe Perchesc767a542012-05-21 19:50:07 -0700860 pr_warn("PIT calibration deviates from %s: %lu %lu\n",
861 hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
862 pr_info("Using PIT calibration value\n");
Thomas Gleixnerfbb16e22008-09-03 00:54:47 +0200863 return tsc_pit_min;
Alok Katariabfc0f592008-07-01 11:43:24 -0700864}
865
Pavel Tatashin03821f42018-07-19 16:55:44 -0400866/**
867 * native_calibrate_cpu_early - can calibrate the cpu early in boot
868 */
869unsigned long native_calibrate_cpu_early(void)
870{
871 unsigned long flags, fast_calibrate = cpu_khz_from_cpuid();
872
873 if (!fast_calibrate)
874 fast_calibrate = cpu_khz_from_msr();
875 if (!fast_calibrate) {
876 local_irq_save(flags);
877 fast_calibrate = quick_pit_calibrate();
878 local_irq_restore(flags);
879 }
880 return fast_calibrate;
881}
882
883
884/**
885 * native_calibrate_cpu - calibrate the cpu
886 */
Pavel Tatashin8dbe4382018-07-19 16:55:45 -0400887static unsigned long native_calibrate_cpu(void)
Pavel Tatashin03821f42018-07-19 16:55:44 -0400888{
889 unsigned long tsc_freq = native_calibrate_cpu_early();
890
891 if (!tsc_freq)
892 tsc_freq = pit_hpet_ptimer_calibrate_cpu();
893
894 return tsc_freq;
895}
896
Dou Liyangaf576852017-07-14 11:34:07 +0800897void recalibrate_cpu_khz(void)
Alok Katariabfc0f592008-07-01 11:43:24 -0700898{
899#ifndef CONFIG_SMP
900 unsigned long cpu_khz_old = cpu_khz;
901
Borislav Petkoveff46772016-04-05 08:29:53 +0200902 if (!boot_cpu_has(X86_FEATURE_TSC))
Dou Liyangaf576852017-07-14 11:34:07 +0800903 return;
Borislav Petkoveff46772016-04-05 08:29:53 +0200904
Len Brownaa297292016-06-17 01:22:51 -0400905 cpu_khz = x86_platform.calibrate_cpu();
Borislav Petkoveff46772016-04-05 08:29:53 +0200906 tsc_khz = x86_platform.calibrate_tsc();
Len Brownaa297292016-06-17 01:22:51 -0400907 if (tsc_khz == 0)
908 tsc_khz = cpu_khz;
Len Brownff4c8662016-06-17 01:22:52 -0400909 else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
910 cpu_khz = tsc_khz;
Borislav Petkoveff46772016-04-05 08:29:53 +0200911 cpu_data(0).loops_per_jiffy = cpufreq_scale(cpu_data(0).loops_per_jiffy,
912 cpu_khz_old, cpu_khz);
Alok Katariabfc0f592008-07-01 11:43:24 -0700913#endif
914}
915
916EXPORT_SYMBOL(recalibrate_cpu_khz);
917
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700918
Suresh Siddhacd7240c2010-08-19 17:03:38 -0700919static unsigned long long cyc2ns_suspend;
920
Marcelo Tosattib74f05d62012-02-13 11:07:27 -0200921void tsc_save_sched_clock_state(void)
Suresh Siddhacd7240c2010-08-19 17:03:38 -0700922{
Peter Zijlstra35af99e2013-11-28 19:38:42 +0100923 if (!sched_clock_stable())
Suresh Siddhacd7240c2010-08-19 17:03:38 -0700924 return;
925
926 cyc2ns_suspend = sched_clock();
927}
928
929/*
930 * Even on processors with invariant TSC, TSC gets reset in some the
931 * ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
932 * arbitrary value (still sync'd across cpu's) during resume from such sleep
933 * states. To cope up with this, recompute the cyc2ns_offset for each cpu so
934 * that sched_clock() continues from the point where it was left off during
935 * suspend.
936 */
Marcelo Tosattib74f05d62012-02-13 11:07:27 -0200937void tsc_restore_sched_clock_state(void)
Suresh Siddhacd7240c2010-08-19 17:03:38 -0700938{
939 unsigned long long offset;
940 unsigned long flags;
941 int cpu;
942
Peter Zijlstra35af99e2013-11-28 19:38:42 +0100943 if (!sched_clock_stable())
Suresh Siddhacd7240c2010-08-19 17:03:38 -0700944 return;
945
946 local_irq_save(flags);
947
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100948 /*
Adam Buchbinder6a6256f2016-02-23 15:34:30 -0800949 * We're coming out of suspend, there's no concurrency yet; don't
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100950 * bother being nice about the RCU stuff, just write to both
951 * data fields.
952 */
953
954 this_cpu_write(cyc2ns.data[0].cyc2ns_offset, 0);
955 this_cpu_write(cyc2ns.data[1].cyc2ns_offset, 0);
956
Suresh Siddhacd7240c2010-08-19 17:03:38 -0700957 offset = cyc2ns_suspend - sched_clock();
958
Peter Zijlstra20d1c862013-11-29 15:40:29 +0100959 for_each_possible_cpu(cpu) {
960 per_cpu(cyc2ns.data[0].cyc2ns_offset, cpu) = offset;
961 per_cpu(cyc2ns.data[1].cyc2ns_offset, cpu) = offset;
962 }
Suresh Siddhacd7240c2010-08-19 17:03:38 -0700963
964 local_irq_restore(flags);
965}
966
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700967#ifdef CONFIG_CPU_FREQ
Rafael J. Wysockic208ac82019-04-18 16:11:37 +0200968/*
969 * Frequency scaling support. Adjust the TSC based timer when the CPU frequency
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700970 * changes.
971 *
Rafael J. Wysockic208ac82019-04-18 16:11:37 +0200972 * NOTE: On SMP the situation is not fixable in general, so simply mark the TSC
973 * as unstable and give up in those cases.
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700974 *
975 * Should fix up last_tsc too. Currently gettimeofday in the
976 * first tick after the change will be slightly wrong.
977 */
978
979static unsigned int ref_freq;
980static unsigned long loops_per_jiffy_ref;
981static unsigned long tsc_khz_ref;
982
983static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
984 void *data)
985{
986 struct cpufreq_freqs *freq = data;
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700987
Rafael J. Wysockic208ac82019-04-18 16:11:37 +0200988 if (num_online_cpus() > 1) {
989 mark_tsc_unstable("cpufreq changes on SMP");
990 return 0;
991 }
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700992
993 if (!ref_freq) {
994 ref_freq = freq->old;
Rafael J. Wysockic208ac82019-04-18 16:11:37 +0200995 loops_per_jiffy_ref = boot_cpu_data.loops_per_jiffy;
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700996 tsc_khz_ref = tsc_khz;
997 }
Rafael J. Wysockic208ac82019-04-18 16:11:37 +0200998
Alok Kataria2dbe06f2008-07-01 11:43:31 -0700999 if ((val == CPUFREQ_PRECHANGE && freq->old < freq->new) ||
Rafael J. Wysockic208ac82019-04-18 16:11:37 +02001000 (val == CPUFREQ_POSTCHANGE && freq->old > freq->new)) {
1001 boot_cpu_data.loops_per_jiffy =
1002 cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
Alok Kataria2dbe06f2008-07-01 11:43:31 -07001003
1004 tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
1005 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
1006 mark_tsc_unstable("cpufreq changes");
Alok Kataria2dbe06f2008-07-01 11:43:31 -07001007
Viresh Kumardf240142019-04-29 15:03:58 +05301008 set_cyc2ns_scale(tsc_khz, freq->policy->cpu, rdtsc());
Peter Zijlstra3896c322014-06-24 14:48:19 +02001009 }
Alok Kataria2dbe06f2008-07-01 11:43:31 -07001010
1011 return 0;
1012}
1013
1014static struct notifier_block time_cpufreq_notifier_block = {
1015 .notifier_call = time_cpufreq_notifier
1016};
1017
Borislav Petkova841cca2016-04-05 08:29:52 +02001018static int __init cpufreq_register_tsc_scaling(void)
Alok Kataria2dbe06f2008-07-01 11:43:31 -07001019{
Borislav Petkov59e21e32016-04-04 22:24:59 +02001020 if (!boot_cpu_has(X86_FEATURE_TSC))
Linus Torvalds060700b2008-08-24 11:52:06 -07001021 return 0;
1022 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1023 return 0;
Alok Kataria2dbe06f2008-07-01 11:43:31 -07001024 cpufreq_register_notifier(&time_cpufreq_notifier_block,
1025 CPUFREQ_TRANSITION_NOTIFIER);
1026 return 0;
1027}
1028
Borislav Petkova841cca2016-04-05 08:29:52 +02001029core_initcall(cpufreq_register_tsc_scaling);
Alok Kataria2dbe06f2008-07-01 11:43:31 -07001030
1031#endif /* CONFIG_CPU_FREQ */
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001032
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001033#define ART_CPUID_LEAF (0x15)
1034#define ART_MIN_DENOMINATOR (1)
1035
1036
1037/*
1038 * If ART is present detect the numerator:denominator to convert to TSC
1039 */
Dou Liyang120fc3f2017-11-08 18:09:52 +08001040static void __init detect_art(void)
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001041{
1042 unsigned int unused[2];
1043
1044 if (boot_cpu_data.cpuid_level < ART_CPUID_LEAF)
1045 return;
1046
mike.travis@hpe.com6c663502017-10-12 11:32:05 -05001047 /*
1048 * Don't enable ART in a VM, non-stop TSC and TSC_ADJUST required,
1049 * and the TSC counter resets must not occur asynchronously.
1050 */
Thomas Gleixner7b3d2f62016-11-19 13:47:33 +00001051 if (boot_cpu_has(X86_FEATURE_HYPERVISOR) ||
1052 !boot_cpu_has(X86_FEATURE_NONSTOP_TSC) ||
mike.travis@hpe.com6c663502017-10-12 11:32:05 -05001053 !boot_cpu_has(X86_FEATURE_TSC_ADJUST) ||
1054 tsc_async_resets)
Thomas Gleixner7b3d2f62016-11-19 13:47:33 +00001055 return;
1056
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001057 cpuid(ART_CPUID_LEAF, &art_to_tsc_denominator,
1058 &art_to_tsc_numerator, unused, unused+1);
1059
Thomas Gleixner7b3d2f62016-11-19 13:47:33 +00001060 if (art_to_tsc_denominator < ART_MIN_DENOMINATOR)
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001061 return;
1062
Thomas Gleixner7b3d2f62016-11-19 13:47:33 +00001063 rdmsrl(MSR_IA32_TSC_ADJUST, art_to_tsc_offset);
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001064
1065 /* Make this sticky over multiple CPU init calls */
1066 setup_force_cpu_cap(X86_FEATURE_ART);
1067}
1068
1069
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001070/* clocksource code */
1071
Thomas Gleixner6a369582016-12-13 13:14:17 +00001072static void tsc_resume(struct clocksource *cs)
1073{
1074 tsc_verify_tsc_adjust(true);
1075}
1076
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001077/*
Thomas Gleixner09ec5442014-07-16 21:05:12 +00001078 * We used to compare the TSC to the cycle_last value in the clocksource
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001079 * structure to avoid a nasty time-warp. This can be observed in a
1080 * very small window right after one CPU updated cycle_last under
1081 * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
1082 * is smaller than the cycle_last reference value due to a TSC which
Ingo Molnard9f6e122021-03-18 15:28:01 +01001083 * is slightly behind. This delta is nowhere else observable, but in
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001084 * that case it results in a forward time jump in the range of hours
1085 * due to the unsigned delta calculation of the time keeping core
1086 * code, which is necessary to support wrapping clocksources like pm
1087 * timer.
Thomas Gleixner09ec5442014-07-16 21:05:12 +00001088 *
1089 * This sanity check is now done in the core timekeeping code.
1090 * checking the result of read_tsc() - cycle_last for being negative.
1091 * That works because CLOCKSOURCE_MASK(64) does not mask out any bit.
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001092 */
Thomas Gleixnera5a1d1c2016-12-21 20:32:01 +01001093static u64 read_tsc(struct clocksource *cs)
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001094{
Thomas Gleixnera5a1d1c2016-12-21 20:32:01 +01001095 return (u64)rdtsc_ordered();
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001096}
1097
Thomas Gleixner12907fb2016-12-15 11:44:28 +01001098static void tsc_cs_mark_unstable(struct clocksource *cs)
1099{
1100 if (tsc_unstable)
1101 return;
Peter Zijlstraf94c8d12017-03-01 15:53:38 +01001102
Thomas Gleixner12907fb2016-12-15 11:44:28 +01001103 tsc_unstable = 1;
Peter Zijlstraf94c8d12017-03-01 15:53:38 +01001104 if (using_native_sched_clock())
1105 clear_sched_clock_stable();
Thomas Gleixner12907fb2016-12-15 11:44:28 +01001106 disable_sched_clock_irqtime();
1107 pr_info("Marking TSC unstable due to clocksource watchdog\n");
1108}
1109
Peter Zijlstrab421b222017-04-21 12:14:13 +02001110static void tsc_cs_tick_stable(struct clocksource *cs)
1111{
1112 if (tsc_unstable)
1113 return;
1114
1115 if (using_native_sched_clock())
1116 sched_clock_tick_stable();
1117}
1118
Thomas Gleixnereec399d2020-02-07 13:38:54 +01001119static int tsc_cs_enable(struct clocksource *cs)
1120{
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01001121 vclocks_set_used(VDSO_CLOCKMODE_TSC);
Thomas Gleixnereec399d2020-02-07 13:38:54 +01001122 return 0;
1123}
1124
Thomas Gleixner09ec5442014-07-16 21:05:12 +00001125/*
1126 * .mask MUST be CLOCKSOURCE_MASK(64). See comment above read_tsc()
1127 */
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001128static struct clocksource clocksource_tsc_early = {
Thomas Gleixnereec399d2020-02-07 13:38:54 +01001129 .name = "tsc-early",
1130 .rating = 299,
Paul E. McKenney2e27e792021-05-27 12:01:22 -07001131 .uncertainty_margin = 32 * NSEC_PER_MSEC,
Thomas Gleixnereec399d2020-02-07 13:38:54 +01001132 .read = read_tsc,
1133 .mask = CLOCKSOURCE_MASK(64),
1134 .flags = CLOCK_SOURCE_IS_CONTINUOUS |
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001135 CLOCK_SOURCE_MUST_VERIFY,
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01001136 .vdso_clock_mode = VDSO_CLOCKMODE_TSC,
Thomas Gleixnereec399d2020-02-07 13:38:54 +01001137 .enable = tsc_cs_enable,
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001138 .resume = tsc_resume,
1139 .mark_unstable = tsc_cs_mark_unstable,
1140 .tick_stable = tsc_cs_tick_stable,
Peter Zijlstrae3b4f790252018-04-30 12:00:12 +02001141 .list = LIST_HEAD_INIT(clocksource_tsc_early.list),
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001142};
1143
1144/*
1145 * Must mark VALID_FOR_HRES early such that when we unregister tsc_early
1146 * this one will immediately take over. We will only register if TSC has
1147 * been found good.
1148 */
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001149static struct clocksource clocksource_tsc = {
Thomas Gleixnereec399d2020-02-07 13:38:54 +01001150 .name = "tsc",
1151 .rating = 300,
1152 .read = read_tsc,
1153 .mask = CLOCKSOURCE_MASK(64),
1154 .flags = CLOCK_SOURCE_IS_CONTINUOUS |
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001155 CLOCK_SOURCE_VALID_FOR_HRES |
Paul E. McKenney7560c022021-05-27 12:01:20 -07001156 CLOCK_SOURCE_MUST_VERIFY |
1157 CLOCK_SOURCE_VERIFY_PERCPU,
Thomas Gleixnerb95a8a22020-02-07 13:38:56 +01001158 .vdso_clock_mode = VDSO_CLOCKMODE_TSC,
Thomas Gleixnereec399d2020-02-07 13:38:54 +01001159 .enable = tsc_cs_enable,
Thomas Gleixner6a369582016-12-13 13:14:17 +00001160 .resume = tsc_resume,
Thomas Gleixner12907fb2016-12-15 11:44:28 +01001161 .mark_unstable = tsc_cs_mark_unstable,
Peter Zijlstrab421b222017-04-21 12:14:13 +02001162 .tick_stable = tsc_cs_tick_stable,
Peter Zijlstrae3b4f790252018-04-30 12:00:12 +02001163 .list = LIST_HEAD_INIT(clocksource_tsc.list),
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001164};
1165
1166void mark_tsc_unstable(char *reason)
1167{
Peter Zijlstraf94c8d12017-03-01 15:53:38 +01001168 if (tsc_unstable)
1169 return;
1170
1171 tsc_unstable = 1;
1172 if (using_native_sched_clock())
Peter Zijlstra35af99e2013-11-28 19:38:42 +01001173 clear_sched_clock_stable();
Peter Zijlstraf94c8d12017-03-01 15:53:38 +01001174 disable_sched_clock_irqtime();
1175 pr_info("Marking TSC unstable due to %s\n", reason);
Peter Zijlstrae3b4f790252018-04-30 12:00:12 +02001176
1177 clocksource_mark_unstable(&clocksource_tsc_early);
1178 clocksource_mark_unstable(&clocksource_tsc);
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001179}
1180
1181EXPORT_SYMBOL_GPL(mark_tsc_unstable);
1182
Alok Kataria395628e2008-10-24 17:22:01 -07001183static void __init check_system_tsc_reliable(void)
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001184{
David Woodhouse03da3ff2015-09-16 14:10:03 +01001185#if defined(CONFIG_MGEODEGX1) || defined(CONFIG_MGEODE_LX) || defined(CONFIG_X86_GENERIC)
1186 if (is_geode_lx()) {
1187 /* RTSC counts during suspend */
Alok Kataria395628e2008-10-24 17:22:01 -07001188#define RTSC_SUSP 0x100
David Woodhouse03da3ff2015-09-16 14:10:03 +01001189 unsigned long res_low, res_high;
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001190
David Woodhouse03da3ff2015-09-16 14:10:03 +01001191 rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
1192 /* Geode_LX - the OLPC CPU has a very reliable TSC */
1193 if (res_low & RTSC_SUSP)
1194 tsc_clocksource_reliable = 1;
1195 }
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001196#endif
Alok Kataria395628e2008-10-24 17:22:01 -07001197 if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
1198 tsc_clocksource_reliable = 1;
1199}
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001200
1201/*
1202 * Make an educated guess if the TSC is trustworthy and synchronized
1203 * over all CPUs.
1204 */
Paul Gortmaker148f9bb2013-06-18 18:23:59 -04001205int unsynchronized_tsc(void)
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001206{
Borislav Petkov59e21e32016-04-04 22:24:59 +02001207 if (!boot_cpu_has(X86_FEATURE_TSC) || tsc_unstable)
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001208 return 1;
1209
Ingo Molnar3e5095d2009-01-27 17:07:08 +01001210#ifdef CONFIG_SMP
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001211 if (apic_is_clustered_box())
1212 return 1;
1213#endif
1214
1215 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1216 return 0;
john stultzd3b8f882009-08-17 16:40:47 -07001217
1218 if (tsc_clocksource_reliable)
1219 return 0;
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001220 /*
1221 * Intel systems are normally all synchronized.
1222 * Exceptions must mark TSC as unstable:
1223 */
1224 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
1225 /* assume multi socket systems are not synchronized: */
1226 if (num_possible_cpus() > 1)
john stultzd3b8f882009-08-17 16:40:47 -07001227 return 1;
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001228 }
1229
john stultzd3b8f882009-08-17 16:40:47 -07001230 return 0;
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001231}
1232
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001233/*
1234 * Convert ART to TSC given numerator/denominator found in detect_art()
1235 */
Thomas Gleixnera5a1d1c2016-12-21 20:32:01 +01001236struct system_counterval_t convert_art_to_tsc(u64 art)
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001237{
1238 u64 tmp, res, rem;
1239
1240 rem = do_div(art, art_to_tsc_denominator);
1241
1242 res = art * art_to_tsc_numerator;
1243 tmp = rem * art_to_tsc_numerator;
1244
1245 do_div(tmp, art_to_tsc_denominator);
1246 res += tmp + art_to_tsc_offset;
1247
1248 return (struct system_counterval_t) {.cs = art_related_clocksource,
1249 .cycles = res};
1250}
1251EXPORT_SYMBOL(convert_art_to_tsc);
John Stultz08ec0c52010-07-27 17:00:00 -07001252
Rajvi Jingarfc804f62018-03-08 09:28:36 -08001253/**
1254 * convert_art_ns_to_tsc() - Convert ART in nanoseconds to TSC.
1255 * @art_ns: ART (Always Running Timer) in unit of nanoseconds
1256 *
1257 * PTM requires all timestamps to be in units of nanoseconds. When user
1258 * software requests a cross-timestamp, this function converts system timestamp
1259 * to TSC.
1260 *
1261 * This is valid when CPU feature flag X86_FEATURE_TSC_KNOWN_FREQ is set
1262 * indicating the tsc_khz is derived from CPUID[15H]. Drivers should check
1263 * that this flag is set before conversion to TSC is attempted.
1264 *
1265 * Return:
1266 * struct system_counterval_t - system counter value with the pointer to the
1267 * corresponding clocksource
1268 * @cycles: System counter value
1269 * @cs: Clocksource corresponding to system counter value. Used
Ingo Molnard9f6e122021-03-18 15:28:01 +01001270 * by timekeeping code to verify comparability of two cycle
Rajvi Jingarfc804f62018-03-08 09:28:36 -08001271 * values.
1272 */
1273
1274struct system_counterval_t convert_art_ns_to_tsc(u64 art_ns)
1275{
1276 u64 tmp, res, rem;
1277
1278 rem = do_div(art_ns, USEC_PER_SEC);
1279
1280 res = art_ns * tsc_khz;
1281 tmp = rem * tsc_khz;
1282
1283 do_div(tmp, USEC_PER_SEC);
1284 res += tmp;
1285
1286 return (struct system_counterval_t) { .cs = art_related_clocksource,
1287 .cycles = res};
1288}
1289EXPORT_SYMBOL(convert_art_ns_to_tsc);
1290
1291
John Stultz08ec0c52010-07-27 17:00:00 -07001292static void tsc_refine_calibration_work(struct work_struct *work);
1293static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
1294/**
1295 * tsc_refine_calibration_work - Further refine tsc freq calibration
1296 * @work - ignored.
1297 *
1298 * This functions uses delayed work over a period of a
1299 * second to further refine the TSC freq value. Since this is
1300 * timer based, instead of loop based, we don't block the boot
1301 * process while this longer calibration is done.
1302 *
Lucas De Marchi0d2eb442011-03-17 16:24:16 -03001303 * If there are any calibration anomalies (too many SMIs, etc),
John Stultz08ec0c52010-07-27 17:00:00 -07001304 * or the refined calibration is off by 1% of the fast early
1305 * calibration, we throw out the new calibration and use the
1306 * early calibration.
1307 */
1308static void tsc_refine_calibration_work(struct work_struct *work)
1309{
Daniel Vaceka786ef12018-11-05 18:10:40 +01001310 static u64 tsc_start = ULLONG_MAX, ref_start;
John Stultz08ec0c52010-07-27 17:00:00 -07001311 static int hpet;
1312 u64 tsc_stop, ref_stop, delta;
1313 unsigned long freq;
Peter Zijlstraaa7b6302017-04-21 11:32:46 +02001314 int cpu;
John Stultz08ec0c52010-07-27 17:00:00 -07001315
1316 /* Don't bother refining TSC on unstable systems */
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001317 if (tsc_unstable)
Peter Zijlstrae9088ad2018-04-30 12:00:09 +02001318 goto unreg;
John Stultz08ec0c52010-07-27 17:00:00 -07001319
1320 /*
1321 * Since the work is started early in boot, we may be
1322 * delayed the first time we expire. So set the workqueue
1323 * again once we know timers are working.
1324 */
Daniel Vaceka786ef12018-11-05 18:10:40 +01001325 if (tsc_start == ULLONG_MAX) {
1326restart:
John Stultz08ec0c52010-07-27 17:00:00 -07001327 /*
1328 * Only set hpet once, to avoid mixing hardware
1329 * if the hpet becomes enabled later.
1330 */
1331 hpet = is_hpet_enabled();
John Stultz08ec0c52010-07-27 17:00:00 -07001332 tsc_start = tsc_read_refs(&ref_start, hpet);
Daniel Vaceka786ef12018-11-05 18:10:40 +01001333 schedule_delayed_work(&tsc_irqwork, HZ);
John Stultz08ec0c52010-07-27 17:00:00 -07001334 return;
1335 }
1336
1337 tsc_stop = tsc_read_refs(&ref_stop, hpet);
1338
1339 /* hpet or pmtimer available ? */
John Stultz62627be2011-01-14 09:06:28 -08001340 if (ref_start == ref_stop)
John Stultz08ec0c52010-07-27 17:00:00 -07001341 goto out;
1342
Daniel Vaceka786ef12018-11-05 18:10:40 +01001343 /* Check, whether the sampling was disturbed */
1344 if (tsc_stop == ULLONG_MAX)
1345 goto restart;
John Stultz08ec0c52010-07-27 17:00:00 -07001346
1347 delta = tsc_stop - tsc_start;
1348 delta *= 1000000LL;
1349 if (hpet)
1350 freq = calc_hpet_ref(delta, ref_start, ref_stop);
1351 else
1352 freq = calc_pmtimer_ref(delta, ref_start, ref_stop);
1353
1354 /* Make sure we're within 1% */
1355 if (abs(tsc_khz - freq) > tsc_khz/100)
1356 goto out;
1357
1358 tsc_khz = freq;
Joe Perchesc767a542012-05-21 19:50:07 -07001359 pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
1360 (unsigned long)tsc_khz / 1000,
1361 (unsigned long)tsc_khz % 1000);
John Stultz08ec0c52010-07-27 17:00:00 -07001362
Nicolai Stange6731b0d2016-07-14 17:22:55 +02001363 /* Inform the TSC deadline clockevent devices about the recalibration */
1364 lapic_update_tsc_freq();
1365
Peter Zijlstraaa7b6302017-04-21 11:32:46 +02001366 /* Update the sched_clock() rate to match the clocksource one */
1367 for_each_possible_cpu(cpu)
Arnd Bergmann5c3c2ea2017-05-17 22:39:24 +02001368 set_cyc2ns_scale(tsc_khz, cpu, tsc_stop);
Peter Zijlstraaa7b6302017-04-21 11:32:46 +02001369
John Stultz08ec0c52010-07-27 17:00:00 -07001370out:
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001371 if (tsc_unstable)
Peter Zijlstrae9088ad2018-04-30 12:00:09 +02001372 goto unreg;
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001373
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001374 if (boot_cpu_has(X86_FEATURE_ART))
1375 art_related_clocksource = &clocksource_tsc;
John Stultz08ec0c52010-07-27 17:00:00 -07001376 clocksource_register_khz(&clocksource_tsc, tsc_khz);
Peter Zijlstrae9088ad2018-04-30 12:00:09 +02001377unreg:
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001378 clocksource_unregister(&clocksource_tsc_early);
John Stultz08ec0c52010-07-27 17:00:00 -07001379}
1380
1381
1382static int __init init_tsc_clocksource(void)
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001383{
Pavel Tatashinfe9af812018-07-19 16:55:30 -04001384 if (!boot_cpu_has(X86_FEATURE_TSC) || !tsc_khz)
Thomas Gleixnera8760ec2010-12-13 11:28:02 +01001385 return 0;
1386
Peter Zijlstrae9088ad2018-04-30 12:00:09 +02001387 if (tsc_unstable)
1388 goto unreg;
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001389
Juri Lelli0f0b7e1c2019-03-07 13:09:13 +01001390 if (tsc_clocksource_reliable || no_tsc_watchdog)
Alok Kataria395628e2008-10-24 17:22:01 -07001391 clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
Alok Kataria57779dc2012-02-21 18:19:55 -08001392
Feng Tang82f9c082013-03-12 11:56:47 +08001393 if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
1394 clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
1395
Alok Kataria57779dc2012-02-21 18:19:55 -08001396 /*
Bin Gao47c95a42016-11-15 12:27:21 -08001397 * When TSC frequency is known (retrieved via MSR or CPUID), we skip
1398 * the refined calibration and directly register it as a clocksource.
Alok Kataria57779dc2012-02-21 18:19:55 -08001399 */
Thomas Gleixner984fece2016-11-18 10:38:09 +01001400 if (boot_cpu_has(X86_FEATURE_TSC_KNOWN_FREQ)) {
Peter Zijlstra44fee882017-03-13 15:57:12 +01001401 if (boot_cpu_has(X86_FEATURE_ART))
1402 art_related_clocksource = &clocksource_tsc;
Alok Kataria57779dc2012-02-21 18:19:55 -08001403 clocksource_register_khz(&clocksource_tsc, tsc_khz);
Peter Zijlstrae9088ad2018-04-30 12:00:09 +02001404unreg:
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001405 clocksource_unregister(&clocksource_tsc_early);
Alok Kataria57779dc2012-02-21 18:19:55 -08001406 return 0;
1407 }
1408
John Stultz08ec0c52010-07-27 17:00:00 -07001409 schedule_delayed_work(&tsc_irqwork, 0);
1410 return 0;
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001411}
John Stultz08ec0c52010-07-27 17:00:00 -07001412/*
1413 * We use device_initcall here, to ensure we run after the hpet
1414 * is fully initialized, which may occur at fs_initcall time.
1415 */
1416device_initcall(init_tsc_clocksource);
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001417
Pavel Tatashin8dbe4382018-07-19 16:55:45 -04001418static bool __init determine_cpu_tsc_frequencies(bool early)
Dou Liyangeb496062017-07-14 11:34:06 +08001419{
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001420 /* Make sure that cpu and tsc are not already calibrated */
1421 WARN_ON(cpu_khz || tsc_khz);
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001422
Pavel Tatashin8dbe4382018-07-19 16:55:45 -04001423 if (early) {
1424 cpu_khz = x86_platform.calibrate_cpu();
Krzysztof Piecuchbd35c772020-01-23 16:09:26 +00001425 if (tsc_early_khz)
1426 tsc_khz = tsc_early_khz;
1427 else
1428 tsc_khz = x86_platform.calibrate_tsc();
Pavel Tatashin8dbe4382018-07-19 16:55:45 -04001429 } else {
1430 /* We should not be here with non-native cpu calibration */
1431 WARN_ON(x86_platform.calibrate_cpu != native_calibrate_cpu);
1432 cpu_khz = pit_hpet_ptimer_calibrate_cpu();
1433 }
Len Brownff4c8662016-06-17 01:22:52 -04001434
1435 /*
Dou Liyang608008a2018-07-30 15:54:20 +08001436 * Trust non-zero tsc_khz as authoritative,
Len Brownff4c8662016-06-17 01:22:52 -04001437 * and use it to sanity check cpu_khz,
1438 * which will be off if system timer is off.
1439 */
Len Brownaa297292016-06-17 01:22:51 -04001440 if (tsc_khz == 0)
1441 tsc_khz = cpu_khz;
Len Brownff4c8662016-06-17 01:22:52 -04001442 else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
1443 cpu_khz = tsc_khz;
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001444
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001445 if (tsc_khz == 0)
1446 return false;
1447
1448 pr_info("Detected %lu.%03lu MHz processor\n",
1449 (unsigned long)cpu_khz / KHZ,
1450 (unsigned long)cpu_khz % KHZ);
1451
1452 if (cpu_khz != tsc_khz) {
1453 pr_info("Detected %lu.%03lu MHz TSC",
1454 (unsigned long)tsc_khz / KHZ,
1455 (unsigned long)tsc_khz % KHZ);
1456 }
1457 return true;
1458}
1459
1460static unsigned long __init get_loops_per_jiffy(void)
1461{
Chuanhua Lei17f6bac2018-09-06 18:03:23 +08001462 u64 lpj = (u64)tsc_khz * KHZ;
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001463
1464 do_div(lpj, HZ);
1465 return lpj;
1466}
1467
Dou Liyang608008a2018-07-30 15:54:20 +08001468static void __init tsc_enable_sched_clock(void)
1469{
1470 /* Sanitize TSC ADJUST before cyc2ns gets initialized */
1471 tsc_store_and_check_tsc_adjust(true);
1472 cyc2ns_init_boot_cpu();
1473 static_branch_enable(&__use_tsc);
1474}
1475
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001476void __init tsc_early_init(void)
1477{
1478 if (!boot_cpu_has(X86_FEATURE_TSC))
1479 return;
Mike Travis2647c432018-10-02 13:01:46 -05001480 /* Don't change UV TSC multi-chassis synchronization */
1481 if (is_early_uv_system())
1482 return;
Pavel Tatashin8dbe4382018-07-19 16:55:45 -04001483 if (!determine_cpu_tsc_frequencies(true))
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001484 return;
1485 loops_per_jiffy = get_loops_per_jiffy();
Pavel Tatashine2a9ca22018-07-19 16:55:39 -04001486
Dou Liyang608008a2018-07-30 15:54:20 +08001487 tsc_enable_sched_clock();
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001488}
1489
1490void __init tsc_init(void)
1491{
Pavel Tatashin8dbe4382018-07-19 16:55:45 -04001492 /*
1493 * native_calibrate_cpu_early can only calibrate using methods that are
1494 * available early in boot.
1495 */
1496 if (x86_platform.calibrate_cpu == native_calibrate_cpu_early)
1497 x86_platform.calibrate_cpu = native_calibrate_cpu;
1498
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001499 if (!boot_cpu_has(X86_FEATURE_TSC)) {
Andy Lutomirskib47dcbd2014-10-15 10:12:07 -07001500 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001501 return;
1502 }
1503
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001504 if (!tsc_khz) {
1505 /* We failed to determine frequencies earlier, try again */
Pavel Tatashin8dbe4382018-07-19 16:55:45 -04001506 if (!determine_cpu_tsc_frequencies(false)) {
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001507 mark_tsc_unstable("could not calculate TSC khz");
1508 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
1509 return;
1510 }
Dou Liyang608008a2018-07-30 15:54:20 +08001511 tsc_enable_sched_clock();
Len Brown4b5b21272017-12-22 00:27:56 -05001512 }
1513
Pavel Tatashine2a9ca22018-07-19 16:55:39 -04001514 cyc2ns_init_secondary_cpus();
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001515
Venkatesh Pallipadie82b8e42010-10-04 17:03:20 -07001516 if (!no_sched_irq_time)
1517 enable_sched_clock_irqtime();
1518
Pavel Tatashincf7a63e2018-07-19 16:55:38 -04001519 lpj_fine = get_loops_per_jiffy();
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001520 use_tsc_delay();
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001521
Zhenzhong Duana1272dd2017-06-21 01:23:37 -07001522 check_system_tsc_reliable();
1523
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001524 if (unsynchronized_tsc()) {
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001525 mark_tsc_unstable("TSCs unsynchronized");
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001526 return;
1527 }
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001528
Michael Zhivich63ec58b2019-10-24 13:59:45 -04001529 if (tsc_clocksource_reliable || no_tsc_watchdog)
1530 clocksource_tsc_early.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
1531
Peter Zijlstraaa83c452017-12-22 10:20:13 +01001532 clocksource_register_khz(&clocksource_tsc_early, tsc_khz);
Christopher S. Hallf9677e02016-02-29 06:33:47 -08001533 detect_art();
Alok Kataria8fbbc4b2008-07-01 11:43:34 -07001534}
1535
Jack Steinerb5652012011-11-15 15:33:56 -08001536#ifdef CONFIG_SMP
1537/*
1538 * If we have a constant TSC and are using the TSC for the delay loop,
1539 * we can skip clock calibration if another cpu in the same socket has already
1540 * been calibrated. This assumes that CONSTANT_TSC applies to all
1541 * cpus in the socket - this should be a safe assumption.
1542 */
Paul Gortmaker148f9bb2013-06-18 18:23:59 -04001543unsigned long calibrate_delay_is_known(void)
Jack Steinerb5652012011-11-15 15:33:56 -08001544{
Thomas Gleixnerc25323c2016-02-18 20:53:43 +01001545 int sibling, cpu = smp_processor_id();
Pavel Tatashin76ce7cf2017-10-27 20:11:00 -04001546 int constant_tsc = cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC);
1547 const struct cpumask *mask = topology_core_cpumask(cpu);
Jack Steinerb5652012011-11-15 15:33:56 -08001548
Pavel Tatashinfe9af812018-07-19 16:55:30 -04001549 if (!constant_tsc || !mask)
Thomas Gleixnerf508a5b2016-03-18 08:35:29 +01001550 return 0;
1551
1552 sibling = cpumask_any_but(mask, cpu);
Thomas Gleixnerc25323c2016-02-18 20:53:43 +01001553 if (sibling < nr_cpu_ids)
1554 return cpu_data(sibling).loops_per_jiffy;
Jack Steinerb5652012011-11-15 15:33:56 -08001555 return 0;
1556}
1557#endif