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