xref: /openbmc/linux/tools/perf/util/evsel.c (revision 53651b28cfb637ef604abc189d877948d1af39bb)
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 (opts->kernel_callchains)
684 		attr->exclude_callchain_user = 1;
685 	if (opts->user_callchains)
686 		attr->exclude_callchain_kernel = 1;
687 	if (param->record_mode == CALLCHAIN_LBR) {
688 		if (!opts->branch_stack) {
689 			if (attr->exclude_user) {
690 				pr_warning("LBR callstack option is only available "
691 					   "to get user callchain information. "
692 					   "Falling back to framepointers.\n");
693 			} else {
694 				perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
695 				attr->branch_sample_type = PERF_SAMPLE_BRANCH_USER |
696 							PERF_SAMPLE_BRANCH_CALL_STACK |
697 							PERF_SAMPLE_BRANCH_NO_CYCLES |
698 							PERF_SAMPLE_BRANCH_NO_FLAGS;
699 			}
700 		} else
701 			 pr_warning("Cannot use LBR callstack with branch stack. "
702 				    "Falling back to framepointers.\n");
703 	}
704 
705 	if (param->record_mode == CALLCHAIN_DWARF) {
706 		if (!function) {
707 			perf_evsel__set_sample_bit(evsel, REGS_USER);
708 			perf_evsel__set_sample_bit(evsel, STACK_USER);
709 			if (opts->sample_user_regs && DWARF_MINIMAL_REGS != PERF_REGS_MASK) {
710 				attr->sample_regs_user |= DWARF_MINIMAL_REGS;
711 				pr_warning("WARNING: The use of --call-graph=dwarf may require all the user registers, "
712 					   "specifying a subset with --user-regs may render DWARF unwinding unreliable, "
713 					   "so the minimal registers set (IP, SP) is explicitly forced.\n");
714 			} else {
715 				attr->sample_regs_user |= PERF_REGS_MASK;
716 			}
717 			attr->sample_stack_user = param->dump_size;
718 			attr->exclude_callchain_user = 1;
719 		} else {
720 			pr_info("Cannot use DWARF unwind for function trace event,"
721 				" falling back to framepointers.\n");
722 		}
723 	}
724 
725 	if (function) {
726 		pr_info("Disabling user space callchains for function trace event.\n");
727 		attr->exclude_callchain_user = 1;
728 	}
729 }
730 
731 void perf_evsel__config_callchain(struct perf_evsel *evsel,
732 				  struct record_opts *opts,
733 				  struct callchain_param *param)
734 {
735 	if (param->enabled)
736 		return __perf_evsel__config_callchain(evsel, opts, param);
737 }
738 
739 static void
740 perf_evsel__reset_callgraph(struct perf_evsel *evsel,
741 			    struct callchain_param *param)
742 {
743 	struct perf_event_attr *attr = &evsel->attr;
744 
745 	perf_evsel__reset_sample_bit(evsel, CALLCHAIN);
746 	if (param->record_mode == CALLCHAIN_LBR) {
747 		perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
748 		attr->branch_sample_type &= ~(PERF_SAMPLE_BRANCH_USER |
749 					      PERF_SAMPLE_BRANCH_CALL_STACK);
750 	}
751 	if (param->record_mode == CALLCHAIN_DWARF) {
752 		perf_evsel__reset_sample_bit(evsel, REGS_USER);
753 		perf_evsel__reset_sample_bit(evsel, STACK_USER);
754 	}
755 }
756 
757 static void apply_config_terms(struct perf_evsel *evsel,
758 			       struct record_opts *opts, bool track)
759 {
760 	struct perf_evsel_config_term *term;
761 	struct list_head *config_terms = &evsel->config_terms;
762 	struct perf_event_attr *attr = &evsel->attr;
763 	/* callgraph default */
764 	struct callchain_param param = {
765 		.record_mode = callchain_param.record_mode,
766 	};
767 	u32 dump_size = 0;
768 	int max_stack = 0;
769 	const char *callgraph_buf = NULL;
770 
771 	list_for_each_entry(term, config_terms, list) {
772 		switch (term->type) {
773 		case PERF_EVSEL__CONFIG_TERM_PERIOD:
774 			if (!(term->weak && opts->user_interval != ULLONG_MAX)) {
775 				attr->sample_period = term->val.period;
776 				attr->freq = 0;
777 				perf_evsel__reset_sample_bit(evsel, PERIOD);
778 			}
779 			break;
780 		case PERF_EVSEL__CONFIG_TERM_FREQ:
781 			if (!(term->weak && opts->user_freq != UINT_MAX)) {
782 				attr->sample_freq = term->val.freq;
783 				attr->freq = 1;
784 				perf_evsel__set_sample_bit(evsel, PERIOD);
785 			}
786 			break;
787 		case PERF_EVSEL__CONFIG_TERM_TIME:
788 			if (term->val.time)
789 				perf_evsel__set_sample_bit(evsel, TIME);
790 			else
791 				perf_evsel__reset_sample_bit(evsel, TIME);
792 			break;
793 		case PERF_EVSEL__CONFIG_TERM_CALLGRAPH:
794 			callgraph_buf = term->val.callgraph;
795 			break;
796 		case PERF_EVSEL__CONFIG_TERM_BRANCH:
797 			if (term->val.branch && strcmp(term->val.branch, "no")) {
798 				perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
799 				parse_branch_str(term->val.branch,
800 						 &attr->branch_sample_type);
801 			} else
802 				perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
803 			break;
804 		case PERF_EVSEL__CONFIG_TERM_STACK_USER:
805 			dump_size = term->val.stack_user;
806 			break;
807 		case PERF_EVSEL__CONFIG_TERM_MAX_STACK:
808 			max_stack = term->val.max_stack;
809 			break;
810 		case PERF_EVSEL__CONFIG_TERM_MAX_EVENTS:
811 			evsel->max_events = term->val.max_events;
812 			break;
813 		case PERF_EVSEL__CONFIG_TERM_INHERIT:
814 			/*
815 			 * attr->inherit should has already been set by
816 			 * perf_evsel__config. If user explicitly set
817 			 * inherit using config terms, override global
818 			 * opt->no_inherit setting.
819 			 */
820 			attr->inherit = term->val.inherit ? 1 : 0;
821 			break;
822 		case PERF_EVSEL__CONFIG_TERM_OVERWRITE:
823 			attr->write_backward = term->val.overwrite ? 1 : 0;
824 			break;
825 		case PERF_EVSEL__CONFIG_TERM_DRV_CFG:
826 			break;
827 		case PERF_EVSEL__CONFIG_TERM_PERCORE:
828 			break;
829 		default:
830 			break;
831 		}
832 	}
833 
834 	/* User explicitly set per-event callgraph, clear the old setting and reset. */
835 	if ((callgraph_buf != NULL) || (dump_size > 0) || max_stack) {
836 		bool sample_address = false;
837 
838 		if (max_stack) {
839 			param.max_stack = max_stack;
840 			if (callgraph_buf == NULL)
841 				callgraph_buf = "fp";
842 		}
843 
844 		/* parse callgraph parameters */
845 		if (callgraph_buf != NULL) {
846 			if (!strcmp(callgraph_buf, "no")) {
847 				param.enabled = false;
848 				param.record_mode = CALLCHAIN_NONE;
849 			} else {
850 				param.enabled = true;
851 				if (parse_callchain_record(callgraph_buf, &param)) {
852 					pr_err("per-event callgraph setting for %s failed. "
853 					       "Apply callgraph global setting for it\n",
854 					       evsel->name);
855 					return;
856 				}
857 				if (param.record_mode == CALLCHAIN_DWARF)
858 					sample_address = true;
859 			}
860 		}
861 		if (dump_size > 0) {
862 			dump_size = round_up(dump_size, sizeof(u64));
863 			param.dump_size = dump_size;
864 		}
865 
866 		/* If global callgraph set, clear it */
867 		if (callchain_param.enabled)
868 			perf_evsel__reset_callgraph(evsel, &callchain_param);
869 
870 		/* set perf-event callgraph */
871 		if (param.enabled) {
872 			if (sample_address) {
873 				perf_evsel__set_sample_bit(evsel, ADDR);
874 				perf_evsel__set_sample_bit(evsel, DATA_SRC);
875 				evsel->attr.mmap_data = track;
876 			}
877 			perf_evsel__config_callchain(evsel, opts, &param);
878 		}
879 	}
880 }
881 
882 static bool is_dummy_event(struct perf_evsel *evsel)
883 {
884 	return (evsel->attr.type == PERF_TYPE_SOFTWARE) &&
885 	       (evsel->attr.config == PERF_COUNT_SW_DUMMY);
886 }
887 
888 /*
889  * The enable_on_exec/disabled value strategy:
890  *
891  *  1) For any type of traced program:
892  *    - all independent events and group leaders are disabled
893  *    - all group members are enabled
894  *
895  *     Group members are ruled by group leaders. They need to
896  *     be enabled, because the group scheduling relies on that.
897  *
898  *  2) For traced programs executed by perf:
899  *     - all independent events and group leaders have
900  *       enable_on_exec set
901  *     - we don't specifically enable or disable any event during
902  *       the record command
903  *
904  *     Independent events and group leaders are initially disabled
905  *     and get enabled by exec. Group members are ruled by group
906  *     leaders as stated in 1).
907  *
908  *  3) For traced programs attached by perf (pid/tid):
909  *     - we specifically enable or disable all events during
910  *       the record command
911  *
912  *     When attaching events to already running traced we
913  *     enable/disable events specifically, as there's no
914  *     initial traced exec call.
915  */
916 void perf_evsel__config(struct perf_evsel *evsel, struct record_opts *opts,
917 			struct callchain_param *callchain)
918 {
919 	struct perf_evsel *leader = evsel->leader;
920 	struct perf_event_attr *attr = &evsel->attr;
921 	int track = evsel->tracking;
922 	bool per_cpu = opts->target.default_per_cpu && !opts->target.per_thread;
923 
924 	attr->sample_id_all = perf_missing_features.sample_id_all ? 0 : 1;
925 	attr->inherit	    = !opts->no_inherit;
926 	attr->write_backward = opts->overwrite ? 1 : 0;
927 
928 	perf_evsel__set_sample_bit(evsel, IP);
929 	perf_evsel__set_sample_bit(evsel, TID);
930 
931 	if (evsel->sample_read) {
932 		perf_evsel__set_sample_bit(evsel, READ);
933 
934 		/*
935 		 * We need ID even in case of single event, because
936 		 * PERF_SAMPLE_READ process ID specific data.
937 		 */
938 		perf_evsel__set_sample_id(evsel, false);
939 
940 		/*
941 		 * Apply group format only if we belong to group
942 		 * with more than one members.
943 		 */
944 		if (leader->nr_members > 1) {
945 			attr->read_format |= PERF_FORMAT_GROUP;
946 			attr->inherit = 0;
947 		}
948 	}
949 
950 	/*
951 	 * We default some events to have a default interval. But keep
952 	 * it a weak assumption overridable by the user.
953 	 */
954 	if (!attr->sample_period || (opts->user_freq != UINT_MAX ||
955 				     opts->user_interval != ULLONG_MAX)) {
956 		if (opts->freq) {
957 			perf_evsel__set_sample_bit(evsel, PERIOD);
958 			attr->freq		= 1;
959 			attr->sample_freq	= opts->freq;
960 		} else {
961 			attr->sample_period = opts->default_interval;
962 		}
963 	}
964 
965 	/*
966 	 * Disable sampling for all group members other
967 	 * than leader in case leader 'leads' the sampling.
968 	 */
969 	if ((leader != evsel) && leader->sample_read) {
970 		attr->freq           = 0;
971 		attr->sample_freq    = 0;
972 		attr->sample_period  = 0;
973 		attr->write_backward = 0;
974 
975 		/*
976 		 * We don't get sample for slave events, we make them
977 		 * when delivering group leader sample. Set the slave
978 		 * event to follow the master sample_type to ease up
979 		 * report.
980 		 */
981 		attr->sample_type = leader->attr.sample_type;
982 	}
983 
984 	if (opts->no_samples)
985 		attr->sample_freq = 0;
986 
987 	if (opts->inherit_stat) {
988 		evsel->attr.read_format |=
989 			PERF_FORMAT_TOTAL_TIME_ENABLED |
990 			PERF_FORMAT_TOTAL_TIME_RUNNING |
991 			PERF_FORMAT_ID;
992 		attr->inherit_stat = 1;
993 	}
994 
995 	if (opts->sample_address) {
996 		perf_evsel__set_sample_bit(evsel, ADDR);
997 		attr->mmap_data = track;
998 	}
999 
1000 	/*
1001 	 * We don't allow user space callchains for  function trace
1002 	 * event, due to issues with page faults while tracing page
1003 	 * fault handler and its overall trickiness nature.
1004 	 */
1005 	if (perf_evsel__is_function_event(evsel))
1006 		evsel->attr.exclude_callchain_user = 1;
1007 
1008 	if (callchain && callchain->enabled && !evsel->no_aux_samples)
1009 		perf_evsel__config_callchain(evsel, opts, callchain);
1010 
1011 	if (opts->sample_intr_regs) {
1012 		attr->sample_regs_intr = opts->sample_intr_regs;
1013 		perf_evsel__set_sample_bit(evsel, REGS_INTR);
1014 	}
1015 
1016 	if (opts->sample_user_regs) {
1017 		attr->sample_regs_user |= opts->sample_user_regs;
1018 		perf_evsel__set_sample_bit(evsel, REGS_USER);
1019 	}
1020 
1021 	if (target__has_cpu(&opts->target) || opts->sample_cpu)
1022 		perf_evsel__set_sample_bit(evsel, CPU);
1023 
1024 	/*
1025 	 * When the user explicitly disabled time don't force it here.
1026 	 */
1027 	if (opts->sample_time &&
1028 	    (!perf_missing_features.sample_id_all &&
1029 	    (!opts->no_inherit || target__has_cpu(&opts->target) || per_cpu ||
1030 	     opts->sample_time_set)))
1031 		perf_evsel__set_sample_bit(evsel, TIME);
1032 
1033 	if (opts->raw_samples && !evsel->no_aux_samples) {
1034 		perf_evsel__set_sample_bit(evsel, TIME);
1035 		perf_evsel__set_sample_bit(evsel, RAW);
1036 		perf_evsel__set_sample_bit(evsel, CPU);
1037 	}
1038 
1039 	if (opts->sample_address)
1040 		perf_evsel__set_sample_bit(evsel, DATA_SRC);
1041 
1042 	if (opts->sample_phys_addr)
1043 		perf_evsel__set_sample_bit(evsel, PHYS_ADDR);
1044 
1045 	if (opts->no_buffering) {
1046 		attr->watermark = 0;
1047 		attr->wakeup_events = 1;
1048 	}
1049 	if (opts->branch_stack && !evsel->no_aux_samples) {
1050 		perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
1051 		attr->branch_sample_type = opts->branch_stack;
1052 	}
1053 
1054 	if (opts->sample_weight)
1055 		perf_evsel__set_sample_bit(evsel, WEIGHT);
1056 
1057 	attr->task  = track;
1058 	attr->mmap  = track;
1059 	attr->mmap2 = track && !perf_missing_features.mmap2;
1060 	attr->comm  = track;
1061 	attr->ksymbol = track && !perf_missing_features.ksymbol;
1062 	attr->bpf_event = track && !opts->no_bpf_event &&
1063 		!perf_missing_features.bpf_event;
1064 
1065 	if (opts->record_namespaces)
1066 		attr->namespaces  = track;
1067 
1068 	if (opts->record_switch_events)
1069 		attr->context_switch = track;
1070 
1071 	if (opts->sample_transaction)
1072 		perf_evsel__set_sample_bit(evsel, TRANSACTION);
1073 
1074 	if (opts->running_time) {
1075 		evsel->attr.read_format |=
1076 			PERF_FORMAT_TOTAL_TIME_ENABLED |
1077 			PERF_FORMAT_TOTAL_TIME_RUNNING;
1078 	}
1079 
1080 	/*
1081 	 * XXX see the function comment above
1082 	 *
1083 	 * Disabling only independent events or group leaders,
1084 	 * keeping group members enabled.
1085 	 */
1086 	if (perf_evsel__is_group_leader(evsel))
1087 		attr->disabled = 1;
1088 
1089 	/*
1090 	 * Setting enable_on_exec for independent events and
1091 	 * group leaders for traced executed by perf.
1092 	 */
1093 	if (target__none(&opts->target) && perf_evsel__is_group_leader(evsel) &&
1094 		!opts->initial_delay)
1095 		attr->enable_on_exec = 1;
1096 
1097 	if (evsel->immediate) {
1098 		attr->disabled = 0;
1099 		attr->enable_on_exec = 0;
1100 	}
1101 
1102 	clockid = opts->clockid;
1103 	if (opts->use_clockid) {
1104 		attr->use_clockid = 1;
1105 		attr->clockid = opts->clockid;
1106 	}
1107 
1108 	if (evsel->precise_max)
1109 		attr->precise_ip = 3;
1110 
1111 	if (opts->all_user) {
1112 		attr->exclude_kernel = 1;
1113 		attr->exclude_user   = 0;
1114 	}
1115 
1116 	if (opts->all_kernel) {
1117 		attr->exclude_kernel = 0;
1118 		attr->exclude_user   = 1;
1119 	}
1120 
1121 	if (evsel->own_cpus || evsel->unit)
1122 		evsel->attr.read_format |= PERF_FORMAT_ID;
1123 
1124 	/*
1125 	 * Apply event specific term settings,
1126 	 * it overloads any global configuration.
1127 	 */
1128 	apply_config_terms(evsel, opts, track);
1129 
1130 	evsel->ignore_missing_thread = opts->ignore_missing_thread;
1131 
1132 	/* The --period option takes the precedence. */
1133 	if (opts->period_set) {
1134 		if (opts->period)
1135 			perf_evsel__set_sample_bit(evsel, PERIOD);
1136 		else
1137 			perf_evsel__reset_sample_bit(evsel, PERIOD);
1138 	}
1139 
1140 	/*
1141 	 * For initial_delay, a dummy event is added implicitly.
1142 	 * The software event will trigger -EOPNOTSUPP error out,
1143 	 * if BRANCH_STACK bit is set.
1144 	 */
1145 	if (opts->initial_delay && is_dummy_event(evsel))
1146 		perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
1147 }
1148 
1149 static int perf_evsel__alloc_fd(struct perf_evsel *evsel, int ncpus, int nthreads)
1150 {
1151 	if (evsel->system_wide)
1152 		nthreads = 1;
1153 
1154 	evsel->fd = xyarray__new(ncpus, nthreads, sizeof(int));
1155 
1156 	if (evsel->fd) {
1157 		int cpu, thread;
1158 		for (cpu = 0; cpu < ncpus; cpu++) {
1159 			for (thread = 0; thread < nthreads; thread++) {
1160 				FD(evsel, cpu, thread) = -1;
1161 			}
1162 		}
1163 	}
1164 
1165 	return evsel->fd != NULL ? 0 : -ENOMEM;
1166 }
1167 
1168 static int perf_evsel__run_ioctl(struct perf_evsel *evsel,
1169 			  int ioc,  void *arg)
1170 {
1171 	int cpu, thread;
1172 
1173 	for (cpu = 0; cpu < xyarray__max_x(evsel->fd); cpu++) {
1174 		for (thread = 0; thread < xyarray__max_y(evsel->fd); thread++) {
1175 			int fd = FD(evsel, cpu, thread),
1176 			    err = ioctl(fd, ioc, arg);
1177 
1178 			if (err)
1179 				return err;
1180 		}
1181 	}
1182 
1183 	return 0;
1184 }
1185 
1186 int perf_evsel__apply_filter(struct perf_evsel *evsel, const char *filter)
1187 {
1188 	return perf_evsel__run_ioctl(evsel,
1189 				     PERF_EVENT_IOC_SET_FILTER,
1190 				     (void *)filter);
1191 }
1192 
1193 int perf_evsel__set_filter(struct perf_evsel *evsel, const char *filter)
1194 {
1195 	char *new_filter = strdup(filter);
1196 
1197 	if (new_filter != NULL) {
1198 		free(evsel->filter);
1199 		evsel->filter = new_filter;
1200 		return 0;
1201 	}
1202 
1203 	return -1;
1204 }
1205 
1206 static int perf_evsel__append_filter(struct perf_evsel *evsel,
1207 				     const char *fmt, const char *filter)
1208 {
1209 	char *new_filter;
1210 
1211 	if (evsel->filter == NULL)
1212 		return perf_evsel__set_filter(evsel, filter);
1213 
1214 	if (asprintf(&new_filter, fmt, evsel->filter, filter) > 0) {
1215 		free(evsel->filter);
1216 		evsel->filter = new_filter;
1217 		return 0;
1218 	}
1219 
1220 	return -1;
1221 }
1222 
1223 int perf_evsel__append_tp_filter(struct perf_evsel *evsel, const char *filter)
1224 {
1225 	return perf_evsel__append_filter(evsel, "(%s) && (%s)", filter);
1226 }
1227 
1228 int perf_evsel__append_addr_filter(struct perf_evsel *evsel, const char *filter)
1229 {
1230 	return perf_evsel__append_filter(evsel, "%s,%s", filter);
1231 }
1232 
1233 int perf_evsel__enable(struct perf_evsel *evsel)
1234 {
1235 	int err = perf_evsel__run_ioctl(evsel, PERF_EVENT_IOC_ENABLE, 0);
1236 
1237 	if (!err)
1238 		evsel->disabled = false;
1239 
1240 	return err;
1241 }
1242 
1243 int perf_evsel__disable(struct perf_evsel *evsel)
1244 {
1245 	int err = perf_evsel__run_ioctl(evsel, PERF_EVENT_IOC_DISABLE, 0);
1246 	/*
1247 	 * We mark it disabled here so that tools that disable a event can
1248 	 * ignore events after they disable it. I.e. the ring buffer may have
1249 	 * already a few more events queued up before the kernel got the stop
1250 	 * request.
1251 	 */
1252 	if (!err)
1253 		evsel->disabled = true;
1254 
1255 	return err;
1256 }
1257 
1258 int perf_evsel__alloc_id(struct perf_evsel *evsel, int ncpus, int nthreads)
1259 {
1260 	if (ncpus == 0 || nthreads == 0)
1261 		return 0;
1262 
1263 	if (evsel->system_wide)
1264 		nthreads = 1;
1265 
1266 	evsel->sample_id = xyarray__new(ncpus, nthreads, sizeof(struct perf_sample_id));
1267 	if (evsel->sample_id == NULL)
1268 		return -ENOMEM;
1269 
1270 	evsel->id = zalloc(ncpus * nthreads * sizeof(u64));
1271 	if (evsel->id == NULL) {
1272 		xyarray__delete(evsel->sample_id);
1273 		evsel->sample_id = NULL;
1274 		return -ENOMEM;
1275 	}
1276 
1277 	return 0;
1278 }
1279 
1280 static void perf_evsel__free_fd(struct perf_evsel *evsel)
1281 {
1282 	xyarray__delete(evsel->fd);
1283 	evsel->fd = NULL;
1284 }
1285 
1286 static void perf_evsel__free_id(struct perf_evsel *evsel)
1287 {
1288 	xyarray__delete(evsel->sample_id);
1289 	evsel->sample_id = NULL;
1290 	zfree(&evsel->id);
1291 }
1292 
1293 static void perf_evsel__free_config_terms(struct perf_evsel *evsel)
1294 {
1295 	struct perf_evsel_config_term *term, *h;
1296 
1297 	list_for_each_entry_safe(term, h, &evsel->config_terms, list) {
1298 		list_del(&term->list);
1299 		free(term);
1300 	}
1301 }
1302 
1303 void perf_evsel__close_fd(struct perf_evsel *evsel)
1304 {
1305 	int cpu, thread;
1306 
1307 	for (cpu = 0; cpu < xyarray__max_x(evsel->fd); cpu++)
1308 		for (thread = 0; thread < xyarray__max_y(evsel->fd); ++thread) {
1309 			close(FD(evsel, cpu, thread));
1310 			FD(evsel, cpu, thread) = -1;
1311 		}
1312 }
1313 
1314 void perf_evsel__exit(struct perf_evsel *evsel)
1315 {
1316 	assert(list_empty(&evsel->node));
1317 	assert(evsel->evlist == NULL);
1318 	perf_evsel__free_counts(evsel);
1319 	perf_evsel__free_fd(evsel);
1320 	perf_evsel__free_id(evsel);
1321 	perf_evsel__free_config_terms(evsel);
1322 	cgroup__put(evsel->cgrp);
1323 	cpu_map__put(evsel->cpus);
1324 	cpu_map__put(evsel->own_cpus);
1325 	thread_map__put(evsel->threads);
1326 	zfree(&evsel->group_name);
1327 	zfree(&evsel->name);
1328 	perf_evsel__object.fini(evsel);
1329 }
1330 
1331 void perf_evsel__delete(struct perf_evsel *evsel)
1332 {
1333 	perf_evsel__exit(evsel);
1334 	free(evsel);
1335 }
1336 
1337 void perf_evsel__compute_deltas(struct perf_evsel *evsel, int cpu, int thread,
1338 				struct perf_counts_values *count)
1339 {
1340 	struct perf_counts_values tmp;
1341 
1342 	if (!evsel->prev_raw_counts)
1343 		return;
1344 
1345 	if (cpu == -1) {
1346 		tmp = evsel->prev_raw_counts->aggr;
1347 		evsel->prev_raw_counts->aggr = *count;
1348 	} else {
1349 		tmp = *perf_counts(evsel->prev_raw_counts, cpu, thread);
1350 		*perf_counts(evsel->prev_raw_counts, cpu, thread) = *count;
1351 	}
1352 
1353 	count->val = count->val - tmp.val;
1354 	count->ena = count->ena - tmp.ena;
1355 	count->run = count->run - tmp.run;
1356 }
1357 
1358 void perf_counts_values__scale(struct perf_counts_values *count,
1359 			       bool scale, s8 *pscaled)
1360 {
1361 	s8 scaled = 0;
1362 
1363 	if (scale) {
1364 		if (count->run == 0) {
1365 			scaled = -1;
1366 			count->val = 0;
1367 		} else if (count->run < count->ena) {
1368 			scaled = 1;
1369 			count->val = (u64)((double) count->val * count->ena / count->run);
1370 		}
1371 	}
1372 
1373 	if (pscaled)
1374 		*pscaled = scaled;
1375 }
1376 
1377 static int perf_evsel__read_size(struct perf_evsel *evsel)
1378 {
1379 	u64 read_format = evsel->attr.read_format;
1380 	int entry = sizeof(u64); /* value */
1381 	int size = 0;
1382 	int nr = 1;
1383 
1384 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1385 		size += sizeof(u64);
1386 
1387 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1388 		size += sizeof(u64);
1389 
1390 	if (read_format & PERF_FORMAT_ID)
1391 		entry += sizeof(u64);
1392 
1393 	if (read_format & PERF_FORMAT_GROUP) {
1394 		nr = evsel->nr_members;
1395 		size += sizeof(u64);
1396 	}
1397 
1398 	size += entry * nr;
1399 	return size;
1400 }
1401 
1402 int perf_evsel__read(struct perf_evsel *evsel, int cpu, int thread,
1403 		     struct perf_counts_values *count)
1404 {
1405 	size_t size = perf_evsel__read_size(evsel);
1406 
1407 	memset(count, 0, sizeof(*count));
1408 
1409 	if (FD(evsel, cpu, thread) < 0)
1410 		return -EINVAL;
1411 
1412 	if (readn(FD(evsel, cpu, thread), count->values, size) <= 0)
1413 		return -errno;
1414 
1415 	return 0;
1416 }
1417 
1418 static int
1419 perf_evsel__read_one(struct perf_evsel *evsel, int cpu, int thread)
1420 {
1421 	struct perf_counts_values *count = perf_counts(evsel->counts, cpu, thread);
1422 
1423 	return perf_evsel__read(evsel, cpu, thread, count);
1424 }
1425 
1426 static void
1427 perf_evsel__set_count(struct perf_evsel *counter, int cpu, int thread,
1428 		      u64 val, u64 ena, u64 run)
1429 {
1430 	struct perf_counts_values *count;
1431 
1432 	count = perf_counts(counter->counts, cpu, thread);
1433 
1434 	count->val    = val;
1435 	count->ena    = ena;
1436 	count->run    = run;
1437 	count->loaded = true;
1438 }
1439 
1440 static int
1441 perf_evsel__process_group_data(struct perf_evsel *leader,
1442 			       int cpu, int thread, u64 *data)
1443 {
1444 	u64 read_format = leader->attr.read_format;
1445 	struct sample_read_value *v;
1446 	u64 nr, ena = 0, run = 0, i;
1447 
1448 	nr = *data++;
1449 
1450 	if (nr != (u64) leader->nr_members)
1451 		return -EINVAL;
1452 
1453 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1454 		ena = *data++;
1455 
1456 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1457 		run = *data++;
1458 
1459 	v = (struct sample_read_value *) data;
1460 
1461 	perf_evsel__set_count(leader, cpu, thread,
1462 			      v[0].value, ena, run);
1463 
1464 	for (i = 1; i < nr; i++) {
1465 		struct perf_evsel *counter;
1466 
1467 		counter = perf_evlist__id2evsel(leader->evlist, v[i].id);
1468 		if (!counter)
1469 			return -EINVAL;
1470 
1471 		perf_evsel__set_count(counter, cpu, thread,
1472 				      v[i].value, ena, run);
1473 	}
1474 
1475 	return 0;
1476 }
1477 
1478 static int
1479 perf_evsel__read_group(struct perf_evsel *leader, int cpu, int thread)
1480 {
1481 	struct perf_stat_evsel *ps = leader->stats;
1482 	u64 read_format = leader->attr.read_format;
1483 	int size = perf_evsel__read_size(leader);
1484 	u64 *data = ps->group_data;
1485 
1486 	if (!(read_format & PERF_FORMAT_ID))
1487 		return -EINVAL;
1488 
1489 	if (!perf_evsel__is_group_leader(leader))
1490 		return -EINVAL;
1491 
1492 	if (!data) {
1493 		data = zalloc(size);
1494 		if (!data)
1495 			return -ENOMEM;
1496 
1497 		ps->group_data = data;
1498 	}
1499 
1500 	if (FD(leader, cpu, thread) < 0)
1501 		return -EINVAL;
1502 
1503 	if (readn(FD(leader, cpu, thread), data, size) <= 0)
1504 		return -errno;
1505 
1506 	return perf_evsel__process_group_data(leader, cpu, thread, data);
1507 }
1508 
1509 int perf_evsel__read_counter(struct perf_evsel *evsel, int cpu, int thread)
1510 {
1511 	u64 read_format = evsel->attr.read_format;
1512 
1513 	if (read_format & PERF_FORMAT_GROUP)
1514 		return perf_evsel__read_group(evsel, cpu, thread);
1515 	else
1516 		return perf_evsel__read_one(evsel, cpu, thread);
1517 }
1518 
1519 int __perf_evsel__read_on_cpu(struct perf_evsel *evsel,
1520 			      int cpu, int thread, bool scale)
1521 {
1522 	struct perf_counts_values count;
1523 	size_t nv = scale ? 3 : 1;
1524 
1525 	if (FD(evsel, cpu, thread) < 0)
1526 		return -EINVAL;
1527 
1528 	if (evsel->counts == NULL && perf_evsel__alloc_counts(evsel, cpu + 1, thread + 1) < 0)
1529 		return -ENOMEM;
1530 
1531 	if (readn(FD(evsel, cpu, thread), &count, nv * sizeof(u64)) <= 0)
1532 		return -errno;
1533 
1534 	perf_evsel__compute_deltas(evsel, cpu, thread, &count);
1535 	perf_counts_values__scale(&count, scale, NULL);
1536 	*perf_counts(evsel->counts, cpu, thread) = count;
1537 	return 0;
1538 }
1539 
1540 static int get_group_fd(struct perf_evsel *evsel, int cpu, int thread)
1541 {
1542 	struct perf_evsel *leader = evsel->leader;
1543 	int fd;
1544 
1545 	if (perf_evsel__is_group_leader(evsel))
1546 		return -1;
1547 
1548 	/*
1549 	 * Leader must be already processed/open,
1550 	 * if not it's a bug.
1551 	 */
1552 	BUG_ON(!leader->fd);
1553 
1554 	fd = FD(leader, cpu, thread);
1555 	BUG_ON(fd == -1);
1556 
1557 	return fd;
1558 }
1559 
1560 struct bit_names {
1561 	int bit;
1562 	const char *name;
1563 };
1564 
1565 static void __p_bits(char *buf, size_t size, u64 value, struct bit_names *bits)
1566 {
1567 	bool first_bit = true;
1568 	int i = 0;
1569 
1570 	do {
1571 		if (value & bits[i].bit) {
1572 			buf += scnprintf(buf, size, "%s%s", first_bit ? "" : "|", bits[i].name);
1573 			first_bit = false;
1574 		}
1575 	} while (bits[++i].name != NULL);
1576 }
1577 
1578 static void __p_sample_type(char *buf, size_t size, u64 value)
1579 {
1580 #define bit_name(n) { PERF_SAMPLE_##n, #n }
1581 	struct bit_names bits[] = {
1582 		bit_name(IP), bit_name(TID), bit_name(TIME), bit_name(ADDR),
1583 		bit_name(READ), bit_name(CALLCHAIN), bit_name(ID), bit_name(CPU),
1584 		bit_name(PERIOD), bit_name(STREAM_ID), bit_name(RAW),
1585 		bit_name(BRANCH_STACK), bit_name(REGS_USER), bit_name(STACK_USER),
1586 		bit_name(IDENTIFIER), bit_name(REGS_INTR), bit_name(DATA_SRC),
1587 		bit_name(WEIGHT), bit_name(PHYS_ADDR),
1588 		{ .name = NULL, }
1589 	};
1590 #undef bit_name
1591 	__p_bits(buf, size, value, bits);
1592 }
1593 
1594 static void __p_branch_sample_type(char *buf, size_t size, u64 value)
1595 {
1596 #define bit_name(n) { PERF_SAMPLE_BRANCH_##n, #n }
1597 	struct bit_names bits[] = {
1598 		bit_name(USER), bit_name(KERNEL), bit_name(HV), bit_name(ANY),
1599 		bit_name(ANY_CALL), bit_name(ANY_RETURN), bit_name(IND_CALL),
1600 		bit_name(ABORT_TX), bit_name(IN_TX), bit_name(NO_TX),
1601 		bit_name(COND), bit_name(CALL_STACK), bit_name(IND_JUMP),
1602 		bit_name(CALL), bit_name(NO_FLAGS), bit_name(NO_CYCLES),
1603 		{ .name = NULL, }
1604 	};
1605 #undef bit_name
1606 	__p_bits(buf, size, value, bits);
1607 }
1608 
1609 static void __p_read_format(char *buf, size_t size, u64 value)
1610 {
1611 #define bit_name(n) { PERF_FORMAT_##n, #n }
1612 	struct bit_names bits[] = {
1613 		bit_name(TOTAL_TIME_ENABLED), bit_name(TOTAL_TIME_RUNNING),
1614 		bit_name(ID), bit_name(GROUP),
1615 		{ .name = NULL, }
1616 	};
1617 #undef bit_name
1618 	__p_bits(buf, size, value, bits);
1619 }
1620 
1621 #define BUF_SIZE		1024
1622 
1623 #define p_hex(val)		snprintf(buf, BUF_SIZE, "%#"PRIx64, (uint64_t)(val))
1624 #define p_unsigned(val)		snprintf(buf, BUF_SIZE, "%"PRIu64, (uint64_t)(val))
1625 #define p_signed(val)		snprintf(buf, BUF_SIZE, "%"PRId64, (int64_t)(val))
1626 #define p_sample_type(val)	__p_sample_type(buf, BUF_SIZE, val)
1627 #define p_branch_sample_type(val) __p_branch_sample_type(buf, BUF_SIZE, val)
1628 #define p_read_format(val)	__p_read_format(buf, BUF_SIZE, val)
1629 
1630 #define PRINT_ATTRn(_n, _f, _p)				\
1631 do {							\
1632 	if (attr->_f) {					\
1633 		_p(attr->_f);				\
1634 		ret += attr__fprintf(fp, _n, buf, priv);\
1635 	}						\
1636 } while (0)
1637 
1638 #define PRINT_ATTRf(_f, _p)	PRINT_ATTRn(#_f, _f, _p)
1639 
1640 int perf_event_attr__fprintf(FILE *fp, struct perf_event_attr *attr,
1641 			     attr__fprintf_f attr__fprintf, void *priv)
1642 {
1643 	char buf[BUF_SIZE];
1644 	int ret = 0;
1645 
1646 	PRINT_ATTRf(type, p_unsigned);
1647 	PRINT_ATTRf(size, p_unsigned);
1648 	PRINT_ATTRf(config, p_hex);
1649 	PRINT_ATTRn("{ sample_period, sample_freq }", sample_period, p_unsigned);
1650 	PRINT_ATTRf(sample_type, p_sample_type);
1651 	PRINT_ATTRf(read_format, p_read_format);
1652 
1653 	PRINT_ATTRf(disabled, p_unsigned);
1654 	PRINT_ATTRf(inherit, p_unsigned);
1655 	PRINT_ATTRf(pinned, p_unsigned);
1656 	PRINT_ATTRf(exclusive, p_unsigned);
1657 	PRINT_ATTRf(exclude_user, p_unsigned);
1658 	PRINT_ATTRf(exclude_kernel, p_unsigned);
1659 	PRINT_ATTRf(exclude_hv, p_unsigned);
1660 	PRINT_ATTRf(exclude_idle, p_unsigned);
1661 	PRINT_ATTRf(mmap, p_unsigned);
1662 	PRINT_ATTRf(comm, p_unsigned);
1663 	PRINT_ATTRf(freq, p_unsigned);
1664 	PRINT_ATTRf(inherit_stat, p_unsigned);
1665 	PRINT_ATTRf(enable_on_exec, p_unsigned);
1666 	PRINT_ATTRf(task, p_unsigned);
1667 	PRINT_ATTRf(watermark, p_unsigned);
1668 	PRINT_ATTRf(precise_ip, p_unsigned);
1669 	PRINT_ATTRf(mmap_data, p_unsigned);
1670 	PRINT_ATTRf(sample_id_all, p_unsigned);
1671 	PRINT_ATTRf(exclude_host, p_unsigned);
1672 	PRINT_ATTRf(exclude_guest, p_unsigned);
1673 	PRINT_ATTRf(exclude_callchain_kernel, p_unsigned);
1674 	PRINT_ATTRf(exclude_callchain_user, p_unsigned);
1675 	PRINT_ATTRf(mmap2, p_unsigned);
1676 	PRINT_ATTRf(comm_exec, p_unsigned);
1677 	PRINT_ATTRf(use_clockid, p_unsigned);
1678 	PRINT_ATTRf(context_switch, p_unsigned);
1679 	PRINT_ATTRf(write_backward, p_unsigned);
1680 	PRINT_ATTRf(namespaces, p_unsigned);
1681 	PRINT_ATTRf(ksymbol, p_unsigned);
1682 	PRINT_ATTRf(bpf_event, p_unsigned);
1683 
1684 	PRINT_ATTRn("{ wakeup_events, wakeup_watermark }", wakeup_events, p_unsigned);
1685 	PRINT_ATTRf(bp_type, p_unsigned);
1686 	PRINT_ATTRn("{ bp_addr, config1 }", bp_addr, p_hex);
1687 	PRINT_ATTRn("{ bp_len, config2 }", bp_len, p_hex);
1688 	PRINT_ATTRf(branch_sample_type, p_branch_sample_type);
1689 	PRINT_ATTRf(sample_regs_user, p_hex);
1690 	PRINT_ATTRf(sample_stack_user, p_unsigned);
1691 	PRINT_ATTRf(clockid, p_signed);
1692 	PRINT_ATTRf(sample_regs_intr, p_hex);
1693 	PRINT_ATTRf(aux_watermark, p_unsigned);
1694 	PRINT_ATTRf(sample_max_stack, p_unsigned);
1695 
1696 	return ret;
1697 }
1698 
1699 static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
1700 				void *priv __maybe_unused)
1701 {
1702 	return fprintf(fp, "  %-32s %s\n", name, val);
1703 }
1704 
1705 static void perf_evsel__remove_fd(struct perf_evsel *pos,
1706 				  int nr_cpus, int nr_threads,
1707 				  int thread_idx)
1708 {
1709 	for (int cpu = 0; cpu < nr_cpus; cpu++)
1710 		for (int thread = thread_idx; thread < nr_threads - 1; thread++)
1711 			FD(pos, cpu, thread) = FD(pos, cpu, thread + 1);
1712 }
1713 
1714 static int update_fds(struct perf_evsel *evsel,
1715 		      int nr_cpus, int cpu_idx,
1716 		      int nr_threads, int thread_idx)
1717 {
1718 	struct perf_evsel *pos;
1719 
1720 	if (cpu_idx >= nr_cpus || thread_idx >= nr_threads)
1721 		return -EINVAL;
1722 
1723 	evlist__for_each_entry(evsel->evlist, pos) {
1724 		nr_cpus = pos != evsel ? nr_cpus : cpu_idx;
1725 
1726 		perf_evsel__remove_fd(pos, nr_cpus, nr_threads, thread_idx);
1727 
1728 		/*
1729 		 * Since fds for next evsel has not been created,
1730 		 * there is no need to iterate whole event list.
1731 		 */
1732 		if (pos == evsel)
1733 			break;
1734 	}
1735 	return 0;
1736 }
1737 
1738 static bool ignore_missing_thread(struct perf_evsel *evsel,
1739 				  int nr_cpus, int cpu,
1740 				  struct thread_map *threads,
1741 				  int thread, int err)
1742 {
1743 	pid_t ignore_pid = thread_map__pid(threads, thread);
1744 
1745 	if (!evsel->ignore_missing_thread)
1746 		return false;
1747 
1748 	/* The system wide setup does not work with threads. */
1749 	if (evsel->system_wide)
1750 		return false;
1751 
1752 	/* The -ESRCH is perf event syscall errno for pid's not found. */
1753 	if (err != -ESRCH)
1754 		return false;
1755 
1756 	/* If there's only one thread, let it fail. */
1757 	if (threads->nr == 1)
1758 		return false;
1759 
1760 	/*
1761 	 * We should remove fd for missing_thread first
1762 	 * because thread_map__remove() will decrease threads->nr.
1763 	 */
1764 	if (update_fds(evsel, nr_cpus, cpu, threads->nr, thread))
1765 		return false;
1766 
1767 	if (thread_map__remove(threads, thread))
1768 		return false;
1769 
1770 	pr_warning("WARNING: Ignored open failure for pid %d\n",
1771 		   ignore_pid);
1772 	return true;
1773 }
1774 
1775 static void display_attr(struct perf_event_attr *attr)
1776 {
1777 	if (verbose >= 2) {
1778 		fprintf(stderr, "%.60s\n", graph_dotted_line);
1779 		fprintf(stderr, "perf_event_attr:\n");
1780 		perf_event_attr__fprintf(stderr, attr, __open_attr__fprintf, NULL);
1781 		fprintf(stderr, "%.60s\n", graph_dotted_line);
1782 	}
1783 }
1784 
1785 static int perf_event_open(struct perf_evsel *evsel,
1786 			   pid_t pid, int cpu, int group_fd,
1787 			   unsigned long flags)
1788 {
1789 	int precise_ip = evsel->attr.precise_ip;
1790 	int fd;
1791 
1792 	while (1) {
1793 		pr_debug2("sys_perf_event_open: pid %d  cpu %d  group_fd %d  flags %#lx",
1794 			  pid, cpu, group_fd, flags);
1795 
1796 		fd = sys_perf_event_open(&evsel->attr, pid, cpu, group_fd, flags);
1797 		if (fd >= 0)
1798 			break;
1799 
1800 		/*
1801 		 * Do quick precise_ip fallback if:
1802 		 *  - there is precise_ip set in perf_event_attr
1803 		 *  - maximum precise is requested
1804 		 *  - sys_perf_event_open failed with ENOTSUP error,
1805 		 *    which is associated with wrong precise_ip
1806 		 */
1807 		if (!precise_ip || !evsel->precise_max || (errno != ENOTSUP))
1808 			break;
1809 
1810 		/*
1811 		 * We tried all the precise_ip values, and it's
1812 		 * still failing, so leave it to standard fallback.
1813 		 */
1814 		if (!evsel->attr.precise_ip) {
1815 			evsel->attr.precise_ip = precise_ip;
1816 			break;
1817 		}
1818 
1819 		pr_debug2("\nsys_perf_event_open failed, error %d\n", -ENOTSUP);
1820 		evsel->attr.precise_ip--;
1821 		pr_debug2("decreasing precise_ip by one (%d)\n", evsel->attr.precise_ip);
1822 		display_attr(&evsel->attr);
1823 	}
1824 
1825 	return fd;
1826 }
1827 
1828 int perf_evsel__open(struct perf_evsel *evsel, struct cpu_map *cpus,
1829 		     struct thread_map *threads)
1830 {
1831 	int cpu, thread, nthreads;
1832 	unsigned long flags = PERF_FLAG_FD_CLOEXEC;
1833 	int pid = -1, err;
1834 	enum { NO_CHANGE, SET_TO_MAX, INCREASED_MAX } set_rlimit = NO_CHANGE;
1835 
1836 	if (perf_missing_features.write_backward && evsel->attr.write_backward)
1837 		return -EINVAL;
1838 
1839 	if (cpus == NULL) {
1840 		static struct cpu_map *empty_cpu_map;
1841 
1842 		if (empty_cpu_map == NULL) {
1843 			empty_cpu_map = cpu_map__dummy_new();
1844 			if (empty_cpu_map == NULL)
1845 				return -ENOMEM;
1846 		}
1847 
1848 		cpus = empty_cpu_map;
1849 	}
1850 
1851 	if (threads == NULL) {
1852 		static struct thread_map *empty_thread_map;
1853 
1854 		if (empty_thread_map == NULL) {
1855 			empty_thread_map = thread_map__new_by_tid(-1);
1856 			if (empty_thread_map == NULL)
1857 				return -ENOMEM;
1858 		}
1859 
1860 		threads = empty_thread_map;
1861 	}
1862 
1863 	if (evsel->system_wide)
1864 		nthreads = 1;
1865 	else
1866 		nthreads = threads->nr;
1867 
1868 	if (evsel->fd == NULL &&
1869 	    perf_evsel__alloc_fd(evsel, cpus->nr, nthreads) < 0)
1870 		return -ENOMEM;
1871 
1872 	if (evsel->cgrp) {
1873 		flags |= PERF_FLAG_PID_CGROUP;
1874 		pid = evsel->cgrp->fd;
1875 	}
1876 
1877 fallback_missing_features:
1878 	if (perf_missing_features.clockid_wrong)
1879 		evsel->attr.clockid = CLOCK_MONOTONIC; /* should always work */
1880 	if (perf_missing_features.clockid) {
1881 		evsel->attr.use_clockid = 0;
1882 		evsel->attr.clockid = 0;
1883 	}
1884 	if (perf_missing_features.cloexec)
1885 		flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
1886 	if (perf_missing_features.mmap2)
1887 		evsel->attr.mmap2 = 0;
1888 	if (perf_missing_features.exclude_guest)
1889 		evsel->attr.exclude_guest = evsel->attr.exclude_host = 0;
1890 	if (perf_missing_features.lbr_flags)
1891 		evsel->attr.branch_sample_type &= ~(PERF_SAMPLE_BRANCH_NO_FLAGS |
1892 				     PERF_SAMPLE_BRANCH_NO_CYCLES);
1893 	if (perf_missing_features.group_read && evsel->attr.inherit)
1894 		evsel->attr.read_format &= ~(PERF_FORMAT_GROUP|PERF_FORMAT_ID);
1895 	if (perf_missing_features.ksymbol)
1896 		evsel->attr.ksymbol = 0;
1897 	if (perf_missing_features.bpf_event)
1898 		evsel->attr.bpf_event = 0;
1899 retry_sample_id:
1900 	if (perf_missing_features.sample_id_all)
1901 		evsel->attr.sample_id_all = 0;
1902 
1903 	display_attr(&evsel->attr);
1904 
1905 	for (cpu = 0; cpu < cpus->nr; cpu++) {
1906 
1907 		for (thread = 0; thread < nthreads; thread++) {
1908 			int fd, group_fd;
1909 
1910 			if (!evsel->cgrp && !evsel->system_wide)
1911 				pid = thread_map__pid(threads, thread);
1912 
1913 			group_fd = get_group_fd(evsel, cpu, thread);
1914 retry_open:
1915 			test_attr__ready();
1916 
1917 			fd = perf_event_open(evsel, pid, cpus->map[cpu],
1918 					     group_fd, flags);
1919 
1920 			FD(evsel, cpu, thread) = fd;
1921 
1922 			if (fd < 0) {
1923 				err = -errno;
1924 
1925 				if (ignore_missing_thread(evsel, cpus->nr, cpu, threads, thread, err)) {
1926 					/*
1927 					 * We just removed 1 thread, so take a step
1928 					 * back on thread index and lower the upper
1929 					 * nthreads limit.
1930 					 */
1931 					nthreads--;
1932 					thread--;
1933 
1934 					/* ... and pretend like nothing have happened. */
1935 					err = 0;
1936 					continue;
1937 				}
1938 
1939 				pr_debug2("\nsys_perf_event_open failed, error %d\n",
1940 					  err);
1941 				goto try_fallback;
1942 			}
1943 
1944 			pr_debug2(" = %d\n", fd);
1945 
1946 			if (evsel->bpf_fd >= 0) {
1947 				int evt_fd = fd;
1948 				int bpf_fd = evsel->bpf_fd;
1949 
1950 				err = ioctl(evt_fd,
1951 					    PERF_EVENT_IOC_SET_BPF,
1952 					    bpf_fd);
1953 				if (err && errno != EEXIST) {
1954 					pr_err("failed to attach bpf fd %d: %s\n",
1955 					       bpf_fd, strerror(errno));
1956 					err = -EINVAL;
1957 					goto out_close;
1958 				}
1959 			}
1960 
1961 			set_rlimit = NO_CHANGE;
1962 
1963 			/*
1964 			 * If we succeeded but had to kill clockid, fail and
1965 			 * have perf_evsel__open_strerror() print us a nice
1966 			 * error.
1967 			 */
1968 			if (perf_missing_features.clockid ||
1969 			    perf_missing_features.clockid_wrong) {
1970 				err = -EINVAL;
1971 				goto out_close;
1972 			}
1973 		}
1974 	}
1975 
1976 	return 0;
1977 
1978 try_fallback:
1979 	/*
1980 	 * perf stat needs between 5 and 22 fds per CPU. When we run out
1981 	 * of them try to increase the limits.
1982 	 */
1983 	if (err == -EMFILE && set_rlimit < INCREASED_MAX) {
1984 		struct rlimit l;
1985 		int old_errno = errno;
1986 
1987 		if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
1988 			if (set_rlimit == NO_CHANGE)
1989 				l.rlim_cur = l.rlim_max;
1990 			else {
1991 				l.rlim_cur = l.rlim_max + 1000;
1992 				l.rlim_max = l.rlim_cur;
1993 			}
1994 			if (setrlimit(RLIMIT_NOFILE, &l) == 0) {
1995 				set_rlimit++;
1996 				errno = old_errno;
1997 				goto retry_open;
1998 			}
1999 		}
2000 		errno = old_errno;
2001 	}
2002 
2003 	if (err != -EINVAL || cpu > 0 || thread > 0)
2004 		goto out_close;
2005 
2006 	/*
2007 	 * Must probe features in the order they were added to the
2008 	 * perf_event_attr interface.
2009 	 */
2010 	if (!perf_missing_features.bpf_event && evsel->attr.bpf_event) {
2011 		perf_missing_features.bpf_event = true;
2012 		pr_debug2("switching off bpf_event\n");
2013 		goto fallback_missing_features;
2014 	} else if (!perf_missing_features.ksymbol && evsel->attr.ksymbol) {
2015 		perf_missing_features.ksymbol = true;
2016 		pr_debug2("switching off ksymbol\n");
2017 		goto fallback_missing_features;
2018 	} else if (!perf_missing_features.write_backward && evsel->attr.write_backward) {
2019 		perf_missing_features.write_backward = true;
2020 		pr_debug2("switching off write_backward\n");
2021 		goto out_close;
2022 	} else if (!perf_missing_features.clockid_wrong && evsel->attr.use_clockid) {
2023 		perf_missing_features.clockid_wrong = true;
2024 		pr_debug2("switching off clockid\n");
2025 		goto fallback_missing_features;
2026 	} else if (!perf_missing_features.clockid && evsel->attr.use_clockid) {
2027 		perf_missing_features.clockid = true;
2028 		pr_debug2("switching off use_clockid\n");
2029 		goto fallback_missing_features;
2030 	} else if (!perf_missing_features.cloexec && (flags & PERF_FLAG_FD_CLOEXEC)) {
2031 		perf_missing_features.cloexec = true;
2032 		pr_debug2("switching off cloexec flag\n");
2033 		goto fallback_missing_features;
2034 	} else if (!perf_missing_features.mmap2 && evsel->attr.mmap2) {
2035 		perf_missing_features.mmap2 = true;
2036 		pr_debug2("switching off mmap2\n");
2037 		goto fallback_missing_features;
2038 	} else if (!perf_missing_features.exclude_guest &&
2039 		   (evsel->attr.exclude_guest || evsel->attr.exclude_host)) {
2040 		perf_missing_features.exclude_guest = true;
2041 		pr_debug2("switching off exclude_guest, exclude_host\n");
2042 		goto fallback_missing_features;
2043 	} else if (!perf_missing_features.sample_id_all) {
2044 		perf_missing_features.sample_id_all = true;
2045 		pr_debug2("switching off sample_id_all\n");
2046 		goto retry_sample_id;
2047 	} else if (!perf_missing_features.lbr_flags &&
2048 			(evsel->attr.branch_sample_type &
2049 			 (PERF_SAMPLE_BRANCH_NO_CYCLES |
2050 			  PERF_SAMPLE_BRANCH_NO_FLAGS))) {
2051 		perf_missing_features.lbr_flags = true;
2052 		pr_debug2("switching off branch sample type no (cycles/flags)\n");
2053 		goto fallback_missing_features;
2054 	} else if (!perf_missing_features.group_read &&
2055 		    evsel->attr.inherit &&
2056 		   (evsel->attr.read_format & PERF_FORMAT_GROUP) &&
2057 		   perf_evsel__is_group_leader(evsel)) {
2058 		perf_missing_features.group_read = true;
2059 		pr_debug2("switching off group read\n");
2060 		goto fallback_missing_features;
2061 	}
2062 out_close:
2063 	if (err)
2064 		threads->err_thread = thread;
2065 
2066 	do {
2067 		while (--thread >= 0) {
2068 			close(FD(evsel, cpu, thread));
2069 			FD(evsel, cpu, thread) = -1;
2070 		}
2071 		thread = nthreads;
2072 	} while (--cpu >= 0);
2073 	return err;
2074 }
2075 
2076 void perf_evsel__close(struct perf_evsel *evsel)
2077 {
2078 	if (evsel->fd == NULL)
2079 		return;
2080 
2081 	perf_evsel__close_fd(evsel);
2082 	perf_evsel__free_fd(evsel);
2083 }
2084 
2085 int perf_evsel__open_per_cpu(struct perf_evsel *evsel,
2086 			     struct cpu_map *cpus)
2087 {
2088 	return perf_evsel__open(evsel, cpus, NULL);
2089 }
2090 
2091 int perf_evsel__open_per_thread(struct perf_evsel *evsel,
2092 				struct thread_map *threads)
2093 {
2094 	return perf_evsel__open(evsel, NULL, threads);
2095 }
2096 
2097 static int perf_evsel__parse_id_sample(const struct perf_evsel *evsel,
2098 				       const union perf_event *event,
2099 				       struct perf_sample *sample)
2100 {
2101 	u64 type = evsel->attr.sample_type;
2102 	const u64 *array = event->sample.array;
2103 	bool swapped = evsel->needs_swap;
2104 	union u64_swap u;
2105 
2106 	array += ((event->header.size -
2107 		   sizeof(event->header)) / sizeof(u64)) - 1;
2108 
2109 	if (type & PERF_SAMPLE_IDENTIFIER) {
2110 		sample->id = *array;
2111 		array--;
2112 	}
2113 
2114 	if (type & PERF_SAMPLE_CPU) {
2115 		u.val64 = *array;
2116 		if (swapped) {
2117 			/* undo swap of u64, then swap on individual u32s */
2118 			u.val64 = bswap_64(u.val64);
2119 			u.val32[0] = bswap_32(u.val32[0]);
2120 		}
2121 
2122 		sample->cpu = u.val32[0];
2123 		array--;
2124 	}
2125 
2126 	if (type & PERF_SAMPLE_STREAM_ID) {
2127 		sample->stream_id = *array;
2128 		array--;
2129 	}
2130 
2131 	if (type & PERF_SAMPLE_ID) {
2132 		sample->id = *array;
2133 		array--;
2134 	}
2135 
2136 	if (type & PERF_SAMPLE_TIME) {
2137 		sample->time = *array;
2138 		array--;
2139 	}
2140 
2141 	if (type & PERF_SAMPLE_TID) {
2142 		u.val64 = *array;
2143 		if (swapped) {
2144 			/* undo swap of u64, then swap on individual u32s */
2145 			u.val64 = bswap_64(u.val64);
2146 			u.val32[0] = bswap_32(u.val32[0]);
2147 			u.val32[1] = bswap_32(u.val32[1]);
2148 		}
2149 
2150 		sample->pid = u.val32[0];
2151 		sample->tid = u.val32[1];
2152 		array--;
2153 	}
2154 
2155 	return 0;
2156 }
2157 
2158 static inline bool overflow(const void *endp, u16 max_size, const void *offset,
2159 			    u64 size)
2160 {
2161 	return size > max_size || offset + size > endp;
2162 }
2163 
2164 #define OVERFLOW_CHECK(offset, size, max_size)				\
2165 	do {								\
2166 		if (overflow(endp, (max_size), (offset), (size)))	\
2167 			return -EFAULT;					\
2168 	} while (0)
2169 
2170 #define OVERFLOW_CHECK_u64(offset) \
2171 	OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
2172 
2173 static int
2174 perf_event__check_size(union perf_event *event, unsigned int sample_size)
2175 {
2176 	/*
2177 	 * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
2178 	 * up to PERF_SAMPLE_PERIOD.  After that overflow() must be used to
2179 	 * check the format does not go past the end of the event.
2180 	 */
2181 	if (sample_size + sizeof(event->header) > event->header.size)
2182 		return -EFAULT;
2183 
2184 	return 0;
2185 }
2186 
2187 int perf_evsel__parse_sample(struct perf_evsel *evsel, union perf_event *event,
2188 			     struct perf_sample *data)
2189 {
2190 	u64 type = evsel->attr.sample_type;
2191 	bool swapped = evsel->needs_swap;
2192 	const u64 *array;
2193 	u16 max_size = event->header.size;
2194 	const void *endp = (void *)event + max_size;
2195 	u64 sz;
2196 
2197 	/*
2198 	 * used for cross-endian analysis. See git commit 65014ab3
2199 	 * for why this goofiness is needed.
2200 	 */
2201 	union u64_swap u;
2202 
2203 	memset(data, 0, sizeof(*data));
2204 	data->cpu = data->pid = data->tid = -1;
2205 	data->stream_id = data->id = data->time = -1ULL;
2206 	data->period = evsel->attr.sample_period;
2207 	data->cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2208 	data->misc    = event->header.misc;
2209 	data->id = -1ULL;
2210 	data->data_src = PERF_MEM_DATA_SRC_NONE;
2211 
2212 	if (event->header.type != PERF_RECORD_SAMPLE) {
2213 		if (!evsel->attr.sample_id_all)
2214 			return 0;
2215 		return perf_evsel__parse_id_sample(evsel, event, data);
2216 	}
2217 
2218 	array = event->sample.array;
2219 
2220 	if (perf_event__check_size(event, evsel->sample_size))
2221 		return -EFAULT;
2222 
2223 	if (type & PERF_SAMPLE_IDENTIFIER) {
2224 		data->id = *array;
2225 		array++;
2226 	}
2227 
2228 	if (type & PERF_SAMPLE_IP) {
2229 		data->ip = *array;
2230 		array++;
2231 	}
2232 
2233 	if (type & PERF_SAMPLE_TID) {
2234 		u.val64 = *array;
2235 		if (swapped) {
2236 			/* undo swap of u64, then swap on individual u32s */
2237 			u.val64 = bswap_64(u.val64);
2238 			u.val32[0] = bswap_32(u.val32[0]);
2239 			u.val32[1] = bswap_32(u.val32[1]);
2240 		}
2241 
2242 		data->pid = u.val32[0];
2243 		data->tid = u.val32[1];
2244 		array++;
2245 	}
2246 
2247 	if (type & PERF_SAMPLE_TIME) {
2248 		data->time = *array;
2249 		array++;
2250 	}
2251 
2252 	if (type & PERF_SAMPLE_ADDR) {
2253 		data->addr = *array;
2254 		array++;
2255 	}
2256 
2257 	if (type & PERF_SAMPLE_ID) {
2258 		data->id = *array;
2259 		array++;
2260 	}
2261 
2262 	if (type & PERF_SAMPLE_STREAM_ID) {
2263 		data->stream_id = *array;
2264 		array++;
2265 	}
2266 
2267 	if (type & PERF_SAMPLE_CPU) {
2268 
2269 		u.val64 = *array;
2270 		if (swapped) {
2271 			/* undo swap of u64, then swap on individual u32s */
2272 			u.val64 = bswap_64(u.val64);
2273 			u.val32[0] = bswap_32(u.val32[0]);
2274 		}
2275 
2276 		data->cpu = u.val32[0];
2277 		array++;
2278 	}
2279 
2280 	if (type & PERF_SAMPLE_PERIOD) {
2281 		data->period = *array;
2282 		array++;
2283 	}
2284 
2285 	if (type & PERF_SAMPLE_READ) {
2286 		u64 read_format = evsel->attr.read_format;
2287 
2288 		OVERFLOW_CHECK_u64(array);
2289 		if (read_format & PERF_FORMAT_GROUP)
2290 			data->read.group.nr = *array;
2291 		else
2292 			data->read.one.value = *array;
2293 
2294 		array++;
2295 
2296 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2297 			OVERFLOW_CHECK_u64(array);
2298 			data->read.time_enabled = *array;
2299 			array++;
2300 		}
2301 
2302 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2303 			OVERFLOW_CHECK_u64(array);
2304 			data->read.time_running = *array;
2305 			array++;
2306 		}
2307 
2308 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2309 		if (read_format & PERF_FORMAT_GROUP) {
2310 			const u64 max_group_nr = UINT64_MAX /
2311 					sizeof(struct sample_read_value);
2312 
2313 			if (data->read.group.nr > max_group_nr)
2314 				return -EFAULT;
2315 			sz = data->read.group.nr *
2316 			     sizeof(struct sample_read_value);
2317 			OVERFLOW_CHECK(array, sz, max_size);
2318 			data->read.group.values =
2319 					(struct sample_read_value *)array;
2320 			array = (void *)array + sz;
2321 		} else {
2322 			OVERFLOW_CHECK_u64(array);
2323 			data->read.one.id = *array;
2324 			array++;
2325 		}
2326 	}
2327 
2328 	if (evsel__has_callchain(evsel)) {
2329 		const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
2330 
2331 		OVERFLOW_CHECK_u64(array);
2332 		data->callchain = (struct ip_callchain *)array++;
2333 		if (data->callchain->nr > max_callchain_nr)
2334 			return -EFAULT;
2335 		sz = data->callchain->nr * sizeof(u64);
2336 		OVERFLOW_CHECK(array, sz, max_size);
2337 		array = (void *)array + sz;
2338 	}
2339 
2340 	if (type & PERF_SAMPLE_RAW) {
2341 		OVERFLOW_CHECK_u64(array);
2342 		u.val64 = *array;
2343 
2344 		/*
2345 		 * Undo swap of u64, then swap on individual u32s,
2346 		 * get the size of the raw area and undo all of the
2347 		 * swap. The pevent interface handles endianity by
2348 		 * itself.
2349 		 */
2350 		if (swapped) {
2351 			u.val64 = bswap_64(u.val64);
2352 			u.val32[0] = bswap_32(u.val32[0]);
2353 			u.val32[1] = bswap_32(u.val32[1]);
2354 		}
2355 		data->raw_size = u.val32[0];
2356 
2357 		/*
2358 		 * The raw data is aligned on 64bits including the
2359 		 * u32 size, so it's safe to use mem_bswap_64.
2360 		 */
2361 		if (swapped)
2362 			mem_bswap_64((void *) array, data->raw_size);
2363 
2364 		array = (void *)array + sizeof(u32);
2365 
2366 		OVERFLOW_CHECK(array, data->raw_size, max_size);
2367 		data->raw_data = (void *)array;
2368 		array = (void *)array + data->raw_size;
2369 	}
2370 
2371 	if (type & PERF_SAMPLE_BRANCH_STACK) {
2372 		const u64 max_branch_nr = UINT64_MAX /
2373 					  sizeof(struct branch_entry);
2374 
2375 		OVERFLOW_CHECK_u64(array);
2376 		data->branch_stack = (struct branch_stack *)array++;
2377 
2378 		if (data->branch_stack->nr > max_branch_nr)
2379 			return -EFAULT;
2380 		sz = data->branch_stack->nr * sizeof(struct branch_entry);
2381 		OVERFLOW_CHECK(array, sz, max_size);
2382 		array = (void *)array + sz;
2383 	}
2384 
2385 	if (type & PERF_SAMPLE_REGS_USER) {
2386 		OVERFLOW_CHECK_u64(array);
2387 		data->user_regs.abi = *array;
2388 		array++;
2389 
2390 		if (data->user_regs.abi) {
2391 			u64 mask = evsel->attr.sample_regs_user;
2392 
2393 			sz = hweight64(mask) * sizeof(u64);
2394 			OVERFLOW_CHECK(array, sz, max_size);
2395 			data->user_regs.mask = mask;
2396 			data->user_regs.regs = (u64 *)array;
2397 			array = (void *)array + sz;
2398 		}
2399 	}
2400 
2401 	if (type & PERF_SAMPLE_STACK_USER) {
2402 		OVERFLOW_CHECK_u64(array);
2403 		sz = *array++;
2404 
2405 		data->user_stack.offset = ((char *)(array - 1)
2406 					  - (char *) event);
2407 
2408 		if (!sz) {
2409 			data->user_stack.size = 0;
2410 		} else {
2411 			OVERFLOW_CHECK(array, sz, max_size);
2412 			data->user_stack.data = (char *)array;
2413 			array = (void *)array + sz;
2414 			OVERFLOW_CHECK_u64(array);
2415 			data->user_stack.size = *array++;
2416 			if (WARN_ONCE(data->user_stack.size > sz,
2417 				      "user stack dump failure\n"))
2418 				return -EFAULT;
2419 		}
2420 	}
2421 
2422 	if (type & PERF_SAMPLE_WEIGHT) {
2423 		OVERFLOW_CHECK_u64(array);
2424 		data->weight = *array;
2425 		array++;
2426 	}
2427 
2428 	if (type & PERF_SAMPLE_DATA_SRC) {
2429 		OVERFLOW_CHECK_u64(array);
2430 		data->data_src = *array;
2431 		array++;
2432 	}
2433 
2434 	if (type & PERF_SAMPLE_TRANSACTION) {
2435 		OVERFLOW_CHECK_u64(array);
2436 		data->transaction = *array;
2437 		array++;
2438 	}
2439 
2440 	data->intr_regs.abi = PERF_SAMPLE_REGS_ABI_NONE;
2441 	if (type & PERF_SAMPLE_REGS_INTR) {
2442 		OVERFLOW_CHECK_u64(array);
2443 		data->intr_regs.abi = *array;
2444 		array++;
2445 
2446 		if (data->intr_regs.abi != PERF_SAMPLE_REGS_ABI_NONE) {
2447 			u64 mask = evsel->attr.sample_regs_intr;
2448 
2449 			sz = hweight64(mask) * sizeof(u64);
2450 			OVERFLOW_CHECK(array, sz, max_size);
2451 			data->intr_regs.mask = mask;
2452 			data->intr_regs.regs = (u64 *)array;
2453 			array = (void *)array + sz;
2454 		}
2455 	}
2456 
2457 	data->phys_addr = 0;
2458 	if (type & PERF_SAMPLE_PHYS_ADDR) {
2459 		data->phys_addr = *array;
2460 		array++;
2461 	}
2462 
2463 	return 0;
2464 }
2465 
2466 int perf_evsel__parse_sample_timestamp(struct perf_evsel *evsel,
2467 				       union perf_event *event,
2468 				       u64 *timestamp)
2469 {
2470 	u64 type = evsel->attr.sample_type;
2471 	const u64 *array;
2472 
2473 	if (!(type & PERF_SAMPLE_TIME))
2474 		return -1;
2475 
2476 	if (event->header.type != PERF_RECORD_SAMPLE) {
2477 		struct perf_sample data = {
2478 			.time = -1ULL,
2479 		};
2480 
2481 		if (!evsel->attr.sample_id_all)
2482 			return -1;
2483 		if (perf_evsel__parse_id_sample(evsel, event, &data))
2484 			return -1;
2485 
2486 		*timestamp = data.time;
2487 		return 0;
2488 	}
2489 
2490 	array = event->sample.array;
2491 
2492 	if (perf_event__check_size(event, evsel->sample_size))
2493 		return -EFAULT;
2494 
2495 	if (type & PERF_SAMPLE_IDENTIFIER)
2496 		array++;
2497 
2498 	if (type & PERF_SAMPLE_IP)
2499 		array++;
2500 
2501 	if (type & PERF_SAMPLE_TID)
2502 		array++;
2503 
2504 	if (type & PERF_SAMPLE_TIME)
2505 		*timestamp = *array;
2506 
2507 	return 0;
2508 }
2509 
2510 size_t perf_event__sample_event_size(const struct perf_sample *sample, u64 type,
2511 				     u64 read_format)
2512 {
2513 	size_t sz, result = sizeof(struct sample_event);
2514 
2515 	if (type & PERF_SAMPLE_IDENTIFIER)
2516 		result += sizeof(u64);
2517 
2518 	if (type & PERF_SAMPLE_IP)
2519 		result += sizeof(u64);
2520 
2521 	if (type & PERF_SAMPLE_TID)
2522 		result += sizeof(u64);
2523 
2524 	if (type & PERF_SAMPLE_TIME)
2525 		result += sizeof(u64);
2526 
2527 	if (type & PERF_SAMPLE_ADDR)
2528 		result += sizeof(u64);
2529 
2530 	if (type & PERF_SAMPLE_ID)
2531 		result += sizeof(u64);
2532 
2533 	if (type & PERF_SAMPLE_STREAM_ID)
2534 		result += sizeof(u64);
2535 
2536 	if (type & PERF_SAMPLE_CPU)
2537 		result += sizeof(u64);
2538 
2539 	if (type & PERF_SAMPLE_PERIOD)
2540 		result += sizeof(u64);
2541 
2542 	if (type & PERF_SAMPLE_READ) {
2543 		result += sizeof(u64);
2544 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2545 			result += sizeof(u64);
2546 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2547 			result += sizeof(u64);
2548 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2549 		if (read_format & PERF_FORMAT_GROUP) {
2550 			sz = sample->read.group.nr *
2551 			     sizeof(struct sample_read_value);
2552 			result += sz;
2553 		} else {
2554 			result += sizeof(u64);
2555 		}
2556 	}
2557 
2558 	if (type & PERF_SAMPLE_CALLCHAIN) {
2559 		sz = (sample->callchain->nr + 1) * sizeof(u64);
2560 		result += sz;
2561 	}
2562 
2563 	if (type & PERF_SAMPLE_RAW) {
2564 		result += sizeof(u32);
2565 		result += sample->raw_size;
2566 	}
2567 
2568 	if (type & PERF_SAMPLE_BRANCH_STACK) {
2569 		sz = sample->branch_stack->nr * sizeof(struct branch_entry);
2570 		sz += sizeof(u64);
2571 		result += sz;
2572 	}
2573 
2574 	if (type & PERF_SAMPLE_REGS_USER) {
2575 		if (sample->user_regs.abi) {
2576 			result += sizeof(u64);
2577 			sz = hweight64(sample->user_regs.mask) * sizeof(u64);
2578 			result += sz;
2579 		} else {
2580 			result += sizeof(u64);
2581 		}
2582 	}
2583 
2584 	if (type & PERF_SAMPLE_STACK_USER) {
2585 		sz = sample->user_stack.size;
2586 		result += sizeof(u64);
2587 		if (sz) {
2588 			result += sz;
2589 			result += sizeof(u64);
2590 		}
2591 	}
2592 
2593 	if (type & PERF_SAMPLE_WEIGHT)
2594 		result += sizeof(u64);
2595 
2596 	if (type & PERF_SAMPLE_DATA_SRC)
2597 		result += sizeof(u64);
2598 
2599 	if (type & PERF_SAMPLE_TRANSACTION)
2600 		result += sizeof(u64);
2601 
2602 	if (type & PERF_SAMPLE_REGS_INTR) {
2603 		if (sample->intr_regs.abi) {
2604 			result += sizeof(u64);
2605 			sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
2606 			result += sz;
2607 		} else {
2608 			result += sizeof(u64);
2609 		}
2610 	}
2611 
2612 	if (type & PERF_SAMPLE_PHYS_ADDR)
2613 		result += sizeof(u64);
2614 
2615 	return result;
2616 }
2617 
2618 int perf_event__synthesize_sample(union perf_event *event, u64 type,
2619 				  u64 read_format,
2620 				  const struct perf_sample *sample)
2621 {
2622 	u64 *array;
2623 	size_t sz;
2624 	/*
2625 	 * used for cross-endian analysis. See git commit 65014ab3
2626 	 * for why this goofiness is needed.
2627 	 */
2628 	union u64_swap u;
2629 
2630 	array = event->sample.array;
2631 
2632 	if (type & PERF_SAMPLE_IDENTIFIER) {
2633 		*array = sample->id;
2634 		array++;
2635 	}
2636 
2637 	if (type & PERF_SAMPLE_IP) {
2638 		*array = sample->ip;
2639 		array++;
2640 	}
2641 
2642 	if (type & PERF_SAMPLE_TID) {
2643 		u.val32[0] = sample->pid;
2644 		u.val32[1] = sample->tid;
2645 		*array = u.val64;
2646 		array++;
2647 	}
2648 
2649 	if (type & PERF_SAMPLE_TIME) {
2650 		*array = sample->time;
2651 		array++;
2652 	}
2653 
2654 	if (type & PERF_SAMPLE_ADDR) {
2655 		*array = sample->addr;
2656 		array++;
2657 	}
2658 
2659 	if (type & PERF_SAMPLE_ID) {
2660 		*array = sample->id;
2661 		array++;
2662 	}
2663 
2664 	if (type & PERF_SAMPLE_STREAM_ID) {
2665 		*array = sample->stream_id;
2666 		array++;
2667 	}
2668 
2669 	if (type & PERF_SAMPLE_CPU) {
2670 		u.val32[0] = sample->cpu;
2671 		u.val32[1] = 0;
2672 		*array = u.val64;
2673 		array++;
2674 	}
2675 
2676 	if (type & PERF_SAMPLE_PERIOD) {
2677 		*array = sample->period;
2678 		array++;
2679 	}
2680 
2681 	if (type & PERF_SAMPLE_READ) {
2682 		if (read_format & PERF_FORMAT_GROUP)
2683 			*array = sample->read.group.nr;
2684 		else
2685 			*array = sample->read.one.value;
2686 		array++;
2687 
2688 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2689 			*array = sample->read.time_enabled;
2690 			array++;
2691 		}
2692 
2693 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2694 			*array = sample->read.time_running;
2695 			array++;
2696 		}
2697 
2698 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2699 		if (read_format & PERF_FORMAT_GROUP) {
2700 			sz = sample->read.group.nr *
2701 			     sizeof(struct sample_read_value);
2702 			memcpy(array, sample->read.group.values, sz);
2703 			array = (void *)array + sz;
2704 		} else {
2705 			*array = sample->read.one.id;
2706 			array++;
2707 		}
2708 	}
2709 
2710 	if (type & PERF_SAMPLE_CALLCHAIN) {
2711 		sz = (sample->callchain->nr + 1) * sizeof(u64);
2712 		memcpy(array, sample->callchain, sz);
2713 		array = (void *)array + sz;
2714 	}
2715 
2716 	if (type & PERF_SAMPLE_RAW) {
2717 		u.val32[0] = sample->raw_size;
2718 		*array = u.val64;
2719 		array = (void *)array + sizeof(u32);
2720 
2721 		memcpy(array, sample->raw_data, sample->raw_size);
2722 		array = (void *)array + sample->raw_size;
2723 	}
2724 
2725 	if (type & PERF_SAMPLE_BRANCH_STACK) {
2726 		sz = sample->branch_stack->nr * sizeof(struct branch_entry);
2727 		sz += sizeof(u64);
2728 		memcpy(array, sample->branch_stack, sz);
2729 		array = (void *)array + sz;
2730 	}
2731 
2732 	if (type & PERF_SAMPLE_REGS_USER) {
2733 		if (sample->user_regs.abi) {
2734 			*array++ = sample->user_regs.abi;
2735 			sz = hweight64(sample->user_regs.mask) * sizeof(u64);
2736 			memcpy(array, sample->user_regs.regs, sz);
2737 			array = (void *)array + sz;
2738 		} else {
2739 			*array++ = 0;
2740 		}
2741 	}
2742 
2743 	if (type & PERF_SAMPLE_STACK_USER) {
2744 		sz = sample->user_stack.size;
2745 		*array++ = sz;
2746 		if (sz) {
2747 			memcpy(array, sample->user_stack.data, sz);
2748 			array = (void *)array + sz;
2749 			*array++ = sz;
2750 		}
2751 	}
2752 
2753 	if (type & PERF_SAMPLE_WEIGHT) {
2754 		*array = sample->weight;
2755 		array++;
2756 	}
2757 
2758 	if (type & PERF_SAMPLE_DATA_SRC) {
2759 		*array = sample->data_src;
2760 		array++;
2761 	}
2762 
2763 	if (type & PERF_SAMPLE_TRANSACTION) {
2764 		*array = sample->transaction;
2765 		array++;
2766 	}
2767 
2768 	if (type & PERF_SAMPLE_REGS_INTR) {
2769 		if (sample->intr_regs.abi) {
2770 			*array++ = sample->intr_regs.abi;
2771 			sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
2772 			memcpy(array, sample->intr_regs.regs, sz);
2773 			array = (void *)array + sz;
2774 		} else {
2775 			*array++ = 0;
2776 		}
2777 	}
2778 
2779 	if (type & PERF_SAMPLE_PHYS_ADDR) {
2780 		*array = sample->phys_addr;
2781 		array++;
2782 	}
2783 
2784 	return 0;
2785 }
2786 
2787 struct tep_format_field *perf_evsel__field(struct perf_evsel *evsel, const char *name)
2788 {
2789 	return tep_find_field(evsel->tp_format, name);
2790 }
2791 
2792 void *perf_evsel__rawptr(struct perf_evsel *evsel, struct perf_sample *sample,
2793 			 const char *name)
2794 {
2795 	struct tep_format_field *field = perf_evsel__field(evsel, name);
2796 	int offset;
2797 
2798 	if (!field)
2799 		return NULL;
2800 
2801 	offset = field->offset;
2802 
2803 	if (field->flags & TEP_FIELD_IS_DYNAMIC) {
2804 		offset = *(int *)(sample->raw_data + field->offset);
2805 		offset &= 0xffff;
2806 	}
2807 
2808 	return sample->raw_data + offset;
2809 }
2810 
2811 u64 format_field__intval(struct tep_format_field *field, struct perf_sample *sample,
2812 			 bool needs_swap)
2813 {
2814 	u64 value;
2815 	void *ptr = sample->raw_data + field->offset;
2816 
2817 	switch (field->size) {
2818 	case 1:
2819 		return *(u8 *)ptr;
2820 	case 2:
2821 		value = *(u16 *)ptr;
2822 		break;
2823 	case 4:
2824 		value = *(u32 *)ptr;
2825 		break;
2826 	case 8:
2827 		memcpy(&value, ptr, sizeof(u64));
2828 		break;
2829 	default:
2830 		return 0;
2831 	}
2832 
2833 	if (!needs_swap)
2834 		return value;
2835 
2836 	switch (field->size) {
2837 	case 2:
2838 		return bswap_16(value);
2839 	case 4:
2840 		return bswap_32(value);
2841 	case 8:
2842 		return bswap_64(value);
2843 	default:
2844 		return 0;
2845 	}
2846 
2847 	return 0;
2848 }
2849 
2850 u64 perf_evsel__intval(struct perf_evsel *evsel, struct perf_sample *sample,
2851 		       const char *name)
2852 {
2853 	struct tep_format_field *field = perf_evsel__field(evsel, name);
2854 
2855 	if (!field)
2856 		return 0;
2857 
2858 	return field ? format_field__intval(field, sample, evsel->needs_swap) : 0;
2859 }
2860 
2861 bool perf_evsel__fallback(struct perf_evsel *evsel, int err,
2862 			  char *msg, size_t msgsize)
2863 {
2864 	int paranoid;
2865 
2866 	if ((err == ENOENT || err == ENXIO || err == ENODEV) &&
2867 	    evsel->attr.type   == PERF_TYPE_HARDWARE &&
2868 	    evsel->attr.config == PERF_COUNT_HW_CPU_CYCLES) {
2869 		/*
2870 		 * If it's cycles then fall back to hrtimer based
2871 		 * cpu-clock-tick sw counter, which is always available even if
2872 		 * no PMU support.
2873 		 *
2874 		 * PPC returns ENXIO until 2.6.37 (behavior changed with commit
2875 		 * b0a873e).
2876 		 */
2877 		scnprintf(msg, msgsize, "%s",
2878 "The cycles event is not supported, trying to fall back to cpu-clock-ticks");
2879 
2880 		evsel->attr.type   = PERF_TYPE_SOFTWARE;
2881 		evsel->attr.config = PERF_COUNT_SW_CPU_CLOCK;
2882 
2883 		zfree(&evsel->name);
2884 		return true;
2885 	} else if (err == EACCES && !evsel->attr.exclude_kernel &&
2886 		   (paranoid = perf_event_paranoid()) > 1) {
2887 		const char *name = perf_evsel__name(evsel);
2888 		char *new_name;
2889 		const char *sep = ":";
2890 
2891 		/* Is there already the separator in the name. */
2892 		if (strchr(name, '/') ||
2893 		    strchr(name, ':'))
2894 			sep = "";
2895 
2896 		if (asprintf(&new_name, "%s%su", name, sep) < 0)
2897 			return false;
2898 
2899 		if (evsel->name)
2900 			free(evsel->name);
2901 		evsel->name = new_name;
2902 		scnprintf(msg, msgsize,
2903 "kernel.perf_event_paranoid=%d, trying to fall back to excluding kernel samples", paranoid);
2904 		evsel->attr.exclude_kernel = 1;
2905 
2906 		return true;
2907 	}
2908 
2909 	return false;
2910 }
2911 
2912 static bool find_process(const char *name)
2913 {
2914 	size_t len = strlen(name);
2915 	DIR *dir;
2916 	struct dirent *d;
2917 	int ret = -1;
2918 
2919 	dir = opendir(procfs__mountpoint());
2920 	if (!dir)
2921 		return false;
2922 
2923 	/* Walk through the directory. */
2924 	while (ret && (d = readdir(dir)) != NULL) {
2925 		char path[PATH_MAX];
2926 		char *data;
2927 		size_t size;
2928 
2929 		if ((d->d_type != DT_DIR) ||
2930 		     !strcmp(".", d->d_name) ||
2931 		     !strcmp("..", d->d_name))
2932 			continue;
2933 
2934 		scnprintf(path, sizeof(path), "%s/%s/comm",
2935 			  procfs__mountpoint(), d->d_name);
2936 
2937 		if (filename__read_str(path, &data, &size))
2938 			continue;
2939 
2940 		ret = strncmp(name, data, len);
2941 		free(data);
2942 	}
2943 
2944 	closedir(dir);
2945 	return ret ? false : true;
2946 }
2947 
2948 int perf_evsel__open_strerror(struct perf_evsel *evsel, struct target *target,
2949 			      int err, char *msg, size_t size)
2950 {
2951 	char sbuf[STRERR_BUFSIZE];
2952 	int printed = 0;
2953 
2954 	switch (err) {
2955 	case EPERM:
2956 	case EACCES:
2957 		if (err == EPERM)
2958 			printed = scnprintf(msg, size,
2959 				"No permission to enable %s event.\n\n",
2960 				perf_evsel__name(evsel));
2961 
2962 		return scnprintf(msg + printed, size - printed,
2963 		 "You may not have permission to collect %sstats.\n\n"
2964 		 "Consider tweaking /proc/sys/kernel/perf_event_paranoid,\n"
2965 		 "which controls use of the performance events system by\n"
2966 		 "unprivileged users (without CAP_SYS_ADMIN).\n\n"
2967 		 "The current value is %d:\n\n"
2968 		 "  -1: Allow use of (almost) all events by all users\n"
2969 		 "      Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK\n"
2970 		 ">= 0: Disallow ftrace function tracepoint by users without CAP_SYS_ADMIN\n"
2971 		 "      Disallow raw tracepoint access by users without CAP_SYS_ADMIN\n"
2972 		 ">= 1: Disallow CPU event access by users without CAP_SYS_ADMIN\n"
2973 		 ">= 2: Disallow kernel profiling by users without CAP_SYS_ADMIN\n\n"
2974 		 "To make this setting permanent, edit /etc/sysctl.conf too, e.g.:\n\n"
2975 		 "	kernel.perf_event_paranoid = -1\n" ,
2976 				 target->system_wide ? "system-wide " : "",
2977 				 perf_event_paranoid());
2978 	case ENOENT:
2979 		return scnprintf(msg, size, "The %s event is not supported.",
2980 				 perf_evsel__name(evsel));
2981 	case EMFILE:
2982 		return scnprintf(msg, size, "%s",
2983 			 "Too many events are opened.\n"
2984 			 "Probably the maximum number of open file descriptors has been reached.\n"
2985 			 "Hint: Try again after reducing the number of events.\n"
2986 			 "Hint: Try increasing the limit with 'ulimit -n <limit>'");
2987 	case ENOMEM:
2988 		if (evsel__has_callchain(evsel) &&
2989 		    access("/proc/sys/kernel/perf_event_max_stack", F_OK) == 0)
2990 			return scnprintf(msg, size,
2991 					 "Not enough memory to setup event with callchain.\n"
2992 					 "Hint: Try tweaking /proc/sys/kernel/perf_event_max_stack\n"
2993 					 "Hint: Current value: %d", sysctl__max_stack());
2994 		break;
2995 	case ENODEV:
2996 		if (target->cpu_list)
2997 			return scnprintf(msg, size, "%s",
2998 	 "No such device - did you specify an out-of-range profile CPU?");
2999 		break;
3000 	case EOPNOTSUPP:
3001 		if (evsel->attr.sample_period != 0)
3002 			return scnprintf(msg, size,
3003 	"%s: PMU Hardware doesn't support sampling/overflow-interrupts. Try 'perf stat'",
3004 					 perf_evsel__name(evsel));
3005 		if (evsel->attr.precise_ip)
3006 			return scnprintf(msg, size, "%s",
3007 	"\'precise\' request may not be supported. Try removing 'p' modifier.");
3008 #if defined(__i386__) || defined(__x86_64__)
3009 		if (evsel->attr.type == PERF_TYPE_HARDWARE)
3010 			return scnprintf(msg, size, "%s",
3011 	"No hardware sampling interrupt available.\n");
3012 #endif
3013 		break;
3014 	case EBUSY:
3015 		if (find_process("oprofiled"))
3016 			return scnprintf(msg, size,
3017 	"The PMU counters are busy/taken by another profiler.\n"
3018 	"We found oprofile daemon running, please stop it and try again.");
3019 		break;
3020 	case EINVAL:
3021 		if (evsel->attr.write_backward && perf_missing_features.write_backward)
3022 			return scnprintf(msg, size, "Reading from overwrite event is not supported by this kernel.");
3023 		if (perf_missing_features.clockid)
3024 			return scnprintf(msg, size, "clockid feature not supported.");
3025 		if (perf_missing_features.clockid_wrong)
3026 			return scnprintf(msg, size, "wrong clockid (%d).", clockid);
3027 		break;
3028 	default:
3029 		break;
3030 	}
3031 
3032 	return scnprintf(msg, size,
3033 	"The sys_perf_event_open() syscall returned with %d (%s) for event (%s).\n"
3034 	"/bin/dmesg | grep -i perf may provide additional information.\n",
3035 			 err, str_error_r(err, sbuf, sizeof(sbuf)),
3036 			 perf_evsel__name(evsel));
3037 }
3038 
3039 struct perf_env *perf_evsel__env(struct perf_evsel *evsel)
3040 {
3041 	if (evsel && evsel->evlist)
3042 		return evsel->evlist->env;
3043 	return NULL;
3044 }
3045 
3046 static int store_evsel_ids(struct perf_evsel *evsel, struct perf_evlist *evlist)
3047 {
3048 	int cpu, thread;
3049 
3050 	for (cpu = 0; cpu < xyarray__max_x(evsel->fd); cpu++) {
3051 		for (thread = 0; thread < xyarray__max_y(evsel->fd);
3052 		     thread++) {
3053 			int fd = FD(evsel, cpu, thread);
3054 
3055 			if (perf_evlist__id_add_fd(evlist, evsel,
3056 						   cpu, thread, fd) < 0)
3057 				return -1;
3058 		}
3059 	}
3060 
3061 	return 0;
3062 }
3063 
3064 int perf_evsel__store_ids(struct perf_evsel *evsel, struct perf_evlist *evlist)
3065 {
3066 	struct cpu_map *cpus = evsel->cpus;
3067 	struct thread_map *threads = evsel->threads;
3068 
3069 	if (perf_evsel__alloc_id(evsel, cpus->nr, threads->nr))
3070 		return -ENOMEM;
3071 
3072 	return store_evsel_ids(evsel, evlist);
3073 }
3074