aboutsummaryrefslogtreecommitdiffstats
path: root/utils/aperf.c
blob: c5ceb4bd8c55ade3b1adcdfedb99a0d582678a5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
 *  Copyright (C) 2009  Thomas Renninger <trenn@suse.de>, Novell Inc.
 *
 *  Inspired by these projects:
 *    cpuid (by Todd Allen)
 *    msr-tools (by H. Peter Anvin <hpa@zytor.com>)
 *
 *  Licensed under the terms of the GNU GPL License version 2.
 *
 *
 *  What does this program do:
 *
 *  On latest processors exist two MSR registers refered to as:
 *    - MPERF increasing with maxium (P0) frequency in C0
 *    - APERF increasing with current/actual frequency in C0
 *
 *  From this information the average frequency over a time period can be
 *  calculated and this is what this tool does.
 *
 *  A nice falloff feature beside the average frequency is the time
 *  a processor core remained in C0 (working state) or any CX (sleep state)
 *  processor sleep state during the measured time period. This information
 *  can be determined from the fact that MPERF only increases in C0 state.
 *
 *  Note: There were kernels which reset MPERF/APERF registers to 0.
 *        This got reverted by git commit
 *                  18b2646fe3babeb40b34a0c1751e0bf5adfdc64c
 *        which was commited to 2.6.30-rcX mainline kernels
 *        For kernels where the kernel rests MPERF/APERF registers to 0,
 *        this tool will not work. It cannot be detected whether this happened.
 *
 * Possible ToDos/Enhancments:
 *
 *  - Refresh the screen when mulitple cpus are poked and display results
 *    on one screen
 *    -This would introduce a lot more complexity, not sure whether it's
 *       wanted/needed. I'd vote to better not do that.
 *  - Manpage
 *  - Translations
 *  - ...
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/time.h>
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>

#include "cpufreq.h"
#include "cpuid.h"

#define MSR_IA32_APERF 0x000000E8
#define MSR_IA32_MPERF 0x000000E7

struct avg_perf_cpu_info
{
	unsigned long max_freq;
	uint64_t saved_aperf;
	uint64_t saved_mperf;
	uint32_t is_valid:1;
};

static int cpu_has_effective_freq()
{
	/* largest base level */
	if (cpuid_eax(0) < 6)
		return 0;

	return cpuid_ecx(6) & 0x1;
}

/*
 * read_msr
 *
 * Will return 0 on success and -1 on failure.
 * Possible errno values could be:
 * EFAULT -If the read/write did not fully complete
 * EIO    -If the CPU does not support MSRs
 * ENXIO  -If the CPU does not exist
 */

static int read_msr(int cpu, unsigned int idx, unsigned long long *val)
{
	int fd;
	char msr_file_name[64];

	sprintf(msr_file_name, "/dev/cpu/%d/msr", cpu);
	fd = open(msr_file_name, O_RDONLY);
	if (fd < 0)
		return -1;
	if (lseek(fd, idx, SEEK_CUR) == -1)
		goto err;
	if (read(fd, val, sizeof val) != sizeof *val)
		goto err;
	close(fd);
	return 0;
 err:
	close(fd);
	return -1;
}

/*
 * get_aperf_mperf()
 *
 * Returns the current aperf/mperf MSR values of cpu
 */
static int get_aperf_mperf(unsigned int cpu, uint64_t *aperf, uint64_t *mperf)
{
	int retval;

	retval = read_msr(cpu, MSR_IA32_APERF, (unsigned long long*)aperf);
	if (retval < 0)
		return retval;

	retval = read_msr(cpu, MSR_IA32_MPERF, (unsigned long long*)mperf);
	if (retval < 0)
		return retval;
	return 0;
}

/*
 * get_average_perf()
 *
 * Returns the average performance (also considers boosted frequencies)
 * 
 * Input:
 *   aperf_diff: Difference of the aperf register over a time period
 *   mperf_diff: Difference of the mperf register over the same time period
 *   max_freq:   Maximum frequency (P0)
 *
 * Returns:
 *   Average performance over the time period
 */
static unsigned long get_average_perf(unsigned long max_freq,
				      uint64_t aperf_diff,
				      uint64_t mperf_diff)
{
	unsigned int perf_percent = 0;
	if (((unsigned long)(-1) / 100) < aperf_diff) {
		int shift_count = 7;
		aperf_diff >>= shift_count;
		mperf_diff >>= shift_count;
	}
	perf_percent = (aperf_diff * 100) / mperf_diff;
	return (max_freq * perf_percent) / 100;
}

