1 /*
2  *  (C) 2010,2011       Thomas Renninger <trenn@suse.de>, Novell Inc.
3  *
4  *  Licensed under the terms of the GNU GPL License version 2.
5  */
6 
7 #if defined(__i386__) || defined(__x86_64__)
8 
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <limits.h>
14 
15 #include <cpufreq.h>
16 
17 #include "helpers/helpers.h"
18 #include "idle_monitor/cpupower-monitor.h"
19 
20 #define MSR_APERF	0xE8
21 #define MSR_MPERF	0xE7
22 
23 #define MSR_TSC	0x10
24 
25 #define MSR_AMD_HWCR 0xc0010015
26 
27 enum mperf_id { C0 = 0, Cx, AVG_FREQ, MPERF_CSTATE_COUNT };
28 
29 static int mperf_get_count_percent(unsigned int self_id, double *percent,
30 				   unsigned int cpu);
31 static int mperf_get_count_freq(unsigned int id, unsigned long long *count,
32 				unsigned int cpu);
33 static struct timespec time_start, time_end;
34 
35 static cstate_t mperf_cstates[MPERF_CSTATE_COUNT] = {
36 	{
37 		.name			= "C0",
38 		.desc			= N_("Processor Core not idle"),
39 		.id			= C0,
40 		.range			= RANGE_THREAD,
41 		.get_count_percent	= mperf_get_count_percent,
42 	},
43 	{
44 		.name			= "Cx",
45 		.desc			= N_("Processor Core in an idle state"),
46 		.id			= Cx,
47 		.range			= RANGE_THREAD,
48 		.get_count_percent	= mperf_get_count_percent,
49 	},
50 
51 	{
52 		.name			= "Freq",
53 		.desc			= N_("Average Frequency (including boost) in MHz"),
54 		.id			= AVG_FREQ,
55 		.range			= RANGE_THREAD,
56 		.get_count		= mperf_get_count_freq,
57 	},
58 };
59 
60 enum MAX_FREQ_MODE { MAX_FREQ_SYSFS, MAX_FREQ_TSC_REF };
61 static int max_freq_mode;
62 /*
63  * The max frequency mperf is ticking at (in C0), either retrieved via:
64  *   1) calculated after measurements if we know TSC ticks at mperf/P0 frequency
65  *   2) cpufreq /sys/devices/.../cpu0/cpufreq/cpuinfo_max_freq at init time
66  * 1. Is preferred as it also works without cpufreq subsystem (e.g. on Xen)
67  */
68 static unsigned long max_frequency;
69 
70 static unsigned long long tsc_at_measure_start;
71 static unsigned long long tsc_at_measure_end;
72 static unsigned long long *mperf_previous_count;
73 static unsigned long long *aperf_previous_count;
74 static unsigned long long *mperf_current_count;
75 static unsigned long long *aperf_current_count;
76 
77 /* valid flag for all CPUs. If a MSR read failed it will be zero */
78 static int *is_valid;
79 
mperf_get_tsc(unsigned long long * tsc)80 static int mperf_get_tsc(unsigned long long *tsc)
81 {
82 	int ret;
83 
84 	ret = read_msr(base_cpu, MSR_TSC, tsc);
85 	if (ret)
86 		dprint("Reading TSC MSR failed, returning %llu\n", *tsc);
87 	return ret;
88 }
89 
mperf_init_stats(unsigned int cpu)90 static int mperf_init_stats(unsigned int cpu)
91 {
92 	unsigned long long val;
93 	int ret;
94 
95 	ret = read_msr(cpu, MSR_APERF, &val);
96 	aperf_previous_count[cpu] = val;
97 	ret |= read_msr(cpu, MSR_MPERF, &val);
98 	mperf_previous_count[cpu] = val;
99 	is_valid[cpu] = !ret;
100 
101 	return 0;
102 }
103 
mperf_measure_stats(unsigned int cpu)104 static int mperf_measure_stats(unsigned int cpu)
105 {
106 	unsigned long long val;
107 	int ret;
108 
109 	ret = read_msr(cpu, MSR_APERF, &val);
110 	aperf_current_count[cpu] = val;
111 	ret |= read_msr(cpu, MSR_MPERF, &val);
112 	mperf_current_count[cpu] = val;
113 	is_valid[cpu] = !ret;
114 
115 	return 0;
116 }
117 
mperf_get_count_percent(unsigned int id,double * percent,unsigned int cpu)118 static int mperf_get_count_percent(unsigned int id, double *percent,
119 				   unsigned int cpu)
120 {
121 	unsigned long long aperf_diff, mperf_diff, tsc_diff;
122 	unsigned long long timediff;
123 
124 	if (!is_valid[cpu])
125 		return -1;
126 
127 	if (id != C0 && id != Cx)
128 		return -1;
129 
130 	mperf_diff = mperf_current_count[cpu] - mperf_previous_count[cpu];
131 	aperf_diff = aperf_current_count[cpu] - aperf_previous_count[cpu];
132 
133 	if (max_freq_mode == MAX_FREQ_TSC_REF) {
134 		tsc_diff = tsc_at_measure_end - tsc_at_measure_start;
135 		*percent = 100.0 * mperf_diff / tsc_diff;
136 		dprint("%s: TSC Ref - mperf_diff: %llu, tsc_diff: %llu\n",
137 		       mperf_cstates[id].name, mperf_diff, tsc_diff);
138 	} else if (max_freq_mode == MAX_FREQ_SYSFS) {
139 		timediff = max_frequency * timespec_diff_us(time_start, time_end);
140 		*percent = 100.0 * mperf_diff / timediff;
141 		dprint("%s: MAXFREQ - mperf_diff: %llu, time_diff: %llu\n",
142 		       mperf_cstates[id].name, mperf_diff, timediff);
143 	} else
144 		return -1;
145 
146 	if (id == Cx)
147 		*percent = 100.0 - *percent;
148 
149 	dprint("%s: previous: %llu - current: %llu - (%u)\n",
150 		mperf_cstates[id].name, mperf_diff, aperf_diff, cpu);
151 	dprint("%s: %f\n", mperf_cstates[id].name, *percent);
152 	return 0;
153 }
154 
mperf_get_count_freq(unsigned int id,unsigned long long * count,unsigned int cpu)155 static int mperf_get_count_freq(unsigned int id, unsigned long long *count,
156 				unsigned int cpu)
157 {
158 	unsigned long long aperf_diff, mperf_diff, time_diff, tsc_diff;
159 
160 	if (id != AVG_FREQ)
161 		return 1;
162 
163 	if (!is_valid[cpu])
164 		return -1;
165 
166 	mperf_diff = mperf_current_count[cpu] - mperf_previous_count[cpu];
167 	aperf_diff = aperf_current_count[cpu] - aperf_previous_count[cpu];
168 
169 	if (max_freq_mode == MAX_FREQ_TSC_REF) {
170 		/* Calculate max_freq from TSC count */
171 		tsc_diff = tsc_at_measure_end - tsc_at_measure_start;
172 		time_diff = timespec_diff_us(time_start, time_end);
173 		max_frequency = tsc_diff / time_diff;
174 	}
175 
176 	*count = max_frequency * ((double)aperf_diff / mperf_diff);
177 	dprint("%s: Average freq based on %s maximum frequency:\n",
178 	       mperf_cstates[id].name,
179 	       (max_freq_mode == MAX_FREQ_TSC_REF) ? "TSC calculated" : "sysfs read");
180 	dprint("max_frequency: %lu\n", max_frequency);
181 	dprint("aperf_diff: %llu\n", aperf_diff);
182 	dprint("mperf_diff: %llu\n", mperf_diff);
183 	dprint("avg freq:   %llu\n", *count);
184 	return 0;
185 }
186 
mperf_start(void)187 static int mperf_start(void)
188 {
189 	int cpu;
190 	unsigned long long dbg;
191 
192 	clock_gettime(CLOCK_REALTIME, &time_start);
193 	mperf_get_tsc(&tsc_at_measure_start);
194 
195 	for (cpu = 0; cpu < cpu_count; cpu++)
196 		mperf_init_stats(cpu);
197 
198 	mperf_get_tsc(&dbg);
199 	dprint("TSC diff: %llu\n", dbg - tsc_at_measure_start);
200 	return 0;
201 }
202 
mperf_stop(void)203 static int mperf_stop(void)
204 {
205 	unsigned long long dbg;
206 	int cpu;
207 
208 	for (cpu = 0; cpu < cpu_count; cpu++)
209 		mperf_measure_stats(cpu);
210 
211 	mperf_get_tsc(&tsc_at_measure_end);
212 	clock_gettime(CLOCK_REALTIME, &time_end);
213 
214 	mperf_get_tsc(&dbg);
215 	dprint("TSC diff: %llu\n", dbg - tsc_at_measure_end);
216 
217 	return 0;
218 }
219 
220 /*
221  * Mperf register is defined to tick at P0 (maximum) frequency
222  *
223  * Instead of reading out P0 which can be tricky to read out from HW,
224  * we use TSC counter if it reliably ticks at P0/mperf frequency.
225  *
226  * Still try to fall back to:
227  * /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
228  * on older Intel HW without invariant TSC feature.
229  * Or on AMD machines where TSC does not tick at P0 (do not exist yet, but
230  * it's still double checked (MSR_AMD_HWCR)).
231  *
232  * On these machines the user would still get useful mperf
233  * stats when acpi-cpufreq driver is loaded.
234  */
init_maxfreq_mode(void)235 static int init_maxfreq_mode(void)
236 {
237 	int ret;
238 	unsigned long long hwcr;
239 	unsigned long min;
240 
241 	if (!(cpupower_cpu_info.caps & CPUPOWER_CAP_INV_TSC))
242 		goto use_sysfs;
243 
244 	if (cpupower_cpu_info.vendor == X86_VENDOR_AMD) {
245 		/* MSR_AMD_HWCR tells us whether TSC runs at P0/mperf
246 		 * freq.
247 		 * A test whether hwcr is accessable/available would be:
248 		 * (cpupower_cpu_info.family > 0x10 ||
249 		 *   cpupower_cpu_info.family == 0x10 &&
250 		 *   cpupower_cpu_info.model >= 0x2))
251 		 * This should be the case for all aperf/mperf
252 		 * capable AMD machines and is therefore safe to test here.
253 		 * Compare with Linus kernel git commit: acf01734b1747b1ec4
254 		 */
255 		ret = read_msr(0, MSR_AMD_HWCR, &hwcr);
256 		/*
257 		 * If the MSR read failed, assume a Xen system that did
258 		 * not explicitly provide access to it and assume TSC works
259 		*/
260 		if (ret != 0) {
261 			dprint("TSC read 0x%x failed - assume TSC working\n",
262 			       MSR_AMD_HWCR);
263 			return 0;
264 		} else if (1 & (hwcr >> 24)) {
265 			max_freq_mode = MAX_FREQ_TSC_REF;
266 			return 0;
267 		} else { /* Use sysfs max frequency if available */ }
268 	} else if (cpupower_cpu_info.vendor == X86_VENDOR_INTEL) {
269 		/*
270 		 * On Intel we assume mperf (in C0) is ticking at same
271 		 * rate than TSC
272 		 */
273 		max_freq_mode = MAX_FREQ_TSC_REF;
274 		return 0;
275 	}
276 use_sysfs:
277 	if (cpufreq_get_hardware_limits(0, &min, &max_frequency)) {
278 		dprint("Cannot retrieve max freq from cpufreq kernel "
279 		       "subsystem\n");
280 		return -1;
281 	}
282 	max_freq_mode = MAX_FREQ_SYSFS;
283 	max_frequency /= 1000; /* Default automatically to MHz value */
284 	return 0;
285 }
286 
287 /*
288  * This monitor provides:
289  *
290  * 1) Average frequency a CPU resided in
291  *    This always works if the CPU has aperf/mperf capabilities
292  *
293  * 2) C0 and Cx (any sleep state) time a CPU resided in
294  *    Works if mperf timer stops ticking in sleep states which
295  *    seem to be the case on all current HW.
296  * Both is directly retrieved from HW registers and is independent
297  * from kernel statistics.
298  */
299 struct cpuidle_monitor mperf_monitor;
mperf_register(void)300 struct cpuidle_monitor *mperf_register(void)
301 {
302 	if (!(cpupower_cpu_info.caps & CPUPOWER_CAP_APERF))
303 		return NULL;
304 
305 	if (init_maxfreq_mode())
306 		return NULL;
307 
308 	/* Free this at program termination */
309 	is_valid = calloc(cpu_count, sizeof(int));
310 	mperf_previous_count = calloc(cpu_count, sizeof(unsigned long long));
311 	aperf_previous_count = calloc(cpu_count, sizeof(unsigned long long));
312 	mperf_current_count = calloc(cpu_count, sizeof(unsigned long long));
313 	aperf_current_count = calloc(cpu_count, sizeof(unsigned long long));
314 
315 	mperf_monitor.name_len = strlen(mperf_monitor.name);
316 	return &mperf_monitor;
317 }
318 
mperf_unregister(void)319 void mperf_unregister(void)
320 {
321 	free(mperf_previous_count);
322 	free(aperf_previous_count);
323 	free(mperf_current_count);
324 	free(aperf_current_count);
325 	free(is_valid);
326 }
327 
328 struct cpuidle_monitor mperf_monitor = {
329 	.name			= "Mperf",
330 	.hw_states_num		= MPERF_CSTATE_COUNT,
331 	.hw_states		= mperf_cstates,
332 	.start			= mperf_start,
333 	.stop			= mperf_stop,
334 	.do_register		= mperf_register,
335 	.unregister		= mperf_unregister,
336 	.needs_root		= 1,
337 	.overflow_s		= 922000000 /* 922337203 seconds TSC overflow
338 					       at 20GHz */
339 };
340 #endif /* #if defined(__i386__) || defined(__x86_64__) */
341