~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/tools/perf/util/evsel.c

Version: ~ [ linux-5.8 ] ~ [ linux-5.7.12 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.55 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.136 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.191 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.232 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.232 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 // SPDX-License-Identifier: GPL-2.0-only
  2 /*
  3  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
  4  *
  5  * Parts came from builtin-{top,stat,record}.c, see those files for further
  6  * copyright notes.
  7  */
  8 
  9 #include <byteswap.h>
 10 #include <errno.h>
 11 #include <inttypes.h>
 12 #include <linux/bitops.h>
 13 #include <api/fs/fs.h>
 14 #include <api/fs/tracing_path.h>
 15 #include <traceevent/event-parse.h>
 16 #include <linux/hw_breakpoint.h>
 17 #include <linux/perf_event.h>
 18 #include <linux/compiler.h>
 19 #include <linux/err.h>
 20 #include <sys/ioctl.h>
 21 #include <sys/resource.h>
 22 #include <sys/types.h>
 23 #include <dirent.h>
 24 #include "asm/bug.h"
 25 #include "callchain.h"
 26 #include "cgroup.h"
 27 #include "event.h"
 28 #include "evsel.h"
 29 #include "evlist.h"
 30 #include "util.h"
 31 #include "cpumap.h"
 32 #include "thread_map.h"
 33 #include "target.h"
 34 #include "perf_regs.h"
 35 #include "debug.h"
 36 #include "trace-event.h"
 37 #include "stat.h"
 38 #include "memswap.h"
 39 #include "util/parse-branch-options.h"
 40 
 41 #include "sane_ctype.h"
 42 
 43 struct perf_missing_features perf_missing_features;
 44 
 45 static clockid_t clockid;
 46 
 47 static int perf_evsel__no_extra_init(struct perf_evsel *evsel __maybe_unused)
 48 {
 49         return 0;
 50 }
 51 
 52 void __weak test_attr__ready(void) { }
 53 
 54 static void perf_evsel__no_extra_fini(struct perf_evsel *evsel __maybe_unused)
 55 {
 56 }
 57 
 58 static struct {
 59         size_t  size;
 60         int     (*init)(struct perf_evsel *evsel);
 61         void    (*fini)(struct perf_evsel *evsel);
 62 } perf_evsel__object = {
 63         .size = sizeof(struct perf_evsel),
 64         .init = perf_evsel__no_extra_init,
 65         .fini = perf_evsel__no_extra_fini,
 66 };
 67 
 68 int perf_evsel__object_config(size_t object_size,
 69                               int (*init)(struct perf_evsel *evsel),
 70                               void (*fini)(struct perf_evsel *evsel))
 71 {
 72 
 73         if (object_size == 0)
 74                 goto set_methods;
 75 
 76         if (perf_evsel__object.size > object_size)
 77                 return -EINVAL;
 78 
 79         perf_evsel__object.size = object_size;
 80 
 81 set_methods:
 82         if (init != NULL)
 83                 perf_evsel__object.init = init;
 84 
 85         if (fini != NULL)
 86                 perf_evsel__object.fini = fini;
 87 
 88         return 0;
 89 }
 90 
 91 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
 92 
 93 int __perf_evsel__sample_size(u64 sample_type)
 94 {
 95         u64 mask = sample_type & PERF_SAMPLE_MASK;
 96         int size = 0;
 97         int i;
 98 
 99         for (i = 0; i < 64; i++) {
100                 if (mask & (1ULL << i))
101                         size++;
102         }
103 
104         size *= sizeof(u64);
105 
106         return size;
107 }
108 
109 /**
110  * __perf_evsel__calc_id_pos - calculate id_pos.
111  * @sample_type: sample type
112  *
113  * This function returns the position of the event id (PERF_SAMPLE_ID or
114  * PERF_SAMPLE_IDENTIFIER) in a sample event i.e. in the array of struct
115  * sample_event.
116  */
117 static int __perf_evsel__calc_id_pos(u64 sample_type)
118 {
119         int idx = 0;
120 
121         if (sample_type & PERF_SAMPLE_IDENTIFIER)
122                 return 0;
123 
124         if (!(sample_type & PERF_SAMPLE_ID))
125                 return -1;
126 
127         if (sample_type & PERF_SAMPLE_IP)
128                 idx += 1;
129 
130         if (sample_type & PERF_SAMPLE_TID)
131                 idx += 1;
132 
133         if (sample_type & PERF_SAMPLE_TIME)
134                 idx += 1;
135 
136         if (sample_type & PERF_SAMPLE_ADDR)
137                 idx += 1;
138 
139         return idx;
140 }
141 
142 /**
143  * __perf_evsel__calc_is_pos - calculate is_pos.
144  * @sample_type: sample type
145  *
146  * This function returns the position (counting backwards) of the event id
147  * (PERF_SAMPLE_ID or PERF_SAMPLE_IDENTIFIER) in a non-sample event i.e. if
148  * sample_id_all is used there is an id sample appended to non-sample events.
149  */
150 static int __perf_evsel__calc_is_pos(u64 sample_type)
151 {
152         int idx = 1;
153 
154         if (sample_type & PERF_SAMPLE_IDENTIFIER)
155                 return 1;
156 
157         if (!(sample_type & PERF_SAMPLE_ID))
158                 return -1;
159 
160         if (sample_type & PERF_SAMPLE_CPU)
161                 idx += 1;
162 
163         if (sample_type & PERF_SAMPLE_STREAM_ID)
164                 idx += 1;
165 
166         return idx;
167 }
168 
169 void perf_evsel__calc_id_pos(struct perf_evsel *evsel)
170 {
171         evsel->id_pos = __perf_evsel__calc_id_pos(evsel->attr.sample_type);
172         evsel->is_pos = __perf_evsel__calc_is_pos(evsel->attr.sample_type);
173 }
174 
175 void __perf_evsel__set_sample_bit(struct perf_evsel *evsel,
176                                   enum perf_event_sample_format bit)
177 {
178         if (!(evsel->attr.sample_type & bit)) {
179                 evsel->attr.sample_type |= bit;
180                 evsel->sample_size += sizeof(u64);
181                 perf_evsel__calc_id_pos(evsel);
182         }
183 }
184 
185 void __perf_evsel__reset_sample_bit(struct perf_evsel *evsel,
186                                     enum perf_event_sample_format bit)
187 {
188         if (evsel->attr.sample_type & bit) {
189                 evsel->attr.sample_type &= ~bit;
190                 evsel->sample_size -= sizeof(u64);
191                 perf_evsel__calc_id_pos(evsel);
192         }
193 }
194 
195 void perf_evsel__set_sample_id(struct perf_evsel *evsel,
196                                bool can_sample_identifier)
197 {
198         if (can_sample_identifier) {
199                 perf_evsel__reset_sample_bit(evsel, ID);
200                 perf_evsel__set_sample_bit(evsel, IDENTIFIER);
201         } else {
202                 perf_evsel__set_sample_bit(evsel, ID);
203         }
204         evsel->attr.read_format |= PERF_FORMAT_ID;
205 }
206 
207 /**
208  * perf_evsel__is_function_event - Return whether given evsel is a function
209  * trace event
210  *
211  * @evsel - evsel selector to be tested
212  *
213  * Return %true if event is function trace event
214  */
215 bool perf_evsel__is_function_event(struct perf_evsel *evsel)
216 {
217 #define FUNCTION_EVENT "ftrace:function"
218 
219         return evsel->name &&
220                !strncmp(FUNCTION_EVENT, evsel->name, sizeof(FUNCTION_EVENT));
221 
222 #undef FUNCTION_EVENT
223 }
224 
225 void perf_evsel__init(struct perf_evsel *evsel,
226                       struct perf_event_attr *attr, int idx)
227 {
228         evsel->idx         = idx;
229         evsel->tracking    = !idx;
230         evsel->attr        = *attr;
231         evsel->leader      = evsel;
232         evsel->unit        = "";
233         evsel->scale       = 1.0;
234         evsel->max_events  = ULONG_MAX;
235         evsel->evlist      = NULL;
236         evsel->bpf_fd      = -1;
237         INIT_LIST_HEAD(&evsel->node);
238         INIT_LIST_HEAD(&evsel->config_terms);
239         perf_evsel__object.init(evsel);
240         evsel->sample_size = __perf_evsel__sample_size(attr->sample_type);
241         perf_evsel__calc_id_pos(evsel);
242         evsel->cmdline_group_boundary = false;
243         evsel->metric_expr   = NULL;
244         evsel->metric_name   = NULL;
245         evsel->metric_events = NULL;
246         evsel->collect_stat  = false;
247         evsel->pmu_name      = NULL;
248 }
249 
250 struct perf_evsel *perf_evsel__new_idx(struct perf_event_attr *attr, int idx)
251 {
252         struct perf_evsel *evsel = zalloc(perf_evsel__object.size);
253 
254         if (!evsel)
255                 return NULL;
256         perf_evsel__init(evsel, attr, idx);
257 
258         if (perf_evsel__is_bpf_output(evsel)) {
259                 evsel->attr.sample_type |= (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
260                                             PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
261                 evsel->attr.sample_period = 1;
262         }
263 
264         if (perf_evsel__is_clock(evsel)) {
265                 /*
266                  * The evsel->unit points to static alias->unit
267                  * so it's ok to use static string in here.
268                  */
269                 static const char *unit = "msec";
270 
271                 evsel->unit = unit;
272                 evsel->scale = 1e-6;
273         }
274 
275         return evsel;
276 }
277 
278 static bool perf_event_can_profile_kernel(void)
279 {
280         return geteuid() == 0 || perf_event_paranoid() == -1;
281 }
282 
283 struct perf_evsel *perf_evsel__new_cycles(bool precise)
284 {
285         struct perf_event_attr attr = {
286                 .type   = PERF_TYPE_HARDWARE,
287                 .config = PERF_COUNT_HW_CPU_CYCLES,
288                 .exclude_kernel = !perf_event_can_profile_kernel(),
289         };
290         struct perf_evsel *evsel;
291 
292         event_attr_init(&attr);
293 
294         if (!precise)
295                 goto new_event;
296 
297         /*
298          * Now let the usual logic to set up the perf_event_attr defaults
299          * to kick in when we return and before perf_evsel__open() is called.
300          */
301 new_event:
302         evsel = perf_evsel__new(&attr);
303         if (evsel == NULL)
304                 goto out;
305 
306         evsel->precise_max = true;
307 
308         /* use asprintf() because free(evsel) assumes name is allocated */
309         if (asprintf(&evsel->name, "cycles%s%s%.*s",
310                      (attr.precise_ip || attr.exclude_kernel) ? ":" : "",
311                      attr.exclude_kernel ? "u" : "",
312                      attr.precise_ip ? attr.precise_ip + 1 : 0, "ppp") < 0)
313                 goto error_free;
314 out:
315         return evsel;
316 error_free:
317         perf_evsel__delete(evsel);
318         evsel = NULL;
319         goto out;
320 }
321 
322 /*
323  * Returns pointer with encoded error via <linux/err.h> interface.
324  */
325 struct perf_evsel *perf_evsel__newtp_idx(const char *sys, const char *name, int idx)
326 {
327         struct perf_evsel *evsel = zalloc(perf_evsel__object.size);
328         int err = -ENOMEM;
329 
330         if (evsel == NULL) {
331                 goto out_err;
332         } else {
333                 struct perf_event_attr attr = {
334                         .type          = PERF_TYPE_TRACEPOINT,
335                         .sample_type   = (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
336                                           PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
337                 };
338 
339                 if (asprintf(&evsel->name, "%s:%s", sys, name) < 0)
340                         goto out_free;
341 
342                 evsel->tp_format = trace_event__tp_format(sys, name);
343                 if (IS_ERR(evsel->tp_format)) {
344                         err = PTR_ERR(evsel->tp_format);
345                         goto out_free;
346                 }
347 
348                 event_attr_init(&attr);
349                 attr.config = evsel->tp_format->id;
350                 attr.sample_period = 1;
351                 perf_evsel__init(evsel, &attr, idx);
352         }
353 
354         return evsel;
355 
356 out_free:
357         zfree(&evsel->name);
358         free(evsel);
359 out_err:
360         return ERR_PTR(err);
361 }
362 
363 const char *perf_evsel__hw_names[PERF_COUNT_HW_MAX] = {
364         "cycles",
365         "instructions",
366         "cache-references",
367         "cache-misses",
368         "branches",
369         "branch-misses",
370         "bus-cycles",
371         "stalled-cycles-frontend",
372         "stalled-cycles-backend",
373         "ref-cycles",
374 };
375 
376 static const char *__perf_evsel__hw_name(u64 config)
377 {
378         if (config < PERF_COUNT_HW_MAX && perf_evsel__hw_names[config])
379                 return perf_evsel__hw_names[config];
380 
381         return "unknown-hardware";
382 }
383 
384 static int perf_evsel__add_modifiers(struct perf_evsel *evsel, char *bf, size_t size)
385 {
386         int colon = 0, r = 0;
387         struct perf_event_attr *attr = &evsel->attr;
388         bool exclude_guest_default = false;
389 
390 #define MOD_PRINT(context, mod) do {                                    \
391                 if (!attr->exclude_##context) {                         \
392                         if (!colon) colon = ++r;                        \
393                         r += scnprintf(bf + r, size - r, "%c", mod);    \
394                 } } while(0)
395 
396         if (attr->exclude_kernel || attr->exclude_user || attr->exclude_hv) {
397                 MOD_PRINT(kernel, 'k');
398                 MOD_PRINT(user, 'u');
399                 MOD_PRINT(hv, 'h');
400                 exclude_guest_default = true;
401         }
402 
403         if (attr->precise_ip) {
404                 if (!colon)
405                         colon = ++r;
406                 r += scnprintf(bf + r, size - r, "%.*s", attr->precise_ip, "ppp");
407                 exclude_guest_default = true;
408         }
409 
410         if (attr->exclude_host || attr->exclude_guest == exclude_guest_default) {
411                 MOD_PRINT(host, 'H');
412                 MOD_PRINT(guest, 'G');
413         }
414 #undef MOD_PRINT
415         if (colon)
416                 bf[colon - 1] = ':';
417         return r;
418 }
419 
420 static int perf_evsel__hw_name(struct perf_evsel *evsel, char *bf, size_t size)
421 {
422         int r = scnprintf(bf, size, "%s", __perf_evsel__hw_name(evsel->attr.config));
423         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
424 }
425 
426 const char *perf_evsel__sw_names[PERF_COUNT_SW_MAX] = {
427         "cpu-clock",
428         "task-clock",
429         "page-faults",
430         "context-switches",
431         "cpu-migrations",
432         "minor-faults",
433         "major-faults",
434         "alignment-faults",
435         "emulation-faults",
436         "dummy",
437 };
438 
439 static const char *__perf_evsel__sw_name(u64 config)
440 {
441         if (config < PERF_COUNT_SW_MAX && perf_evsel__sw_names[config])
442                 return perf_evsel__sw_names[config];
443         return "unknown-software";
444 }
445 
446 static int perf_evsel__sw_name(struct perf_evsel *evsel, char *bf, size_t size)
447 {
448         int r = scnprintf(bf, size, "%s", __perf_evsel__sw_name(evsel->attr.config));
449         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
450 }
451 
452 static int __perf_evsel__bp_name(char *bf, size_t size, u64 addr, u64 type)
453 {
454         int r;
455 
456         r = scnprintf(bf, size, "mem:0x%" PRIx64 ":", addr);
457 
458         if (type & HW_BREAKPOINT_R)
459                 r += scnprintf(bf + r, size - r, "r");
460 
461         if (type & HW_BREAKPOINT_W)
462                 r += scnprintf(bf + r, size - r, "w");
463 
464         if (type & HW_BREAKPOINT_X)
465                 r += scnprintf(bf + r, size - r, "x");
466 
467         return r;
468 }
469 
470 static int perf_evsel__bp_name(struct perf_evsel *evsel, char *bf, size_t size)
471 {
472         struct perf_event_attr *attr = &evsel->attr;
473         int r = __perf_evsel__bp_name(bf, size, attr->bp_addr, attr->bp_type);
474         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
475 }
476 
477 const char *perf_evsel__hw_cache[PERF_COUNT_HW_CACHE_MAX]
478                                 [PERF_EVSEL__MAX_ALIASES] = {
479  { "L1-dcache", "l1-d",         "l1d",          "L1-data",              },
480  { "L1-icache", "l1-i",         "l1i",          "L1-instruction",       },
481  { "LLC",       "L2",                                                   },
482  { "dTLB",      "d-tlb",        "Data-TLB",                             },
483  { "iTLB",      "i-tlb",        "Instruction-TLB",                      },
484  { "branch",    "branches",     "bpu",          "btb",          "bpc",  },
485  { "node",                                                              },
486 };
487 
488 const char *perf_evsel__hw_cache_op[PERF_COUNT_HW_CACHE_OP_MAX]
489                                    [PERF_EVSEL__MAX_ALIASES] = {
490  { "load",      "loads",        "read",                                 },
491  { "store",     "stores",       "write",                                },
492  { "prefetch",  "prefetches",   "speculative-read", "speculative-load", },
493 };
494 
495 const char *perf_evsel__hw_cache_result[PERF_COUNT_HW_CACHE_RESULT_MAX]
496                                        [PERF_EVSEL__MAX_ALIASES] = {
497  { "refs",      "Reference",    "ops",          "access",               },
498  { "misses",    "miss",                                                 },
499 };
500 
501 #define C(x)            PERF_COUNT_HW_CACHE_##x
502 #define CACHE_READ      (1 << C(OP_READ))
503 #define CACHE_WRITE     (1 << C(OP_WRITE))
504 #define CACHE_PREFETCH  (1 << C(OP_PREFETCH))
505 #define COP(x)          (1 << x)
506 
507 /*
508  * cache operartion stat
509  * L1I : Read and prefetch only
510  * ITLB and BPU : Read-only
511  */
512 static unsigned long perf_evsel__hw_cache_stat[C(MAX)] = {
513  [C(L1D)]       = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
514  [C(L1I)]       = (CACHE_READ | CACHE_PREFETCH),
515  [C(LL)]        = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
516  [C(DTLB)]      = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
517  [C(ITLB)]      = (CACHE_READ),
518  [C(BPU)]       = (CACHE_READ),
519  [C(NODE)]      = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
520 };
521 
522 bool perf_evsel__is_cache_op_valid(u8 type, u8 op)
523 {
524         if (perf_evsel__hw_cache_stat[type] & COP(op))
525                 return true;    /* valid */
526         else
527                 return false;   /* invalid */
528 }
529 
530 int __perf_evsel__hw_cache_type_op_res_name(u8 type, u8 op, u8 result,
531                                             char *bf, size_t size)
532 {
533         if (result) {
534                 return scnprintf(bf, size, "%s-%s-%s", perf_evsel__hw_cache[type][0],
535                                  perf_evsel__hw_cache_op[op][0],
536                                  perf_evsel__hw_cache_result[result][0]);
537         }
538 
539         return scnprintf(bf, size, "%s-%s", perf_evsel__hw_cache[type][0],
540                          perf_evsel__hw_cache_op[op][1]);
541 }
542 
543 static int __perf_evsel__hw_cache_name(u64 config, char *bf, size_t size)
544 {
545         u8 op, result, type = (config >>  0) & 0xff;
546         const char *err = "unknown-ext-hardware-cache-type";
547 
548         if (type >= PERF_COUNT_HW_CACHE_MAX)
549                 goto out_err;
550 
551         op = (config >>  8) & 0xff;
552         err = "unknown-ext-hardware-cache-op";
553         if (op >= PERF_COUNT_HW_CACHE_OP_MAX)
554                 goto out_err;
555 
556         result = (config >> 16) & 0xff;
557         err = "unknown-ext-hardware-cache-result";
558         if (result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
559                 goto out_err;
560 
561         err = "invalid-cache";
562         if (!perf_evsel__is_cache_op_valid(type, op))
563                 goto out_err;
564 
565         return __perf_evsel__hw_cache_type_op_res_name(type, op, result, bf, size);
566 out_err:
567         return scnprintf(bf, size, "%s", err);
568 }
569 
570 static int perf_evsel__hw_cache_name(struct perf_evsel *evsel, char *bf, size_t size)
571 {
572         int ret = __perf_evsel__hw_cache_name(evsel->attr.config, bf, size);
573         return ret + perf_evsel__add_modifiers(evsel, bf + ret, size - ret);
574 }
575 
576 static int perf_evsel__raw_name(struct perf_evsel *evsel, char *bf, size_t size)
577 {
578         int ret = scnprintf(bf, size, "raw 0x%" PRIx64, evsel->attr.config);
579         return ret + perf_evsel__add_modifiers(evsel, bf + ret, size - ret);
580 }
581 
582 static int perf_evsel__tool_name(char *bf, size_t size)
583 {
584         int ret = scnprintf(bf, size, "duration_time");
585         return ret;
586 }
587 
588 const char *perf_evsel__name(struct perf_evsel *evsel)
589 {
590         char bf[128];
591 
592         if (!evsel)
593                 goto out_unknown;
594 
595         if (evsel->name)
596                 return evsel->name;
597 
598         switch (evsel->attr.type) {
599         case PERF_TYPE_RAW:
600                 perf_evsel__raw_name(evsel, bf, sizeof(bf));
601                 break;
602 
603         case PERF_TYPE_HARDWARE:
604                 perf_evsel__hw_name(evsel, bf, sizeof(bf));
605                 break;
606 
607         case PERF_TYPE_HW_CACHE:
608                 perf_evsel__hw_cache_name(evsel, bf, sizeof(bf));
609                 break;
610 
611         case PERF_TYPE_SOFTWARE:
612                 if (evsel->tool_event)
613                         perf_evsel__tool_name(bf, sizeof(bf));
614                 else
615                         perf_evsel__sw_name(evsel, bf, sizeof(bf));
616                 break;
617 
618         case PERF_TYPE_TRACEPOINT:
619                 scnprintf(bf, sizeof(bf), "%s", "unknown tracepoint");
620                 break;
621 
622         case PERF_TYPE_BREAKPOINT:
623                 perf_evsel__bp_name(evsel, bf, sizeof(bf));
624                 break;
625 
626         default:
627                 scnprintf(bf, sizeof(bf), "unknown attr type: %d",
628                           evsel->attr.type);
629                 break;
630         }
631 
632         evsel->name = strdup(bf);
633 
634         if (evsel->name)
635                 return evsel->name;
636 out_unknown:
637         return "unknown";
638 }
639 
640 const char *perf_evsel__group_name(struct perf_evsel *evsel)
641 {
642         return evsel->group_name ?: "anon group";
643 }
644 
645 /*
646  * Returns the group details for the specified leader,
647  * with following rules.
648  *
649  *  For record -e '{cycles,instructions}'
650  *    'anon group { cycles:u, instructions:u }'
651  *
652  *  For record -e 'cycles,instructions' and report --group
653  *    'cycles:u, instructions:u'
654  */
655 int perf_evsel__group_desc(struct perf_evsel *evsel, char *buf, size_t size)
656 {
657         int ret = 0;
658         struct perf_evsel *pos;
659         const char *group_name = perf_evsel__group_name(evsel);
660 
661         if (!evsel->forced_leader)
662                 ret = scnprintf(buf, size, "%s { ", group_name);
663 
664         ret += scnprintf(buf + ret, size - ret, "%s",
665                          perf_evsel__name(evsel));
666 
667         for_each_group_member(pos, evsel)
668                 ret += scnprintf(buf + ret, size - ret, ", %s",
669                                  perf_evsel__name(pos));
670 
671         if (!evsel->forced_leader)
672                 ret += scnprintf(buf + ret, size - ret, " }");
673 
674         return ret;
675 }
676 
677 static void __perf_evsel__config_callchain(struct perf_evsel *evsel,
678                                            struct record_opts *opts,
679                                            struct callchain_param *param)
680 {
681         bool function = perf_evsel__is_function_event(evsel);
682         struct perf_event_attr *attr = &evsel->attr;
683 
684         perf_evsel__set_sample_bit(evsel, CALLCHAIN);
685 
686         attr->sample_max_stack = param->max_stack;
687 
688         if (param->record_mode == CALLCHAIN_LBR) {
689                 if (!opts->branch_stack) {
690                         if (attr->exclude_user) {
691                                 pr_warning("LBR callstack option is only available "
692                                            "to get user callchain information. "
693                                            "Falling back to framepointers.\n");
694                         } else {
695                                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
696                                 attr->branch_sample_type = PERF_SAMPLE_BRANCH_USER |
697                                                         PERF_SAMPLE_BRANCH_CALL_STACK |
698                                                         PERF_SAMPLE_BRANCH_NO_CYCLES |
699                                                         PERF_SAMPLE_BRANCH_NO_FLAGS;
700                         }
701                 } else
702                          pr_warning("Cannot use LBR callstack with branch stack. "
703                                     "Falling back to framepointers.\n");
704         }
705 
706         if (param->record_mode == CALLCHAIN_DWARF) {
707                 if (!function) {
708                         perf_evsel__set_sample_bit(evsel, REGS_USER);
709                         perf_evsel__set_sample_bit(evsel, STACK_USER);
710                         attr->sample_regs_user |= PERF_REGS_MASK;
711                         attr->sample_stack_user = param->dump_size;
712                         attr->exclude_callchain_user = 1;
713                 } else {
714                         pr_info("Cannot use DWARF unwind for function trace event,"
715                                 " falling back to framepointers.\n");
716                 }
717         }
718 
719         if (function) {
720                 pr_info("Disabling user space callchains for function trace event.\n");
721                 attr->exclude_callchain_user = 1;
722         }
723 }
724 
725 void perf_evsel__config_callchain(struct perf_evsel *evsel,
726                                   struct record_opts *opts,
727                                   struct callchain_param *param)
728 {
729         if (param->enabled)
730                 return __perf_evsel__config_callchain(evsel, opts, param);
731 }
732 
733 static void
734 perf_evsel__reset_callgraph(struct perf_evsel *evsel,
735                             struct callchain_param *param)
736 {
737         struct perf_event_attr *attr = &evsel->attr;
738 
739         perf_evsel__reset_sample_bit(evsel, CALLCHAIN);
740         if (param->record_mode == CALLCHAIN_LBR) {
741                 perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
742                 attr->branch_sample_type &= ~(PERF_SAMPLE_BRANCH_USER |
743                                               PERF_SAMPLE_BRANCH_CALL_STACK);
744         }
745         if (param->record_mode == CALLCHAIN_DWARF) {
746                 perf_evsel__reset_sample_bit(evsel, REGS_USER);
747                 perf_evsel__reset_sample_bit(evsel, STACK_USER);
748         }
749 }
750 
751 static void apply_config_terms(struct perf_evsel *evsel,
752                                struct record_opts *opts, bool track)
753 {
754         struct perf_evsel_config_term *term;
755         struct list_head *config_terms = &evsel->config_terms;
756         struct perf_event_attr *attr = &evsel->attr;
757         /* callgraph default */
758         struct callchain_param param = {
759                 .record_mode = callchain_param.record_mode,
760         };
761         u32 dump_size = 0;
762         int max_stack = 0;
763         const char *callgraph_buf = NULL;
764 
765         list_for_each_entry(term, config_terms, list) {
766                 switch (term->type) {
767                 case PERF_EVSEL__CONFIG_TERM_PERIOD:
768                         if (!(term->weak && opts->user_interval != ULLONG_MAX)) {
769                                 attr->sample_period = term->val.period;
770                                 attr->freq = 0;
771                                 perf_evsel__reset_sample_bit(evsel, PERIOD);
772                         }
773                         break;
774                 case PERF_EVSEL__CONFIG_TERM_FREQ:
775                         if (!(term->weak && opts->user_freq != UINT_MAX)) {
776                                 attr->sample_freq = term->val.freq;
777                                 attr->freq = 1;
778                                 perf_evsel__set_sample_bit(evsel, PERIOD);
779                         }
780                         break;
781                 case PERF_EVSEL__CONFIG_TERM_TIME:
782                         if (term->val.time)
783                                 perf_evsel__set_sample_bit(evsel, TIME);
784                         else
785                                 perf_evsel__reset_sample_bit(evsel, TIME);
786                         break;
787                 case PERF_EVSEL__CONFIG_TERM_CALLGRAPH:
788                         callgraph_buf = term->val.callgraph;
789                         break;
790                 case PERF_EVSEL__CONFIG_TERM_BRANCH:
791                         if (term->val.branch && strcmp(term->val.branch, "no")) {
792                                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
793                                 parse_branch_str(term->val.branch,
794                                                  &attr->branch_sample_type);
795                         } else
796                                 perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
797                         break;
798                 case PERF_EVSEL__CONFIG_TERM_STACK_USER:
799                         dump_size = term->val.stack_user;
800                         break;
801                 case PERF_EVSEL__CONFIG_TERM_MAX_STACK:
802                         max_stack = term->val.max_stack;
803                         break;
804                 case PERF_EVSEL__CONFIG_TERM_MAX_EVENTS:
805                         evsel->max_events = term->val.max_events;
806                         break;
807                 case PERF_EVSEL__CONFIG_TERM_INHERIT:
808                         /*
809                          * attr->inherit should has already been set by
810                          * perf_evsel__config. If user explicitly set
811                          * inherit using config terms, override global
812                          * opt->no_inherit setting.
813                          */
814                         attr->inherit = term->val.inherit ? 1 : 0;
815                         break;
816                 case PERF_EVSEL__CONFIG_TERM_OVERWRITE:
817                         attr->write_backward = term->val.overwrite ? 1 : 0;
818                         break;
819                 case PERF_EVSEL__CONFIG_TERM_DRV_CFG:
820                         break;
821                 case PERF_EVSEL__CONFIG_TERM_PERCORE:
822                         break;
823                 default:
824                         break;
825                 }
826         }
827 
828         /* User explicitly set per-event callgraph, clear the old setting and reset. */
829         if ((callgraph_buf != NULL) || (dump_size > 0) || max_stack) {
830                 bool sample_address = false;
831 
832                 if (max_stack) {
833                         param.max_stack = max_stack;
834                         if (callgraph_buf == NULL)
835                                 callgraph_buf = "fp";
836                 }
837 
838                 /* parse callgraph parameters */
839                 if (callgraph_buf != NULL) {
840                         if (!strcmp(callgraph_buf, "no")) {
841                                 param.enabled = false;
842                                 param.record_mode = CALLCHAIN_NONE;
843                         } else {
844                                 param.enabled = true;
845                                 if (parse_callchain_record(callgraph_buf, &param)) {
846                                         pr_err("per-event callgraph setting for %s failed. "
847                                                "Apply callgraph global setting for it\n",
848                                                evsel->name);
849                                         return;
850                                 }
851                                 if (param.record_mode == CALLCHAIN_DWARF)
852                                         sample_address = true;
853                         }
854                 }
855                 if (dump_size > 0) {
856                         dump_size = round_up(dump_size, sizeof(u64));
857                         param.dump_size = dump_size;
858                 }
859 
860                 /* If global callgraph set, clear it */
861                 if (callchain_param.enabled)
862                         perf_evsel__reset_callgraph(evsel, &callchain_param);
863 
864                 /* set perf-event callgraph */
865                 if (param.enabled) {
866                         if (sample_address) {
867                                 perf_evsel__set_sample_bit(evsel, ADDR);
868                                 perf_evsel__set_sample_bit(evsel, DATA_SRC);
869                                 evsel->attr.mmap_data = track;
870                         }
871                         perf_evsel__config_callchain(evsel, opts, &param);
872                 }
873         }
874 }
875 
876 static bool is_dummy_event(struct perf_evsel *evsel)
877 {
878         return (evsel->attr.type == PERF_TYPE_SOFTWARE) &&
879                (evsel->attr.config == PERF_COUNT_SW_DUMMY);
880 }
881 
882 /*
883  * The enable_on_exec/disabled value strategy:
884  *
885  *  1) For any type of traced program:
886  *    - all independent events and group leaders are disabled
887  *    - all group members are enabled
888  *
889  *     Group members are ruled by group leaders. They need to
890  *     be enabled, because the group scheduling relies on that.
891  *
892  *  2) For traced programs executed by perf:
893  *     - all independent events and group leaders have
894  *       enable_on_exec set
895  *     - we don't specifically enable or disable any event during
896  *       the record command
897  *
898  *     Independent events and group leaders are initially disabled
899  *     and get enabled by exec. Group members are ruled by group
900  *     leaders as stated in 1).
901  *
902  *  3) For traced programs attached by perf (pid/tid):
903  *     - we specifically enable or disable all events during
904  *       the record command
905  *
906  *     When attaching events to already running traced we
907  *     enable/disable events specifically, as there's no
908  *     initial traced exec call.
909  */
910 void perf_evsel__config(struct perf_evsel *evsel, struct record_opts *opts,
911                         struct callchain_param *callchain)
912 {
913         struct perf_evsel *leader = evsel->leader;
914         struct perf_event_attr *attr = &evsel->attr;
915         int track = evsel->tracking;
916         bool per_cpu = opts->target.default_per_cpu && !opts->target.per_thread;
917 
918         attr->sample_id_all = perf_missing_features.sample_id_all ? 0 : 1;
919         attr->inherit       = !opts->no_inherit;
920         attr->write_backward = opts->overwrite ? 1 : 0;
921 
922         perf_evsel__set_sample_bit(evsel, IP);
923         perf_evsel__set_sample_bit(evsel, TID);
924 
925         if (evsel->sample_read) {
926                 perf_evsel__set_sample_bit(evsel, READ);
927 
928                 /*
929                  * We need ID even in case of single event, because
930                  * PERF_SAMPLE_READ process ID specific data.
931                  */
932                 perf_evsel__set_sample_id(evsel, false);
933 
934                 /*
935                  * Apply group format only if we belong to group
936                  * with more than one members.
937                  */
938                 if (leader->nr_members > 1) {
939                         attr->read_format |= PERF_FORMAT_GROUP;
940                         attr->inherit = 0;
941                 }
942         }
943 
944         /*
945          * We default some events to have a default interval. But keep
946          * it a weak assumption overridable by the user.
947          */
948         if (!attr->sample_period || (opts->user_freq != UINT_MAX ||
949                                      opts->user_interval != ULLONG_MAX)) {
950                 if (opts->freq) {
951                         perf_evsel__set_sample_bit(evsel, PERIOD);
952                         attr->freq              = 1;
953                         attr->sample_freq       = opts->freq;
954                 } else {
955                         attr->sample_period = opts->default_interval;
956                 }
957         }
958 
959         /*
960          * Disable sampling for all group members other
961          * than leader in case leader 'leads' the sampling.
962          */
963         if ((leader != evsel) && leader->sample_read) {
964                 attr->freq           = 0;
965                 attr->sample_freq    = 0;
966                 attr->sample_period  = 0;
967                 attr->write_backward = 0;
968 
969                 /*
970                  * We don't get sample for slave events, we make them
971                  * when delivering group leader sample. Set the slave
972                  * event to follow the master sample_type to ease up
973                  * report.
974                  */
975                 attr->sample_type = leader->attr.sample_type;
976         }
977 
978         if (opts->no_samples)
979                 attr->sample_freq = 0;
980 
981         if (opts->inherit_stat) {
982                 evsel->attr.read_format |=
983                         PERF_FORMAT_TOTAL_TIME_ENABLED |
984                         PERF_FORMAT_TOTAL_TIME_RUNNING |
985                         PERF_FORMAT_ID;
986                 attr->inherit_stat = 1;
987         }
988 
989         if (opts->sample_address) {
990                 perf_evsel__set_sample_bit(evsel, ADDR);
991                 attr->mmap_data = track;
992         }
993 
994         /*
995          * We don't allow user space callchains for  function trace
996          * event, due to issues with page faults while tracing page
997          * fault handler and its overall trickiness nature.
998          */
999         if (perf_evsel__is_function_event(evsel))
1000                 evsel->attr.exclude_callchain_user = 1;
1001 
1002         if (callchain && callchain->enabled && !evsel->no_aux_samples)
1003                 perf_evsel__config_callchain(evsel, opts, callchain);
1004 
1005         if (opts->sample_intr_regs) {
1006                 attr->sample_regs_intr = opts->sample_intr_regs;
1007                 perf_evsel__set_sample_bit(evsel, REGS_INTR);
1008         }
1009 
1010         if (opts->sample_user_regs) {
1011                 attr->sample_regs_user |= opts->sample_user_regs;
1012                 perf_evsel__set_sample_bit(evsel, REGS_USER);
1013         }
1014 
1015         if (target__has_cpu(&opts->target) || opts->sample_cpu)
1016                 perf_evsel__set_sample_bit(evsel, CPU);
1017 
1018         /*
1019          * When the user explicitly disabled time don't force it here.
1020          */
1021         if (opts->sample_time &&
1022             (!perf_missing_features.sample_id_all &&
1023             (!opts->no_inherit || target__has_cpu(&opts->target) || per_cpu ||
1024              opts->sample_time_set)))
1025                 perf_evsel__set_sample_bit(evsel, TIME);
1026 
1027         if (opts->raw_samples && !evsel->no_aux_samples) {
1028                 perf_evsel__set_sample_bit(evsel, TIME);
1029                 perf_evsel__set_sample_bit(evsel, RAW);
1030                 perf_evsel__set_sample_bit(evsel, CPU);
1031         }
1032 
1033         if (opts->sample_address)
1034                 perf_evsel__set_sample_bit(evsel, DATA_SRC);
1035 
1036         if (opts->sample_phys_addr)
1037                 perf_evsel__set_sample_bit(evsel, PHYS_ADDR);
1038 
1039         if (opts->no_buffering) {
1040                 attr->watermark = 0;
1041                 attr->wakeup_events = 1;
1042         }
1043         if (opts->branch_stack && !evsel->no_aux_samples) {
1044                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
1045                 attr->branch_sample_type = opts->branch_stack;
1046         }
1047 
1048         if (opts->sample_weight)
1049                 perf_evsel__set_sample_bit(evsel, WEIGHT);
1050 
1051         attr->task  = track;
1052         attr->mmap  = track;
1053         attr->mmap2 = track && !perf_missing_features.mmap2;
1054         attr->comm  = track;
1055         attr->ksymbol = track && !perf_missing_features.ksymbol;
1056         attr->bpf_event = track && !opts->no_bpf_event &&
1057                 !perf_missing_features.bpf_event;
1058 
1059         if (opts->record_namespaces)
1060                 attr->namespaces  = track;
1061 
1062         if (opts->record_switch_events)
1063                 attr->context_switch = track;
1064 
1065         if (opts->sample_transaction)
1066                 perf_evsel__set_sample_bit(evsel, TRANSACTION);
1067 
1068         if (opts->running_time) {
1069                 evsel->attr.read_format |=
1070                         PERF_FORMAT_TOTAL_TIME_ENABLED |
1071                         PERF_FORMAT_TOTAL_TIME_RUNNING;
1072         }
1073 
1074         /*
1075          * XXX see the function comment above
1076          *
1077          * Disabling only independent events or group leaders,
1078          * keeping group members enabled.
1079          */
1080         if (perf_evsel__is_group_leader(evsel))
1081                 attr->disabled = 1;
1082 
1083         /*
1084          * Setting enable_on_exec for independent events and
1085          * group leaders for traced executed by perf.
1086          */
1087         if (target__none(&opts->target) && perf_evsel__is_group_leader(evsel) &&
1088                 !opts->initial_delay)
1089                 attr->enable_on_exec = 1;
1090 
1091         if (evsel->immediate) {
1092                 attr->disabled = 0;
1093                 attr->enable_on_exec = 0;
1094         }
1095 
1096         clockid = opts->clockid;
1097         if (opts->use_clockid) {
1098                 attr->use_clockid = 1;
1099                 attr->clockid = opts->clockid;
1100         }
1101 
1102         if (evsel->precise_max)
1103                 attr->precise_ip = 3;
1104 
1105         if (opts->all_user) {
1106                 attr->exclude_kernel = 1;
1107                 attr->exclude_user   = 0;
1108         }
1109 
1110         if (opts->all_kernel) {
1111                 attr->exclude_kernel = 0;
1112                 attr->exclude_user   = 1;
1113         }
1114 
1115         if (evsel->own_cpus || evsel->unit)
1116                 evsel->attr.read_format |= PERF_FORMAT_ID;
1117 
1118         /*
1119          * Apply event specific term settings,
1120          * it overloads any global configuration.
1121          */
1122         apply_config_terms(evsel, opts, track);
1123 
1124         evsel->ignore_missing_thread = opts->ignore_missing_thread;
1125 
1126         /* The --period option takes the precedence. */
1127         if (opts->period_set) {
1128                 if (opts->period)
1129                         perf_evsel__set_sample_bit(evsel, PERIOD);
1130                 else
1131                         perf_evsel__reset_sample_bit(evsel, PERIOD);
1132         }
1133 
1134         /*
1135          * For initial_delay, a dummy event is added implicitly.
1136          * The software event will trigger -EOPNOTSUPP error out,
1137          * if BRANCH_STACK bit is set.
1138          */
1139         if (opts->initial_delay && is_dummy_event(evsel))
1140                 perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
1141 }
1142 
1143 static int perf_evsel__alloc_fd(struct perf_evsel *evsel, int ncpus, int nthreads)
1144 {
1145         if (evsel->system_wide)
1146                 nthreads = 1;
1147 
1148         evsel->fd = xyarray__new(ncpus, nthreads, sizeof(int));
1149 
1150         if (evsel->fd) {
1151                 int cpu, thread;
1152                 for (cpu = 0; cpu < ncpus; cpu++) {
1153                         for (thread = 0; thread < nthreads; thread++) {
1154                                 FD(evsel, cpu, thread) = -1;
1155                         }
1156                 }
1157         }
1158 
1159         return evsel->fd != NULL ? 0 : -ENOMEM;
1160 }
1161 
1162 static int perf_evsel__run_ioctl(struct perf_evsel *evsel,
1163                           int ioc,  void *arg)
1164 {
1165         int cpu, thread;
1166 
1167         for (cpu = 0; cpu < xyarray__max_x(evsel->fd); cpu++) {
1168                 for (thread = 0; thread < xyarray__max_y(evsel->fd); thread++) {
1169                         int fd = FD(evsel, cpu, thread),
1170                             err = ioctl(fd, ioc, arg);
1171 
1172                         if (err)
1173                                 return err;
1174                 }
1175         }
1176 
1177         return 0;
1178 }
1179 
1180 int perf_evsel__apply_filter(struct perf_evsel *evsel, const char *filter)
1181 {
1182         return perf_evsel__run_ioctl(evsel,
1183                                      PERF_EVENT_IOC_SET_FILTER,
1184                                      (void *)filter);
1185 }
1186 
1187 int perf_evsel__set_filter(struct perf_evsel *evsel, const char *filter)
1188 {
1189         char *new_filter = strdup(filter);
1190 
1191         if (new_filter != NULL) {
1192                 free(evsel->filter);
1193                 evsel->filter = new_filter;
1194                 return 0;
1195         }
1196 
1197         return -1;
1198 }
1199 
1200 static int perf_evsel__append_filter(struct perf_evsel *evsel,
1201                                      const char *fmt, const char *filter)
1202 {
1203         char *new_filter;
1204 
1205         if (evsel->filter == NULL)
1206                 return perf_evsel__set_filter(evsel, filter);
1207 
1208         if (asprintf(&new_filter, fmt, evsel->filter, filter) > 0) {
1209                 free(evsel->filter);
1210                 evsel->filter = new_filter;
1211                 return 0;
1212         }
1213 
1214         return -1;
1215 }
1216 
1217 int perf_evsel__append_tp_filter(struct perf_evsel *evsel, const char *filter)
1218 {
1219         return perf_evsel__append_filter(evsel, "(%s) && (%s)", filter);
1220 }
1221 
1222 int perf_evsel__append_addr_filter(struct perf_evsel *evsel, const char *filter)
1223 {
1224         return perf_evsel__append_filter(evsel, "%s,%s", filter);
1225 }
1226 
1227 int perf_evsel__enable(struct perf_evsel *evsel)
1228 {
1229         int err = perf_evsel__run_ioctl(evsel, PERF_EVENT_IOC_ENABLE, 0);
1230 
1231         if (!err)
1232                 evsel->disabled = false;
1233 
1234         return err;
1235 }
1236 
1237 int perf_evsel__disable(struct perf_evsel *evsel)
1238 {
1239         int err = perf_evsel__run_ioctl(evsel, PERF_EVENT_IOC_DISABLE, 0);
1240         /*
1241          * We mark it disabled here so that tools that disable a event can
1242          * ignore events after they disable it. I.e. the ring buffer may have
1243          * already a few more events queued up before the kernel got the stop
1244          * request.
1245          */
1246         if (!err)
1247                 evsel->disabled = true;
1248 
1249         return err;
1250 }
1251 
1252 int perf_evsel__alloc_id(struct perf_evsel *evsel, int ncpus, int nthreads)
1253 {
1254         if (ncpus == 0 || nthreads == 0)
1255                 return 0;
1256 
1257         if (evsel->system_wide)
1258                 nthreads = 1;
1259 
1260         evsel->sample_id = xyarray__new(ncpus, nthreads, sizeof(struct perf_sample_id));
1261         if (evsel->sample_id == NULL)
1262                 return -ENOMEM;
1263 
1264         evsel->id = zalloc(ncpus * nthreads * sizeof(u64));
1265         if (evsel->id == NULL) {
1266                 xyarray__delete(evsel->sample_id);
1267                 evsel->sample_id = NULL;
1268                 return -ENOMEM;
1269         }
1270 
1271         return 0;
1272 }
1273 
1274 static void perf_evsel__free_fd(struct perf_evsel *evsel)
1275 {
1276         xyarray__delete(evsel->fd);
1277         evsel->fd = NULL;
1278 }
1279 
1280 static void perf_evsel__free_id(struct perf_evsel *evsel)
1281 {
1282         xyarray__delete(evsel->sample_id);
1283         evsel->sample_id = NULL;
1284         zfree(&evsel->id);
1285         evsel->ids = 0;
1286 }
1287 
1288 static void perf_evsel__free_config_terms(struct perf_evsel *evsel)
1289 {
1290         struct perf_evsel_config_term *term, *h;
1291 
1292         list_for_each_entry_safe(term, h, &evsel->config_terms, list) {
1293                 list_del(&term->list);
1294                 free(term);
1295         }
1296 }
1297 
1298 void perf_evsel__close_fd(struct perf_evsel *evsel)
1299 {
1300         int cpu, thread;
1301 
1302         for (cpu = 0; cpu < xyarray__max_x(evsel->fd); cpu++)
1303                 for (thread = 0; thread < xyarray__max_y(evsel->fd); ++thread) {
1304                         close(FD(evsel, cpu, thread));
1305                         FD(evsel, cpu, thread) = -1;
1306                 }
1307 }
1308 
1309 void perf_evsel__exit(struct perf_evsel *evsel)
1310 {
1311         assert(list_empty(&evsel->node));
1312         assert(evsel->evlist == NULL);
1313         perf_evsel__free_counts(evsel);
1314         perf_evsel__free_fd(evsel);
1315         perf_evsel__free_id(evsel);
1316         perf_evsel__free_config_terms(evsel);
1317         cgroup__put(evsel->cgrp);
1318         cpu_map__put(evsel->cpus);
1319         cpu_map__put(evsel->own_cpus);
1320         thread_map__put(evsel->threads);
1321         zfree(&evsel->group_name);
1322         zfree(&evsel->name);
1323         perf_evsel__object.fini(evsel);
1324 }
1325 
1326 void perf_evsel__delete(struct perf_evsel *evsel)
1327 {
1328         perf_evsel__exit(evsel);
1329         free(evsel);
1330 }
1331 
1332 void perf_evsel__compute_deltas(struct perf_evsel *evsel, int cpu, int thread,
1333                                 struct perf_counts_values *count)
1334 {
1335         struct perf_counts_values tmp;
1336 
1337         if (!evsel->prev_raw_counts)
1338                 return;
1339 
1340         if (cpu == -1) {
1341                 tmp = evsel->prev_raw_counts->aggr;
1342                 evsel->prev_raw_counts->aggr = *count;
1343         } else {
1344                 tmp = *perf_counts(evsel->prev_raw_counts, cpu, thread);
1345                 *perf_counts(evsel->prev_raw_counts, cpu, thread) = *count;
1346         }
1347 
1348         count->val = count->val - tmp.val;
1349         count->ena = count->ena - tmp.ena;
1350         count->run = count->run - tmp.run;
1351 }
1352 
1353 void perf_counts_values__scale(struct perf_counts_values *count,
1354                                bool scale, s8 *pscaled)
1355 {
1356         s8 scaled = 0;
1357 
1358         if (scale) {
1359                 if (count->run == 0) {
1360                         scaled = -1;
1361                         count->val = 0;
1362                 } else if (count->run < count->ena) {
1363                         scaled = 1;
1364                         count->val = (u64)((double) count->val * count->ena / count->run);
1365                 }
1366         }
1367 
1368         if (pscaled)
1369                 *pscaled = scaled;
1370 }
1371 
1372 static int perf_evsel__read_size(struct perf_evsel *evsel)
1373 {
1374         u64 read_format = evsel->attr.read_format;
1375         int entry = sizeof(u64); /* value */
1376         int size = 0;
1377         int nr = 1;
1378 
1379         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1380                 size += sizeof(u64);
1381 
1382         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1383                 size += sizeof(u64);
1384 
1385         if (read_format & PERF_FORMAT_ID)
1386                 entry += sizeof(u64);
1387 
1388         if (read_format & PERF_FORMAT_GROUP) {
1389                 nr = evsel->nr_members;
1390                 size += sizeof(u64);
1391         }
1392 
1393         size += entry * nr;
1394         return size;
1395 }
1396 
1397 int perf_evsel__read(struct perf_evsel *evsel, int cpu, int thread,
1398                      struct perf_counts_values *count)
1399 {
1400         size_t size = perf_evsel__read_size(evsel);
1401 
1402         memset(count, 0, sizeof(*count));
1403 
1404         if (FD(evsel, cpu, thread) < 0)
1405                 return -EINVAL;
1406 
1407         if (readn(FD(evsel, cpu, thread), count->values, size) <= 0)
1408                 return -errno;
1409 
1410         return 0;
1411 }
1412 
1413 static int
1414 perf_evsel__read_one(struct perf_evsel *evsel, int cpu, int thread)
1415 {
1416         struct perf_counts_values *count = perf_counts(evsel->counts, cpu, thread);
1417 
1418         return perf_evsel__read(evsel, cpu, thread, count);
1419 }
1420 
1421 static void
1422 perf_evsel__set_count(struct perf_evsel *counter, int cpu, int thread,
1423                       u64 val, u64 ena, u64 run)
1424 {
1425         struct perf_counts_values *count;
1426 
1427         count = perf_counts(counter->counts, cpu, thread);
1428 
1429         count->val    = val;
1430         count->ena    = ena;
1431         count->run    = run;
1432         count->loaded = true;
1433 }
1434 
1435 static int
1436 perf_evsel__process_group_data(struct perf_evsel *leader,
1437                                int cpu, int thread, u64 *data)
1438 {
1439         u64 read_format = leader->attr.read_format;
1440         struct sample_read_value *v;
1441         u64 nr, ena = 0, run = 0, i;
1442 
1443         nr = *data++;
1444 
1445         if (nr != (u64) leader->nr_members)
1446                 return -EINVAL;
1447 
1448         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1449                 ena = *data++;
1450 
1451         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1452                 run = *data++;
1453 
1454         v = (struct sample_read_value *) data;
1455 
1456         perf_evsel__set_count(leader, cpu, thread,
1457                               v[0].value, ena, run);
1458 
1459         for (i = 1; i < nr; i++) {
1460                 struct perf_evsel *counter;
1461 
1462                 counter = perf_evlist__id2evsel(leader->evlist, v[i].id);
1463                 if (!counter)
1464                         return -EINVAL;
1465 
1466                 perf_evsel__set_count(counter, cpu, thread,
1467                                       v[i].value, ena, run);
1468         }
1469 
1470         return 0;
1471 }
1472 
1473 static int
1474 perf_evsel__read_group(struct perf_evsel *leader, int cpu, int thread)
1475 {
1476         struct perf_stat_evsel *ps = leader->stats;
1477         u64 read_format = leader->attr.read_format;
1478         int size = perf_evsel__read_size(leader);
1479         u64 *data = ps->group_data;
1480 
1481         if (!(read_format & PERF_FORMAT_ID))
1482                 return -EINVAL;
1483 
1484         if (!perf_evsel__is_group_leader(leader))
1485                 return -EINVAL;
1486 
1487         if (!data) {
1488                 data = zalloc(size);
1489                 if (!data)
1490                         return -ENOMEM;
1491 
1492                 ps->group_data = data;
1493         }
1494 
1495         if (FD(leader, cpu, thread) < 0)
1496                 return -EINVAL;
1497 
1498         if (readn(FD(leader, cpu, thread), data, size) <= 0)
1499                 return -errno;
1500 
1501         return perf_evsel__process_group_data(leader, cpu, thread, data);
1502 }
1503 
1504 int perf_evsel__read_counter(struct perf_evsel *evsel, int cpu, int thread)
1505 {
1506         u64 read_format = evsel->attr.read_format;
1507 
1508         if (read_format & PERF_FORMAT_GROUP)
1509                 return perf_evsel__read_group(evsel, cpu, thread);
1510         else
1511                 return perf_evsel__read_one(evsel, cpu, thread);
1512 }
1513 
1514 int __perf_evsel__read_on_cpu(struct perf_evsel *evsel,
1515                               int cpu, int thread, bool scale)
1516 {
1517         struct perf_counts_values count;
1518         size_t nv = scale ? 3 : 1;
1519 
1520         if (FD(evsel, cpu, thread) < 0)
1521                 return -EINVAL;
1522 
1523         if (evsel->counts == NULL && perf_evsel__alloc_counts(evsel, cpu + 1, thread + 1) < 0)
1524                 return -ENOMEM;
1525 
1526         if (readn(FD(evsel, cpu, thread), &count, nv * sizeof(u64)) <= 0)
1527                 return -errno;
1528 
1529         perf_evsel__compute_deltas(evsel, cpu, thread, &count);
1530         perf_counts_values__scale(&count, scale, NULL);
1531         *perf_counts(evsel->counts, cpu, thread) = count;
1532         return 0;
1533 }
1534 
1535 static int get_group_fd(struct perf_evsel *evsel, int cpu, int thread)
1536 {
1537         struct perf_evsel *leader = evsel->leader;
1538         int fd;
1539 
1540         if (perf_evsel__is_group_leader(evsel))
1541                 return -1;
1542 
1543         /*
1544          * Leader must be already processed/open,
1545          * if not it's a bug.
1546          */
1547         BUG_ON(!leader->fd);
1548 
1549         fd = FD(leader, cpu, thread);
1550         BUG_ON(fd == -1);
1551 
1552         return fd;
1553 }
1554 
1555 struct bit_names {
1556         int bit;
1557         const char *name;
1558 };
1559 
1560 static void __p_bits(char *buf, size_t size, u64 value, struct bit_names *bits)
1561 {
1562         bool first_bit = true;
1563         int i = 0;
1564 
1565         do {
1566                 if (value & bits[i].bit) {
1567                         buf += scnprintf(buf, size, "%s%s", first_bit ? "" : "|", bits[i].name);
1568                         first_bit = false;
1569                 }
1570         } while (bits[++i].name != NULL);
1571 }
1572 
1573 static void __p_sample_type(char *buf, size_t size, u64 value)
1574 {
1575 #define bit_name(n) { PERF_SAMPLE_##n, #n }
1576         struct bit_names bits[] = {
1577                 bit_name(IP), bit_name(TID), bit_name(TIME), bit_name(ADDR),
1578                 bit_name(READ), bit_name(CALLCHAIN), bit_name(ID), bit_name(CPU),
1579                 bit_name(PERIOD), bit_name(STREAM_ID), bit_name(RAW),
1580                 bit_name(BRANCH_STACK), bit_name(REGS_USER), bit_name(STACK_USER),
1581                 bit_name(IDENTIFIER), bit_name(REGS_INTR), bit_name(DATA_SRC),
1582                 bit_name(WEIGHT), bit_name(PHYS_ADDR),
1583                 { .name = NULL, }
1584         };
1585 #undef bit_name
1586         __p_bits(buf, size, value, bits);
1587 }
1588 
1589 static void __p_branch_sample_type(char *buf, size_t size, u64 value)
1590 {
1591 #define bit_name(n) { PERF_SAMPLE_BRANCH_##n, #n }
1592         struct bit_names bits[] = {
1593                 bit_name(USER), bit_name(KERNEL), bit_name(HV), bit_name(ANY),
1594                 bit_name(ANY_CALL), bit_name(ANY_RETURN), bit_name(IND_CALL),
1595                 bit_name(ABORT_TX), bit_name(IN_TX), bit_name(NO_TX),
1596                 bit_name(COND), bit_name(CALL_STACK), bit_name(IND_JUMP),
1597                 bit_name(CALL), bit_name(NO_FLAGS), bit_name(NO_CYCLES),
1598                 { .name = NULL, }
1599         };
1600 #undef bit_name
1601         __p_bits(buf, size, value, bits);
1602 }
1603 
1604 static void __p_read_format(char *buf, size_t size, u64 value)
1605 {
1606 #define bit_name(n) { PERF_FORMAT_##n, #n }
1607         struct bit_names bits[] = {
1608                 bit_name(TOTAL_TIME_ENABLED), bit_name(TOTAL_TIME_RUNNING),
1609                 bit_name(ID), bit_name(GROUP),
1610                 { .name = NULL, }
1611         };
1612 #undef bit_name
1613         __p_bits(buf, size, value, bits);
1614 }
1615 
1616 #define BUF_SIZE                1024
1617 
1618 #define p_hex(val)              snprintf(buf, BUF_SIZE, "%#"PRIx64, (uint64_t)(val))
1619 #define p_unsigned(val)         snprintf(buf, BUF_SIZE, "%"PRIu64, (uint64_t)(val))
1620 #define p_signed(val)           snprintf(buf, BUF_SIZE, "%"PRId64, (int64_t)(val))
1621 #define p_sample_type(val)      __p_sample_type(buf, BUF_SIZE, val)
1622 #define p_branch_sample_type(val) __p_branch_sample_type(buf, BUF_SIZE, val)
1623 #define p_read_format(val)      __p_read_format(buf, BUF_SIZE, val)
1624 
1625 #define PRINT_ATTRn(_n, _f, _p)                         \
1626 do {                                                    \
1627         if (attr->_f) {                                 \
1628                 _p(attr->_f);                           \
1629                 ret += attr__fprintf(fp, _n, buf, priv);\
1630         }                                               \
1631 } while (0)
1632 
1633 #define PRINT_ATTRf(_f, _p)     PRINT_ATTRn(#_f, _f, _p)
1634 
1635 int perf_event_attr__fprintf(FILE *fp, struct perf_event_attr *attr,
1636                              attr__fprintf_f attr__fprintf, void *priv)
1637 {
1638         char buf[BUF_SIZE];
1639         int ret = 0;
1640 
1641         PRINT_ATTRf(type, p_unsigned);
1642         PRINT_ATTRf(size, p_unsigned);
1643         PRINT_ATTRf(config, p_hex);
1644         PRINT_ATTRn("{ sample_period, sample_freq }", sample_period, p_unsigned);
1645         PRINT_ATTRf(sample_type, p_sample_type);
1646         PRINT_ATTRf(read_format, p_read_format);
1647 
1648         PRINT_ATTRf(disabled, p_unsigned);
1649         PRINT_ATTRf(inherit, p_unsigned);
1650         PRINT_ATTRf(pinned, p_unsigned);
1651         PRINT_ATTRf(exclusive, p_unsigned);
1652         PRINT_ATTRf(exclude_user, p_unsigned);
1653         PRINT_ATTRf(exclude_kernel, p_unsigned);
1654         PRINT_ATTRf(exclude_hv, p_unsigned);
1655         PRINT_ATTRf(exclude_idle, p_unsigned);
1656         PRINT_ATTRf(mmap, p_unsigned);
1657         PRINT_ATTRf(comm, p_unsigned);
1658         PRINT_ATTRf(freq, p_unsigned);
1659         PRINT_ATTRf(inherit_stat, p_unsigned);
1660         PRINT_ATTRf(enable_on_exec, p_unsigned);
1661         PRINT_ATTRf(task, p_unsigned);
1662         PRINT_ATTRf(watermark, p_unsigned);
1663         PRINT_ATTRf(precise_ip, p_unsigned);
1664         PRINT_ATTRf(mmap_data, p_unsigned);
1665         PRINT_ATTRf(sample_id_all, p_unsigned);
1666         PRINT_ATTRf(exclude_host, p_unsigned);
1667         PRINT_ATTRf(exclude_guest, p_unsigned);
1668         PRINT_ATTRf(exclude_callchain_kernel, p_unsigned);
1669         PRINT_ATTRf(exclude_callchain_user, p_unsigned);
1670         PRINT_ATTRf(mmap2, p_unsigned);
1671         PRINT_ATTRf(comm_exec, p_unsigned);
1672         PRINT_ATTRf(use_clockid, p_unsigned);
1673         PRINT_ATTRf(context_switch, p_unsigned);
1674         PRINT_ATTRf(write_backward, p_unsigned);
1675         PRINT_ATTRf(namespaces, p_unsigned);
1676         PRINT_ATTRf(ksymbol, p_unsigned);
1677         PRINT_ATTRf(bpf_event, p_unsigned);
1678 
1679         PRINT_ATTRn("{ wakeup_events, wakeup_watermark }", wakeup_events, p_unsigned);
1680         PRINT_ATTRf(bp_type, p_unsigned);
1681         PRINT_ATTRn("{ bp_addr, config1 }", bp_addr, p_hex);
1682         PRINT_ATTRn("{ bp_len, config2 }", bp_len, p_hex);
1683         PRINT_ATTRf(branch_sample_type, p_branch_sample_type);
1684         PRINT_ATTRf(sample_regs_user, p_hex);
1685         PRINT_ATTRf(sample_stack_user, p_unsigned);
1686         PRINT_ATTRf(clockid, p_signed);
1687         PRINT_ATTRf(sample_regs_intr, p_hex);
1688         PRINT_ATTRf(aux_watermark, p_unsigned);
1689         PRINT_ATTRf(sample_max_stack, p_unsigned);
1690 
1691         return ret;
1692 }
1693 
1694 static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
1695                                 void *priv __maybe_unused)
1696 {
1697         return fprintf(fp, "  %-32s %s\n", name, val);
1698 }
1699 
1700 static void perf_evsel__remove_fd(struct perf_evsel *pos,
1701                                   int nr_cpus, int nr_threads,
1702                                   int thread_idx)
1703 {
1704         for (int cpu = 0; cpu < nr_cpus; cpu++)
1705                 for (int thread = thread_idx; thread < nr_threads - 1; thread++)
1706                         FD(pos, cpu, thread) = FD(pos, cpu, thread + 1);
1707 }
1708 
1709 static int update_fds(struct perf_evsel *evsel,
1710                       int nr_cpus, int cpu_idx,
1711                       int nr_threads, int thread_idx)
1712 {
1713         struct perf_evsel *pos;
1714 
1715         if (cpu_idx >= nr_cpus || thread_idx >= nr_threads)
1716                 return -EINVAL;
1717 
1718         evlist__for_each_entry(evsel->evlist, pos) {
1719                 nr_cpus = pos != evsel ? nr_cpus : cpu_idx;
1720 
1721                 perf_evsel__remove_fd(pos, nr_cpus, nr_threads, thread_idx);
1722 
1723                 /*
1724                  * Since fds for next evsel has not been created,
1725                  * there is no need to iterate whole event list.
1726                  */
1727                 if (pos == evsel)
1728                         break;
1729         }
1730         return 0;
1731 }
1732 
1733 static bool ignore_missing_thread(struct perf_evsel *evsel,
1734                                   int nr_cpus, int cpu,
1735                                   struct thread_map *threads,
1736                                   int thread, int err)
1737 {
1738         pid_t ignore_pid = thread_map__pid(threads, thread);
1739 
1740         if (!evsel->ignore_missing_thread)
1741                 return false;
1742 
1743         /* The system wide setup does not work with threads. */
1744         if (evsel->system_wide)
1745                 return false;
1746 
1747         /* The -ESRCH is perf event syscall errno for pid's not found. */
1748         if (err != -ESRCH)
1749                 return false;
1750 
1751         /* If there's only one thread, let it fail. */
1752         if (threads->nr == 1)
1753                 return false;
1754 
1755         /*
1756          * We should remove fd for missing_thread first
1757          * because thread_map__remove() will decrease threads->nr.
1758          */
1759         if (update_fds(evsel, nr_cpus, cpu, threads->nr, thread))
1760                 return false;
1761 
1762         if (thread_map__remove(threads, thread))
1763                 return false;
1764 
1765         pr_warning("WARNING: Ignored open failure for pid %d\n",
1766                    ignore_pid);
1767         return true;
1768 }
1769 
1770 static void display_attr(struct perf_event_attr *attr)
1771 {
1772         if (verbose >= 2) {
1773                 fprintf(stderr, "%.60s\n", graph_dotted_line);
1774                 fprintf(stderr, "perf_event_attr:\n");
1775                 perf_event_attr__fprintf(stderr, attr, __open_attr__fprintf, NULL);
1776                 fprintf(stderr, "%.60s\n", graph_dotted_line);
1777         }
1778 }
1779 
1780 static int perf_event_open(struct perf_evsel *evsel,
1781                            pid_t pid, int cpu, int group_fd,
1782                            unsigned long flags)
1783 {
1784         int precise_ip = evsel->attr.precise_ip;
1785         int fd;
1786 
1787         while (1) {
1788                 pr_debug2("sys_perf_event_open: pid %d  cpu %d  group_fd %d  flags %#lx",
1789                           pid, cpu, group_fd, flags);
1790 
1791                 fd = sys_perf_event_open(&evsel->attr, pid, cpu, group_fd, flags);
1792                 if (fd >= 0)
1793                         break;
1794 
1795                 /*
1796                  * Do quick precise_ip fallback if:
1797                  *  - there is precise_ip set in perf_event_attr
1798                  *  - maximum precise is requested
1799                  *  - sys_perf_event_open failed with ENOTSUP error,
1800                  *    which is associated with wrong precise_ip
1801                  */
1802                 if (!precise_ip || !evsel->precise_max || (errno != ENOTSUP))
1803                         break;
1804 
1805                 /*
1806                  * We tried all the precise_ip values, and it's
1807                  * still failing, so leave it to standard fallback.
1808                  */
1809                 if (!evsel->attr.precise_ip) {
1810                         evsel->attr.precise_ip = precise_ip;
1811                         break;
1812                 }
1813 
1814                 pr_debug2("\nsys_perf_event_open failed, error %d\n", -ENOTSUP);
1815                 evsel->attr.precise_ip--;
1816                 pr_debug2("decreasing precise_ip by one (%d)\n", evsel->attr.precise_ip);
1817                 display_attr(&evsel->attr);
1818         }
1819 
1820         return fd;
1821 }
1822 
1823 int perf_evsel__open(struct perf_evsel *evsel, struct cpu_map *cpus,
1824                      struct thread_map *threads)
1825 {
1826         int cpu, thread, nthreads;
1827         unsigned long flags = PERF_FLAG_FD_CLOEXEC;
1828         int pid = -1, err;
1829         enum { NO_CHANGE, SET_TO_MAX, INCREASED_MAX } set_rlimit = NO_CHANGE;
1830 
1831         if (perf_missing_features.write_backward && evsel->attr.write_backward)
1832                 return -EINVAL;
1833 
1834         if (cpus == NULL) {
1835                 static struct cpu_map *empty_cpu_map;
1836 
1837                 if (empty_cpu_map == NULL) {
1838                         empty_cpu_map = cpu_map__dummy_new();
1839                         if (empty_cpu_map == NULL)
1840                                 return -ENOMEM;
1841                 }
1842 
1843                 cpus = empty_cpu_map;
1844         }
1845 
1846         if (threads == NULL) {
1847                 static struct thread_map *empty_thread_map;
1848 
1849                 if (empty_thread_map == NULL) {
1850                         empty_thread_map = thread_map__new_by_tid(-1);
1851                         if (empty_thread_map == NULL)
1852                                 return -ENOMEM;
1853                 }
1854 
1855                 threads = empty_thread_map;
1856         }
1857 
1858         if (evsel->system_wide)
1859                 nthreads = 1;
1860         else
1861                 nthreads = threads->nr;
1862 
1863         if (evsel->fd == NULL &&
1864             perf_evsel__alloc_fd(evsel, cpus->nr, nthreads) < 0)
1865                 return -ENOMEM;
1866 
1867         if (evsel->cgrp) {
1868                 flags |= PERF_FLAG_PID_CGROUP;
1869                 pid = evsel->cgrp->fd;
1870         }
1871 
1872 fallback_missing_features:
1873         if (perf_missing_features.clockid_wrong)
1874                 evsel->attr.clockid = CLOCK_MONOTONIC; /* should always work */
1875         if (perf_missing_features.clockid) {
1876                 evsel->attr.use_clockid = 0;
1877                 evsel->attr.clockid = 0;
1878         }
1879         if (perf_missing_features.cloexec)
1880                 flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
1881         if (perf_missing_features.mmap2)
1882                 evsel->attr.mmap2 = 0;
1883         if (perf_missing_features.exclude_guest)
1884                 evsel->attr.exclude_guest = evsel->attr.exclude_host = 0;
1885         if (perf_missing_features.lbr_flags)
1886                 evsel->attr.branch_sample_type &= ~(PERF_SAMPLE_BRANCH_NO_FLAGS |
1887                                      PERF_SAMPLE_BRANCH_NO_CYCLES);
1888         if (perf_missing_features.group_read && evsel->attr.inherit)
1889                 evsel->attr.read_format &= ~(PERF_FORMAT_GROUP|PERF_FORMAT_ID);
1890         if (perf_missing_features.ksymbol)
1891                 evsel->attr.ksymbol = 0;
1892         if (perf_missing_features.bpf_event)
1893                 evsel->attr.bpf_event = 0;
1894 retry_sample_id:
1895         if (perf_missing_features.sample_id_all)
1896                 evsel->attr.sample_id_all = 0;
1897 
1898         display_attr(&evsel->attr);
1899 
1900         for (cpu = 0; cpu < cpus->nr; cpu++) {
1901 
1902                 for (thread = 0; thread < nthreads; thread++) {
1903                         int fd, group_fd;
1904 
1905                         if (!evsel->cgrp && !evsel->system_wide)
1906                                 pid = thread_map__pid(threads, thread);
1907 
1908                         group_fd = get_group_fd(evsel, cpu, thread);
1909 retry_open:
1910                         test_attr__ready();
1911 
1912                         fd = perf_event_open(evsel, pid, cpus->map[cpu],
1913                                              group_fd, flags);
1914 
1915                         FD(evsel, cpu, thread) = fd;
1916 
1917                         if (fd < 0) {
1918                                 err = -errno;
1919 
1920                                 if (ignore_missing_thread(evsel, cpus->nr, cpu, threads, thread, err)) {
1921                                         /*
1922                                          * We just removed 1 thread, so take a step
1923                                          * back on thread index and lower the upper
1924                                          * nthreads limit.
1925                                          */
1926                                         nthreads--;
1927                                         thread--;
1928 
1929                                         /* ... and pretend like nothing have happened. */
1930                                         err = 0;
1931                                         continue;
1932                                 }
1933 
1934                                 pr_debug2("\nsys_perf_event_open failed, error %d\n",
1935                                           err);
1936                                 goto try_fallback;
1937                         }
1938 
1939                         pr_debug2(" = %d\n", fd);
1940 
1941                         if (evsel->bpf_fd >= 0) {
1942                                 int evt_fd = fd;
1943                                 int bpf_fd = evsel->bpf_fd;
1944 
1945                                 err = ioctl(evt_fd,
1946                                             PERF_EVENT_IOC_SET_BPF,
1947                                             bpf_fd);
1948                                 if (err && errno != EEXIST) {
1949                                         pr_err("failed to attach bpf fd %d: %s\n",
1950                                                bpf_fd, strerror(errno));
1951                                         err = -EINVAL;
1952                                         goto out_close;
1953                                 }
1954                         }
1955 
1956                         set_rlimit = NO_CHANGE;
1957 
1958                         /*
1959                          * If we succeeded but had to kill clockid, fail and
1960                          * have perf_evsel__open_strerror() print us a nice
1961                          * error.
1962                          */
1963                         if (perf_missing_features.clockid ||
1964                             perf_missing_features.clockid_wrong) {
1965                                 err = -EINVAL;
1966                                 goto out_close;
1967                         }
1968                 }
1969         }
1970 
1971         return 0;
1972 
1973 try_fallback:
1974         /*
1975          * perf stat needs between 5 and 22 fds per CPU. When we run out
1976          * of them try to increase the limits.
1977          */
1978         if (err == -EMFILE && set_rlimit < INCREASED_MAX) {
1979                 struct rlimit l;
1980                 int old_errno = errno;
1981 
1982                 if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
1983                         if (set_rlimit == NO_CHANGE)
1984                                 l.rlim_cur = l.rlim_max;
1985                         else {
1986                                 l.rlim_cur = l.rlim_max + 1000;
1987                                 l.rlim_max = l.rlim_cur;
1988                         }
1989                         if (setrlimit(RLIMIT_NOFILE, &l) == 0) {
1990                                 set_rlimit++;
1991                                 errno = old_errno;
1992                                 goto retry_open;
1993                         }
1994                 }
1995                 errno = old_errno;
1996         }
1997 
1998         if (err != -EINVAL || cpu > 0 || thread > 0)
1999                 goto out_close;
2000 
2001         /*
2002          * Must probe features in the order they were added to the
2003          * perf_event_attr interface.
2004          */
2005         if (!perf_missing_features.bpf_event && evsel->attr.bpf_event) {
2006                 perf_missing_features.bpf_event = true;
2007                 pr_debug2("switching off bpf_event\n");
2008                 goto fallback_missing_features;
2009         } else if (!perf_missing_features.ksymbol && evsel->attr.ksymbol) {
2010                 perf_missing_features.ksymbol = true;
2011                 pr_debug2("switching off ksymbol\n");
2012                 goto fallback_missing_features;
2013         } else if (!perf_missing_features.write_backward && evsel->attr.write_backward) {
2014                 perf_missing_features.write_backward = true;
2015                 pr_debug2("switching off write_backward\n");
2016                 goto out_close;
2017         } else if (!perf_missing_features.clockid_wrong && evsel->attr.use_clockid) {
2018                 perf_missing_features.clockid_wrong = true;
2019                 pr_debug2("switching off clockid\n");
2020                 goto fallback_missing_features;
2021         } else if (!perf_missing_features.clockid && evsel->attr.use_clockid) {
2022                 perf_missing_features.clockid = true;
2023                 pr_debug2("switching off use_clockid\n");
2024                 goto fallback_missing_features;
2025         } else if (!perf_missing_features.cloexec && (flags & PERF_FLAG_FD_CLOEXEC)) {
2026                 perf_missing_features.cloexec = true;
2027                 pr_debug2("switching off cloexec flag\n");
2028                 goto fallback_missing_features;
2029         } else if (!perf_missing_features.mmap2 && evsel->attr.mmap2) {
2030                 perf_missing_features.mmap2 = true;
2031                 pr_debug2("switching off mmap2\n");
2032                 goto fallback_missing_features;
2033         } else if (!perf_missing_features.exclude_guest &&
2034                    (evsel->attr.exclude_guest || evsel->attr.exclude_host)) {
2035                 perf_missing_features.exclude_guest = true;
2036                 pr_debug2("switching off exclude_guest, exclude_host\n");
2037                 goto fallback_missing_features;
2038         } else if (!perf_missing_features.sample_id_all) {
2039                 perf_missing_features.sample_id_all = true;
2040                 pr_debug2("switching off sample_id_all\n");
2041                 goto retry_sample_id;
2042         } else if (!perf_missing_features.lbr_flags &&
2043                         (evsel->attr.branch_sample_type &
2044                          (PERF_SAMPLE_BRANCH_NO_CYCLES |
2045                           PERF_SAMPLE_BRANCH_NO_FLAGS))) {
2046                 perf_missing_features.lbr_flags = true;
2047                 pr_debug2("switching off branch sample type no (cycles/flags)\n");
2048                 goto fallback_missing_features;
2049         } else if (!perf_missing_features.group_read &&
2050                     evsel->attr.inherit &&
2051                    (evsel->attr.read_format & PERF_FORMAT_GROUP) &&
2052                    perf_evsel__is_group_leader(evsel)) {
2053                 perf_missing_features.group_read = true;
2054                 pr_debug2("switching off group read\n");
2055                 goto fallback_missing_features;
2056         }
2057 out_close:
2058         if (err)
2059                 threads->err_thread = thread;
2060 
2061         do {
2062                 while (--thread >= 0) {
2063                         close(FD(evsel, cpu, thread));
2064                         FD(evsel, cpu, thread) = -1;
2065                 }
2066                 thread = nthreads;
2067         } while (--cpu >= 0);
2068         return err;
2069 }
2070 
2071 void perf_evsel__close(struct perf_evsel *evsel)
2072 {
2073         if (evsel->fd == NULL)
2074                 return;
2075 
2076         perf_evsel__close_fd(evsel);
2077         perf_evsel__free_fd(evsel);
2078         perf_evsel__free_id(evsel);
2079 }
2080 
2081 int perf_evsel__open_per_cpu(struct perf_evsel *evsel,
2082                              struct cpu_map *cpus)
2083 {
2084         return perf_evsel__open(evsel, cpus, NULL);
2085 }
2086 
2087 int perf_evsel__open_per_thread(struct perf_evsel *evsel,
2088                                 struct thread_map *threads)
2089 {
2090         return perf_evsel__open(evsel, NULL, threads);
2091 }
2092 
2093 static int perf_evsel__parse_id_sample(const struct perf_evsel *evsel,
2094                                        const union perf_event *event,
2095                                        struct perf_sample *sample)
2096 {
2097         u64 type = evsel->attr.sample_type;
2098         const u64 *array = event->sample.array;
2099         bool swapped = evsel->needs_swap;
2100         union u64_swap u;
2101 
2102         array += ((event->header.size -
2103                    sizeof(event->header)) / sizeof(u64)) - 1;
2104 
2105         if (type & PERF_SAMPLE_IDENTIFIER) {
2106                 sample->id = *array;
2107                 array--;
2108         }
2109 
2110         if (type & PERF_SAMPLE_CPU) {
2111                 u.val64 = *array;
2112                 if (swapped) {
2113                         /* undo swap of u64, then swap on individual u32s */
2114                         u.val64 = bswap_64(u.val64);
2115                         u.val32[0] = bswap_32(u.val32[0]);
2116                 }
2117 
2118                 sample->cpu = u.val32[0];
2119                 array--;
2120         }
2121 
2122         if (type & PERF_SAMPLE_STREAM_ID) {
2123                 sample->stream_id = *array;
2124                 array--;
2125         }
2126 
2127         if (type & PERF_SAMPLE_ID) {
2128                 sample->id = *array;
2129                 array--;
2130         }
2131 
2132         if (type & PERF_SAMPLE_TIME) {
2133                 sample->time = *array;
2134                 array--;
2135         }
2136 
2137         if (type & PERF_SAMPLE_TID) {
2138                 u.val64 = *array;
2139                 if (swapped) {
2140                         /* undo swap of u64, then swap on individual u32s */
2141                         u.val64 = bswap_64(u.val64);
2142                         u.val32[0] = bswap_32(u.val32[0]);
2143                         u.val32[1] = bswap_32(u.val32[1]);
2144                 }
2145 
2146                 sample->pid = u.val32[0];
2147                 sample->tid = u.val32[1];
2148                 array--;
2149         }
2150 
2151         return 0;
2152 }
2153 
2154 static inline bool overflow(const void *endp, u16 max_size, const void *offset,
2155                             u64 size)
2156 {
2157         return size > max_size || offset + size > endp;
2158 }
2159 
2160 #define OVERFLOW_CHECK(offset, size, max_size)                          \
2161         do {                                                            \
2162                 if (overflow(endp, (max_size), (offset), (size)))       \
2163                         return -EFAULT;                                 \
2164         } while (0)
2165 
2166 #define OVERFLOW_CHECK_u64(offset) \
2167         OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
2168 
2169 static int
2170 perf_event__check_size(union perf_event *event, unsigned int sample_size)
2171 {
2172         /*
2173          * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
2174          * up to PERF_SAMPLE_PERIOD.  After that overflow() must be used to
2175          * check the format does not go past the end of the event.
2176          */
2177         if (sample_size + sizeof(event->header) > event->header.size)
2178                 return -EFAULT;
2179 
2180         return 0;
2181 }
2182 
2183 int perf_evsel__parse_sample(struct perf_evsel *evsel, union perf_event *event,
2184                              struct perf_sample *data)
2185 {
2186         u64 type = evsel->attr.sample_type;
2187         bool swapped = evsel->needs_swap;
2188         const u64 *array;
2189         u16 max_size = event->header.size;
2190         const void *endp = (void *)event + max_size;
2191         u64 sz;
2192 
2193         /*
2194          * used for cross-endian analysis. See git commit 65014ab3
2195          * for why this goofiness is needed.
2196          */
2197         union u64_swap u;
2198 
2199         memset(data, 0, sizeof(*data));
2200         data->cpu = data->pid = data->tid = -1;
2201         data->stream_id = data->id = data->time = -1ULL;
2202         data->period = evsel->attr.sample_period;
2203         data->cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2204         data->misc    = event->header.misc;
2205         data->id = -1ULL;
2206         data->data_src = PERF_MEM_DATA_SRC_NONE;
2207 
2208         if (event->header.type != PERF_RECORD_SAMPLE) {
2209                 if (!evsel->attr.sample_id_all)
2210                         return 0;
2211                 return perf_evsel__parse_id_sample(evsel, event, data);
2212         }
2213 
2214         array = event->sample.array;
2215 
2216         if (perf_event__check_size(event, evsel->sample_size))
2217                 return -EFAULT;
2218 
2219         if (type & PERF_SAMPLE_IDENTIFIER) {
2220                 data->id = *array;
2221                 array++;
2222         }
2223 
2224         if (type & PERF_SAMPLE_IP) {
2225                 data->ip = *array;
2226                 array++;
2227         }
2228 
2229         if (type & PERF_SAMPLE_TID) {
2230                 u.val64 = *array;
2231                 if (swapped) {
2232                         /* undo swap of u64, then swap on individual u32s */
2233                         u.val64 = bswap_64(u.val64);
2234                         u.val32[0] = bswap_32(u.val32[0]);
2235                         u.val32[1] = bswap_32(u.val32[1]);
2236                 }
2237 
2238                 data->pid = u.val32[0];
2239                 data->tid = u.val32[1];
2240                 array++;
2241         }
2242 
2243         if (type & PERF_SAMPLE_TIME) {
2244                 data->time = *array;
2245                 array++;
2246         }
2247 
2248         if (type & PERF_SAMPLE_ADDR) {
2249                 data->addr = *array;
2250                 array++;
2251         }
2252 
2253         if (type & PERF_SAMPLE_ID) {
2254                 data->id = *array;
2255                 array++;
2256         }
2257 
2258         if (type & PERF_SAMPLE_STREAM_ID) {
2259                 data->stream_id = *array;
2260                 array++;
2261         }
2262 
2263         if (type & PERF_SAMPLE_CPU) {
2264 
2265                 u.val64 = *array;
2266                 if (swapped) {
2267                         /* undo swap of u64, then swap on individual u32s */
2268                         u.val64 = bswap_64(u.val64);
2269                         u.val32[0] = bswap_32(u.val32[0]);
2270                 }
2271 
2272                 data->cpu = u.val32[0];
2273                 array++;
2274         }
2275 
2276         if (type & PERF_SAMPLE_PERIOD) {
2277                 data->period = *array;
2278                 array++;
2279         }
2280 
2281         if (type & PERF_SAMPLE_READ) {
2282                 u64 read_format = evsel->attr.read_format;
2283 
2284                 OVERFLOW_CHECK_u64(array);
2285                 if (read_format & PERF_FORMAT_GROUP)
2286                         data->read.group.nr = *array;
2287                 else
2288                         data->read.one.value = *array;
2289 
2290                 array++;
2291 
2292                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2293                         OVERFLOW_CHECK_u64(array);
2294                         data->read.time_enabled = *array;
2295                         array++;
2296                 }
2297 
2298                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2299                         OVERFLOW_CHECK_u64(array);
2300                         data->read.time_running = *array;
2301                         array++;
2302                 }
2303 
2304                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2305                 if (read_format & PERF_FORMAT_GROUP) {
2306                         const u64 max_group_nr = UINT64_MAX /
2307                                         sizeof(struct sample_read_value);
2308 
2309                         if (data->read.group.nr > max_group_nr)
2310                                 return -EFAULT;
2311                         sz = data->read.group.nr *
2312                              sizeof(struct sample_read_value);
2313                         OVERFLOW_CHECK(array, sz, max_size);
2314                         data->read.group.values =
2315                                         (struct sample_read_value *)array;
2316                         array = (void *)array + sz;
2317                 } else {
2318                         OVERFLOW_CHECK_u64(array);
2319                         data->read.one.id = *array;
2320                         array++;
2321                 }
2322         }
2323 
2324         if (evsel__has_callchain(evsel)) {
2325                 const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
2326 
2327                 OVERFLOW_CHECK_u64(array);
2328                 data->callchain = (struct ip_callchain *)array++;
2329                 if (data->callchain->nr > max_callchain_nr)
2330                         return -EFAULT;
2331                 sz = data->callchain->nr * sizeof(u64);
2332                 OVERFLOW_CHECK(array, sz, max_size);
2333                 array = (void *)array + sz;
2334         }
2335 
2336         if (type & PERF_SAMPLE_RAW) {
2337                 OVERFLOW_CHECK_u64(array);
2338                 u.val64 = *array;
2339 
2340                 /*
2341                  * Undo swap of u64, then swap on individual u32s,
2342                  * get the size of the raw area and undo all of the
2343                  * swap. The pevent interface handles endianity by
2344                  * itself.
2345                  */
2346                 if (swapped) {
2347                         u.val64 = bswap_64(u.val64);
2348                         u.val32[0] = bswap_32(u.val32[0]);
2349                         u.val32[1] = bswap_32(u.val32[1]);
2350                 }
2351                 data->raw_size = u.val32[0];
2352 
2353                 /*
2354                  * The raw data is aligned on 64bits including the
2355                  * u32 size, so it's safe to use mem_bswap_64.
2356                  */
2357                 if (swapped)
2358                         mem_bswap_64((void *) array, data->raw_size);
2359 
2360                 array = (void *)array + sizeof(u32);
2361 
2362                 OVERFLOW_CHECK(array, data->raw_size, max_size);
2363                 data->raw_data = (void *)array;
2364                 array = (void *)array + data->raw_size;
2365         }
2366 
2367         if (type & PERF_SAMPLE_BRANCH_STACK) {
2368                 const u64 max_branch_nr = UINT64_MAX /
2369                                           sizeof(struct branch_entry);
2370 
2371                 OVERFLOW_CHECK_u64(array);
2372                 data->branch_stack = (struct branch_stack *)array++;
2373 
2374                 if (data->branch_stack->nr > max_branch_nr)
2375                         return -EFAULT;
2376                 sz = data->branch_stack->nr * sizeof(struct branch_entry);
2377                 OVERFLOW_CHECK(array, sz, max_size);
2378                 array = (void *)array + sz;
2379         }
2380 
2381         if (type & PERF_SAMPLE_REGS_USER) {
2382                 OVERFLOW_CHECK_u64(array);
2383                 data->user_regs.abi = *array;
2384                 array++;
2385 
2386                 if (data->user_regs.abi) {
2387                         u64 mask = evsel->attr.sample_regs_user;
2388 
2389                         sz = hweight64(mask) * sizeof(u64);
2390                         OVERFLOW_CHECK(array, sz, max_size);
2391                         data->user_regs.mask = mask;
2392                         data->user_regs.regs = (u64 *)array;
2393                         array = (void *)array + sz;
2394                 }
2395         }
2396 
2397         if (type & PERF_SAMPLE_STACK_USER) {
2398                 OVERFLOW_CHECK_u64(array);
2399                 sz = *array++;
2400 
2401                 data->user_stack.offset = ((char *)(array - 1)
2402                                           - (char *) event);
2403 
2404                 if (!sz) {
2405                         data->user_stack.size = 0;
2406                 } else {
2407                         OVERFLOW_CHECK(array, sz, max_size);
2408                         data->user_stack.data = (char *)array;
2409                         array = (void *)array + sz;
2410                         OVERFLOW_CHECK_u64(array);
2411                         data->user_stack.size = *array++;
2412                         if (WARN_ONCE(data->user_stack.size > sz,
2413                                       "user stack dump failure\n"))
2414                                 return -EFAULT;
2415                 }
2416         }
2417 
2418         if (type & PERF_SAMPLE_WEIGHT) {
2419                 OVERFLOW_CHECK_u64(array);
2420                 data->weight = *array;
2421                 array++;
2422         }
2423 
2424         if (type & PERF_SAMPLE_DATA_SRC) {
2425                 OVERFLOW_CHECK_u64(array);
2426                 data->data_src = *array;
2427                 array++;
2428         }
2429 
2430         if (type & PERF_SAMPLE_TRANSACTION) {
2431                 OVERFLOW_CHECK_u64(array);
2432                 data->transaction = *array;
2433                 array++;
2434         }
2435 
2436         data->intr_regs.abi = PERF_SAMPLE_REGS_ABI_NONE;
2437         if (type & PERF_SAMPLE_REGS_INTR) {
2438                 OVERFLOW_CHECK_u64(array);
2439                 data->intr_regs.abi = *array;
2440                 array++;
2441 
2442                 if (data->intr_regs.abi != PERF_SAMPLE_REGS_ABI_NONE) {
2443                         u64 mask = evsel->attr.sample_regs_intr;
2444 
2445                         sz = hweight64(mask) * sizeof(u64);
2446                         OVERFLOW_CHECK(array, sz, max_size);
2447                         data->intr_regs.mask = mask;
2448                         data->intr_regs.regs = (u64 *)array;
2449                         array = (void *)array + sz;
2450                 }
2451         }
2452 
2453         data->phys_addr = 0;
2454         if (type & PERF_SAMPLE_PHYS_ADDR) {
2455                 data->phys_addr = *array;
2456                 array++;
2457         }
2458 
2459         return 0;
2460 }
2461 
2462 int perf_evsel__parse_sample_timestamp(struct perf_evsel *evsel,
2463                                        union perf_event *event,
2464                                        u64 *timestamp)
2465 {
2466         u64 type = evsel->attr.sample_type;
2467         const u64 *array;
2468 
2469         if (!(type & PERF_SAMPLE_TIME))
2470                 return -1;
2471 
2472         if (event->header.type != PERF_RECORD_SAMPLE) {
2473                 struct perf_sample data = {
2474                         .time = -1ULL,
2475                 };
2476 
2477                 if (!evsel->attr.sample_id_all)
2478                         return -1;
2479                 if (perf_evsel__parse_id_sample(evsel, event, &data))
2480                         return -1;
2481 
2482                 *timestamp = data.time;
2483                 return 0;
2484         }
2485 
2486         array = event->sample.array;
2487 
2488         if (perf_event__check_size(event, evsel->sample_size))
2489                 return -EFAULT;
2490 
2491         if (type & PERF_SAMPLE_IDENTIFIER)
2492                 array++;
2493 
2494         if (type & PERF_SAMPLE_IP)
2495                 array++;
2496 
2497         if (type & PERF_SAMPLE_TID)
2498                 array++;
2499 
2500         if (type & PERF_SAMPLE_TIME)
2501                 *timestamp = *array;
2502 
2503         return 0;
2504 }
2505 
2506 size_t perf_event__sample_event_size(const struct perf_sample *sample, u64 type,
2507                                      u64 read_format)
2508 {
2509         size_t sz, result = sizeof(struct sample_event);
2510 
2511         if (type & PERF_SAMPLE_IDENTIFIER)
2512                 result += sizeof(u64);
2513 
2514         if (type & PERF_SAMPLE_IP)
2515                 result += sizeof(u64);
2516 
2517         if (type & PERF_SAMPLE_TID)
2518                 result += sizeof(u64);
2519 
2520         if (type & PERF_SAMPLE_TIME)
2521                 result += sizeof(u64);
2522 
2523         if (type & PERF_SAMPLE_ADDR)
2524                 result += sizeof(u64);
2525 
2526         if (type & PERF_SAMPLE_ID)
2527                 result += sizeof(u64);
2528 
2529         if (type & PERF_SAMPLE_STREAM_ID)
2530                 result += sizeof(u64);
2531 
2532         if (type & PERF_SAMPLE_CPU)
2533                 result += sizeof(u64);
2534 
2535         if (type & PERF_SAMPLE_PERIOD)
2536                 result += sizeof(u64);
2537 
2538         if (type & PERF_SAMPLE_READ) {
2539                 result += sizeof(u64);
2540                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2541                         result += sizeof(u64);
2542                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2543                         result += sizeof(u64);
2544                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2545                 if (read_format & PERF_FORMAT_GROUP) {
2546                         sz = sample->read.group.nr *
2547                              sizeof(struct sample_read_value);
2548                         result += sz;
2549                 } else {
2550                         result += sizeof(u64);
2551                 }
2552         }
2553 
2554         if (type & PERF_SAMPLE_CALLCHAIN) {
2555                 sz = (sample->callchain->nr + 1) * sizeof(u64);
2556                 result += sz;
2557         }
2558 
2559         if (type & PERF_SAMPLE_RAW) {
2560                 result += sizeof(u32);
2561                 result += sample->raw_size;
2562         }
2563 
2564         if (type & PERF_SAMPLE_BRANCH_STACK) {
2565                 sz = sample->branch_stack->nr * sizeof(struct branch_entry);
2566                 sz += sizeof(u64);
2567                 result += sz;
2568         }
2569 
2570         if (type & PERF_SAMPLE_REGS_USER) {
2571                 if (sample->user_regs.abi) {
2572                         result += sizeof(u64);
2573                         sz = hweight64(sample->user_regs.mask) * sizeof(u64);
2574                         result += sz;
2575                 } else {
2576                         result += sizeof(u64);
2577                 }
2578         }
2579 
2580         if (type & PERF_SAMPLE_STACK_USER) {
2581                 sz = sample->user_stack.size;
2582                 result += sizeof(u64);
2583                 if (sz) {
2584                         result += sz;
2585                         result += sizeof(u64);
2586                 }
2587         }
2588 
2589         if (type & PERF_SAMPLE_WEIGHT)
2590                 result += sizeof(u64);
2591 
2592         if (type & PERF_SAMPLE_DATA_SRC)
2593                 result += sizeof(u64);
2594 
2595         if (type & PERF_SAMPLE_TRANSACTION)
2596                 result += sizeof(u64);
2597 
2598         if (type & PERF_SAMPLE_REGS_INTR) {
2599                 if (sample->intr_regs.abi) {
2600                         result += sizeof(u64);
2601                         sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
2602                         result += sz;
2603                 } else {
2604                         result += sizeof(u64);
2605                 }
2606         }
2607 
2608         if (type & PERF_SAMPLE_PHYS_ADDR)
2609                 result += sizeof(u64);
2610 
2611         return result;
2612 }
2613 
2614 int perf_event__synthesize_sample(union perf_event *event, u64 type,
2615                                   u64 read_format,
2616                                   const struct perf_sample *sample)
2617 {
2618         u64 *array;
2619         size_t sz;
2620         /*
2621          * used for cross-endian analysis. See git commit 65014ab3
2622          * for why this goofiness is needed.
2623          */
2624         union u64_swap u;
2625 
2626         array = event->sample.array;
2627 
2628         if (type & PERF_SAMPLE_IDENTIFIER) {
2629                 *array = sample->id;
2630                 array++;
2631         }
2632 
2633         if (type & PERF_SAMPLE_IP) {
2634                 *array = sample->ip;
2635                 array++;
2636         }
2637 
2638         if (type & PERF_SAMPLE_TID) {
2639                 u.val32[0] = sample->pid;
2640                 u.val32[1] = sample->tid;
2641                 *array = u.val64;
2642                 array++;
2643         }
2644 
2645         if (type & PERF_SAMPLE_TIME) {
2646                 *array = sample->time;
2647                 array++;
2648         }
2649 
2650         if (type & PERF_SAMPLE_ADDR) {
2651                 *array = sample->addr;
2652                 array++;
2653         }
2654 
2655         if (type & PERF_SAMPLE_ID) {
2656                 *array = sample->id;
2657                 array++;
2658         }
2659 
2660         if (type & PERF_SAMPLE_STREAM_ID) {
2661                 *array = sample->stream_id;
2662                 array++;
2663         }
2664 
2665         if (type & PERF_SAMPLE_CPU) {
2666                 u.val32[0] = sample->cpu;
2667                 u.val32[1] = 0;
2668                 *array = u.val64;
2669                 array++;
2670         }
2671 
2672         if (type & PERF_SAMPLE_PERIOD) {
2673                 *array = sample->period;
2674                 array++;
2675         }
2676 
2677         if (type & PERF_SAMPLE_READ) {
2678                 if (read_format & PERF_FORMAT_GROUP)
2679                         *array = sample->read.group.nr;
2680                 else
2681                         *array = sample->read.one.value;
2682                 array++;
2683 
2684                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2685                         *array = sample->read.time_enabled;
2686                         array++;
2687                 }
2688 
2689                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2690                         *array = sample->read.time_running;
2691                         array++;
2692                 }
2693 
2694                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2695                 if (read_format & PERF_FORMAT_GROUP) {
2696                         sz = sample->read.group.nr *
2697                              sizeof(struct sample_read_value);
2698                         memcpy(array, sample->read.group.values, sz);
2699                         array = (void *)array + sz;
2700                 } else {
2701                         *array = sample->read.one.id;
2702                         array++;
2703                 }
2704         }
2705 
2706         if (type & PERF_SAMPLE_CALLCHAIN) {
2707                 sz = (sample->callchain->nr + 1) * sizeof(u64);
2708                 memcpy(array, sample->callchain, sz);
2709                 array = (void *)array + sz;
2710         }
2711 
2712         if (type & PERF_SAMPLE_RAW) {
2713                 u.val32[0] = sample->raw_size;
2714                 *array = u.val64;
2715                 array = (void *)array + sizeof(u32);
2716 
2717                 memcpy(array, sample->raw_data, sample->raw_size);
2718                 array = (void *)array + sample->raw_size;
2719         }
2720 
2721         if (type & PERF_SAMPLE_BRANCH_STACK) {
2722                 sz = sample->branch_stack->nr * sizeof(struct branch_entry);
2723                 sz += sizeof(u64);
2724                 memcpy(array, sample->branch_stack, sz);
2725                 array = (void *)array + sz;
2726         }
2727 
2728         if (type & PERF_SAMPLE_REGS_USER) {
2729                 if (sample->user_regs.abi) {
2730                         *array++ = sample->user_regs.abi;
2731                         sz = hweight64(sample->user_regs.mask) * sizeof(u64);
2732                         memcpy(array, sample->user_regs.regs, sz);
2733                         array = (void *)array + sz;
2734                 } else {
2735                         *array++ = 0;
2736                 }
2737         }
2738 
2739         if (type & PERF_SAMPLE_STACK_USER) {
2740                 sz = sample->user_stack.size;
2741                 *array++ = sz;
2742                 if (sz) {
2743                         memcpy(array, sample->user_stack.data, sz);
2744                         array = (void *)array + sz;
2745                         *array++ = sz;
2746                 }
2747         }
2748 
2749         if (type & PERF_SAMPLE_WEIGHT) {
2750                 *array = sample->weight;
2751                 array++;
2752         }
2753 
2754         if (type & PERF_SAMPLE_DATA_SRC) {
2755                 *array = sample->data_src;
2756                 array++;
2757         }
2758 
2759         if (type & PERF_SAMPLE_TRANSACTION) {
2760                 *array = sample->transaction;
2761                 array++;
2762         }
2763 
2764         if (type & PERF_SAMPLE_REGS_INTR) {
2765                 if (sample->intr_regs.abi) {
2766                         *array++ = sample->intr_regs.abi;
2767                         sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
2768                         memcpy(array, sample->intr_regs.regs, sz);
2769                         array = (void *)array + sz;
2770                 } else {
2771                         *array++ = 0;
2772                 }
2773         }
2774 
2775         if (type & PERF_SAMPLE_PHYS_ADDR) {
2776                 *array = sample->phys_addr;
2777                 array++;
2778         }
2779 
2780         return 0;
2781 }
2782 
2783 struct tep_format_field *perf_evsel__field(struct perf_evsel *evsel, const char *name)
2784 {
2785         return tep_find_field(evsel->tp_format, name);
2786 }
2787 
2788 void *perf_evsel__rawptr(struct perf_evsel *evsel, struct perf_sample *sample,
2789                          const char *name)
2790 {
2791         struct tep_format_field *field = perf_evsel__field(evsel, name);
2792         int offset;
2793 
2794         if (!field)
2795                 return NULL;
2796 
2797         offset = field->offset;
2798 
2799         if (field->flags & TEP_FIELD_IS_DYNAMIC) {
2800                 offset = *(int *)(sample->raw_data + field->offset);
2801                 offset &= 0xffff;
2802         }
2803 
2804         return sample->raw_data + offset;
2805 }
2806 
2807 u64 format_field__intval(struct tep_format_field *field, struct perf_sample *sample,
2808                          bool needs_swap)
2809 {
2810         u64 value;
2811         void *ptr = sample->raw_data + field->offset;
2812 
2813         switch (field->size) {
2814         case 1:
2815                 return *(u8 *)ptr;
2816         case 2:
2817                 value = *(u16 *)ptr;
2818                 break;
2819         case 4:
2820                 value = *(u32 *)ptr;
2821                 break;
2822         case 8:
2823                 memcpy(&value, ptr, sizeof(u64));
2824                 break;
2825         default:
2826                 return 0;
2827         }
2828 
2829         if (!needs_swap)
2830                 return value;
2831 
2832         switch (field->size) {
2833         case 2:
2834                 return bswap_16(value);
2835         case 4:
2836                 return bswap_32(value);
2837         case 8:
2838                 return bswap_64(value);
2839         default:
2840                 return 0;
2841         }
2842 
2843         return 0;
2844 }
2845 
2846 u64 perf_evsel__intval(struct perf_evsel *evsel, struct perf_sample *sample,
2847                        const char *name)
2848 {
2849         struct tep_format_field *field = perf_evsel__field(evsel, name);
2850 
2851         if (!field)
2852                 return 0;
2853 
2854         return field ? format_field__intval(field, sample, evsel->needs_swap) : 0;
2855 }
2856 
2857 bool perf_evsel__fallback(struct perf_evsel *evsel, int err,
2858                           char *msg, size_t msgsize)
2859 {
2860         int paranoid;
2861 
2862         if ((err == ENOENT || err == ENXIO || err == ENODEV) &&
2863             evsel->attr.type   == PERF_TYPE_HARDWARE &&
2864             evsel->attr.config == PERF_COUNT_HW_CPU_CYCLES) {
2865                 /*
2866                  * If it's cycles then fall back to hrtimer based
2867                  * cpu-clock-tick sw counter, which is always available even if
2868                  * no PMU support.
2869                  *
2870                  * PPC returns ENXIO until 2.6.37 (behavior changed with commit
2871                  * b0a873e).
2872                  */
2873                 scnprintf(msg, msgsize, "%s",
2874 "The cycles event is not supported, trying to fall back to cpu-clock-ticks");
2875 
2876                 evsel->attr.type   = PERF_TYPE_SOFTWARE;
2877                 evsel->attr.config = PERF_COUNT_SW_CPU_CLOCK;
2878 
2879                 zfree(&evsel->name);
2880                 return true;
2881         } else if (err == EACCES && !evsel->attr.exclude_kernel &&
2882                    (paranoid = perf_event_paranoid()) > 1) {
2883                 const char *name = perf_evsel__name(evsel);
2884                 char *new_name;
2885                 const char *sep = ":";
2886 
2887                 /* Is there already the separator in the name. */
2888                 if (strchr(name, '/') ||
2889                     strchr(name, ':'))
2890                         sep = "";
2891 
2892                 if (asprintf(&new_name, "%s%su", name, sep) < 0)
2893                         return false;
2894 
2895                 if (evsel->name)
2896                         free(evsel->name);
2897                 evsel->name = new_name;
2898                 scnprintf(msg, msgsize,
2899 "kernel.perf_event_paranoid=%d, trying to fall back to excluding kernel samples", paranoid);
2900                 evsel->attr.exclude_kernel = 1;
2901 
2902                 return true;
2903         }
2904 
2905         return false;
2906 }
2907 
2908 static bool find_process(const char *name)
2909 {
2910         size_t len = strlen(name);
2911         DIR *dir;
2912         struct dirent *d;
2913         int ret = -1;
2914 
2915         dir = opendir(procfs__mountpoint());
2916         if (!dir)
2917                 return false;
2918 
2919         /* Walk through the directory. */
2920         while (ret && (d = readdir(dir)) != NULL) {
2921                 char path[PATH_MAX];
2922                 char *data;
2923                 size_t size;
2924 
2925                 if ((d->d_type != DT_DIR) ||
2926                      !strcmp(".", d->d_name) ||
2927                      !strcmp("..", d->d_name))
2928                         continue;
2929 
2930                 scnprintf(path, sizeof(path), "%s/%s/comm",
2931                           procfs__mountpoint(), d->d_name);
2932 
2933                 if (filename__read_str(path, &data, &size))
2934                         continue;
2935 
2936                 ret = strncmp(name, data, len);
2937                 free(data);
2938         }
2939 
2940         closedir(dir);
2941         return ret ? false : true;
2942 }
2943 
2944 int perf_evsel__open_strerror(struct perf_evsel *evsel, struct target *target,
2945                               int err, char *msg, size_t size)
2946 {
2947         char sbuf[STRERR_BUFSIZE];
2948         int printed = 0;
2949 
2950         switch (err) {
2951         case EPERM:
2952         case EACCES:
2953                 if (err == EPERM)
2954                         printed = scnprintf(msg, size,
2955                                 "No permission to enable %s event.\n\n",
2956                                 perf_evsel__name(evsel));
2957 
2958                 return scnprintf(msg + printed, size - printed,
2959                  "You may not have permission to collect %sstats.\n\n"
2960                  "Consider tweaking /proc/sys/kernel/perf_event_paranoid,\n"
2961                  "which controls use of the performance events system by\n"
2962                  "unprivileged users (without CAP_SYS_ADMIN).\n\n"
2963                  "The current value is %d:\n\n"
2964                  "  -1: Allow use of (almost) all events by all users\n"
2965                  "      Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK\n"
2966                  ">= 0: Disallow ftrace function tracepoint by users without CAP_SYS_ADMIN\n"
2967                  "      Disallow raw tracepoint access by users without CAP_SYS_ADMIN\n"
2968                  ">= 1: Disallow CPU event access by users without CAP_SYS_ADMIN\n"
2969                  ">= 2: Disallow kernel profiling by users without CAP_SYS_ADMIN\n\n"
2970                  "To make this setting permanent, edit /etc/sysctl.conf too, e.g.:\n\n"
2971                  "      kernel.perf_event_paranoid = -1\n" ,
2972                                  target->system_wide ? "system-wide " : "",
2973                                  perf_event_paranoid());
2974         case ENOENT:
2975                 return scnprintf(msg, size, "The %s event is not supported.",
2976                                  perf_evsel__name(evsel));
2977         case EMFILE:
2978                 return scnprintf(msg, size, "%s",
2979                          "Too many events are opened.\n"
2980                          "Probably the maximum number of open file descriptors has been reached.\n"
2981                          "Hint: Try again after reducing the number of events.\n"
2982                          "Hint: Try increasing the limit with 'ulimit -n <limit>'");
2983         case ENOMEM:
2984                 if (evsel__has_callchain(evsel) &&
2985                     access("/proc/sys/kernel/perf_event_max_stack", F_OK) == 0)
2986                         return scnprintf(msg, size,
2987                                          "Not enough memory to setup event with callchain.\n"
2988                                          "Hint: Try tweaking /proc/sys/kernel/perf_event_max_stack\n"
2989                                          "Hint: Current value: %d", sysctl__max_stack());
2990                 break;
2991         case ENODEV:
2992                 if (target->cpu_list)
2993                         return scnprintf(msg, size, "%s",
2994          "No such device - did you specify an out-of-range profile CPU?");
2995                 break;
2996         case EOPNOTSUPP:
2997                 if (evsel->attr.sample_period != 0)
2998                         return scnprintf(msg, size,
2999         "%s: PMU Hardware doesn't support sampling/overflow-interrupts. Try 'perf stat'",
3000                                          perf_evsel__name(evsel));
3001                 if (evsel->attr.precise_ip)
3002                         return scnprintf(msg, size, "%s",
3003         "\'precise\' request may not be supported. Try removing 'p' modifier.");
3004 #if defined(__i386__) || defined(__x86_64__)
3005                 if (evsel->attr.type == PERF_TYPE_HARDWARE)
3006                         return scnprintf(msg, size, "%s",
3007         "No hardware sampling interrupt available.\n");
3008 #endif
3009                 break;
3010         case EBUSY:
3011                 if (find_process("oprofiled"))
3012                         return scnprintf(msg, size,
3013         "The PMU counters are busy/taken by another profiler.\n"
3014         "We found oprofile daemon running, please stop it and try again.");
3015                 break;
3016         case EINVAL:
3017                 if (evsel->attr.write_backward && perf_missing_features.write_backward)
3018                         return scnprintf(msg, size, "Reading from overwrite event is not supported by this kernel.");
3019                 if (perf_missing_features.clockid)
3020                         return scnprintf(msg, size, "clockid feature not supported.");
3021                 if (perf_missing_features.clockid_wrong)
3022                         return scnprintf(msg, size, "wrong clockid (%d).", clockid);
3023                 break;
3024         default:
3025                 break;
3026         }
3027 
3028         return scnprintf(msg, size,
3029         "The sys_perf_event_open() syscall returned with %d (%s) for event (%s).\n"
3030         "/bin/dmesg | grep -i perf may provide additional information.\n",
3031                          err, str_error_r(err, sbuf, sizeof(sbuf)),
3032                          perf_evsel__name(evsel));
3033 }
3034 
3035 struct perf_env *perf_evsel__env(struct perf_evsel *evsel)
3036 {
3037         if (evsel && evsel->evlist)
3038                 return evsel->evlist->env;
3039         return NULL;
3040 }
3041 
3042 static int store_evsel_ids(struct perf_evsel *evsel, struct perf_evlist *evlist)
3043 {
3044         int cpu, thread;
3045 
3046         for (cpu = 0; cpu < xyarray__max_x(evsel->fd); cpu++) {
3047                 for (thread = 0; thread < xyarray__max_y(evsel->fd);
3048                      thread++) {
3049                         int fd = FD(evsel, cpu, thread);
3050 
3051                         if (perf_evlist__id_add_fd(evlist, evsel,
3052                                                    cpu, thread, fd) < 0)
3053                                 return -1;
3054                 }
3055         }
3056 
3057         return 0;
3058 }
3059 
3060 int perf_evsel__store_ids(struct perf_evsel *evsel, struct perf_evlist *evlist)
3061 {
3062         struct cpu_map *cpus = evsel->cpus;
3063         struct thread_map *threads = evsel->threads;
3064 
3065         if (perf_evsel__alloc_id(evsel, cpus->nr, threads->nr))
3066                 return -ENOMEM;
3067 
3068         return store_evsel_ids(evsel, evlist);
3069 }
3070 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp