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