blob: 70a0e2beb3e8a7edb72dbb8c4e646fb55f5b79bf [file] [log] [blame]
Neil Leeder4832fc22011-11-22 16:49:08 -05001/*
2 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 and
6 * only version 2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
13
14/*
15 * A very simple perf program to periodically print the performance
16 * counter reqested on the command line to standard out at the rate
17 * specified.
18 *
19 * This is valuable for showing the output in a simple plot or
20 * exporting the counter data for post processing. No attempt
21 * to process the data is made.
22 *
23 * Scaling is not supported, use only as many counters as are
24 * provided by the hardware.
25 *
26 * Math functions are support to combine counter results by using
27 * the -m flag.
28 *
29 * The -r -w flags supports user signalling for input. This assumes
30 * that a pipe/fifo is needed so the -rw cmd line arg is a string
31 * that is the name of the named pipe to open for read/write. User
32 * sends data on the read pipe to the process to collect a sample.
33 * Commands are also supported on the pipe.
34 *
35 */
36
37#include "perf.h"
38#include "builtin.h"
39#include "util/util.h"
40#include "util/parse-options.h"
41#include "util/parse-events.h"
42#include "util/event.h"
43#include "util/evsel.h"
44#include "util/evlist.h"
45#include "util/debug.h"
46#include "util/header.h"
47#include "util/cpumap.h"
48#include "util/thread.h"
49#include <signal.h>
50#include <sys/types.h>
51
52#define PERF_PERIODIC_ERROR -1
53
54/* number of pieces of data on each read. */
55#define DATA_SIZE 2
56
57#define DEFAULT_FIFO_NAME "xxbadFiFo"
58#define MAX_NAMELEN 50
59
60struct perf_evlist *evsel_list;
61
62/*
63 * command line variables and settings
64 * Default to current process, no_inherit, process
65 */
66static pid_t target_pid = -1; /* all */
67static bool system_wide;
68static int cpumask = -1; /* all */
69static int ncounts;
70static int ms_sleep = 1000; /* 1 second */
71static char const *operations = "nnnnnnnnnnnnnnnn"; /* nop */
72static bool math_enabled;
73static bool calc_delta;
74static double old_accum, accum;
75static int math_op_index;
76static char const *wfifo_name = DEFAULT_FIFO_NAME;
77static char const *rfifo_name = DEFAULT_FIFO_NAME;
78static bool use_fifo;
79static bool is_ratio;
80static FILE *fd_in, *fd_out;
81
82static FILE *tReadFifo, *tWriteFifo;
83
84/*
85 * Raw results from perf, we track the current value and
86 * the old value.
87 */
88struct perf_raw_results_s {
89 u64 values;
90 u64 old_value;
91};
92
93/*
94 * Everything we need to support a perf counter across multiple
95 * CPUs. We need to support multiple file descriptors (perf_fd)
96 * because perf requires a fd per counter, so 1 per core enabled.
97 *
98 * Raw results values are calculated across all the cores as they
99 * are read.
100 */
101struct perf_setup_s {
102 int event_index;
103 struct perf_event_attr *attr;
104 int perf_fd[MAX_NR_CPUS];
105 pid_t pid;
106 int cpu;
107 int flags;
108 int group;
109 struct perf_raw_results_s data;
110 struct perf_raw_results_s totals;
111 struct perf_raw_results_s output;
112};
113
114static void do_cleanup(void)
115{
116 if (fd_in) {
117 if (0 != fclose(fd_in))
118 error("Error closing fd_in\n");
119 }
120 if (fd_out) {
121 if (0 != fclose(fd_out))
122 error("Error closing fd_out\n");
123 }
124 if (use_fifo) {
125 if (0 != unlink(rfifo_name))
126 error("Error unlinking rfifo\n");
127 if (0 != unlink(wfifo_name))
128 error("Error unlinking wfifo\n");
129 }
130}
131
132/*
133 * Unexpected signal for error indication, cleanup
134 */
135static int sig_dummy;
136static void sig_do_cleanup(int sig)
137{
138 sig_dummy = sig;
139 do_cleanup();
140 exit(0);
141}
142
143#define PERIODIC_MAX_STRLEN 100
144/*
145 * Delay for either a timed period or the wait on the read_fifo
146 */
147static void delay(unsigned long milli)
148{
149 char tmp_stg[PERIODIC_MAX_STRLEN];
150 int done;
151 int ret;
152
153 if (use_fifo) {
154 do {
155 done = true;
156 ret = fscanf(tReadFifo, "%s", tmp_stg);
157 if (ret == 0)
158 return;
159 /*
160 * Look for a command request, and if we get a command
161 * Need to process and then wait again w/o sending data.
162 */
163 if (strncmp(tmp_stg, "PID", strnlen(tmp_stg,
164 PERIODIC_MAX_STRLEN)) == 0) {
165 fprintf(fd_out, " %u\n", getpid());
166 fflush(fd_out);
167 done = false;
168 } else if (strncmp(tmp_stg, "EXIT",
169 strnlen(tmp_stg, PERIODIC_MAX_STRLEN))
170 == 0) {
171 do_cleanup();
172 exit(0);
173 }
174
175 } while (done != true);
176 } else
177 usleep(milli*1000);
178}
179
180/*
181 * Create a perf counter event.
182 * Some interesting behaviour that is not documented anywhere else:
183 * the CPU will not work if out of range.
184 * The CPU will only work for a single CPU, so to collect the counts
185 * on the system in SMP based systems a counter needs to be created
186 * for each CPU.
187 */
188static int create_perf_counter(struct perf_setup_s *p)
189{
190 struct cpu_map *cpus;
191 int cpu;
192
193 cpus = cpu_map__new(NULL);
194 if (p == NULL)
195 return PERF_PERIODIC_ERROR;
196 for (cpu = 0; cpu < cpus->nr; cpu++) {
197 p->perf_fd[cpu] = sys_perf_event_open(p->attr, target_pid, cpu,
198 -1, 0);
199 if (p->perf_fd[cpu] < 0)
200 return PERF_PERIODIC_ERROR;
201 }
202 return 0;
203}
204
205/*
206 * Perf init setup
207 */
208static int perf_setup_init(struct perf_setup_s *p)
209{
210 if (p == NULL)
211 return PERF_PERIODIC_ERROR;
212
213 bzero(p, sizeof(struct perf_setup_s));
214 p->group = -1;
215 p->flags = 0;
216
217 p->output.values = 0;
218 p->output.old_value = 0;
219 p->data.values = 0;
220 p->data.old_value = 0;
221 p->totals.old_value = 0;
222 p->totals.values = 0;
223
224 return 0;
225}
226
227/*
228 * Read in ALL the performance counters configured for the CPU,
229 * one performance monitor per core that was configured during
230 * "all" mode
231 */
232static int perf_setup_read(struct perf_setup_s *p)
233{
234 u64 data[DATA_SIZE];
235 int i, status;
236
237 p->totals.values = 0;
238 p->data.values = 0;
239 for (i = 0; i < MAX_NR_CPUS; i++) {
240 if (p->perf_fd[i] == 0)
241 continue;
242 status = read(p->perf_fd[i], &data, sizeof(data));
243 p->data.values += data[0];
244 p->totals.values += data[0];
245 }
246
247 /*
248 * Normally we show totals, we want to support
249 * showing deltas from the previous value so external apps do not have
250 * to do this...
251 */
252 if (calc_delta) {
253 p->output.values = p->data.values - p->data.old_value;
254 p->data.old_value = p->data.values;
255 } else
256 p->output.values = p->totals.values;
257 return 0;
258}
259
260static int perf_setup_show(struct perf_setup_s *p)
261{
262 if (p == NULL)
263 return PERF_PERIODIC_ERROR;
264 fprintf(fd_out, " %llu", p->output.values);
265 return 0;
266}
267
268
269static const char * const periodic_usage[] = {
270 "perf periodic [<options>]",
271 NULL
272};
273
274static const struct option options[] = {
275 OPT_CALLBACK('e', "event", &evsel_list, "event",
276 "event selector. use 'perf list' to list available events",
277 parse_events),
278 OPT_STRING('m', "math-operations", &operations, "nnnnnn",
279 "math operation to perform on values collected asmd in order"),
280 OPT_STRING('r', "readpipe", &rfifo_name, "xxbadFiFo",
281 "wait for a user input fifo - will be created"),
282 OPT_STRING('w', "writepipe", &wfifo_name, "xxbadFifo",
283 "write data out on this pipe - pipe is created"),
284 OPT_INTEGER('i', "increment", &ncounts,
285 "number of times periods to count/iterate (default 0-forever)"),
286 OPT_INTEGER('p', "pid", &target_pid,
287 "stat events on existing process id"),
288 OPT_INTEGER('c', "cpumask", &cpumask,
289 "cpumask to enable counters, default all (-1)"),
290 OPT_INTEGER('s', "sleep", &ms_sleep,
291 "how long to sleep in ms between each sample (default 1000)"),
292 OPT_BOOLEAN('a', "all-cpus", &system_wide,
293 "system-wide collection from all CPUs overrides cpumask"),
294 OPT_BOOLEAN('d', "delta", &calc_delta,
295 "calculate and display the delta values math funcs will use delta"),
296 OPT_INCR('v', "verbose", &verbose,
297 "be more verbose (show counter open errors, etc)"),
298 OPT_END()
299};
300
301/*
302 * After every period we reset any math that was performed.
303 */
304static void reset_math(void)
305{
306 math_op_index = 0;
307 old_accum = accum;
308 accum = 0;
309}
310
311static void do_math_op(struct perf_setup_s *p)
312{
313 if (!math_enabled)
314 return;
315 switch (operations[math_op_index++]) {
316 case 'm':
317 accum *= (double)p->output.values; break;
318 case 'a':
319 accum += (double)p->output.values; break;
320 case 's':
321 accum -= (double)p->output.values; break;
322 case 'd':
323 accum /= (double)p->output.values; break;
324 case 'z':
325 accum = 0; break;
326 case 't':
327 accum = (double)p->output.values; break; /*transfer*/
328 case 'T':
329 accum += old_accum; break; /*total*/
330 case 'i': /* ignore */
331 default:
332 break;
333 }
334}
335
336int cmd_periodic(int argc, const char **argv, const char *prefix __used)
337{
338 int status = 0;
339 int c, i;
340 struct perf_setup_s *p[MAX_COUNTERS];
341 struct perf_evsel *counter;
342 FILE *fp;
343 int nr_counters = 0;
344
345 evsel_list = perf_evlist__new(NULL, NULL);
346 if (evsel_list == NULL)
347 return -ENOMEM;
348
349 argc = parse_options(argc, argv, options, periodic_usage,
350 PARSE_OPT_STOP_AT_NON_OPTION);
351
352 if (system_wide)
353 cpumask = -1;
354
355 /*
356 * The r & w option redirects stdout to a newly created pipe and
357 * waits for input on the read pipe before continuing
358 */
359 fd_in = stdin;
360 fd_out = stdout;
361 if (strncmp(rfifo_name, DEFAULT_FIFO_NAME,
362 strnlen(rfifo_name, MAX_NAMELEN))) {
363 fp = fopen(rfifo_name, "r");
364 if (fp != NULL) {
365 fclose(fp);
366 remove(rfifo_name);
367 }
368 if (mkfifo(rfifo_name, 0777) == -1) {
369 error("Could not open read fifo\n");
370 do_cleanup();
371 return PERF_PERIODIC_ERROR;
372 }
373 tReadFifo = fopen(rfifo_name, "r+");
374 if (tReadFifo == 0) {
375 do_cleanup();
376 error("Could not open read fifo file\n");
377 return PERF_PERIODIC_ERROR;
378 }
379 use_fifo = true;
380 }
381 if (strncmp(wfifo_name, DEFAULT_FIFO_NAME,
382 strnlen(wfifo_name, MAX_NAMELEN))) {
383 fp = fopen(wfifo_name, "r");
384 if (fp != NULL) {
385 fclose(fp);
386 remove(wfifo_name);
387 }
388 if (mkfifo(wfifo_name, 0777) == -1) {
389 do_cleanup();
390 error("Could not open write fifo\n");
391 return PERF_PERIODIC_ERROR;
392 }
393 fd_out = fopen(wfifo_name, "w+");
394 if (fd_out == 0) {
395 do_cleanup();
396 error("Could not open write fifo file\n");
397 return PERF_PERIODIC_ERROR;
398 }
399 tWriteFifo = fd_out;
400 }
401
402 math_enabled = (operations[0] != 'n');
403
404 /*
405 * If we don't ignore SIG_PIPE then when the other side
406 * of a pipe closes we shutdown too...
407 */
408 signal(SIGPIPE, SIG_IGN);
409 signal(SIGINT, sig_do_cleanup);
410 signal(SIGQUIT, sig_do_cleanup);
411 signal(SIGKILL, sig_do_cleanup);
412 signal(SIGTERM, sig_do_cleanup);
413
414 i = 0;
415 list_for_each_entry(counter, &evsel_list->entries, node) {
416 p[i] = malloc(sizeof(struct perf_setup_s));
417 if (p[i] == NULL) {
418 error("Error allocating perf_setup_s\n");
419 do_cleanup();
420 return PERF_PERIODIC_ERROR;
421 }
422 bzero(p[i], sizeof(struct perf_setup_s));
423 perf_setup_init(p[i]);
424 p[i]->attr = &(counter->attr);
425 p[i]->event_index = counter->idx;
426 if (create_perf_counter(p[i]) < 0) {
427 do_cleanup();
428 die("Not all events could be opened.\n");
429 return PERF_PERIODIC_ERROR;
430 }
431 i++;
432 nr_counters++;
433 }
434 i = 0;
435 while (1) {
436
437 /*
438 * Wait first otherwise single sample will print w/o signal
439 * when using the -u (user signal) flag
440 */
441 delay(ms_sleep);
442
443 /*
444 * Do the collection, read and then perform any math operations
445 */
446 for (c = 0; c < nr_counters; c++) {
447 status = perf_setup_read(p[c]);
448 do_math_op(p[c]);
449 }
450
451 /*
452 * After all collection and math, we perform one last math
453 * to allow totaling, if enabled etc, then either printout
454 * a single float value when the math is enabled or ...
455 */
456 if (math_enabled) {
457 do_math_op(p[c]);
458 if (is_ratio)
459 fprintf(fd_out, "%#f\n", accum*100);
460 else
461 fprintf(fd_out, "%#f\n", accum);
462 } else {
463 /*
464 * ... print out one integer value for each counter
465 */
466 for (c = 0; c < nr_counters; c++)
467 status = perf_setup_show(p[c]);
468 fprintf(fd_out, "\n");
469 }
470
471 /*
472 * Did the user give us an iteration count?
473 */
474 if ((ncounts != 0) && (++i >= ncounts))
475 break;
476 reset_math();
477 fflush(fd_out); /* make sure data is flushed out the pipe*/
478 }
479
480 do_cleanup();
481
482 return status;
483}