/*
 * get_C_state_time()
 *
 * Calculates the time the processor was in C0 and Cx processor sleep states
 *
 * As mperf does only tick in C0 at maximum frequency, this is a nice "falloff"
 * functionality and more accurate than powertop or other kernel timer based
 * C-state measurings (and can be used to verify whether they are correct.
 *
 * Input:
 *   time_diff:  The time passed for which the mperf_diff was calulcated on
 *   mperf_diff: The value the mperf register increased during time_diff
 *   max_freq:   Maximum frequency of the processor (P0) in kHz
 *
 * Output:
 *   C0_time:    The time the processor was in C0
 *   CX_time:    The time the processor was in CX
 *   percent:    Percentage the processor stayed in C0
 */
static int get_C_state_time(struct timeval time_diff, uint64_t mperf_diff,
		     unsigned long max_freq,
		     struct timeval *C0_time, struct timeval *CX_time,
		     unsigned int *percent)
{
	unsigned long long overall_msecs, expected_ticks, c0_time, cx_time;

	overall_msecs = (time_diff.tv_sec * 1000 * 1000  + time_diff.tv_usec)
		/ 1000;

	expected_ticks = max_freq * overall_msecs;
	*percent = (mperf_diff * 100) / expected_ticks;

	cx_time = (expected_ticks - mperf_diff) / max_freq;
	c0_time = mperf_diff / max_freq;

	CX_time->tv_sec  = cx_time / 1000;
	CX_time->tv_usec = cx_time % 1000;
	C0_time->tv_sec  = c0_time / 1000;
	C0_time->tv_usec = c0_time % 1000;
	return 0;
}

static int get_measure_start_info(unsigned int cpu,
				  struct avg_perf_cpu_info *cpu_info)
{
	unsigned long min, max;
	uint64_t aperf, mperf;
	int ret;

	cpu_info->is_valid = 0;

	if (cpufreq_get_hardware_limits(cpu, &min, &max))
		return -EINVAL;

	cpu_info->max_freq = max;
	
	ret = get_aperf_mperf(cpu, &aperf, &mperf);
	if (ret < 0)
		return -EINVAL;

	cpu_info->saved_aperf = aperf;
	cpu_info->saved_mperf = mperf;
	cpu_info->is_valid = 1;

	return 0;
}

static void print_cpu_stats(unsigned long average, struct timeval c0_time,
			    struct timeval cx_time, unsigned int c0_percent)
{
	printf("%.7lu\t\t\t", average);
	printf("%.2lu sec %.3lu ms\t", c0_time.tv_sec, c0_time.tv_usec);
	printf("%.2lu sec %.3lu ms\t", cx_time.tv_sec, cx_time.tv_usec);
	printf("%.2u", c0_percent);
}

static int do_measuring_on_cpu(int sleep_time, int once, int cpu)
{
	int ret;
	unsigned long average;
	unsigned int c0_percent;
	struct timeval start_time, current_time, diff_time, C0_time, CX_time;
	uint64_t current_aperf, current_mperf, mperf_diff, aperf_diff;
	struct avg_perf_cpu_info cpu_info;

	ret = get_measure_start_info(cpu, &cpu_info);
	if (ret)
		return ret;

	while(1) {
		gettimeofday(&start_time, NULL);
		sleep(sleep_time);
		/* ToDo: just add a second on the timeval struct? */
		gettimeofday(&current_time, NULL);
		timersub(&current_time, &start_time, &diff_time);
		memcpy(&start_time, &current_time,
		       sizeof(struct timeval));

		if (!cpu_info.is_valid)
			continue;

		printf("%.3u\t", cpu);

		ret = get_aperf_mperf(cpu, &current_aperf, &current_mperf);
		if (ret < 0) {
			printf("[offline]\n");
			continue;
		}

		mperf_diff = current_mperf - cpu_info.saved_mperf;
		aperf_diff = current_aperf - cpu_info.saved_aperf;

		get_C_state_time(diff_time, mperf_diff,
				 cpu_info.max_freq,
				 &C0_time, &CX_time,
				 &c0_percent);
		average = get_average_perf(cpu_info.max_freq,
					   aperf_diff, mperf_diff);
		cpu_info.saved_mperf = current_mperf;
		cpu_info.saved_aperf = current_aperf;
		print_cpu_stats(average, C0_time, CX_time, c0_percent);

		if (once) {
			printf("\n");
			break;
		} else {
			printf("\r");
			fflush(stdout);
		}
	}
	return 0;
}

