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