2 * x86 APERF/MPERF KHz calculation for
3 * /sys/.../cpufreq/scaling_cur_freq
5 * Copyright (C) 2017 Intel Corp.
6 * Author: Len Brown <len.brown@intel.com>
8 * This file is licensed under GPLv2.
11 #include <linux/delay.h>
12 #include <linux/ktime.h>
13 #include <linux/math64.h>
14 #include <linux/percpu.h>
15 #include <linux/smp.h>
17 struct aperfmperf_sample {
24 static DEFINE_PER_CPU(struct aperfmperf_sample, samples);
26 #define APERFMPERF_CACHE_THRESHOLD_MS 10
27 #define APERFMPERF_REFRESH_DELAY_MS 20
28 #define APERFMPERF_STALE_THRESHOLD_MS 1000
31 * aperfmperf_snapshot_khz()
32 * On the current CPU, snapshot APERF, MPERF, and jiffies
33 * unless we already did it within 10ms
34 * calculate kHz, save snapshot
36 static void aperfmperf_snapshot_khz(void *dummy)
38 u64 aperf, aperf_delta;
39 u64 mperf, mperf_delta;
40 struct aperfmperf_sample *s = this_cpu_ptr(&samples);
41 ktime_t now = ktime_get();
42 s64 time_delta = ktime_ms_delta(now, s->time);
44 /* Don't bother re-computing within the cache threshold time. */
45 if (time_delta < APERFMPERF_CACHE_THRESHOLD_MS)
48 rdmsrl(MSR_IA32_APERF, aperf);
49 rdmsrl(MSR_IA32_MPERF, mperf);
51 aperf_delta = aperf - s->aperf;
52 mperf_delta = mperf - s->mperf;
55 * There is no architectural guarantee that MPERF
56 * increments faster than we can read it.
65 /* If the previous iteration was too long ago, discard it. */
66 if (time_delta > APERFMPERF_STALE_THRESHOLD_MS)
69 s->khz = div64_u64((cpu_khz * aperf_delta), mperf_delta);
72 unsigned int arch_freq_get_on_cpu(int cpu)
79 if (!static_cpu_has(X86_FEATURE_APERFMPERF))
82 smp_call_function_single(cpu, aperfmperf_snapshot_khz, NULL, 1);
83 khz = per_cpu(samples.khz, cpu);
87 msleep(APERFMPERF_REFRESH_DELAY_MS);
88 smp_call_function_single(cpu, aperfmperf_snapshot_khz, NULL, 1);
90 return per_cpu(samples.khz, cpu);