[6893b5]: libperf_events / operf_counter.cpp  Maximize  Restore  History

Download this file

607 lines (532 with data), 17.3 kB

  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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/**
* @file pe_profiling/operf_counter.cpp
* C++ class implementation that abstracts the user-to-kernel interface
* for using Linux Performance Events Subsystem.
*
* @remark Copyright 2011 OProfile authors
* @remark Read the file COPYING
*
* Created on: Dec 7, 2011
* @author Maynard Johnson
* (C) Copyright IBM Corp. 2011
*
* Modified by Maynard Johnson <maynardj@us.ibm.com>
* (C) Copyright IBM Corporation 2012
*
*/
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include "op_events.h"
#include "operf_counter.h"
#include "op_abi.h"
#include "cverb.h"
#include "operf_process_info.h"
#include "op_libiberty.h"
#include "operf_stats.h"
using namespace std;
using namespace OP_perf_utils;
volatile bool quit;
volatile bool read_quit;
int sample_reads;
int num_mmap_pages;
unsigned int pagesize;
verbose vperf("perf_events");
extern bool first_time_processing;
extern bool throttled;
namespace {
vector<string> event_names;
static const char *__op_magic = "OPFILE";
#define OP_MAGIC (*(u64 *)__op_magic)
} // end anonymous namespace
operf_counter::operf_counter(operf_event_t evt, bool enable_on_exec, bool do_cg,
bool separate_cpu)
{
memset(&attr, 0, sizeof(attr));
attr.size = sizeof(attr);
attr.sample_type = OP_BASIC_SAMPLE_FORMAT;
if (do_cg)
attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
if (separate_cpu)
attr.sample_type |= PERF_SAMPLE_CPU;
attr.type = PERF_TYPE_RAW;
attr.config = evt.evt_code;
attr.sample_period = evt.count;
attr.inherit = 1;
attr.enable_on_exec = enable_on_exec ? 1 : 0;
attr.disabled = 1;
attr.exclude_idle = 0;
attr.exclude_kernel = evt.no_kernel;
attr.exclude_hv = evt.no_hv;
attr.read_format = PERF_FORMAT_ID;
event_name = evt.name;
}
operf_counter::~operf_counter() {
}
int operf_counter::perf_event_open(pid_t ppid, int cpu, unsigned event, operf_record * rec)
{
struct {
u64 count;
u64 id;
} read_data;
if (event == 0) {
attr.mmap = 1;
attr.comm = 1;
}
fd = op_perf_event_open(&attr, ppid, cpu, -1, 0);
if (fd < 0) {
int ret = -1;
cverb << vperf << "perf_event_open failed: " << strerror(errno) << endl;
if (errno == EBUSY) {
cerr << "The performance monitoring hardware reports EBUSY. Is another profiling tool in use?" << endl
<< "On some architectures, tools such as oprofile and perf being used in system-wide "
<< "mode can cause this problem." << endl;
ret = OP_PERF_HANDLED_ERROR;
} else if (errno == ESRCH) {
cerr << "!!!! No samples collected !!!" << endl;
cerr << "The target program/command ended before profiling was started." << endl;
ret = OP_PERF_HANDLED_ERROR;
} else {
cerr << "perf_event_open failed with " << strerror(errno) << endl;
}
return ret;
}
if (read(fd, &read_data, sizeof(read_data)) == -1) {
perror("Error reading perf_event fd");
return -1;
}
rec->register_perf_event_id(event, read_data.id, attr);
cverb << vperf << "perf_event_open returning fd " << fd << endl;
return fd;
}
operf_record::~operf_record()
{
cverb << vperf << "operf_record::~operf_record()" << endl;
if (poll_data)
delete[] poll_data;
close(output_fd);
for (int i = 0; i < samples_array.size(); i++) {
struct mmap_data *md = &samples_array[i];
munmap(md->base, (num_mmap_pages + 1) * pagesize);
}
samples_array.clear();
evts.clear();
perfCounters.clear();
}
operf_record::operf_record(int out_fd, bool sys_wide, pid_t the_pid, bool pid_running,
vector<operf_event_t> & events, vmlinux_info_t vi, bool do_cg,
bool separate_by_cpu)
{
int flags = O_CREAT|O_RDWR|O_TRUNC;
struct sigaction sa;
sigset_t ss;
vmlinux_file = vi.image_name;
kernel_start = vi.start;
kernel_end = vi.end;
pid = the_pid;
pid_started = pid_running;
system_wide = sys_wide;
callgraph = do_cg;
separate_cpu = separate_by_cpu;
total_bytes_recorded = 0;
poll_count = 0;
evts = events;
valid = false;
poll_data = NULL;
if (system_wide && (pid != -1 || pid_started))
return; // object is not valid
output_fd = out_fd;
cverb << vperf << "operf_record ctor using output fd " << output_fd << endl;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_sigaction = op_perfrecord_sigusr1_handler;
sigemptyset(&sa.sa_mask);
sigemptyset(&ss);
sigaddset(&ss, SIGUSR1);
sigprocmask(SIG_UNBLOCK, &ss, NULL);
sa.sa_mask = ss;
sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
cverb << vperf << "calling sigaction" << endl;
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
cverb << vperf << "operf_record ctor: sigaction failed; errno is: "
<< strerror(errno) << endl;
_exit(EXIT_FAILURE);
}
cverb << vperf << "calling setup" << endl;
setup();
}
void operf_record::register_perf_event_id(unsigned event, u64 id, perf_event_attr attr)
{
// It's overkill to blindly do this assignment below every time, since this function
// is invoked once for each event for each cpu; but it's not worth the bother of trying
// to avoid it.
opHeader.h_attrs[event].attr = attr;
cverb << vperf << "Perf header: id = " << hex << (unsigned long long)id << " for event num "
<< event << ", code " << attr.config << endl;
opHeader.h_attrs[event].ids.push_back(id);
}
void operf_record::write_op_header_info()
{
struct OP_file_header f_header;
struct op_file_attr f_attr;
f_header.magic = OP_MAGIC;
f_header.size = sizeof(f_header);
f_header.attr_size = sizeof(f_attr);
f_header.attrs.size = evts.size() * sizeof(f_attr);
f_header.data.size = 0;
add_to_total(op_write_output(output_fd, &f_header, sizeof(f_header)));
for (unsigned i = 0; i < evts.size(); i++) {
struct op_header_evt_info attr = opHeader.h_attrs[i];
f_attr.attr = attr.attr;
f_attr.ids.size = attr.ids.size() * sizeof(u64);
add_to_total(op_write_output(output_fd, &f_attr, sizeof(f_attr)));
}
for (unsigned i = 0; i < evts.size(); i++) {
add_to_total(op_write_output(output_fd, &opHeader.h_attrs[i].ids[0],
opHeader.h_attrs[i].ids.size() * sizeof(u64)));
}
}
int operf_record::prepareToRecord(int cpu, int fd)
{
struct mmap_data md;;
md.prev = 0;
md.mask = num_mmap_pages * pagesize - 1;
fcntl(fd, F_SETFL, O_NONBLOCK);
poll_data[cpu].fd = fd;
poll_data[cpu].events = POLLIN;
poll_count++;
md.base = mmap(NULL, (num_mmap_pages + 1) * pagesize,
PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (md.base == MAP_FAILED) {
perror("failed to mmap");
return -1;
}
samples_array.push_back(md);
return 0;
}
void operf_record::setup()
{
bool all_cpus_avail = true;
int rc = 0;
struct dirent *entry = NULL;
DIR *dir = NULL;
string err_msg;
char cpus_online[129];
bool need_IOC_enable = (system_wide || pid_started);
if (system_wide)
cverb << vperf << "operf_record::setup() for system-wide profiling" << endl;
else
cverb << vperf << "operf_record::setup() with pid_started = " << pid_started << endl;
if (!system_wide && pid_started) {
/* We need to verify the existence of the passed PID before trying
* perf_event_open or all hell will break loose.
*/
char fname[PATH_MAX];
FILE *fp;
snprintf(fname, sizeof(fname), "/proc/%d/status", pid);
fp = fopen(fname, "r");
if (fp == NULL) {
// Process must have finished or invalid PID passed into us.
// We'll bail out now.
cerr << "Unable to find process information for PID " << pid << "." << endl;
cverb << vperf << "couldn't open " << fname << endl;
return;
}
}
pagesize = sysconf(_SC_PAGE_SIZE);
num_mmap_pages = (512 * 1024)/pagesize;
num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
if (!num_cpus)
throw runtime_error("Number of online CPUs is zero; cannot continue");;
poll_data = new struct pollfd [num_cpus];
cverb << vperf << "calling perf_event_open for pid " << pid << " on "
<< num_cpus << " cpus" << endl;
FILE * online_cpus = fopen("/sys/devices/system/cpu/online", "r");
if (!online_cpus) {
fclose(online_cpus);
err_msg = "Internal Error: Number of online cpus cannot be determined.";
rc = -1;
goto error;
}
memset(cpus_online, 0, sizeof(cpus_online));
fgets(cpus_online, sizeof(cpus_online), online_cpus);
if (!cpus_online[0]) {
fclose(online_cpus);
err_msg = "Internal Error: Number of online cpus cannot be determined.";
rc = -1;
goto error;
}
if (index(cpus_online, ',')) {
all_cpus_avail = false;
dir = opendir("/sys/devices/system/cpu");
}
fclose(online_cpus);
for (int cpu = 0; cpu < num_cpus; cpu++) {
int real_cpu;
int mmap_fd;
bool mmap_done_for_cpu = false;
if (all_cpus_avail) {
real_cpu = cpu;
} else {
real_cpu = op_get_next_online_cpu(dir, entry);
if (real_cpu < 0) {
closedir(dir);
err_msg = "Internal Error: Number of online cpus cannot be determined.";
rc = -1;
goto error;
}
}
// Create new row to hold operf_counter objects since we need one
// row for each cpu. Do the same for samples_array.
vector<operf_counter> tmp_pcvec;
perfCounters.push_back(tmp_pcvec);
for (unsigned event = 0; event < evts.size(); event++) {
evts[event].counter = event;
perfCounters[cpu].push_back(operf_counter(evts[event],
(!pid_started && !system_wide),
callgraph, separate_cpu));
if ((rc = perfCounters[cpu][event].perf_event_open(pid, real_cpu, event, this)) < 0) {
err_msg = "Internal Error. Perf event setup failed.";
goto error;
}
if (!mmap_done_for_cpu) {
if (((rc = prepareToRecord(cpu, perfCounters[cpu][event].get_fd()))) < 0) {
err_msg = "Internal Error. Perf event setup failed.";
goto error;
}
mmap_fd = perfCounters[cpu][event].get_fd();
mmap_done_for_cpu = true;
} else {
if (ioctl(perfCounters[cpu][event].get_fd(),
PERF_EVENT_IOC_SET_OUTPUT, mmap_fd) < 0)
goto error;
}
if (need_IOC_enable)
if (ioctl(perfCounters[cpu][event].get_fd(), PERF_EVENT_IOC_ENABLE) < 0)
goto error;
}
}
if (!all_cpus_avail)
closedir(dir);
write_op_header_info();
// Set bit to indicate we're set to go.
valid = true;
return;
error:
delete[] poll_data;
for (int i = 0; i < samples_array.size(); i++) {
struct mmap_data *md = &samples_array[i];
munmap(md->base, (num_mmap_pages + 1) * pagesize);
}
samples_array.clear();
close(output_fd);
if (rc != OP_PERF_HANDLED_ERROR)
throw runtime_error(err_msg);
}
void operf_record::recordPerfData(void)
{
bool disabled = false;
if (pid_started || system_wide) {
if (op_record_process_info(system_wide, pid, this, output_fd) < 0) {
for (int i = 0; i < num_cpus; i++) {
for (unsigned int evt = 0; evt < evts.size(); evt++)
ioctl(perfCounters[i][evt].get_fd(), PERF_EVENT_IOC_DISABLE);
}
throw runtime_error("operf_record: error recording process info");
}
}
op_record_kernel_info(vmlinux_file, kernel_start, kernel_end, output_fd, this);
while (1) {
int prev = sample_reads;
for (int i = 0; i < samples_array.size(); i++) {
if (samples_array[i].base)
op_get_kernel_event_data(&samples_array[i], this);
}
if (quit && disabled)
break;
if (prev == sample_reads) {
poll(poll_data, poll_count, -1);
}
if (quit) {
for (int i = 0; i < num_cpus; i++) {
for (unsigned int evt = 0; evt < evts.size(); evt++)
ioctl(perfCounters[i][evt].get_fd(), PERF_EVENT_IOC_DISABLE);
}
disabled = true;
cverb << vperf << "operf_record::recordPerfData received signal to quit." << endl;
}
}
close(output_fd);
cverb << vdebug << "operf recording finished." << endl;
}
void operf_read::init(int sample_data_pipe_fd, string samples_loc, op_cpu cputype, vector<operf_event_t> & events)
{
struct sigaction sa;
sigset_t ss;
sample_data_fd = sample_data_pipe_fd;
sampledir = samples_loc;
evts = events;
cpu_type = cputype;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_sigaction = op_perfread_sigusr1_handler;
sigemptyset(&sa.sa_mask);
sigemptyset(&ss);
sigaddset(&ss, SIGUSR1);
sigprocmask(SIG_UNBLOCK, &ss, NULL);
sa.sa_mask = ss;
sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
cverb << vperf << "operf-read calling sigaction" << endl;
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
cverb << vperf << "operf-read init: sigaction failed; errno is: "
<< strerror(errno) << endl;
_exit(EXIT_FAILURE);
}
}
operf_read::~operf_read()
{
evts.clear();
}
int operf_read::readPerfHeader(void)
{
struct OP_file_header fheader;
string errmsg;
int num_fattrs;
size_t fattr_size;
vector<struct op_file_attr> f_attr_cache;
errno = 0;
if (read(sample_data_fd, &fheader, sizeof(fheader)) != sizeof(fheader)) {
errmsg = "Error reading header on sample data pipe: " + string(strerror(errno));
goto fail;
}
if (memcmp(&fheader.magic, __op_magic, sizeof(fheader.magic))) {
errmsg = "Error: operf sample data does not have expected header data";
goto fail;
}
cverb << vperf << "operf magic number " << (char *)&fheader.magic << " matches expected __op_magic " << __op_magic << endl;
fattr_size = sizeof(struct op_file_attr);
if (fattr_size != fheader.attr_size) {
errmsg = "Error: perf_events binary incompatibility. Event data collection was apparently "
"performed under a different kernel version than current.";
goto fail;
}
num_fattrs = fheader.attrs.size/fheader.attr_size;
cverb << vperf << "num_fattrs is " << num_fattrs << endl;
for (int i = 0; i < num_fattrs; i++) {
struct op_file_attr f_attr;
streamsize fattr_size = sizeof(f_attr);
if (read(sample_data_fd, (char *)&f_attr, fattr_size) != fattr_size) {
errmsg = "Error reading file attr on sample data pipe: " + string(strerror(errno));
goto fail;
}
opHeader.h_attrs[i].attr = f_attr.attr;
f_attr_cache.push_back(f_attr);
}
for (int i = 0; i < num_fattrs; i++) {
vector<struct op_file_attr>::iterator it = f_attr_cache.begin();
struct op_file_attr f_attr = *(it);
int num_ids = f_attr.ids.size/sizeof(u64);
for (int id = 0; id < num_ids; id++) {
u64 perf_id;
streamsize perfid_size = sizeof(perf_id);
if (read(sample_data_fd, (char *)& perf_id, perfid_size) != perfid_size) {
errmsg = "Error reading perf ID on sample data pipe: " + string(strerror(errno));
goto fail;
}
cverb << vperf << "Perf header: id = " << hex << (unsigned long long)perf_id << endl;
opHeader.h_attrs[i].ids.push_back(perf_id);
}
}
valid = true;
cverb << vperf << "Successfully read perf header" << endl;
return 0;
fail:
cerr << errmsg;
return -1;
}
int operf_read::get_eventnum_by_perf_event_id(u64 id) const
{
for (unsigned i = 0; i < evts.size(); i++) {
struct op_header_evt_info attr = opHeader.h_attrs[i];
for (unsigned j = 0; j < attr.ids.size(); j++) {
if (attr.ids[j] == id)
return i;
}
}
return -1;
}
int operf_read::_get_one_perf_event(event_t * event)
{
static size_t pe_header_size = sizeof(perf_event_header);
char * evt = (char *)event;
ssize_t num_read;
perf_event_header * header = (perf_event_header *)event;
/* A signal handler was setup for the operf_read process to handle interrupts
* (i.e., from ctrl-C), so the read syscalls below may get interrupted. But the
* operf_read process should ignore the interrupt and continue processing
* until there's no more data to read or until the parent operf process
* forces us to stop. So we must try the read operation again if it was
* interrupted.
*/
again:
errno = 0;
if ((num_read = read(sample_data_fd, header, pe_header_size)) < 0) {
cverb << vdebug << "Read 1 of sample data pipe returned with " << strerror(errno) << endl;
if (errno == EINTR)
goto again;
else
return -1;
} else if (num_read == 0) {
return -1;
}
evt += pe_header_size;
if (!header->size)
return -1;
again2:
if ((num_read = read(sample_data_fd, evt, header->size - pe_header_size)) < 0) {
cverb << vdebug << "Read 2 of sample data pipe returned with " << strerror(errno) << endl;
if (errno == EINTR)
goto again2;
else
return -1;
} else if (num_read == 0) {
return -1;
}
return 0;
}
int operf_read::convertPerfData(void)
{
int num_bytes = 0;
// Allocate way more than enough space for a really big event with a long callchain
event_t * event = (event_t *)xmalloc(65536);
for (int i = 0; i < OPERF_MAX_STATS; i++)
operf_stats[i] = 0;
cverb << vdebug << "Converting operf data to oprofile sample data format" << endl;
cverb << vdebug << "sample type is " << hex << opHeader.h_attrs[0].attr.sample_type << endl;
first_time_processing = true;
memset(event, '\0', 65536);
while (1) {
streamsize rec_size = 0;
if (_get_one_perf_event(event) < 0) {
break;
}
rec_size = event->header.size;
op_write_event(event, opHeader.h_attrs[0].attr.sample_type);
num_bytes += rec_size;
}
first_time_processing = false;
op_reprocess_unresolved_events(opHeader.h_attrs[0].attr.sample_type);
op_release_resources();
operf_print_stats(operf_options::session_dir, start_time_human_readable, throttled);
char * cbuf;
cbuf = (char *)xmalloc(operf_options::session_dir.length() + 5);
strcpy(cbuf, operf_options::session_dir.c_str());
strcat(cbuf, "/abi");
op_write_abi_to_file(cbuf);
free(cbuf);
free(event);
return num_bytes;
}

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

JavaScript is required for this form.





No, thanks