static int do_measure_all_cpus(int sleep_time, int once)
{
	int ret;
	unsigned long average;
	unsigned int c0_percent, cpus, cpu;
	struct timeval start_time, current_time, diff_time, C0_time, CX_time;
	uint64_t current_aperf, current_mperf, mperf_diff, aperf_diff;
	struct avg_perf_cpu_info *cpu_list;

	cpus = sysconf(_SC_NPROCESSORS_CONF);

	cpu_list = (struct avg_perf_cpu_info*)
		malloc(cpus * sizeof (struct avg_perf_cpu_info));

	for (cpu = 0; cpu < cpus; cpu++) {
		ret = get_measure_start_info(cpu, &cpu_list[cpu]);
		if   (ret)
		continue;
	}

	while(1) {
		gettimeofday(&start_time, NULL);
		sleep(sleep_time);
		/* ToDo: Just add a second on the timeval struct?
		         Would save one gettimeofday, but would not
			 be that accurate anymore
		*/
		gettimeofday(&current_time, NULL);
		timersub(&current_time, &start_time, &diff_time);
		memcpy(&start_time, &current_time,
		       sizeof(struct timeval));

		for (cpu = 0; cpu < cpus; cpu++) {

			printf("%.3u\t", cpu);

			ret = get_aperf_mperf(cpu, &current_aperf,
					      &current_mperf);

			if ((ret < 0) || !cpu_list[cpu].is_valid) {
				printf("[offline]\n");
				continue;
			}

			mperf_diff = current_mperf - cpu_list[cpu].saved_mperf;
			aperf_diff = current_aperf - cpu_list[cpu].saved_aperf;

			get_C_state_time(diff_time, mperf_diff,
					 cpu_list[cpu].max_freq,
					 &C0_time, &CX_time,
					 &c0_percent);
			average = get_average_perf(cpu_list[cpu].max_freq,
						   aperf_diff, mperf_diff);
			cpu_list[cpu].saved_mperf = current_mperf;
			cpu_list[cpu].saved_aperf = current_aperf;
			print_cpu_stats(average, C0_time, CX_time, c0_percent);
			printf("\n");
		}
		if (once)
			break;
		printf("\n");
	}
	return 0;
}


/******* Options parsing, main ********/

static struct option long_options[] = {
  { "help",		0, 0, 'h' },
  { "intervall",	1, 0, 'i' },
  { "cpu",		1, 0, 'c' },
  { "once",		0, 0, 'o' },
  { 0, 0, 0, 0 }
};

static void usage(void) {
	printf("cpufreq-aperf [OPTIONS]\n\n"
	       "-c [ --cpu ] CPU               "
	       "The CPU core to measure - default all cores\n"
	       "-i [ --intervall ] seconds     "
	       "Refresh rate - default 1 second\n"
	       "-o [ --once ]                  "
	       "Exit after one intervall\n"
	       "-h [ --help ]                  "
	       "This help text\n"
	       "The msr driver must be loaded for this command to work\n");
}

int main(int argc, char *argv[])
{
	int c, ret, cpu = -1;
	int sleep_time = 1, once = 0;
	const char *msr_path = "/dev/cpu/0/msr";

	while ( (c = getopt_long(argc,argv,"c:ohi:",long_options,
				 NULL)) != -1 ) {
		switch ( c ) {
		case 'o':
			once = 1;
			break;
		case 'c':
			cpu = atoi(optarg);
			break;
		case 'h':
			usage();
			exit(0);
		case 'i':
			sleep_time = atoi(optarg);
			break;
		}
	}

	if (!cpu_has_effective_freq()) {
		fprintf(stderr, "CPU doesn't support APERF/MPERF!\n");
		return EXIT_FAILURE;
	}

	ret = access(msr_path, R_OK);
	if (ret < 0) {
		fprintf(stderr, "Error reading %s, load/enable msr.ko\n", msr_path);
		goto out;
	}

	printf("CPU\tAverage freq(KHz)\tTime in C0\tTime in"
	       " Cx\tC0 percentage\n");

	if (cpu == -1)
		ret = do_measure_all_cpus(sleep_time, once);
	else
		ret = do_measuring_on_cpu(sleep_time, once, cpu);

out:
	return ret;
}
/******* Options parsing, main ********/