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