pfm_instance::pfm_instance() { int ret = pfm_initialize(); if (ret != PFM_SUCCESS) errx(1, "cannot initialize library: %s", pfm_strerror(ret)); return; }
void perfevent_initialize(char*events) { int i, ret; perfevent_events = strdup(events); /* * Initialize pfm library (required before we can use it) */ ret = pfm_initialize(); if (ret != PFM_SUCCESS) errx(1, "Cannot initialize library: %s", pfm_strerror(ret)); ret = perf_setup_list_events(events, &perfevent_fds, &perfevent_num_fds); if (ret || !perfevent_num_fds) errx(1, "cannot setup events"); perfevent_fds[0].fd = -1; for(i=0; i < perfevent_num_fds; i++) { /* request timing information necessary for scaling */ perfevent_fds[i].hw.read_format = PERF_FORMAT_SCALE; perfevent_fds[i].hw.disabled = (i == 0); /* do not start now */ perfevent_fds[i].hw.inherit = 1; /* pass on to child threads */ /* each event is in an independent group (multiplexing likely) */ perfevent_fds[i].fd = perf_event_open(&perfevent_fds[i].hw, 0, -1, perfevent_fds[0].fd, 0); if (perfevent_fds[i].fd == -1) err(1, "cannot open event %d", i); } }
int perf_event_open_pfm(const char *str, int group_fd) { struct perf_event_attr attr; pfm_perf_encode_arg_t arg; // Clear memset(&attr, 0, sizeof(attr)); attr.size = sizeof(attr); memset(&arg, 0, sizeof(arg)); arg.size = sizeof(arg); arg.attr = &attr; // Use pfm to populate "attr" if (!pfm_initialized) { if (pfm_initialize() != PFM_SUCCESS) return -2; pfm_initialized = 1; } if (pfm_get_os_event_encoding(str, PFM_PLM0 | PFM_PLM3, PFM_OS_PERF_EVENT, &arg) != PFM_SUCCESS) return -2; #ifdef LOG_PFM_DECODE printf("PFM decode %s = %lx %lx %lx %lx\n", str, attr.type, attr.config, attr.config1, attr.config2); #endif // Generate event return perf_event_open_gen(&attr, group_fd); }
int main(int argc, char **argv) { pfmlib_options_t pfmlib_options; unsigned long delay; pid_t pid; int ret; if (argc < 2) fatal_error("usage: %s pid [timeout]\n", argv[0]); pid = atoi(argv[1]); delay = argc > 2 ? strtoul(argv[2], NULL, 10) : 10; /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfm_set_options(&pfmlib_options); /* * Initialize pfm library (required before we can use it) */ ret = pfm_initialize(); if (ret != PFMLIB_SUCCESS) fatal_error("Cannot initialize library: %s\n", pfm_strerror(ret)); return parent(pid, delay); }
int main(int argc, char **argv) { pfmlib_options_t pfmlib_options; if (argc < 2) fatal_error("You must specify a command to execute\n"); /* * Initialize pfm library (required before we can use it) */ if (pfm_initialize() != PFMLIB_SUCCESS) { fatal_error("Can't initialize library\n"); } /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfmlib_options.pfm_verbose = 0; /* set to 1 for verbose */ pfm_set_options(&pfmlib_options); return mainloop(argv+1); }
int measure(pid_t pid) { perf_event_desc_t *fds = NULL; int i, ret, num_fds = 0; char fn[32]; if (pfm_initialize() != PFM_SUCCESS) errx(1, "libpfm initialization failed\n"); ret = perf_setup_list_events(options.events, &fds, &num_fds); if (ret || (num_fds == 0)) exit(1); fds[0].fd = -1; for(i=0; i < num_fds; i++) { fds[i].hw.disabled = 0; /* start immediately */ /* request timing information necessary for scaling counts */ fds[i].hw.read_format = PERF_FORMAT_SCALE; fds[i].hw.pinned = !i && options.pinned; fds[i].fd = perf_event_open(&fds[i].hw, pid, -1, (options.group? fds[0].fd : -1), 0); if (fds[i].fd == -1) errx(1, "cannot attach event %s", fds[i].name); } /* * no notification is generated by perf_counters * when the monitored thread exits. Thus we need * to poll /proc/ to detect it has disappeared, * otherwise we have to wait until the end of the * timeout */ sprintf(fn, "/proc/%d/status", pid); while(access(fn, F_OK) == 0 && options.delay) { sleep(1); options.delay--; if (options.print) print_counts(fds, num_fds, 1); } if (options.delay) warn("thread %d terminated before timeout", pid); if (!options.print) print_counts(fds, num_fds, 0); for(i=0; i < num_fds; i++) close(fds[i].fd); free(fds); /* free libpfm resources cleanly */ pfm_terminate(); return 0; }
void perf_init() { static int init = 0; if (init) return; init = 1; char* prof_envvar = getenv("MXPA_PROFILE"); if (prof_envvar) { enabled = 1; } else { return; } pfm_initialize(); }
void perfctr_init() { int i; if (!initialized) { char *buf = malloc(64); printf("Initializing performance counters\n"); printf("Stack address %p, heap %p\n", &buf, buf); free(buf); get_events(); /* * Initialize libpfm library (required before we can use it) */ int ret = pfm_initialize(); if (ret != PFM_SUCCESS) errx(1, "cannot initialize library: %s", pfm_strerror(ret)); for (i = 0; i < g_num_events; i++) { g_event_counts[i] = 0; } pthread_mutex_init(&count_lock, NULL); initialized = 1; } }
int main(int argc, char **argv) { unsigned int i, cnum = 0; pfarg_reg_t pc[NUM_PMCS]; pfmlib_regmask_t impl_pmcs; unsigned int num_pmcs; /* * Initialize pfm library (required before we can use it) */ if (pfm_initialize() != PFMLIB_SUCCESS) { printf("Can't initialize library\n"); exit(1); } memset(&impl_pmcs, 0, sizeof(impl_pmcs)); memset(pc, 0, sizeof(pc)); pfm_get_impl_pmcs(&impl_pmcs); pfm_get_num_pmcs(&num_pmcs); for(i=0; num_pmcs ; i++) { if (pfm_regmask_isset(&impl_pmcs, i) == 0) continue; pc[cnum++].reg_num = i; num_pmcs--; } if (perfmonctl(0, PFM_GET_PMC_RESET_VAL, pc, cnum) == -1 ) { if (errno == ENOSYS) { fatal_error("Your kernel does not have performance monitoring support!\n"); } fatal_error("cannot get reset values: %s\n", strerror(errno)); } for (i=0; i < cnum; i++) { printf("PMC%u 0x%lx\n", pc[i].reg_num, pc[i].reg_value); } return 0; }
EXTERNAL void sysPerfEventInit(int numEvents) { int i; TRACE_PRINTF("%s: sysPerfEventInit\n", Me); int ret = pfm_initialize(); if (ret != PFM_SUCCESS) { errx(1, "error in pfm_initialize: %s", pfm_strerror(ret)); } perf_event_fds = (int*)checkCalloc(numEvents, sizeof(int)); if (!perf_event_fds) { errx(1, "error allocating perf_event_fds"); } perf_event_attrs = (struct perf_event_attr *)checkCalloc(numEvents, sizeof(struct perf_event_attr)); if (!perf_event_attrs) { errx(1, "error allocating perf_event_attrs"); } for(i = 0; i < numEvents; i++) { perf_event_attrs[i].size = sizeof(struct perf_event_attr); } enabled = 1; }
int pfm_init_counters(const char** counters) { #ifdef VERBOSE fprintf(stderr, "Initing counters\n"); #endif /* Initialize pfm library */ int i,ret; ret = pfm_initialize(); if (ret != PFM_SUCCESS) { fprintf(stderr, "Cannot initialize libpfm: %s\n", pfm_strerror(ret)); return -1; } ret = perf_setup_argv_events(counters, &fds, &num_fds); if (ret || !num_fds) { fprintf(stderr, "Cannot setup events\n"); return -1; } fds[0].fd = -1; for (i=0; i < num_fds; i++) { /* request timing information necessary for scaling */ fds[i].hw.read_format = PERF_FORMAT_SCALE; fds[i].hw.disabled = 1; /* start paused */ fds[i].fd = perf_event_open(&fds[i].hw, 0, -1, -1, 0); if (fds[i].fd == -1) { fprintf(stderr, "Cannot open event %d\n", i); return -1; } } counter_values = (uint64_t*) malloc(num_fds * sizeof(uint64_t)); return 0; }
int main(void) { int ret; int type = 0; pid_t pid = getpid(); pfmlib_ita2_param_t ita_param; pfarg_reg_t pd[NUM_PMDS]; pfarg_context_t ctx[1]; pfmlib_options_t pfmlib_options; struct sigaction act; /* * Initialize pfm library (required before we can use it) */ if (pfm_initialize() != PFMLIB_SUCCESS) { fatal_error("Can't initialize library\n"); } /* * Let's make sure we run this on the right CPU */ pfm_get_pmu_type(&type); if (type != PFMLIB_ITANIUM2_PMU) { char *model; pfm_get_pmu_name(&model); fatal_error("this program does not work with %s PMU\n", model); } /* * Install the overflow handler (SIGPROF) */ memset(&act, 0, sizeof(act)); act.sa_handler = (sig_t)overflow_handler; sigaction (SIGPROF, &act, 0); /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfmlib_options.pfm_verbose = 0; /* set to 1 for debug */ pfm_set_options(&pfmlib_options); memset(pd, 0, sizeof(pd)); memset(ctx, 0, sizeof(ctx)); /* * prepare parameters to library. we don't use any Itanium * specific features here. so the pfp_model is NULL. */ memset(&evt,0, sizeof(evt)); memset(&ita_param,0, sizeof(ita_param)); /* * because we use a model specific feature, we must initialize the * model specific pfmlib parameter structure and link it to the * common structure. * The magic number is a simple mechanism used by the library to check * that the model specific data structure is decent. You must set it manually * otherwise the model specific feature won't work. */ ita_param.pfp_magic = PFMLIB_ITA2_PARAM_MAGIC; evt.pfp_model = &ita_param; /* * Before calling pfm_find_dispatch(), we must specify what kind * of branches we want to capture. We are interesteed in all the mispredicted branches, * therefore we program we set the various fields of the BTB config to: */ ita_param.pfp_ita2_btb.btb_used = 1; ita_param.pfp_ita2_btb.btb_ds = 0; ita_param.pfp_ita2_btb.btb_tm = 0x3; ita_param.pfp_ita2_btb.btb_ptm = 0x3; ita_param.pfp_ita2_btb.btb_ppm = 0x3; ita_param.pfp_ita2_btb.btb_brt = 0x0; ita_param.pfp_ita2_btb.btb_plm = PFM_PLM3; /* * To count the number of occurence of this instruction, we must * program a counting monitor with the IA64_TAGGED_INST_RETIRED_PMC8 * event. */ if (pfm_find_event_byname("BRANCH_EVENT", &evt.pfp_events[0].event) != PFMLIB_SUCCESS) { fatal_error("cannot find event BRANCH_EVENT\n"); } /* * set the (global) privilege mode: * PFM_PLM3 : user level only */ evt.pfp_dfl_plm = PFM_PLM3; /* * how many counters we use */ evt.pfp_event_count = 1; /* * let the library figure out the values for the PMCS */ if ((ret=pfm_dispatch_events(&evt)) != PFMLIB_SUCCESS) { fatal_error("cannot configure events: %s\n", pfm_strerror(ret)); } /* * for this example, we will get notified ONLY when the sampling * buffer is full. The monitoring is not to be inherited * in derived tasks */ ctx[0].ctx_flags = PFM_FL_INHERIT_NONE; ctx[0].ctx_notify_pid = getpid(); ctx[0].ctx_smpl_entries = SMPL_BUF_NENTRIES; ctx[0].ctx_smpl_regs[0] = smpl_regs = BTB_REGS_MASK; /* * now create the context for self monitoring/per-task */ if (perfmonctl(pid, PFM_CREATE_CONTEXT, ctx, 1) == -1 ) { if (errno == ENOSYS) { fatal_error("Your kernel does not have performance monitoring support!\n"); } fatal_error("Can't create PFM context %s\n", strerror(errno)); } printf("Sampling buffer mapped at %p\n", ctx[0].ctx_smpl_vaddr); smpl_vaddr = ctx[0].ctx_smpl_vaddr; /* * Must be done before any PMD/PMD calls (unfreeze PMU). Initialize * PMC/PMD to safe values. psr.up is cleared. */ if (perfmonctl(pid, PFM_ENABLE, NULL, 0) == -1) { fatal_error("perfmonctl error PFM_ENABLE errno %d\n",errno); } /* * indicate we want notification when buffer is full */ evt.pfp_pc[0].reg_flags |= PFM_REGFL_OVFL_NOTIFY; /* * Now prepare the argument to initialize the PMD and the sampling period */ pd[0].reg_num = evt.pfp_pc[0].reg_num; pd[0].reg_value = (~0UL) - SMPL_PERIOD +1; pd[0].reg_long_reset = (~0UL) - SMPL_PERIOD +1; pd[0].reg_short_reset = (~0UL) - SMPL_PERIOD +1; /* * When our counter overflows, we want to BTB index to be reset, so that we keep * in sync. This is required to make it possible to interpret pmd16 on overflow * to avoid repeating the same branch several times. */ evt.pfp_pc[0].reg_reset_pmds[0] = M_PMD(16); /* * reset pmd16, short and long reset value are set to zero as well */ pd[1].reg_num = 16; pd[1].reg_value = 0UL; /* * Now program the registers * * We don't use the save variable to indicate the number of elements passed to * the kernel because, as we said earlier, pc may contain more elements than * the number of events we specified, i.e., contains more thann coutning monitors. */ if (perfmonctl(pid, PFM_WRITE_PMCS, evt.pfp_pc, evt.pfp_pc_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno); } if (perfmonctl(pid, PFM_WRITE_PMDS, pd, 2) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno); } /* * Let's roll now. */ do_test(100000); /* * We must call the processing routine to cover the last entries recorded * in the sampling buffer, i.e. which may not be full */ process_smpl_buffer(); /* * let's stop this now */ if (perfmonctl(pid, PFM_DESTROY_CONTEXT, NULL, 0) == -1) { fatal_error("perfmonctl error PFM_DESTROY errno %d\n",errno); } return 0; }
static void measure(void) { perf_event_desc_t *fds = NULL; int num_fds = 0; uint64_t values[3]; ssize_t n; int i, ret; int pr[2], pw[2]; pid_t pid; char cc = '0'; ret = pfm_initialize(); if (ret != PFM_SUCCESS) err(1, "cannot initialize libpfm"); if (options.cpu == -1) { srandom(getpid()); options.cpu = random() % sysconf(_SC_NPROCESSORS_ONLN); } ret = pipe(pr); if (ret) err(1, "cannot create read pipe"); ret = pipe(pw); if (ret) err(1, "cannot create write pipe"); ret = perf_setup_list_events(options.events, &fds, &num_fds); if (ret || !num_fds) exit(1); for(i=0; i < num_fds; i++) { fds[i].hw.disabled = 1; fds[i].hw.read_format = PERF_FORMAT_SCALE; fds[i].fd = perf_event_open(&fds[i].hw, 0, -1, -1, 0); if (fds[i].fd == -1) err(1, "cannot open event %d", i); } /* * Pin to CPU0, inherited by child process. That will enforce * the ping-pionging and thus stress the PMU context switch * which is what we want */ ret = pin_cpu(getpid(), options.cpu); if (ret) err(1, "cannot pin to CPU%d", options.cpu); printf("Both processes pinned to CPU%d, running for %d seconds\n", options.cpu, options.delay); /* * create second process which is not monitoring at the moment */ switch(pid=fork()) { case -1: err(1, "cannot create child\n"); case 0: /* do not inherit session fd */ for(i=0; i < num_fds; i++) close(fds[i].fd); /* pr[]: write master, read child */ /* pw[]: read master, write child */ close(pr[1]); close(pw[0]); do_child(pr[0], pw[1]); exit(1); } close(pr[0]); close(pw[1]); /* * Let's roll now */ prctl(PR_TASK_PERF_EVENTS_ENABLE); signal(SIGALRM, sig_handler); alarm(options.delay); /* * ping pong loop */ while(!quit) { n = write(pr[1], "c", 1); if (n < 1) err(1, "write failed"); n = read(pw[0], &cc, 1); if (n < 1) err(1, "read failed"); } prctl(PR_TASK_PERF_EVENTS_DISABLE); for(i=0; i < num_fds; i++) { uint64_t val; double ratio; ret = read(fds[i].fd, values, sizeof(values)); if (ret == -1) err(1,"pfm_read error"); if (ret != sizeof(values)) errx(1, "did not read correct amount %d", ret); val = perf_scale(values); ratio = perf_scale_ratio(values); if (ratio == 1.0) printf("%20"PRIu64" %s\n", val, fds[i].name); else if (ratio == 0.0) printf("%20"PRIu64" %s (did not run: competing session)\n", val, fds[i].name); else printf("%20"PRIu64" %s (scaled from %.2f%% of time)\n", val, fds[i].name, ratio*100.0); } /* * kill child process */ kill(SIGKILL, pid); /* * close pipes */ close(pr[1]); close(pw[0]); /* * and destroy our session */ for(i=0; i < num_fds; i++) close(fds[i].fd); perf_free_fds(fds, num_fds); /* free libpfm resources cleanly */ pfm_terminate(); }
int mainloop(char **arg) { static uint64_t ovfl_count; /* static to avoid setjmp issue */ struct pollfd pollfds[1]; sigset_t bmask; int go[2], ready[2]; uint64_t *val; size_t sz, pgsz; size_t map_size = 0; pid_t pid; int status, ret; int i; char buf; if (pfm_initialize() != PFM_SUCCESS) errx(1, "libpfm initialization failed\n"); pgsz = sysconf(_SC_PAGESIZE); map_size = (options.mmap_pages+1)*pgsz; /* * does allocate fds */ ret = perf_setup_list_events(options.events, &fds, &num_fds); if (ret || !num_fds) errx(1, "cannot setup event list"); memset(pollfds, 0, sizeof(pollfds)); ret = pipe(ready); if (ret) err(1, "cannot create pipe ready"); ret = pipe(go); if (ret) err(1, "cannot create pipe go"); /* * Create the child task */ if ((pid=fork()) == -1) err(1, "cannot fork process\n"); if (pid == 0) { close(ready[0]); close(go[1]); /* * let the parent know we exist */ close(ready[1]); if (read(go[0], &buf, 1) == -1) err(1, "unable to read go_pipe"); exit(child(arg)); } close(ready[1]); close(go[0]); if (read(ready[0], &buf, 1) == -1) err(1, "unable to read child_ready_pipe"); close(ready[0]); fds[0].fd = -1; if (!fds[0].hw.sample_period) errx(1, "need to set sampling period or freq on first event, use :period= or :freq="); for(i=0; i < num_fds; i++) { if (i == 0) { fds[i].hw.disabled = 1; fds[i].hw.enable_on_exec = 1; /* start immediately */ } else fds[i].hw.disabled = 0; if (options.opt_inherit) fds[i].hw.inherit = 1; if (fds[i].hw.sample_period) { /* * set notification threshold to be halfway through the buffer */ fds[i].hw.wakeup_watermark = (options.mmap_pages*pgsz) / 2; fds[i].hw.watermark = 1; fds[i].hw.sample_type = PERF_SAMPLE_IP|PERF_SAMPLE_TID|PERF_SAMPLE_READ|PERF_SAMPLE_TIME|PERF_SAMPLE_PERIOD|PERF_SAMPLE_STREAM_ID; fprintf(options.output_file,"%s period=%"PRIu64" freq=%d\n", fds[i].name, fds[i].hw.sample_period, fds[i].hw.freq); fds[i].hw.read_format = PERF_FORMAT_SCALE; if (num_fds > 1) fds[i].hw.read_format |= PERF_FORMAT_GROUP|PERF_FORMAT_ID; if (fds[i].hw.freq) fds[i].hw.sample_type |= PERF_SAMPLE_PERIOD; } fds[i].fd = perf_event_open(&fds[i].hw, pid, options.cpu, fds[0].fd, 0); if (fds[i].fd == -1) { if (fds[i].hw.precise_ip) err(1, "cannot attach event %s: precise mode may not be supported", fds[i].name); err(1, "cannot attach event %s", fds[i].name); } } /* * kernel adds the header page to the size of the mmapped region */ fds[0].buf = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED, fds[0].fd, 0); if (fds[0].buf == MAP_FAILED) err(1, "cannot mmap buffer"); /* does not include header page */ fds[0].pgmsk = (options.mmap_pages*pgsz)-1; /* * send samples for all events to first event's buffer */ for (i = 1; i < num_fds; i++) { if (!fds[i].hw.sample_period) continue; ret = ioctl(fds[i].fd, PERF_EVENT_IOC_SET_OUTPUT, fds[0].fd); if (ret) err(1, "cannot redirect sampling output"); } /* * we are using PERF_FORMAT_GROUP, therefore the structure * of val is as follows: * * { u64 nr; * { u64 time_enabled; } && PERF_FORMAT_ENABLED * { u64 time_running; } && PERF_FORMAT_RUNNING * { u64 value; * { u64 id; } && PERF_FORMAT_ID * } cntr[nr]; * We are skipping the first 3 values (nr, time_enabled, time_running) * and then for each event we get a pair of values. */ if (num_fds > 1) { sz = (3+2*num_fds)*sizeof(uint64_t); val = malloc(sz); if (!val) err(1, "cannot allocate memory"); ret = read(fds[0].fd, val, sz); if (ret == -1) err(1, "cannot read id %zu", sizeof(val)); for(i=0; i < num_fds; i++) { fds[i].id = val[2*i+1+3]; fprintf(options.output_file,"%"PRIu64" %s\n", fds[i].id, fds[i].name); } free(val); } pollfds[0].fd = fds[0].fd; pollfds[0].events = POLLIN; for(i=0; i < num_fds; i++) { ret = ioctl(fds[i].fd, PERF_EVENT_IOC_ENABLE, 0); if (ret) err(1, "cannot enable event %s\n", fds[i].name); } signal(SIGCHLD, cld_handler); close(go[1]); if (setjmp(jbuf) == 1) goto terminate_session; sigemptyset(&bmask); sigaddset(&bmask, SIGCHLD); /* * core loop */ for(;;) { ret = poll(pollfds, 1, -1); if (ret < 0 && errno == EINTR) break; ovfl_count++; ret = sigprocmask(SIG_SETMASK, &bmask, NULL); if (ret) err(1, "setmask"); process_smpl_buf(&fds[0]); ret = sigprocmask(SIG_UNBLOCK, &bmask, NULL); if (ret) err(1, "unblock"); } terminate_session: /* * cleanup child */ wait4(pid, &status, 0, NULL); for(i=0; i < num_fds; i++) close(fds[i].fd); /* check for partial event buffer */ process_smpl_buf(&fds[0]); munmap(fds[0].buf, map_size); perf_free_fds(fds, num_fds); fprintf(options.output_file, "%"PRIu64" samples collected in %"PRIu64" poll events, %"PRIu64" lost samples\n", collected_samples, ovfl_count, lost_samples); /* free libpfm resources cleanly */ pfm_terminate(); fclose(options.output_file); return 0; }
int parent(char **arg) { perf_event_desc_t *fds = NULL; int status, ret, i, num_fds = 0, grp, group_fd; int ready[2], go[2]; char buf; pid_t pid; // output_file = fopen(file_name, "w"); //if (chroot("/home/pittdvs/cpu2006/benchspec/CPU2006/464.h264ref/run/run_base_ref_amd64-m64-gcc42-nn.0000")) // err(1, "err on chroot()"); if (pfm_initialize() != PFM_SUCCESS) errx(1, "libpfm initialization failed"); for (grp = 0; grp < options.num_groups; grp++) { int ret; ret = perf_setup_list_events(options.events[grp], &fds, &num_fds); if (ret || !num_fds) exit(1); } pid = options.pid; if (!pid) { ret = pipe(ready); if (ret) err(1, "cannot create pipe ready"); ret = pipe(go); if (ret) err(1, "cannot create pipe go"); /* * Create the child task */ if ((pid=fork()) == -1) err(1, "Cannot fork process"); /* * and launch the child code * * The pipe is used to avoid a race condition * between for() and exec(). We need the pid * of the new tak but we want to start measuring * at the first user level instruction. Thus we * need to prevent exec until we have attached * the events. */ if (pid == 0) { close(ready[0]); close(go[1]); /* * let the parent know we exist */ close(ready[1]); if (read(go[0], &buf, 1) == -1) err(1, "unable to read go_pipe"); exit(child(arg)); } close(ready[1]); close(go[0]); if (read(ready[0], &buf, 1) == -1) err(1, "unable to read child_ready_pipe"); close(ready[0]); } for(i=0; i < num_fds; i++) { int is_group_leader; /* boolean */ is_group_leader = perf_is_group_leader(fds, i); if (is_group_leader) { /* this is the group leader */ group_fd = -1; } else { group_fd = fds[fds[i].group_leader].fd; } /* * create leader disabled with enable_on-exec */ if (!options.pid) { fds[i].hw.disabled = is_group_leader; fds[i].hw.enable_on_exec = is_group_leader; } fds[i].hw.read_format = PERF_FORMAT_SCALE; /* request timing information necessary for scaling counts */ if (is_group_leader && options.format_group) fds[i].hw.read_format |= PERF_FORMAT_GROUP; if (options.inherit) fds[i].hw.inherit = 1; if (options.pin && is_group_leader) fds[i].hw.pinned = 1; fds[i].fd = perf_event_open(&fds[i].hw, pid, -1, group_fd, 0); if (fds[i].fd == -1) { warn("cannot attach event%d %s", i, fds[i].name); goto error; } } if (!options.pid) close(go[1]); if (options.print) { if (!options.pid) { while(waitpid(pid, &status, WNOHANG) == 0 && quit == 0) { //sleep(1); //usleep(10000); msleep(100); //better_sleep(0.05); // 50ms print_counts(fds, num_fds); } } else { while(quit == 0) { sleep(1); print_counts(fds, num_fds); } } } else { if (!options.pid) waitpid(pid, &status, 0); else pause(); print_counts(fds, num_fds); } for(i=0; i < num_fds; i++) close(fds[i].fd); free(fds); /* free libpfm resources cleanly */ pfm_terminate(); // fclose(output_file); return 0; error: free(fds); if (!options.pid) kill(SIGKILL, pid); /* free libpfm resources cleanly */ pfm_terminate(); // fclose(output_file); return -1; }
// Setup the counters and populate the counters struct with their data void pc_init(counters_t *counters, int pid) { #ifndef __arm__ return; #else int ret; ret = pfm_initialize(); if (ret != PFM_SUCCESS) { errx(1, "cannot initialize library: %s", pfm_strerror(ret)); } // Set values for getting cycle count memset(&counters->cycles.attr, 0, sizeof(counters->cycles.attr)); memset(&counters->l1_misses.attr, 0, sizeof(counters->l1_misses.attr)); memset(&counters->ic.attr, 0, sizeof(counters->ic.attr)); memset(&counters->cycles.arg, 0, sizeof(counters->cycles.arg)); memset(&counters->l1_misses.arg, 0, sizeof(counters->l1_misses.arg)); memset(&counters->ic.arg, 0, sizeof(counters->ic.arg)); counters->cycles.count = 0; counters->l1_misses.count = 0; counters->ic.count = 0; counters->cycles.arg.size = sizeof(counters->cycles.arg); counters->l1_misses.arg.size = sizeof(counters->l1_misses.arg); counters->ic.arg.size = sizeof(counters->ic.arg); counters->cycles.arg.attr = &counters->cycles.attr; counters->l1_misses.arg.attr = &counters->l1_misses.attr; counters->ic.arg.attr = &counters->ic.attr; // Get the encoding for the events // cycles ret = pfm_get_os_event_encoding("cycles", PFM_PLM0|PFM_PLM3, PFM_OS_PERF_EVENT, &counters->cycles.arg); if (ret != PFM_SUCCESS) { err(1,"Cycles: cannot get encoding %s", pfm_strerror(ret)); } // l1 cache misses ret = pfm_get_os_event_encoding("l1-dcache-load-misses", PFM_PLM0|PFM_PLM3, PFM_OS_PERF_EVENT, &counters->l1_misses.arg); if (ret != PFM_SUCCESS) { err(1,"L1 Cache Misses:cannot get encoding %s", pfm_strerror(ret)); } // instruction count misses ret = pfm_get_os_event_encoding("instructions", PFM_PLM0|PFM_PLM3, PFM_OS_PERF_EVENT, &counters->ic.arg); if (ret != PFM_SUCCESS) { err(1,"Instruction Count:cannot get encoding %s", pfm_strerror(ret)); } // Set more options counters->cycles.attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; counters->l1_misses.attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; counters->ic.attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; // do not start immediately after perf_event_open() counters->cycles.attr.disabled = 1; counters->l1_misses.attr.disabled = 1; counters->ic.attr.disabled = 1; // Open the counters counters->cycles.fd = perf_event_open(&counters->cycles.attr, pid, -1, -1, 0); if (counters->cycles.fd < 0) { err(1, "Cycle: cannot create event"); } counters->l1_misses.fd = perf_event_open(&counters->l1_misses.attr, pid, -1, -1, 0); if (counters->l1_misses.fd < 0) { err(1, "L1 miss: cannot create event"); } counters->ic.fd = perf_event_open(&counters->ic.attr, pid, -1, -1, 0); if (counters->ic.fd < 0) { err(1, "Instruction count: cannot create event"); } return; #endif }
int _papi_libpfm_init(papi_vector_t *my_vector, int cidx) { int retval; unsigned int ncnt; unsigned int version; char pmu_name[PAPI_MIN_STR_LEN]; /* The following checks the version of the PFM library against the version PAPI linked to... */ SUBDBG( "pfm_initialize()\n" ); if ( ( retval = pfm_initialize( ) ) != PFMLIB_SUCCESS ) { PAPIERROR( "pfm_initialize(): %s", pfm_strerror( retval ) ); return PAPI_ESYS; } /* Get the libpfm3 version */ SUBDBG( "pfm_get_version(%p)\n", &version ); if ( pfm_get_version( &version ) != PFMLIB_SUCCESS ) { PAPIERROR( "pfm_get_version(%p): %s", version, pfm_strerror( retval ) ); return PAPI_ESYS; } /* Set the version */ sprintf( my_vector->cmp_info.support_version, "%d.%d", PFM_VERSION_MAJOR( version ), PFM_VERSION_MINOR( version ) ); /* Complain if the compiled-against version doesn't match current version */ if ( PFM_VERSION_MAJOR( version ) != PFM_VERSION_MAJOR( PFMLIB_VERSION ) ) { PAPIERROR( "Version mismatch of libpfm: compiled %#x vs. installed %#x\n", PFM_VERSION_MAJOR( PFMLIB_VERSION ), PFM_VERSION_MAJOR( version ) ); return PAPI_ESYS; } /* Always initialize globals dynamically to handle forks properly. */ _perfmon2_pfm_pmu_type = -1; /* Opened once for all threads. */ SUBDBG( "pfm_get_pmu_type(%p)\n", &_perfmon2_pfm_pmu_type ); if ( pfm_get_pmu_type( &_perfmon2_pfm_pmu_type ) != PFMLIB_SUCCESS ) { PAPIERROR( "pfm_get_pmu_type(%p): %s", _perfmon2_pfm_pmu_type, pfm_strerror( retval ) ); return PAPI_ESYS; } pmu_name[0] = '\0'; if ( pfm_get_pmu_name( pmu_name, PAPI_MIN_STR_LEN ) != PFMLIB_SUCCESS ) { PAPIERROR( "pfm_get_pmu_name(%p,%d): %s", pmu_name, PAPI_MIN_STR_LEN, pfm_strerror( retval ) ); return PAPI_ESYS; } SUBDBG( "PMU is a %s, type %d\n", pmu_name, _perfmon2_pfm_pmu_type ); /* Setup presets */ retval = _papi_load_preset_table( pmu_name, _perfmon2_pfm_pmu_type, cidx ); if ( retval ) return retval; /* Fill in cmp_info */ SUBDBG( "pfm_get_num_events(%p)\n", &ncnt ); if ( ( retval = pfm_get_num_events( &ncnt ) ) != PFMLIB_SUCCESS ) { PAPIERROR( "pfm_get_num_events(%p): %s\n", &ncnt, pfm_strerror( retval ) ); return PAPI_ESYS; } SUBDBG( "pfm_get_num_events: %d\n", ncnt ); my_vector->cmp_info.num_native_events = ncnt; num_native_events = ncnt; pfm_get_num_counters( ( unsigned int * ) &my_vector->cmp_info.num_cntrs ); SUBDBG( "pfm_get_num_counters: %d\n", my_vector->cmp_info.num_cntrs ); if ( _papi_hwi_system_info.hw_info.vendor == PAPI_VENDOR_INTEL ) { /* Pentium4 */ if ( _papi_hwi_system_info.hw_info.cpuid_family == 15 ) { PAPI_NATIVE_EVENT_AND_MASK = 0x000000ff; PAPI_NATIVE_UMASK_AND_MASK = 0x0fffff00; PAPI_NATIVE_UMASK_SHIFT = 8; /* Itanium2 */ } else if ( _papi_hwi_system_info.hw_info.cpuid_family == 31 || _papi_hwi_system_info.hw_info.cpuid_family == 32 ) { PAPI_NATIVE_EVENT_AND_MASK = 0x00000fff; PAPI_NATIVE_UMASK_AND_MASK = 0x0ffff000; PAPI_NATIVE_UMASK_SHIFT = 12; } } return PAPI_OK; }
int main(int argc, char **argv) { struct perf_event_attr attr; int fd, ret; uint64_t count = 0, values[3]; setlocale(LC_ALL, ""); /* * Initialize libpfm library (required before we can use it) */ ret = pfm_initialize(); if (ret != PFM_SUCCESS) errx(1, "cannot initialize library: %s", pfm_strerror(ret)); memset(&attr, 0, sizeof(attr)); /* * 1st argument: event string * 2nd argument: default privilege level (used if not specified in the event string) * 3rd argument: the perf_event_attr to initialize */ ret = pfm_get_perf_event_encoding("cycles", PFM_PLM0|PFM_PLM3, &attr, NULL, NULL); if (ret != PFM_SUCCESS) errx(1, "cannot find encoding: %s", pfm_strerror(ret)); /* * request timing information because event may be multiplexed * and thus it may not count all the time. The scaling information * will be used to scale the raw count as if the event had run all * along */ attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_TOTAL_TIME_RUNNING; /* do not start immediately after perf_event_open() */ attr.disabled = 1; /* * create the event and attach to self * Note that it attaches only to the main thread, there is no inheritance * to threads that may be created subsequently. * * if mulithreaded, then getpid() must be replaced by gettid() */ fd = perf_event_open(&attr, getpid(), -1, -1, 0); if (fd < 0) err(1, "cannot create event"); /* * start counting now */ ret = ioctl(fd, PERF_EVENT_IOC_ENABLE, 0); if (ret) err(1, "ioctl(enable) failed"); printf("Fibonacci(%d)=%lu\n", N, fib(N)); /* * stop counting */ ret = ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); if (ret) err(1, "ioctl(disable) failed"); /* * read the count + scaling values * * It is not necessary to stop an event to read its value */ ret = read(fd, values, sizeof(values)); if (ret != sizeof(values)) err(1, "cannot read results: %s", strerror(errno)); /* * scale count * * values[0] = raw count * values[1] = TIME_ENABLED * values[2] = TIME_RUNNING */ if (values[2]) count = (uint64_t)((double)values[0] * values[1]/values[2]); printf("count=%'"PRIu64"\n", count); close(fd); /* free libpfm resources cleanly */ pfm_terminate(); return 0; }
int main(int argc, char **argv) { char **p; int i, ret; pid_t pid = getpid(); pfmlib_param_t evt; pfarg_reg_t pd[NUM_PMDS]; pfarg_context_t ctx[1]; pfmlib_options_t pfmlib_options; /* * Initialize pfm library (required before we can use it) */ if (pfm_initialize() != PFMLIB_SUCCESS) { printf("Can't initialize library\n"); exit(1); } /* * check that the user did not specify too many events */ if (argc-1 > pfm_get_num_counters()) { printf("Too many events specified\n"); exit(1); } /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfm_set_options(&pfmlib_options); memset(pd, 0, sizeof(pd)); memset(ctx, 0, sizeof(ctx)); /* * prepare parameters to library. we don't use any Itanium * specific features here. so the pfp_model is NULL. */ memset(&evt,0, sizeof(evt)); /* * be nice to user! */ p = argc > 1 ? argv+1 : event_list; for (i=0; *p ; i++, p++) { if (pfm_find_event(*p, &evt.pfp_events[i].event) != PFMLIB_SUCCESS) { fatal_error("Cannot find %s event\n", *p); } } /* * set the default privilege mode for all counters: * PFM_PLM3 : user level only */ evt.pfp_dfl_plm = PFM_PLM3; /* * how many counters we use */ evt.pfp_event_count = i; /* * let the library figure out the values for the PMCS */ if ((ret=pfm_dispatch_events(&evt)) != PFMLIB_SUCCESS) { fatal_error("cannot configure events: %s\n", pfm_strerror(ret)); } /* * for this example, we have decided not to get notified * on counter overflows and the monitoring is not to be inherited * in derived tasks. */ ctx[0].ctx_flags = PFM_FL_INHERIT_NONE; /* * now create the context for self monitoring/per-task */ if (perfmonctl(pid, PFM_CREATE_CONTEXT, ctx, 1) == -1 ) { if (errno == ENOSYS) { fatal_error("Your kernel does not have performance monitoring support!\n"); } fatal_error("Can't create PFM context %s\n", strerror(errno)); } /* * Must be done before any PMD/PMD calls (unfreeze PMU). Initialize * PMC/PMD to safe values. psr.up is cleared. */ if (perfmonctl(pid, PFM_ENABLE, NULL, 0) == -1) { fatal_error("perfmonctl error PFM_ENABLE errno %d\n",errno); } /* * Now prepare the argument to initialize the PMDs. * the memset(pd) initialized the entire array to zero already, so * we just have to fill in the register numbers from the pc[] array. */ for (i=0; i < evt.pfp_event_count; i++) { pd[i].reg_num = evt.pfp_pc[i].reg_num; } /* * Now program the registers * * We don't use the save variable to indicate the number of elements passed to * the kernel because, as we said earlier, pc may contain more elements than * the number of events we specified, i.e., contains more thann coutning monitors. */ if (perfmonctl(pid, PFM_WRITE_PMCS, evt.pfp_pc, evt.pfp_pc_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno); } if (perfmonctl(pid, PFM_WRITE_PMDS, pd, evt.pfp_event_count) == -1) { {int i; for(i=0; i < evt.pfp_event_count; i++) printf("pmd%d: 0x%x\n", i, pd[i].reg_flags);} fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno); } /* * Let's roll now */ pfm_start(); noploop(10000000); pfm_stop(); /* * now read the results */ if (perfmonctl(pid, PFM_READ_PMDS, pd, evt.pfp_event_count) == -1) { fatal_error( "perfmonctl error READ_PMDS errno %d\n",errno); return -1; } /* * print the results * * It is important to realize, that the first event we specified may not * be in PMD4. Not all events can be measured by any monitor. That's why * we need to use the pc[] array to figure out where event i was allocated. * */ for (i=0; i < evt.pfp_event_count; i++) { char *name; pfm_get_event_name(evt.pfp_events[i].event, &name); printf("PMD%u %20lu %s\n", pd[i].reg_num, pd[i].reg_value, name); } /* * let's stop this now */ if (perfmonctl(pid, PFM_DESTROY_CONTEXT, NULL, 0) == -1) { fatal_error( "child: perfmonctl error PFM_DESTROY errno %d\n",errno); } return 0; }
int main(int argc, char **argv) { struct sigaction act; uint64_t *val; size_t sz, pgsz; int ret, i; setlocale(LC_ALL, ""); ret = pfm_initialize(); if (ret != PFM_SUCCESS) errx(1, "Cannot initialize library: %s", pfm_strerror(ret)); pgsz = sysconf(_SC_PAGESIZE); /* * Install the signal handler (SIGIO) * need SA_SIGINFO because we need the fd * in the signal handler */ memset(&act, 0, sizeof(act)); act.sa_sigaction = sigio_handler; act.sa_flags = SA_SIGINFO; sigaction (SIGIO, &act, 0); /* * allocates fd for us */ ret = perf_setup_list_events("cycles," "instructions", &fds, &num_fds); if (ret || (num_fds == 0)) exit(1); fds[0].fd = -1; for(i=0; i < num_fds; i++) { /* want a notification for every each added to the buffer */ fds[i].hw.disabled = !i; if (!i) { fds[i].hw.wakeup_events = 1; fds[i].hw.sample_type = PERF_SAMPLE_IP|PERF_SAMPLE_READ|PERF_SAMPLE_PERIOD; fds[i].hw.sample_period = SMPL_PERIOD; /* read() returns event identification for signal handler */ fds[i].hw.read_format = PERF_FORMAT_GROUP|PERF_FORMAT_ID|PERF_FORMAT_SCALE; } fds[i].fd = perf_event_open(&fds[i].hw, 0, -1, fds[0].fd, 0); if (fds[i].fd == -1) err(1, "cannot attach event %s", fds[i].name); } sz = (3+2*num_fds)*sizeof(uint64_t); val = malloc(sz); if (!val) err(1, "cannot allocated memory"); /* * On overflow, the non lead events are stored in the sample. * However we need some key to figure the order in which they * were laid out in the buffer. The file descriptor does not * work for this. Instead, we extract a unique ID for each event. * That id will be part of the sample for each event value. * Therefore we will be able to match value to events * * PERF_FORMAT_ID: returns unique 64-bit identifier in addition * to event value. */ ret = read(fds[0].fd, val, sz); if (ret == -1) err(1, "cannot read id %zu", sizeof(val)); /* * we are using PERF_FORMAT_GROUP, therefore the structure * of val is as follows: * * { u64 nr; * { u64 time_enabled; } && PERF_FORMAT_ENABLED * { u64 time_running; } && PERF_FORMAT_RUNNING * { u64 value; * { u64 id; } && PERF_FORMAT_ID * } cntr[nr]; * We are skipping the first 3 values (nr, time_enabled, time_running) * and then for each event we get a pair of values. */ for(i=0; i < num_fds; i++) { fds[i].id = val[2*i+1+3]; printf("%"PRIu64" %s\n", fds[i].id, fds[i].name); } fds[0].buf = mmap(NULL, (buffer_pages+1)*pgsz, PROT_READ|PROT_WRITE, MAP_SHARED, fds[0].fd, 0); if (fds[0].buf == MAP_FAILED) err(1, "cannot mmap buffer"); fds[0].pgmsk = (buffer_pages * pgsz) - 1; /* * setup asynchronous notification on the file descriptor */ ret = fcntl(fds[0].fd, F_SETFL, fcntl(fds[0].fd, F_GETFL, 0) | O_ASYNC); if (ret == -1) err(1, "cannot set ASYNC"); /* * necessary if we want to get the file descriptor for * which the SIGIO is sent in siginfo->si_fd. * SA_SIGINFO in itself is not enough */ ret = fcntl(fds[0].fd, F_SETSIG, SIGIO); if (ret == -1) err(1, "cannot setsig"); /* * get ownership of the descriptor */ ret = fcntl(fds[0].fd, F_SETOWN, getpid()); if (ret == -1) err(1, "cannot setown"); /* * enable the group for one period */ ret = ioctl(fds[0].fd, PERF_EVENT_IOC_REFRESH , 1); if (ret == -1) err(1, "cannot refresh"); busyloop(); ret = ioctl(fds[0].fd, PERF_EVENT_IOC_DISABLE, 1); if (ret == -1) err(1, "cannot disable"); /* * destroy our session */ for(i=0; i < num_fds; i++) close(fds[i].fd); perf_free_fds(fds, num_fds); free(val); /* free libpfm resources cleanly */ pfm_terminate(); return 0; }
int main(int argc, char **argv) { pfarg_context_t ctx[1]; pfmlib_input_param_t inp; pfmlib_output_param_t outp; pfarg_reg_t pc[NUM_PMCS]; pfarg_load_t load_args; pfmlib_options_t pfmlib_options; struct sigaction act; size_t len; unsigned int i, num_counters; int ret; /* * Initialize pfm library (required before we can use it) */ if (pfm_initialize() != PFMLIB_SUCCESS) { printf("Can't initialize library\n"); exit(1); } /* * Install the signal handler (SIGIO) */ memset(&act, 0, sizeof(act)); act.sa_handler = (sig_t)sigio_handler; sigaction (SIGIO, &act, 0); /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfm_set_options(&pfmlib_options); memset(pc, 0, sizeof(pc)); memset(ctx, 0, sizeof(ctx)); memset(&load_args, 0, sizeof(load_args)); memset(&inp,0, sizeof(inp)); memset(&outp,0, sizeof(outp)); pfm_get_num_counters(&num_counters); if (pfm_get_cycle_event(&inp.pfp_events[0]) != PFMLIB_SUCCESS) fatal_error("cannot find cycle event\n"); if (pfm_get_inst_retired_event(&inp.pfp_events[1]) != PFMLIB_SUCCESS) fatal_error("cannot find inst retired event\n"); i = 2; if (i > num_counters) { i = num_counters; printf("too many events provided (max=%d events), using first %d event(s)\n", num_counters, i); } /* * set the default privilege mode for all counters: * PFM_PLM3 : user level only */ inp.pfp_dfl_plm = PFM_PLM3; /* * how many counters we use */ inp.pfp_event_count = i; /* * how many counters we use */ if (i > 1) { inp.pfp_event_count = i; pfm_get_max_event_name_len(&len); event1_name = malloc(len+1); if (event1_name == NULL) fatal_error("cannot allocate event name\n"); pfm_get_full_event_name(&inp.pfp_events[1], event1_name, len+1); } /* * let the library figure out the values for the PMCS */ if ((ret=pfm_dispatch_events(&inp, NULL, &outp, NULL)) != PFMLIB_SUCCESS) { fatal_error("Cannot configure events: %s\n", pfm_strerror(ret)); } /* * when we know we are self-monitoring and we have only one context, then * when we get an overflow we know where it is coming from. Therefore we can * save the call to the kernel to extract the notification message. By default, * a message is generated. The queue of messages has a limited size, therefore * it is important to clear the queue by reading the message on overflow. Failure * to do so may result in a queue full and you will lose notification messages. * * With the PFM_FL_OVFL_NO_MSG, no message will be queue, but you will still get * the signal. Similarly, the PFM_MSG_END will be generated. */ ctx[0].ctx_flags = PFM_FL_OVFL_NO_MSG; /* * now create the context for self monitoring/per-task */ if (perfmonctl(0, PFM_CREATE_CONTEXT, ctx, 1) == -1 ) { if (errno == ENOSYS) { fatal_error("Your kernel does not have performance monitoring support!\n"); } fatal_error("Can't create PFM context %s\n", strerror(errno)); } ctx_fd = ctx->ctx_fd; /* * Now prepare the argument to initialize the PMDs and PMCS. * We use pfp_pmc_count to determine the number of registers to * setup. Note that this field can be >= pfp_event_count. */ for (i=0; i < outp.pfp_pmc_count; i++) { pc[i].reg_num = outp.pfp_pmcs[i].reg_num; pc[i].reg_value = outp.pfp_pmcs[i].reg_value; } for (i=0; i < inp.pfp_event_count; i++) { pd[i].reg_num = pc[i].reg_num; } /* * We want to get notified when the counter used for our first * event overflows */ pc[0].reg_flags |= PFM_REGFL_OVFL_NOTIFY; pc[0].reg_reset_pmds[0] |= 1UL << outp.pfp_pmcs[1].reg_num; /* * we arm the first counter, such that it will overflow * after SMPL_PERIOD events have been observed */ pd[0].reg_value = (~0UL) - SMPL_PERIOD + 1; pd[0].reg_long_reset = (~0UL) - SMPL_PERIOD + 1; pd[0].reg_short_reset = (~0UL) - SMPL_PERIOD + 1; /* * Now program the registers * * We don't use the save variable to indicate the number of elements passed to * the kernel because, as we said earlier, pc may contain more elements than * the number of events we specified, i.e., contains more than counting monitors. */ if (perfmonctl(ctx_fd, PFM_WRITE_PMCS, pc, outp.pfp_pmc_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno); } if (perfmonctl(ctx_fd, PFM_WRITE_PMDS, pd, inp.pfp_event_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno); } /* * we want to monitor ourself */ load_args.load_pid = getpid(); if (perfmonctl(ctx_fd, PFM_LOAD_CONTEXT, &load_args, 1) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno); } /* * setup asynchronous notification on the file descriptor */ ret = fcntl(ctx_fd, F_SETFL, fcntl(ctx_fd, F_GETFL, 0) | O_ASYNC); if (ret == -1) { fatal_error("cannot set ASYNC: %s\n", strerror(errno)); } /* * get ownership of the descriptor */ ret = fcntl(ctx_fd, F_SETOWN, getpid()); if (ret == -1) { fatal_error("cannot setown: %s\n", strerror(errno)); } /* * Let's roll now */ pfm_self_start(ctx_fd); busyloop(); pfm_self_stop(ctx_fd); /* * free our context */ close(ctx_fd); return 0; }
int main(int argc, char **argv) { pfmlib_input_param_t inp; pfmlib_output_param_t outp; pfmlib_core_input_param_t mod_inp; pfmlib_options_t pfmlib_options; pfarg_pmr_t pc[NUM_PMCS]; pfarg_pmd_attr_t pd[NUM_PMDS]; pfarg_sinfo_t sif; struct pollfd fds; smpl_arg_t buf_arg; pfarg_msg_t msg; smpl_hdr_t *hdr; void *buf_addr; uint64_t pebs_size; pid_t pid; int ret, fd, type; unsigned int i; uint32_t ctx_flags; if (argc < 2) fatal_error("you need to pass a program to sample\n"); if (pfm_initialize() != PFMLIB_SUCCESS) fatal_error("libpfm intialization failed\n"); /* * check we are on an Intel Core PMU */ pfm_get_pmu_type(&type); if (type != PFMLIB_INTEL_CORE_PMU && type != PFMLIB_INTEL_ATOM_PMU) fatal_error("This program only works with an Intel Core processor\n"); /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfmlib_options.pfm_verbose = 1; /* set to 1 for verbose */ pfm_set_options(&pfmlib_options); memset(pd, 0, sizeof(pd)); memset(pc, 0, sizeof(pc)); memset(&inp, 0, sizeof(inp)); memset(&outp, 0, sizeof(outp)); memset(&mod_inp, 0, sizeof(mod_inp)); memset(&sif, 0, sizeof(sif)); memset(&buf_arg, 0, sizeof(buf_arg)); memset(&fds, 0, sizeof(fds)); /* * search for our sampling event */ if (pfm_find_full_event(SMPL_EVENT, &inp.pfp_events[0]) != PFMLIB_SUCCESS) fatal_error("cannot find sampling event %s\n", SMPL_EVENT); inp.pfp_event_count = 1; inp.pfp_dfl_plm = PFM_PLM3; /* * important: inform libpfm we do use PEBS */ mod_inp.pfp_core_pebs.pebs_used = 1; /* * sampling buffer parameters */ pebs_size = 3 * getpagesize(); buf_arg.buf_size = pebs_size; /* * sampling period cannot use more bits than HW counter can supoprt */ buf_arg.cnt_reset = -SMPL_PERIOD; /* * We want a system-wide context for sampling */ ctx_flags = PFM_FL_SYSTEM_WIDE | PFM_FL_SMPL_FMT; /* * trigger notification (interrupt) when reaching the very end of * the buffer */ buf_arg.intr_thres = (pebs_size/sizeof(smpl_entry_t))*90/100; /* * we want to measure CPU0, thus we pin ourself to the CPU before invoking * perfmon. This ensures that the sampling buffer will be allocated on the * same NUMA node. */ ret = pin_cpu(getpid(), 0); if (ret) fatal_error("cannot pin on CPU0"); /* * create session and sampling buffer */ fd = pfm_create(ctx_flags, &sif, FMT_NAME, &buf_arg, sizeof(buf_arg)); if (fd == -1) { if (errno == ENOSYS) { fatal_error("Your kernel does not have performance monitoring support!\n"); } fatal_error("cannot create session %s, maybe you do not have the PEBS sampling format in the kernel.\nCheck /sys/kernel/perfmon/formats\n", strerror(errno)); } /* * map buffer into our address space */ buf_addr = mmap(NULL, (size_t)buf_arg.buf_size, PROT_READ, MAP_PRIVATE, fd, 0); printf("session [%d] buffer mapped @%p\n", fd, buf_addr); if (buf_addr == MAP_FAILED) fatal_error("cannot mmap sampling buffer errno %d\n", errno); hdr = (smpl_hdr_t *)buf_addr; printf("pebs_base=0x%llx pebs_end=0x%llx index=0x%llx\n" "intr=0x%llx version=%u.%u\n" "entry_size=%zu ds_size=%zu\n", (unsigned long long)hdr->ds.pebs_buf_base, (unsigned long long)hdr->ds.pebs_abs_max, (unsigned long long)hdr->ds.pebs_index, (unsigned long long)hdr->ds.pebs_intr_thres, PFM_VERSION_MAJOR(hdr->version), PFM_VERSION_MINOR(hdr->version), sizeof(smpl_entry_t), sizeof(hdr->ds)); if (PFM_VERSION_MAJOR(hdr->version) < 1) fatal_error("invalid buffer format version\n"); /* * get which PMC registers are available */ detect_unavail_pmu_regs(&sif, &inp.pfp_unavail_pmcs, NULL); /* * let libpfm figure out how to assign event onto PMU registers */ if (pfm_dispatch_events(&inp, &mod_inp, &outp, NULL) != PFMLIB_SUCCESS) fatal_error("cannot assign event %s\n", SMPL_EVENT); /* * propagate PMC setup from libpfm to perfmon */ for (i=0; i < outp.pfp_pmc_count; i++) { pc[i].reg_num = outp.pfp_pmcs[i].reg_num; pc[i].reg_value = outp.pfp_pmcs[i].reg_value; /* * must disable 64-bit emulation on the PMC0 counter. * PMC0 is the only counter useable with PEBS. We must disable * 64-bit emulation to avoid getting interrupts for each * sampling period, PEBS takes care of this part. */ if (pc[i].reg_num == 0) pc[i].reg_flags = PFM_REGFL_NO_EMUL64; } /* * propagate PMD set from libpfm to perfmon */ for (i=0; i < outp.pfp_pmd_count; i++) pd[i].reg_num = outp.pfp_pmds[i].reg_num; /* * setup sampling period for first counter * we want notification on overflow, i.e., when buffer is full */ pd[0].reg_flags = PFM_REGFL_OVFL_NOTIFY; pd[0].reg_value = -SMPL_PERIOD; pd[0].reg_long_reset = -SMPL_PERIOD; pd[0].reg_short_reset = -SMPL_PERIOD; /* * Now program the registers */ if (pfm_write(fd, 0, PFM_RW_PMC, pc, outp.pfp_pmc_count * sizeof(*pc)) == -1) fatal_error("pfm_write error errno %d\n",errno); if (pfm_write(fd, 0, PFM_RW_PMD_ATTR, pd, outp.pfp_pmd_count * sizeof(*pd)) == -1) fatal_error("pfm_write(PMD) error errno %d\n",errno); /* * attach the session to CPU0 */ if (pfm_attach(fd, 0, 0) == -1) fatal_error("pfm_attach error errno %d\n",errno); /* * Create the child task */ signal(SIGCHLD, handler); if ((pid=fork()) == -1) fatal_error("Cannot fork process\n"); if (pid == 0) { /* child does not inherit context file descriptor */ close(fd); /* if child is too short-lived we may not measure it */ child(argv+1); } /* * start monitoring */ if (pfm_set_state(fd, 0, PFM_ST_START) == -1) fatal_error("pfm_set_state(start) error errno %d\n",errno); fds.fd = fd; fds.events = POLLIN; /* * core loop */ for(;done == 0;) { /* * Must use a timeout to avoid a race condition * with the SIGCHLD signal */ ret = poll(&fds, 1, 500); /* * if timeout expired, then check done */ if (ret == 0) continue; if (ret == -1) { if(ret == -1 && errno == EINTR) { warning("read interrupted, retrying\n"); continue; } fatal_error("poll failed: %s\n", strerror(errno)); } ret = read(fd, &msg, sizeof(msg)); if (ret == -1) fatal_error("cannot read perfmon msg: %s\n", strerror(errno)); switch(msg.type) { case PFM_MSG_OVFL: /* the sampling buffer is full */ process_smpl_buf(hdr); /* * reactivate monitoring once we are done with the samples * in syste-wide, interface guarantees monitoring is active * upon return from the pfm_restart() syscall */ if (pfm_set_state(fd, 0, PFM_ST_RESTART) == -1) fatal_error("pfm_set_state(restart) error errno %d\n",errno); break; default: fatal_error("unknown message type %d\n", msg.type); } } /* * cleanup child */ waitpid(pid, NULL, 0); /* * stop monitoring, this is required in order to guarantee that the PEBS buffer * header is updated with the latest position, such that we see see the final * samples */ if (pfm_set_state(fd, 0, PFM_ST_STOP) == -1) fatal_error("pfm_set_state(stop) error errno %d\n",errno); /* * check for any leftover samples. Must have monitoring stopped * for this operation to have guarantee it is up to date */ process_smpl_buf(hdr); /* * close session */ close(fd); /* * unmap sampling buffer and actually free the perfmon session */ munmap(buf_addr, (size_t)buf_arg.buf_size); return 0; }
int main(void) { int ret; int type = 0; char *name; pid_t pid = getpid(); pfmlib_param_t evt; pfmlib_ita2_param_t ita2_param; pfarg_reg_t pd[NUM_PMDS]; pfarg_context_t ctx[1]; pfmlib_options_t pfmlib_options; /* * Initialize pfm library (required before we can use it) */ if (pfm_initialize() != PFMLIB_SUCCESS) { fatal_error("Can't initialize library\n"); } /* * Let's make sure we run this on the right CPU */ pfm_get_pmu_type(&type); if (type != PFMLIB_ITANIUM2_PMU) { char *model; pfm_get_pmu_name(&model); fatal_error("this program does not work with the %s PMU\n", model); } /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfmlib_options.pfm_verbose = 0; /* set to 1 for verbose */ pfm_set_options(&pfmlib_options); memset(pd, 0, sizeof(pd)); memset(ctx, 0, sizeof(ctx)); memset(&evt,0, sizeof(evt)); memset(&ita2_param,0, sizeof(ita2_param)); /* * because we use a model specific feature, we must initialize the * model specific pfmlib parameter structure and link it to the * common structure. * The magic number is a simple mechanism used by the library to check * that the model specific data structure is decent. You must set it manually * otherwise the model specific feature won't work. */ ita2_param.pfp_magic = PFMLIB_ITA2_PARAM_MAGIC; evt.pfp_model = &ita2_param; /* * We indicate that we are using the PMC8 opcode matcher. This is required * otherwise the library add PMC8 to the list of PMC to pogram during * pfm_dispatch_events(). */ ita2_param.pfp_ita2_pmc8.opcm_used = 1; /* * We want to match all the br.cloop in our test function. * This branch is an IP-relative branch for which the major * opcode (bits [40-37]=4) and the btype field is 5 (which represents * bits[6-8]) so it is included in the match/mask fields of PMC8. * It is necessarily in a B slot. * * We don't care which operands are used with br.cloop therefore * the mask field of pmc8 is set such that only the 4 bits of the * opcode and 3 bits of btype must match exactly. This is accomplished by * clearing the top 4 bits and bits [6-8] of the mask field and setting the * remaining bits. Similarly, the match field only has the opcode value and btype * set according to the encoding of br.cloop, the * remaining bits are zero. Bit 60 of PMC8 is set to indicate * that we look only in B slots (this is the only possibility for * this instruction anyway). * * So the binary representation of the value for PMC8 is as follows: * * 6666555555555544444444443333333333222222222211111111110000000000 * 3210987654321098765432109876543210987654321098765432109876543210 * ---------------------------------------------------------------- * 0001010000000000000000101000000000000011111111111111000111111000 * * which yields a value of 0x1400028003fff1f8. * * Depending on the level of optimization to compile this code, it may * be that the count reported could be zero, if the compiler uses a br.cond * instead of br.cloop. * * * The 0x1 sets the ig_ad field to make sure we ignore any range restriction. * Also bit 2 must always be set */ ita2_param.pfp_ita2_pmc8.pmc_val = 0x1400028003fff1fa; /* * To count the number of occurence of this instruction, we must * program a counting monitor with the IA64_TAGGED_INST_RETIRED_PMC8 * event. */ if (pfm_find_event_byname("IA64_TAGGED_INST_RETIRED_IBRP0_PMC8", &evt.pfp_events[0].event) != PFMLIB_SUCCESS) { fatal_error("cannot find event IA64_TAGGED_INST_RETIRED_IBRP0_PMC8\n"); } /* * set the privilege mode: * PFM_PLM3 : user level only */ evt.pfp_dfl_plm = PFM_PLM3; /* * how many counters we use */ evt.pfp_event_count = 1; /* * let the library figure out the values for the PMCS */ if ((ret=pfm_dispatch_events(&evt)) != PFMLIB_SUCCESS) { fatal_error("cannot configure events: %s\n", pfm_strerror(ret)); } /* * for this example, we have decided not to get notified * on counter overflows and the monitoring is not to be inherited * in derived tasks */ ctx[0].ctx_flags = PFM_FL_INHERIT_NONE; /* * now create the context for self monitoring/per-task */ if (perfmonctl(pid, PFM_CREATE_CONTEXT, ctx, 1) == -1 ) { if (errno == ENOSYS) { fatal_error("Your kernel does not have performance monitoring support!\n"); } fatal_error("Can't create PFM context %s\n", strerror(errno)); } /* * Must be done before any PMD/PMD calls (unfreeze PMU). Initialize * PMC/PMD to safe values. psr.up is cleared. */ if (perfmonctl(pid, PFM_ENABLE, NULL, 0) == -1) { fatal_error("perfmonctl error PFM_ENABLE errno %d\n",errno); } /* * Now prepare the argument to initialize the PMD. */ pd[0].reg_num = evt.pfp_pc[0].reg_num; /* * Now program the registers * * We don't use the save variable to indicate the number of elements passed to * the kernel because, as we said earlier, pc may contain more elements than * the number of events we specified, i.e., contains more thann coutning monitors. */ if (perfmonctl(pid, PFM_WRITE_PMCS, evt.pfp_pc, evt.pfp_pc_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno); } if (perfmonctl(pid, PFM_WRITE_PMDS, pd, evt.pfp_event_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno); } /* * Let's roll now. */ pfm_start(); do_test(100UL); pfm_stop(); /* * now read the results */ if (perfmonctl(pid, PFM_READ_PMDS, pd, evt.pfp_event_count) == -1) { fatal_error("perfmonctl error READ_PMDS errno %d\n",errno); } /* * print the results */ pfm_get_event_name(evt.pfp_events[0].event, &name); printf("PMD%u %20lu %s\n", pd[0].reg_num, pd[0].reg_value, name); if (pd[0].reg_value != 0) printf("compiler used br.cloop\n"); else printf("compiler did not use br.cloop\n"); /* * let's stop this now */ if (perfmonctl(pid, PFM_DESTROY_CONTEXT, NULL, 0) == -1) { fatal_error("perfmonctl error PFM_DESTROY errno %d\n",errno); } return 0; }
int mainloop(char **arg) { static uint64_t ovfl_count = 0; /* static to avoid setjmp issue */ struct pollfd pollfds[1]; int ret; int fd = -1; int i; if (pfm_initialize() != PFM_SUCCESS) errx(1, "libpfm initialization failed\n"); pgsz = sysconf(_SC_PAGESIZE); map_size = (options.mmap_pages+1)*pgsz; if (options.cgroup) { fd = open_cgroup(options.cgroup); if (fd == -1) err(1, "cannot open cgroup file %s\n", options.cgroup); } setup_cpu(options.cpu, fd); signal(SIGALRM, handler); signal(SIGINT, handler); pollfds[0].fd = fds[0].fd; pollfds[0].events = POLLIN; printf("monitoring on CPU%d, session ending in %ds\n", options.cpu, options.delay); if (setjmp(jbuf) == 1) goto terminate_session; start_cpu(); alarm(options.delay); /* * core loop */ for(;;) { ret = poll(pollfds, 1, -1); if (ret < 0 && errno == EINTR) break; ovfl_count++; process_smpl_buf(&fds[0]); } terminate_session: for(i=0; i < num_fds; i++) close(fds[i].fd); /* check for partial event buffer */ process_smpl_buf(&fds[0]); munmap(fds[0].buf, map_size); free(fds); printf("%"PRIu64" samples collected in %"PRIu64" poll events, %"PRIu64" lost samples\n", collected_samples, ovfl_count, lost_samples); return 0; }
int main(void) { pfmlib_input_param_t inp; pfmlib_output_param_t outp; pfmlib_ita2_input_param_t ita2_inp; pfarg_reg_t pd[NUM_PMDS]; pfarg_reg_t pc[NUM_PMCS]; pfarg_context_t ctx[1]; pfarg_load_t load_args; pfmlib_options_t pfmlib_options; int ret; int type = 0; int id; unsigned int i; char name[MAX_EVT_NAME_LEN]; /* * Initialize pfm library (required before we can use it) */ if (pfm_initialize() != PFMLIB_SUCCESS) { fatal_error("Can't initialize library\n"); } /* * Let's make sure we run this on the right CPU */ pfm_get_pmu_type(&type); if (type != PFMLIB_ITANIUM2_PMU) { char model[MAX_PMU_NAME_LEN]; pfm_get_pmu_name(model, MAX_PMU_NAME_LEN); fatal_error("this program does not work with the %s PMU\n", model); } /* * pass options to library (optional) */ memset(&pfmlib_options, 0, sizeof(pfmlib_options)); pfmlib_options.pfm_debug = 0; /* set to 1 for debug */ pfmlib_options.pfm_verbose = 0; /* set to 1 for verbose */ pfm_set_options(&pfmlib_options); memset(pd, 0, sizeof(pd)); memset(pc, 0, sizeof(pc)); memset(ctx, 0, sizeof(ctx)); memset(&load_args, 0, sizeof(load_args)); memset(&inp,0, sizeof(inp)); memset(&outp,0, sizeof(outp)); memset(&ita2_inp,0, sizeof(ita2_inp)); /* * We indicate that we are using the PMC8 opcode matcher. This is required * otherwise the library add PMC8 to the list of PMC to pogram during * pfm_dispatch_events(). */ ita2_inp.pfp_ita2_pmc8.opcm_used = 1; /* * We want to match all the br.cloop in our test function. * This branch is an IP-relative branch for which the major * opcode (bits [40-37]=4) and the btype field is 5 (which represents * bits[6-8]) so it is included in the match/mask fields of PMC8. * It is necessarily in a B slot. * * We don't care which operands are used with br.cloop therefore * the mask field of pmc8 is set such that only the 4 bits of the * opcode and 3 bits of btype must match exactly. This is accomplished by * clearing the top 4 bits and bits [6-8] of the mask field and setting the * remaining bits. Similarly, the match field only has the opcode value and btype * set according to the encoding of br.cloop, the * remaining bits are zero. Bit 60 of PMC8 is set to indicate * that we look only in B slots (this is the only possibility for * this instruction anyway). * * So the binary representation of the value for PMC8 is as follows: * * 6666555555555544444444443333333333222222222211111111110000000000 * 3210987654321098765432109876543210987654321098765432109876543210 * ---------------------------------------------------------------- * 0001010000000000000000101000000000000011111111111111000111111000 * * which yields a value of 0x1400028003fff1f8. * * Depending on the level of optimization to compile this code, it may * be that the count reported could be zero, if the compiler uses a br.cond * instead of br.cloop. * * * The 0x1 sets the ig_ad field to make sure we ignore any range restriction. * Also bit 2 must always be set */ ita2_inp.pfp_ita2_pmc8.pmc_val = 0x1400028003fff1fa; /* * To count the number of occurence of this instruction, we must * program a counting monitor with the IA64_TAGGED_INST_RETIRED_PMC8 * event. */ if (pfm_find_full_event("IA64_TAGGED_INST_RETIRED_IBRP0_PMC8", &inp.pfp_events[0]) != PFMLIB_SUCCESS) { fatal_error("cannot find event IA64_TAGGED_INST_RETIRED_IBRP0_PMC8\n"); } /* * set the privilege mode: * PFM_PLM3 : user level only */ inp.pfp_dfl_plm = PFM_PLM3; /* * how many counters we use */ inp.pfp_event_count = 1; /* * let the library figure out the values for the PMCS */ if ((ret=pfm_dispatch_events(&inp, &ita2_inp, &outp, NULL)) != PFMLIB_SUCCESS) { fatal_error("cannot configure events: %s\n", pfm_strerror(ret)); } /* * now create the context for self monitoring/per-task */ if (perfmonctl(0, PFM_CREATE_CONTEXT, ctx, 1) == -1 ) { if (errno == ENOSYS) { fatal_error("Your kernel does not have performance monitoring support!\n"); } fatal_error("Can't create PFM context %s\n", strerror(errno)); } /* * extract the unique identifier for our context, a regular file descriptor */ id = ctx[0].ctx_fd; /* * Now prepare the argument to initialize the PMDs and PMCS. * We must pfp_pmc_count to determine the number of PMC to intialize. * We must use pfp_event_count to determine the number of PMD to initialize. * Some events causes extra PMCs to be used, so pfp_pmc_count may be >= pfp_event_count. * * This step is new compared to libpfm-2.x. It is necessary because the library no * longer knows about the kernel data structures. */ for (i=0; i < outp.pfp_pmc_count; i++) { pc[i].reg_num = outp.pfp_pmcs[i].reg_num; pc[i].reg_value = outp.pfp_pmcs[i].reg_value; } /* * the PMC controlling the event ALWAYS come first, that's why this loop * is safe even when extra PMC are needed to support a particular event. */ for (i=0; i < inp.pfp_event_count; i++) { pd[i].reg_num = pc[i].reg_num; } printf("event_count=%d id=%d\n", inp.pfp_event_count, id); /* * Now program the registers * * We don't use the save variable to indicate the number of elements passed to * the kernel because, as we said earlier, pc may contain more elements than * the number of events we specified, i.e., contains more thann coutning monitors. */ if (perfmonctl(id, PFM_WRITE_PMCS, pc, outp.pfp_pmc_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno); } if (perfmonctl(id, PFM_WRITE_PMDS, pd, inp.pfp_event_count) == -1) { fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno); } /* * now we load (i.e., attach) the context to ourself */ load_args.load_pid = getpid(); if (perfmonctl(id, PFM_LOAD_CONTEXT, &load_args, 1) == -1) { fatal_error("perfmonctl error PFM_LOAD_CONTEXT errno %d\n",errno); } /* * Let's roll now. */ pfm_self_start(id); do_test(100UL); pfm_self_stop(id); /* * now read the results */ if (perfmonctl(id, PFM_READ_PMDS, pd, inp.pfp_event_count) == -1) { fatal_error("perfmonctl error READ_PMDS errno %d\n",errno); } /* * print the results */ pfm_get_full_event_name(&inp.pfp_events[0], name, MAX_EVT_NAME_LEN); printf("PMD%u %20lu %s\n", pd[0].reg_num, pd[0].reg_value, name); if (pd[0].reg_value != 0) printf("compiler used br.cloop\n"); else printf("compiler did not use br.cloop\n"); /* * let's stop this now */ close(id); return 0; }
int mainloop(char **arg) { static uint64_t ovfl_count; /* static to avoid setjmp issue */ struct pollfd pollfds[1]; sigset_t bmask; int go[2], ready[2]; size_t pgsz; size_t map_size = 0; pid_t pid; int status, ret; int i; char buf; if (pfm_initialize() != PFM_SUCCESS) errx(1, "libpfm initialization failed\n"); pgsz = sysconf(_SC_PAGESIZE); map_size = (options.mmap_pages+1)*pgsz; /* * does allocate fds */ ret = perf_setup_list_events(options.events, &fds, &num_fds); if (ret || !num_fds) errx(1, "cannot setup event list"); memset(pollfds, 0, sizeof(pollfds)); ret = pipe(ready); if (ret) err(1, "cannot create pipe ready"); ret = pipe(go); if (ret) err(1, "cannot create pipe go"); /* * Create the child task */ // if ((pid=fork()) == -1) // err(1, "cannot fork process\n"); /* if (pid == 0) { close(ready[0]); close(go[1]); */ /* * let the parent know we exist */ /* close(ready[1]); if (read(go[0], &buf, 1) == -1) err(1, "unable to read go_pipe"); exit(child(arg)); } */ int tid; pid = getpid(); tid = gettid(); printf("From C - pid : %d, tid : %d\n",pid, tid); close(ready[1]); close(go[0]); if (read(ready[0], &buf, 1) == -1) err(1, "unable to read child_ready_pipe"); close(ready[0]); fds[0].fd = -1; fds[0].hw.sample_period=10000; if (!fds[0].hw.sample_period) errx(1, "need to set sampling period or freq on first event, use :period= or :freq="); for(i=0; i < num_fds; i++) { if (i == 0) { fds[i].hw.disabled = 1; fds[i].hw.enable_on_exec = 1; /* start immediately */ } else fds[i].hw.disabled = 0; if (options.opt_inherit) fds[i].hw.inherit = 1; if (fds[i].hw.sample_period) { /* * set notification threshold to be halfway through the buffer */ fds[i].hw.wakeup_watermark = (options.mmap_pages*pgsz) / 2; fds[i].hw.watermark = 1; fds[i].hw.sample_type = PERF_SAMPLE_IP|PERF_SAMPLE_TID|PERF_SAMPLE_READ|PERF_SAMPLE_TIME|PERF_SAMPLE_PERIOD; /* * if we have more than one event, then record event identifier to help with parsing */ if (num_fds > 1) fds[i].hw.sample_type |= PERF_SAMPLE_IDENTIFIER; fprintf(options.output_file,"%s period=%"PRIu64" freq=%d\n", fds[i].name, fds[i].hw.sample_period, fds[i].hw.freq); fds[i].hw.read_format = PERF_FORMAT_SCALE; if (fds[i].hw.freq) fds[i].hw.sample_type |= PERF_SAMPLE_PERIOD; fds[i].hw.sample_period=10000; if (options.mem_mode) fds[i].hw.sample_type |= PERF_SAMPLE_WEIGHT | PERF_SAMPLE_DATA_SRC | PERF_SAMPLE_ADDR; if (options.branch_mode) { fds[i].hw.sample_type |= PERF_SAMPLE_BRANCH_STACK; fds[i].hw.branch_sample_type = PERF_SAMPLE_BRANCH_ANY; } } /* * we are grouping the events, so there may be a limit */ fds[i].fd = perf_event_open(&fds[i].hw, tid+1, options.cpu, fds[0].fd, 0); if (fds[i].fd == -1) { if (fds[i].hw.precise_ip) err(1, "cannot attach event %s: precise mode may not be supported", fds[i].name); err(1, "cannot attach event %s", fds[i].name); } } /* * kernel adds the header page to the size of the mmapped region */ fds[0].buf = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED, fds[0].fd, 0); if (fds[0].buf == MAP_FAILED) err(1, "cannot mmap buffer"); /* does not include header page */ fds[0].pgmsk = (options.mmap_pages*pgsz)-1; /* * send samples for all events to first event's buffer */ for (i = 1; i < num_fds; i++) { if (!fds[i].hw.sample_period) continue; ret = ioctl(fds[i].fd, PERF_EVENT_IOC_SET_OUTPUT, fds[0].fd); if (ret) err(1, "cannot redirect sampling output"); } if (num_fds > 1 && fds[0].fd > -1) { for(i = 0; i < num_fds; i++) { /* * read the event identifier using ioctl * new method replaced the trick with PERF_FORMAT_GROUP + PERF_FORMAT_ID + read() */ ret = ioctl(fds[i].fd, PERF_EVENT_IOC_ID, &fds[i].id); if (ret == -1) err(1, "cannot read ID"); fprintf(options.output_file,"ID %"PRIu64" %s\n", fds[i].id, fds[i].name); } } pollfds[0].fd = fds[0].fd; pollfds[0].events = POLLIN; for(i=0; i < num_fds; i++) { ret = ioctl(fds[i].fd, PERF_EVENT_IOC_ENABLE, 0); if (ret) err(1, "cannot enable event %s\n", fds[i].name); } signal(SIGCHLD, cld_handler); close(go[1]); if (setjmp(jbuf) == 1) goto terminate_session; sigemptyset(&bmask); sigaddset(&bmask, SIGCHLD); /* * core loop */ for(;;) { ret = poll(pollfds, 1, -1); if (ret < 0 && errno == EINTR) break; ovfl_count++; ret = sigprocmask(SIG_SETMASK, &bmask, NULL); if (ret) err(1, "setmask"); process_smpl_buf(&fds[0]); ret = sigprocmask(SIG_UNBLOCK, &bmask, NULL); if (ret) err(1, "unblock"); } printf("How was you day??\n"); terminate_session: /* * cleanup child */ wait4(pid, &status, 0, NULL); for(i=0; i < num_fds; i++) close(fds[i].fd); /* check for partial event buffer */ process_smpl_buf(&fds[0]); munmap(fds[0].buf, map_size); perf_free_fds(fds, num_fds); fprintf(options.output_file, "%"PRIu64" samples collected in %"PRIu64" poll events, %"PRIu64" lost samples\n", collected_samples, ovfl_count, lost_samples); /* free libpfm resources cleanly */ pfm_terminate(); fclose(options.output_file); return 0; }
int main(int argc, char **argv) { pfarg_ctx_t ctx; pfarg_pmc_t pc[NUM_PMCS]; pfarg_pmd_t *pd; pfmlib_input_param_t inp; pfmlib_output_param_t outp; uint64_t cpu_list; void *desc; unsigned int num_counters; uint32_t i, j, k, l, ncpus, npmds; size_t len; int ret; char *name; if (pfm_initialize() != PFMLIB_SUCCESS) fatal_error("cannot initialize libpfm\n"); if (pfms_initialize()) fatal_error("cannot initialize libpfms\n"); pfm_get_num_counters(&num_counters); pfm_get_max_event_name_len(&len); name = malloc(len+1); if (name == NULL) fatal_error("cannot allocate memory for event name\n"); memset(&ctx, 0, sizeof(ctx)); memset(pc, 0, sizeof(pc)); memset(&inp,0, sizeof(inp)); memset(&outp,0, sizeof(outp)); cpu_list = argc > 1 ? strtoul(argv[1], NULL, 0) : 0x3; ncpus = popcount(cpu_list); if (pfm_get_cycle_event(&inp.pfp_events[0].event) != PFMLIB_SUCCESS) fatal_error("cannot find cycle event\n"); if (pfm_get_inst_retired_event(&inp.pfp_events[1].event) != PFMLIB_SUCCESS) fatal_error("cannot find inst retired event\n"); i = 2; inp.pfp_dfl_plm = PFM_PLM3|PFM_PLM0; if (i > num_counters) { i = num_counters; printf("too many events provided (max=%d events), using first %d event(s)\n", num_counters, i); } /* * how many counters we use */ inp.pfp_event_count = i; /* * indicate we are using the monitors for a system-wide session. * This may impact the way the library sets up the PMC values. */ inp.pfp_flags = PFMLIB_PFP_SYSTEMWIDE; /* * let the library figure out the values for the PMCS */ if ((ret=pfm_dispatch_events(&inp, NULL, &outp, NULL)) != PFMLIB_SUCCESS) fatal_error("cannot configure events: %s\n", pfm_strerror(ret)); npmds = ncpus * inp.pfp_event_count; dprint("ncpus=%u npmds=%u\n", ncpus, npmds); pd = calloc(npmds, sizeof(pfarg_pmd_t)); if (pd == NULL) fatal_error("cannot allocate pd array\n"); for (i=0; i < outp.pfp_pmc_count; i++) { pc[i].reg_num = outp.pfp_pmcs[i].reg_num; pc[i].reg_value = outp.pfp_pmcs[i].reg_value; } for(l=0, k = 0; l < ncpus; l++) { for (i=0, j=0; i < inp.pfp_event_count; i++, k++) { pd[k].reg_num = outp.pfp_pmcs[j].reg_pmd_num; for(; j < outp.pfp_pmc_count; j++) if (outp.pfp_pmcs[j].reg_evt_idx != i) break; } } /* * create a context on all CPUs we asked for * * libpfms only works for system-wide, so we set the flag in * the master context. the context argument is not modified by * call. * * desc is an opaque descriptor used to identify session. */ ctx.ctx_flags = PFM_FL_SYSTEM_WIDE; ret = pfms_create(&cpu_list, 1, &ctx, NULL, &desc); if (ret == -1) fatal_error("create error %d\n", ret); /* * program the PMC registers on all CPUs of interest */ ret = pfms_write_pmcs(desc, pc, outp.pfp_pmc_count); if (ret == -1) fatal_error("write_pmcs error %d\n", ret); /* * program the PMD registers on all CPUs of interest */ ret = pfms_write_pmds(desc, pd, inp.pfp_event_count); if (ret == -1) fatal_error("write_pmds error %d\n", ret); /* * load context on all CPUs of interest */ ret = pfms_load(desc); if (ret == -1) fatal_error("load error %d\n", ret); /* * start monitoring on all CPUs of interest */ ret = pfms_start(desc); if (ret == -1) fatal_error("start error %d\n", ret); /* * simulate some work */ sleep(10); /* * stop monitoring on all CPUs of interest */ ret = pfms_stop(desc); if (ret == -1) fatal_error("stop error %d\n", ret); /* * read the PMD registers on all CPUs of interest. * The pd[] array must be organized such that to * read 2 PMDs on each CPU you need: * - 2 * number of CPUs of interest * - the first 2 elements of pd[] read on 1st CPU * - the next 2 elements of pd[] read on the 2nd CPU * - and so on */ ret = pfms_read_pmds(desc, pd, npmds); if (ret == -1) fatal_error("read_pmds error %d\n", ret); /* * pre per-CPU results */ for(j=0, k= 0; j < ncpus; j++) { for (i=0; i < inp.pfp_event_count; i++, k++) { pfm_get_full_event_name(&inp.pfp_events[i], name, len); printf("CPU%-3d PMD%u %20"PRIu64" %s\n", j, pd[k].reg_num, pd[k].reg_value, name); } } /* * destroy context on all CPUs of interest. * After this call desc is invalid */ ret = pfms_close(desc); if (ret == -1) fatal_error("close error %d\n", ret); free(name); return 0; }
int main(int argc, char **argv) { int c, ret; setlocale(LC_ALL, ""); options.cpu = -1; while ((c=getopt(argc, argv,"hc:e:d:xPpG:")) != -1) { switch(c) { case 'x': options.excl = 1; break; case 'p': options.interval = 1; break; case 'e': if (options.num_groups < MAX_GROUPS) { options.events[options.num_groups++] = optarg; } else { errx(1, "you cannot specify more than %d groups.\n", MAX_GROUPS); } break; case 'c': options.cpu = atoi(optarg); break; case 'd': options.delay = atoi(optarg); break; case 'P': options.pin = 1; break; case 'h': usage(); exit(0); case 'G': options.cgroup_name = optarg; break; default: errx(1, "unknown error"); } } if (!options.delay) options.delay = 20; if (!options.events[0]) { options.events[0] = "cycles,instructions"; options.num_groups = 1; } ret = pfm_initialize(); if (ret != PFM_SUCCESS) errx(1, "libpfm initialization failed: %s\n", pfm_strerror(ret)); measure(); /* free libpfm resources cleanly */ pfm_terminate(); return 0; }
int main(int argc, char **argv) { static char *argv_all[2] = { ".*", NULL }; char *endptr = NULL; char **args; int c, match; regex_t preg; char model[MAX_PMU_NAME_LEN]; while ((c=getopt(argc, argv,"hsm:")) != -1) { switch(c) { case 's': options.sort = 1; break; case 'm': options.mask = strtoull(optarg, &endptr, 16); if (*endptr) fatal_error("mask must be in hexadecimal\n"); break; case 'h': usage(); exit(0); default: fatal_error("unknown error"); } } if (pfm_initialize() != PFMLIB_SUCCESS) fatal_error("PMU model not supported by library\n"); if (options.mask == 0) options.mask = ~0; if (optind == argc) { args = argv_all; } else { args = argv + optind; } pfm_get_max_event_name_len(&max_len); name = malloc(max_len+1); if (name == NULL) fatal_error("cannot allocate name buffer\n"); if (argc == 1) *argv = ".*"; /* match everything */ else ++argv; pfm_get_pmu_name(model, MAX_PMU_NAME_LEN); printf("PMU model: %s\n", model); while(*args) { if (regcomp(&preg, *args, REG_ICASE|REG_NOSUB)) fatal_error("error in regular expression for event \"%s\"", *argv); if (options.sort) match = show_info_sorted(&preg); else match = show_info(&preg); if (match == 0) fatal_error("event %s not found", *args); args++; } regfree(&preg); free(name); return 0; }