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