evlist.c 42.9 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3 4 5 6 7
/*
 * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
 *
 * Parts came from builtin-{top,stat,record}.c, see those files for further
 * copyright notes.
 */
8
#include <api/fs/fs.h>
9
#include <errno.h>
10
#include <inttypes.h>
11
#include <poll.h>
12
#include "cpumap.h"
13
#include "util/mmap.h"
14
#include "thread_map.h"
15
#include "target.h"
16 17
#include "evlist.h"
#include "evsel.h"
Adrian Hunter's avatar
Adrian Hunter committed
18
#include "debug.h"
19
#include "units.h"
20
#include <internal/lib.h> // page_size
21
#include "affinity.h"
22
#include "../perf.h"
23
#include "asm/bug.h"
24
#include "bpf-event.h"
25
#include "util/string2.h"
26
#include "util/perf_api_probe.h"
27
#include <signal.h>
28
#include <unistd.h>
29
#include <sched.h>
30
#include <stdlib.h>
31

32
#include "parse-events.h"
33
#include <subcmd/parse-options.h>
34

35
#include <fcntl.h>
36
#include <sys/ioctl.h>
37 38
#include <sys/mman.h>

39 40
#include <linux/bitops.h>
#include <linux/hash.h>
41
#include <linux/log2.h>
42
#include <linux/err.h>
43
#include <linux/string.h>
44
#include <linux/zalloc.h>
45
#include <perf/evlist.h>
46
#include <perf/evsel.h>
47
#include <perf/cpumap.h>
48
#include <perf/mmap.h>
49

50 51
#include <internal/xyarray.h>

52 53 54 55
#ifdef LACKS_SIGQUEUE_PROTOTYPE
int sigqueue(pid_t pid, int sig, const union sigval value);
#endif

56
#define FD(e, x, y) (*(int *)xyarray__entry(e->core.fd, x, y))
57
#define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
58

59 60
void evlist__init(struct evlist *evlist, struct perf_cpu_map *cpus,
		  struct perf_thread_map *threads)
61
{
62
	perf_evlist__init(&evlist->core);
63
	perf_evlist__set_maps(&evlist->core, cpus, threads);
64
	evlist->workload.pid = -1;
65
	evlist->bkw_mmap_state = BKW_MMAP_NOTREADY;
66 67 68
	evlist->ctl_fd.fd = -1;
	evlist->ctl_fd.ack = -1;
	evlist->ctl_fd.pos = -1;
69 70
}

71
struct evlist *evlist__new(void)
72
{
73
	struct evlist *evlist = zalloc(sizeof(*evlist));
74

75
	if (evlist != NULL)
76
		evlist__init(evlist, NULL, NULL);
77 78 79 80

	return evlist;
}

81
struct evlist *perf_evlist__new_default(void)
82
{
83
	struct evlist *evlist = evlist__new();
84

85
	if (evlist && evlist__add_default(evlist)) {
86
		evlist__delete(evlist);
87 88 89 90 91 92
		evlist = NULL;
	}

	return evlist;
}

93
struct evlist *perf_evlist__new_dummy(void)
94
{
95
	struct evlist *evlist = evlist__new();
96

97
	if (evlist && evlist__add_dummy(evlist)) {
98
		evlist__delete(evlist);
99 100 101 102 103 104
		evlist = NULL;
	}

	return evlist;
}

105
/**
106
 * evlist__set_id_pos - set the positions of event ids.
107 108 109 110 111
 * @evlist: selected event list
 *
 * Events with compatible sample types all have the same id_pos
 * and is_pos.  For convenience, put a copy on evlist.
 */
112
void evlist__set_id_pos(struct evlist *evlist)
113
{
114
	struct evsel *first = evlist__first(evlist);
115 116 117 118 119

	evlist->id_pos = first->id_pos;
	evlist->is_pos = first->is_pos;
}

120
static void evlist__update_id_pos(struct evlist *evlist)
121
{
122
	struct evsel *evsel;
123

124
	evlist__for_each_entry(evlist, evsel)
125
		evsel__calc_id_pos(evsel);
126

127
	evlist__set_id_pos(evlist);
128 129
}

130
static void evlist__purge(struct evlist *evlist)
131
{
132
	struct evsel *pos, *n;
133

134
	evlist__for_each_entry_safe(evlist, n, pos) {
135
		list_del_init(&pos->core.node);
136
		pos->evlist = NULL;
137
		evsel__delete(pos);
138 139
	}

140
	evlist->core.nr_entries = 0;
141 142
}

143
void evlist__exit(struct evlist *evlist)
144
{
145
	zfree(&evlist->mmap);
146
	zfree(&evlist->overwrite_mmap);
147
	perf_evlist__exit(&evlist->core);
148 149
}

150
void evlist__delete(struct evlist *evlist)
151
{
152 153 154
	if (evlist == NULL)
		return;

155
	evlist__munmap(evlist);
156
	evlist__close(evlist);
157
	evlist__purge(evlist);
158
	evlist__exit(evlist);
159 160 161
	free(evlist);
}

162
void evlist__add(struct evlist *evlist, struct evsel *entry)
163
{
164
	entry->evlist = evlist;
165
	entry->idx = evlist->core.nr_entries;
166
	entry->tracking = !entry->idx;
167

168 169 170
	perf_evlist__add(&evlist->core, &entry->core);

	if (evlist->core.nr_entries == 1)
171
		evlist__set_id_pos(evlist);
172 173
}

174
void evlist__remove(struct evlist *evlist, struct evsel *evsel)
175 176
{
	evsel->evlist = NULL;
177
	perf_evlist__remove(&evlist->core, &evsel->core);
178 179
}

180
void perf_evlist__splice_list_tail(struct evlist *evlist,
181
				   struct list_head *list)
182
{
183
	struct evsel *evsel, *temp;
184

185
	__evlist__for_each_entry_safe(list, temp, evsel) {
186
		list_del_init(&evsel->core.node);
187
		evlist__add(evlist, evsel);
188
	}
189 190
}

191 192 193 194 195 196 197 198
int __evlist__set_tracepoints_handlers(struct evlist *evlist,
				       const struct evsel_str_handler *assocs, size_t nr_assocs)
{
	size_t i;
	int err;

	for (i = 0; i < nr_assocs; i++) {
		// Adding a handler for an event not in this evlist, just ignore it.
199
		struct evsel *evsel = evlist__find_tracepoint_by_name(evlist, assocs[i].name);
200 201 202 203 204 205 206 207 208 209 210 211 212 213
		if (evsel == NULL)
			continue;

		err = -EEXIST;
		if (evsel->handler != NULL)
			goto out;
		evsel->handler = assocs[i].handler;
	}

	err = 0;
out:
	return err;
}

214
void __evlist__set_leader(struct list_head *list)
215
{
216
	struct evsel *evsel, *leader;
217

218 219
	leader = list_entry(list->next, struct evsel, core.node);
	evsel = list_entry(list->prev, struct evsel, core.node);
220

221
	leader->core.nr_members = evsel->idx - leader->idx + 1;
222

223
	__evlist__for_each_entry(list, evsel) {
224
		evsel->leader = leader;
225 226 227
	}
}

228
void evlist__set_leader(struct evlist *evlist)
229
{
230 231
	if (evlist->core.nr_entries) {
		evlist->nr_groups = evlist->core.nr_entries > 1 ? 1 : 0;
232
		__evlist__set_leader(&evlist->core.entries);
233
	}
234 235
}

236
int __evlist__add_default(struct evlist *evlist, bool precise)
237
{
238
	struct evsel *evsel = evsel__new_cycles(precise);
239

240
	if (evsel == NULL)
241
		return -ENOMEM;
242

243
	evlist__add(evlist, evsel);
244 245
	return 0;
}
246

247
int evlist__add_dummy(struct evlist *evlist)
248 249 250 251 252 253
{
	struct perf_event_attr attr = {
		.type	= PERF_TYPE_SOFTWARE,
		.config = PERF_COUNT_SW_DUMMY,
		.size	= sizeof(attr), /* to capture ABI version */
	};
254
	struct evsel *evsel = evsel__new_idx(&attr, evlist->core.nr_entries);
255 256 257 258

	if (evsel == NULL)
		return -ENOMEM;

259
	evlist__add(evlist, evsel);
260 261 262
	return 0;
}

263
static int evlist__add_attrs(struct evlist *evlist, struct perf_event_attr *attrs, size_t nr_attrs)
264
{
265
	struct evsel *evsel, *n;
266 267 268 269
	LIST_HEAD(head);
	size_t i;

	for (i = 0; i < nr_attrs; i++) {
270
		evsel = evsel__new_idx(attrs + i, evlist->core.nr_entries + i);
271 272
		if (evsel == NULL)
			goto out_delete_partial_list;
273
		list_add_tail(&evsel->core.node, &head);
274 275
	}

276
	perf_evlist__splice_list_tail(evlist, &head);
277 278 279 280

	return 0;

out_delete_partial_list:
281
	__evlist__for_each_entry_safe(&head, n, evsel)
282
		evsel__delete(evsel);
283 284 285
	return -1;
}

286
int __evlist__add_default_attrs(struct evlist *evlist, struct perf_event_attr *attrs, size_t nr_attrs)
287 288 289 290 291 292
{
	size_t i;

	for (i = 0; i < nr_attrs; i++)
		event_attr_init(attrs + i);

293
	return evlist__add_attrs(evlist, attrs, nr_attrs);
294 295
}

296
struct evsel *evlist__find_tracepoint_by_id(struct evlist *evlist, int id)
297
{
298
	struct evsel *evsel;
299

300
	evlist__for_each_entry(evlist, evsel) {
301 302
		if (evsel->core.attr.type   == PERF_TYPE_TRACEPOINT &&
		    (int)evsel->core.attr.config == id)
303 304 305 306 307 308
			return evsel;
	}

	return NULL;
}

309
struct evsel *evlist__find_tracepoint_by_name(struct evlist *evlist, const char *name)
310
{
311
	struct evsel *evsel;
312

313
	evlist__for_each_entry(evlist, evsel) {
314
		if ((evsel->core.attr.type == PERF_TYPE_TRACEPOINT) &&
315 316 317 318 319 320 321
		    (strcmp(evsel->name, name) == 0))
			return evsel;
	}

	return NULL;
}

322
int evlist__add_newtp(struct evlist *evlist, const char *sys, const char *name, void *handler)
323
{
324
	struct evsel *evsel = evsel__newtp(sys, name);
325

326
	if (IS_ERR(evsel))
327 328
		return -1;

329
	evsel->handler = handler;
330
	evlist__add(evlist, evsel);
331 332 333
	return 0;
}

334
static int perf_evlist__nr_threads(struct evlist *evlist,
335
				   struct evsel *evsel)
336
{
337
	if (evsel->core.system_wide)
338 339
		return 1;
	else
340
		return perf_thread_map__nr(evlist->core.threads);
341 342
}

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
void evlist__cpu_iter_start(struct evlist *evlist)
{
	struct evsel *pos;

	/*
	 * Reset the per evsel cpu_iter. This is needed because
	 * each evsel's cpumap may have a different index space,
	 * and some operations need the index to modify
	 * the FD xyarray (e.g. open, close)
	 */
	evlist__for_each_entry(evlist, pos)
		pos->cpu_iter = 0;
}

bool evsel__cpu_iter_skip_no_inc(struct evsel *ev, int cpu)
{
	if (ev->cpu_iter >= ev->core.cpus->nr)
		return true;
	if (cpu >= 0 && ev->core.cpus->map[ev->cpu_iter] != cpu)
		return true;
	return false;
}

bool evsel__cpu_iter_skip(struct evsel *ev, int cpu)
{
	if (!evsel__cpu_iter_skip_no_inc(ev, cpu)) {
		ev->cpu_iter++;
		return false;
	}
	return true;
}

375
void evlist__disable(struct evlist *evlist)
376
{
377
	struct evsel *pos;
378
	struct affinity affinity;
379 380
	int cpu, i, imm = 0;
	bool has_imm = false;
381

382 383 384
	if (affinity__setup(&affinity) < 0)
		return;

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	/* Disable 'immediate' events last */
	for (imm = 0; imm <= 1; imm++) {
		evlist__for_each_cpu(evlist, i, cpu) {
			affinity__set(&affinity, cpu);

			evlist__for_each_entry(evlist, pos) {
				if (evsel__cpu_iter_skip(pos, cpu))
					continue;
				if (pos->disabled || !evsel__is_group_leader(pos) || !pos->core.fd)
					continue;
				if (pos->immediate)
					has_imm = true;
				if (pos->immediate != imm)
					continue;
				evsel__disable_cpu(pos, pos->cpu_iter - 1);
			}
401
		}
402 403
		if (!has_imm)
			break;
404
	}
405

406
	affinity__cleanup(&affinity);
407
	evlist__for_each_entry(evlist, pos) {
408
		if (!evsel__is_group_leader(pos) || !pos->core.fd)
409
			continue;
410
		pos->disabled = true;
411
	}
412 413

	evlist->enabled = false;
414 415
}

416
void evlist__enable(struct evlist *evlist)
417
{
418
	struct evsel *pos;
419 420
	struct affinity affinity;
	int cpu, i;
421

422 423 424 425 426 427 428 429 430
	if (affinity__setup(&affinity) < 0)
		return;

	evlist__for_each_cpu(evlist, i, cpu) {
		affinity__set(&affinity, cpu);

		evlist__for_each_entry(evlist, pos) {
			if (evsel__cpu_iter_skip(pos, cpu))
				continue;
431
			if (!evsel__is_group_leader(pos) || !pos->core.fd)
432 433 434 435 436
				continue;
			evsel__enable_cpu(pos, pos->cpu_iter - 1);
		}
	}
	affinity__cleanup(&affinity);
437
	evlist__for_each_entry(evlist, pos) {
438
		if (!evsel__is_group_leader(pos) || !pos->core.fd)
439
			continue;
440
		pos->disabled = false;
441
	}
442 443 444 445

	evlist->enabled = true;
}

446
void evlist__toggle_enable(struct evlist *evlist)
447
{
448
	(evlist->enabled ? evlist__disable : evlist__enable)(evlist);
449 450
}

451
static int perf_evlist__enable_event_cpu(struct evlist *evlist,
452
					 struct evsel *evsel, int cpu)
453
{
454
	int thread;
455 456
	int nr_threads = perf_evlist__nr_threads(evlist, evsel);

457
	if (!evsel->core.fd)
458 459 460
		return -EINVAL;

	for (thread = 0; thread < nr_threads; thread++) {
461
		int err = ioctl(FD(evsel, cpu, thread), PERF_EVENT_IOC_ENABLE, 0);
462 463 464 465 466 467
		if (err)
			return err;
	}
	return 0;
}

468
static int perf_evlist__enable_event_thread(struct evlist *evlist,
469
					    struct evsel *evsel,
470 471
					    int thread)
{
472
	int cpu;
473
	int nr_cpus = perf_cpu_map__nr(evlist->core.cpus);
474

475
	if (!evsel->core.fd)
476 477 478
		return -EINVAL;

	for (cpu = 0; cpu < nr_cpus; cpu++) {
479
		int err = ioctl(FD(evsel, cpu, thread), PERF_EVENT_IOC_ENABLE, 0);
480 481 482 483 484 485
		if (err)
			return err;
	}
	return 0;
}

486
int perf_evlist__enable_event_idx(struct evlist *evlist,
487
				  struct evsel *evsel, int idx)
488
{
489
	bool per_cpu_mmaps = !perf_cpu_map__empty(evlist->core.cpus);
490 491 492 493 494 495 496

	if (per_cpu_mmaps)
		return perf_evlist__enable_event_cpu(evlist, evsel, idx);
	else
		return perf_evlist__enable_event_thread(evlist, evsel, idx);
}

497
int evlist__add_pollfd(struct evlist *evlist, int fd)
498
{
499
	return perf_evlist__add_pollfd(&evlist->core, fd, NULL, POLLIN, fdarray_flag__default);
500 501
}

502
int evlist__filter_pollfd(struct evlist *evlist, short revents_and_mask)
503
{
504
	return perf_evlist__filter_pollfd(&evlist->core, revents_and_mask);
505 506
}

507
int evlist__poll(struct evlist *evlist, int timeout)
508
{
509
	return perf_evlist__poll(&evlist->core, timeout);
510 511
}

512
struct perf_sample_id *evlist__id2sid(struct evlist *evlist, u64 id)
513 514 515 516 517 518
{
	struct hlist_head *head;
	struct perf_sample_id *sid;
	int hash;

	hash = hash_64(id, PERF_EVLIST__HLIST_BITS);
519
	head = &evlist->core.heads[hash];
520

521
	hlist_for_each_entry(sid, head, node)
522
		if (sid->id == id)
523 524 525 526 527
			return sid;

	return NULL;
}

528
struct evsel *evlist__id2evsel(struct evlist *evlist, u64 id)
529 530 531
{
	struct perf_sample_id *sid;

532
	if (evlist->core.nr_entries == 1 || !id)
533
		return evlist__first(evlist);
534

535
	sid = evlist__id2sid(evlist, id);
536
	if (sid)
537
		return container_of(sid->evsel, struct evsel, core);
538

539
	if (!evlist__sample_id_all(evlist))
540
		return evlist__first(evlist);
541

542 543
	return NULL;
}
544

545
struct evsel *evlist__id2evsel_strict(struct evlist *evlist, u64 id)
546 547 548 549 550 551
{
	struct perf_sample_id *sid;

	if (!id)
		return NULL;

552
	sid = evlist__id2sid(evlist, id);
553
	if (sid)
554
		return container_of(sid->evsel, struct evsel, core);
555 556 557 558

	return NULL;
}

559
static int evlist__event2id(struct evlist *evlist, union perf_event *event, u64 *id)
560
{
561
	const __u64 *array = event->sample.array;
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
	ssize_t n;

	n = (event->header.size - sizeof(event->header)) >> 3;

	if (event->header.type == PERF_RECORD_SAMPLE) {
		if (evlist->id_pos >= n)
			return -1;
		*id = array[evlist->id_pos];
	} else {
		if (evlist->is_pos > n)
			return -1;
		n -= evlist->is_pos;
		*id = array[n];
	}
	return 0;
}

579
struct evsel *evlist__event2evsel(struct evlist *evlist, union perf_event *event)
580
{
581
	struct evsel *first = evlist__first(evlist);
582 583 584 585 586
	struct hlist_head *head;
	struct perf_sample_id *sid;
	int hash;
	u64 id;

587
	if (evlist->core.nr_entries == 1)
588 589
		return first;

590
	if (!first->core.attr.sample_id_all &&
591 592
	    event->header.type != PERF_RECORD_SAMPLE)
		return first;
593

594
	if (evlist__event2id(evlist, event, &id))
595 596 597 598
		return NULL;

	/* Synthesized events have an id of zero */
	if (!id)
599
		return first;
600 601

	hash = hash_64(id, PERF_EVLIST__HLIST_BITS);
602
	head = &evlist->core.heads[hash];
603 604 605

	hlist_for_each_entry(sid, head, node) {
		if (sid->id == id)
606
			return container_of(sid->evsel, struct evsel, core);
607 608 609 610
	}
	return NULL;
}

611
static int perf_evlist__set_paused(struct evlist *evlist, bool value)
612 613 614
{
	int i;

615
	if (!evlist->overwrite_mmap)
616 617
		return 0;

618
	for (i = 0; i < evlist->core.nr_mmaps; i++) {
619
		int fd = evlist->overwrite_mmap[i].core.fd;
620 621 622 623 624 625 626 627 628 629 630
		int err;

		if (fd < 0)
			continue;
		err = ioctl(fd, PERF_EVENT_IOC_PAUSE_OUTPUT, value ? 1 : 0);
		if (err)
			return err;
	}
	return 0;
}

631
static int perf_evlist__pause(struct evlist *evlist)
632 633 634 635
{
	return perf_evlist__set_paused(evlist, true);
}

636
static int perf_evlist__resume(struct evlist *evlist)
637 638 639 640
{
	return perf_evlist__set_paused(evlist, false);
}

641
static void evlist__munmap_nofree(struct evlist *evlist)
642
{
643
	int i;
644

645
	if (evlist->mmap)
646
		for (i = 0; i < evlist->core.nr_mmaps; i++)
647
			perf_mmap__munmap(&evlist->mmap[i].core);
648

649
	if (evlist->overwrite_mmap)
650
		for (i = 0; i < evlist->core.nr_mmaps; i++)
651
			perf_mmap__munmap(&evlist->overwrite_mmap[i].core);
652
}
653

654
void evlist__munmap(struct evlist *evlist)
655
{
656
	evlist__munmap_nofree(evlist);
657
	zfree(&evlist->mmap);
658
	zfree(&evlist->overwrite_mmap);
659 660
}

661 662 663 664 665 666 667
static void perf_mmap__unmap_cb(struct perf_mmap *map)
{
	struct mmap *m = container_of(map, struct mmap, core);

	mmap__munmap(m);
}

668 669
static struct mmap *evlist__alloc_mmap(struct evlist *evlist,
				       bool overwrite)
670
{
671
	int i;
672
	struct mmap *map;
673

674
	map = zalloc(evlist->core.nr_mmaps * sizeof(struct mmap));
675 676
	if (!map)
		return NULL;
677

678
	for (i = 0; i < evlist->core.nr_mmaps; i++) {
679 680
		struct perf_mmap *prev = i ? &map[i - 1].core : NULL;

681 682
		/*
		 * When the perf_mmap() call is made we grab one refcount, plus
683
		 * one extra to let perf_mmap__consume() get the last
684 685 686 687 688 689
		 * events after all real references (perf_mmap__get()) are
		 * dropped.
		 *
		 * Each PERF_EVENT_IOC_SET_OUTPUT points to this mmap and
		 * thus does perf_mmap__get() on it.
		 */
690
		perf_mmap__init(&map[i].core, prev, overwrite, perf_mmap__unmap_cb);
691
	}
692

693
	return map;
694 695
}

696 697 698 699 700 701 702 703 704 705 706
static void
perf_evlist__mmap_cb_idx(struct perf_evlist *_evlist,
			 struct perf_mmap_param *_mp,
			 int idx, bool per_cpu)
{
	struct evlist *evlist = container_of(_evlist, struct evlist, core);
	struct mmap_params *mp = container_of(_mp, struct mmap_params, core);

	auxtrace_mmap_params__set_idx(&mp->auxtrace_mp, evlist, idx, per_cpu);
}

707 708 709 710
static struct perf_mmap*
perf_evlist__mmap_cb_get(struct perf_evlist *_evlist, bool overwrite, int idx)
{
	struct evlist *evlist = container_of(_evlist, struct evlist, core);
711
	struct mmap *maps;
712

713
	maps = overwrite ? evlist->overwrite_mmap : evlist->mmap;
714

715 716 717 718
	if (!maps) {
		maps = evlist__alloc_mmap(evlist, overwrite);
		if (!maps)
			return NULL;
719

720
		if (overwrite) {
721 722
			evlist->overwrite_mmap = maps;
			if (evlist->bkw_mmap_state == BKW_MMAP_NOTREADY)
723
				evlist__toggle_bkw_mmap(evlist, BKW_MMAP_RUNNING);
724 725
		} else {
			evlist->mmap = maps;
726 727 728 729 730 731
		}
	}

	return &maps[idx].core;
}

732 733 734 735 736 737 738 739 740 741
static int
perf_evlist__mmap_cb_mmap(struct perf_mmap *_map, struct perf_mmap_param *_mp,
			  int output, int cpu)
{
	struct mmap *map = container_of(_map, struct mmap, core);
	struct mmap_params *mp = container_of(_mp, struct mmap_params, core);

	return mmap__mmap(map, mp, output, cpu);
}

742
unsigned long perf_event_mlock_kb_in_pages(void)
743
{
744 745
	unsigned long pages;
	int max;
746

747 748 749 750 751 752 753 754 755 756
	if (sysctl__read_int("kernel/perf_event_mlock_kb", &max) < 0) {
		/*
		 * Pick a once upon a time good value, i.e. things look
		 * strange since we can't read a sysctl value, but lets not
		 * die yet...
		 */
		max = 512;
	} else {
		max -= (page_size / 1024);
	}
757

758 759 760 761 762 763 764
	pages = (max * 1024) / page_size;
	if (!is_power_of_2(pages))
		pages = rounddown_pow_of_two(pages);

	return pages;
}

765
size_t evlist__mmap_size(unsigned long pages)
766 767 768 769
{
	if (pages == UINT_MAX)
		pages = perf_event_mlock_kb_in_pages();
	else if (!is_power_of_2(pages))
770 771 772 773 774
		return 0;

	return (pages + 1) * page_size;
}

775 776
static long parse_pages_arg(const char *str, unsigned long min,
			    unsigned long max)
777
{
778
	unsigned long pages, val;
779 780 781 782 783 784 785
	static struct parse_tag tags[] = {
		{ .tag  = 'B', .mult = 1       },
		{ .tag  = 'K', .mult = 1 << 10 },
		{ .tag  = 'M', .mult = 1 << 20 },
		{ .tag  = 'G', .mult = 1 << 30 },
		{ .tag  = 0 },
	};
786

787
	if (str == NULL)
788
		return -EINVAL;
789

790
	val = parse_tag_value(str, tags);
791
	if (val != (unsigned long) -1) {
792 793 794 795 796 797
		/* we got file size value */
		pages = PERF_ALIGN(val, page_size) / page_size;
	} else {
		/* we got pages count value */
		char *eptr;
		pages = strtoul(str, &eptr, 10);
798 799
		if (*eptr != '\0')
			return -EINVAL;
800 801
	}

802
	if (pages == 0 && min == 0) {
803
		/* leave number of pages at 0 */
804
	} else if (!is_power_of_2(pages)) {
805 806
		char buf[100];

807
		/* round pages up to next power of 2 */
808
		pages = roundup_pow_of_two(pages);
809 810
		if (!pages)
			return -EINVAL;
811 812 813 814

		unit_number__scnprintf(buf, sizeof(buf), pages * page_size);
		pr_info("rounding mmap pages size to %s (%lu pages)\n",
			buf, pages);
815 816
	}

817 818 819 820 821 822
	if (pages > max)
		return -EINVAL;

	return pages;
}

823
int __perf_evlist__parse_mmap_pages(unsigned int *mmap_pages, const char *str)
824 825 826 827
{
	unsigned long max = UINT_MAX;
	long pages;

828
	if (max > SIZE_MAX / page_size)
829 830 831 832 833
		max = SIZE_MAX / page_size;

	pages = parse_pages_arg(str, 1, max);
	if (pages < 0) {
		pr_err("Invalid argument for --mmap_pages/-m\n");
834 835 836 837 838 839 840
		return -1;
	}

	*mmap_pages = pages;
	return 0;
}

841 842 843 844 845 846
int perf_evlist__parse_mmap_pages(const struct option *opt, const char *str,
				  int unset __maybe_unused)
{
	return __perf_evlist__parse_mmap_pages(opt->value, str);
}

847
/**
848
 * evlist__mmap_ex - Create mmaps to receive events.
849 850 851
 * @evlist: list of events
 * @pages: map length in pages
 * @overwrite: overwrite older events?
852 853
 * @auxtrace_pages - auxtrace map length in pages
 * @auxtrace_overwrite - overwrite older auxtrace data?
854
 *
855
 * If @overwrite is %false the user needs to signal event consumption using
856
 * perf_mmap__write_tail().  Using evlist__mmap_read() does this
857
 * automatically.
858
 *
859 860 861
 * Similarly, if @auxtrace_overwrite is %false the user needs to signal data
 * consumption using auxtrace_mmap__write_tail().
 *
862
 * Return: %0 on success, negative error code otherwise.
863
 */
864
int evlist__mmap_ex(struct evlist *evlist, unsigned int pages,
865
			 unsigned int auxtrace_pages,
866 867
			 bool auxtrace_overwrite, int nr_cblocks, int affinity, int flush,
			 int comp_level)
868
{
869 870 871 872 873
	/*
	 * Delay setting mp.prot: set it before calling perf_mmap__mmap.
	 * Its value is decided by evsel's write_backward.
	 * So &mp should not be passed through const pointer.
	 */
874 875 876 877 878 879
	struct mmap_params mp = {
		.nr_cblocks	= nr_cblocks,
		.affinity	= affinity,
		.flush		= flush,
		.comp_level	= comp_level
	};
880
	struct perf_evlist_mmap_ops ops = {
881 882 883
		.idx  = perf_evlist__mmap_cb_idx,
		.get  = perf_evlist__mmap_cb_get,
		.mmap = perf_evlist__mmap_cb_mmap,
884
	};
885

886 887
	evlist->core.mmap_len = evlist__mmap_size(pages);
	pr_debug("mmap size %zuB\n", evlist->core.mmap_len);
888

889
	auxtrace_mmap_params__init(&mp.auxtrace_mp, evlist->core.mmap_len,
890 891
				   auxtrace_pages, auxtrace_overwrite);

892
	return perf_evlist__mmap_ops(&evlist->core, &ops, &mp.core);
893
}
894

895
int evlist__mmap(struct evlist *evlist, unsigned int pages)
896
{
897
	return evlist__mmap_ex(evlist, pages, 0, false, 0, PERF_AFFINITY_SYS, 1, 0);
898 899
}

900
int perf_evlist__create_maps(struct evlist *evlist, struct target *target)
901
{
902
	bool all_threads = (target->per_thread && target->system_wide);
903
	struct perf_cpu_map *cpus;
904
	struct perf_thread_map *threads;
905

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
	/*
	 * If specify '-a' and '--per-thread' to perf record, perf record
	 * will override '--per-thread'. target->per_thread = false and
	 * target->system_wide = true.
	 *
	 * If specify '--per-thread' only to perf record,
	 * target->per_thread = true and target->system_wide = false.
	 *
	 * So target->per_thread && target->system_wide is false.
	 * For perf record, thread_map__new_str doesn't call
	 * thread_map__new_all_cpus. That will keep perf record's
	 * current behavior.
	 *
	 * For perf stat, it allows the case that target->per_thread and
	 * target->system_wide are all true. It means to collect system-wide
	 * per-thread data. thread_map__new_str will call
	 * thread_map__new_all_cpus to enumerate all threads.
	 */
924
	threads = thread_map__new_str(target->pid, target->tid, target->uid,
925
				      all_threads);
926

927
	if (!threads)
928 929
		return -1;

930
	if (target__uses_dummy_map(target))
931
		cpus = perf_cpu_map__dummy_new();
932
	else
933
		cpus = perf_cpu_map__new(target->cpu_list);
934

935
	if (!cpus)
936 937
		goto out_delete_threads;

938
	evlist->core.has_user_cpus = !!target->cpu_list;
939

940
	perf_evlist__set_maps(&evlist->core, cpus, threads);
941

942 943 944 945
	/* as evlist now has references, put count here */
	perf_cpu_map__put(cpus);
	perf_thread_map__put(threads);

946
	return 0;
947 948

out_delete_threads:
949
	perf_thread_map__put(threads);
950 951 952
	return -1;
}

953
int evlist__apply_filters(struct evlist *evlist, struct evsel **err_evsel)
954
{
955
	struct evsel *evsel;
956
	int err = 0;
957

958
	evlist__for_each_entry(evlist, evsel) {
959
		if (evsel->filter == NULL)
960
			continue;
961

962 963 964 965
		/*
		 * filters only work for tracepoint event, which doesn't have cpu limit.
		 * So evlist and evsel should always be same.
		 */
966
		err = perf_evsel__apply_filter(&evsel->core, evsel->filter);
967 968
		if (err) {
			*err_evsel = evsel;
969
			break;
970
		}
971 972
	}

973 974 975
	return err;
}

976
int evlist__set_tp_filter(struct evlist *evlist, const char *filter)
977
{
978
	struct evsel *evsel;
979 980
	int err = 0;

981 982 983
	if (filter == NULL)
		return -1;

984
	evlist__for_each_entry(evlist, evsel) {
985
		if (evsel->core.attr.type != PERF_TYPE_TRACEPOINT)
986 987
			continue;

988
		err = evsel__set_filter(evsel, filter);
989 990 991 992 993
		if (err)
			break;
	}

	return err;
994
}
995

996
int evlist__append_tp_filter(struct evlist *evlist, const char *filter)
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
{
	struct evsel *evsel;
	int err = 0;

	if (filter == NULL)
		return -1;

	evlist__for_each_entry(evlist, evsel) {
		if (evsel->core.attr.type != PERF_TYPE_TRACEPOINT)
			continue;

1008
		err = evsel__append_tp_filter(evsel, filter);
1009 1010 1011 1012 1013 1014 1015
		if (err)
			break;
	}

	return err;
}

1016
char *asprintf__tp_filter_pids(size_t npids, pid_t *pids)
1017 1018
{
	char *filter;
1019
	size_t i;
1020

1021 1022 1023
	for (i = 0; i < npids; ++i) {
		if (i == 0) {
			if (asprintf(&filter, "common_pid != %d", pids[i]) < 0)
1024
				return NULL;
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		} else {
			char *tmp;

			if (asprintf(&tmp, "%s && common_pid != %d", filter, pids[i]) < 0)
				goto out_free;

			free(filter);
			filter = tmp;
		}
	}
1035

1036
	return filter;
1037
out_free:
1038 1039 1040 1041
	free(filter);
	return NULL;
}

1042
int evlist__set_tp_filter_pids(struct evlist *evlist, size_t npids, pid_t *pids)
1043 1044
{
	char *filter = asprintf__tp_filter_pids(npids, pids);
1045
	int ret = evlist__set_tp_filter(evlist, filter);
1046

1047 1048 1049 1050
	free(filter);
	return ret;
}

1051
int evlist__set_tp_filter_pid(struct evlist *evlist, pid_t pid)
1052
{
1053
	return evlist__set_tp_filter_pids(evlist, 1, &pid);
1054 1055
}

1056
int evlist__append_tp_filter_pids(struct evlist *evlist, size_t npids, pid_t *pids)
1057 1058
{
	char *filter = asprintf__tp_filter_pids(npids, pids);
1059
	int ret = evlist__append_tp_filter(evlist, filter);
1060 1061 1062 1063 1064

	free(filter);
	return ret;
}

1065
int evlist__append_tp_filter_pid(struct evlist *evlist, pid_t pid)
1066
{
1067
	return evlist__append_tp_filter_pids(evlist, 1, &pid);
1068 1069
}

1070
bool evlist__valid_sample_type(struct evlist *evlist)
1071
{
1072
	struct evsel *pos;
1073

1074
	if (evlist->core.nr_entries == 1)
1075 1076 1077 1078 1079
		return true;

	if (evlist->id_pos < 0 || evlist->is_pos < 0)
		return false;

1080
	evlist__for_each_entry(evlist, pos) {
1081 1082
		if (pos->id_pos != evlist->id_pos ||
		    pos->is_pos != evlist->is_pos)
1083
			return false;
1084 1085
	}

1086
	return true;
1087 1088
}

1089
u64 __evlist__combined_sample_type(struct evlist *evlist)
1090
{
1091
	struct evsel *evsel;
1092 1093 1094 1095

	if (evlist->combined_sample_type)
		return evlist->combined_sample_type;

1096
	evlist__for_each_entry(evlist, evsel)
1097
		evlist->combined_sample_type |= evsel->core.attr.sample_type;
1098 1099 1100 1101

	return evlist->combined_sample_type;
}

1102
u64 evlist__combined_sample_type(struct evlist *evlist)
1103 1104
{
	evlist->combined_sample_type = 0;
1105
	return __evlist__combined_sample_type(evlist);
1106 1107
}

1108
u64 evlist__combined_branch_type(struct evlist *evlist)
1109
{
1110
	struct evsel *evsel;
1111 1112
	u64 branch_type = 0;

1113
	evlist__for_each_entry(evlist, evsel)
1114
		branch_type |= evsel->core.attr.branch_sample_type;
1115 1116 1117
	return branch_type;
}

1118
bool perf_evlist__valid_read_format(struct evlist *evlist)
1119
{
1120
	struct evsel *first = evlist__first(evlist), *pos = first;
1121 1122
	u64 read_format = first->core.attr.read_format;
	u64 sample_type = first->core.attr.sample_type;
1123

1124
	evlist__for_each_entry(evlist, pos) {
1125 1126 1127 1128
		if (read_format != pos->core.attr.read_format) {
			pr_debug("Read format differs %#" PRIx64 " vs %#" PRIx64 "\n",
				 read_format, (u64)pos->core.attr.read_format);
		}
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
	}

	/* PERF_SAMPLE_READ imples PERF_FORMAT_ID. */
	if ((sample_type & PERF_SAMPLE_READ) &&
	    !(read_format & PERF_FORMAT_ID)) {
		return false;
	}

	return true;
}

1140
u16 perf_evlist__id_hdr_size(struct evlist *evlist)
1141
{
1142
	struct evsel *first = evlist__first(evlist);
1143 1144 1145 1146
	struct perf_sample *data;
	u64 sample_type;
	u16 size = 0;

1147
	if (!first->core.attr.sample_id_all)
1148 1149
		goto out;

1150
	sample_type = first->core.attr.sample_type;
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

	if (sample_type & PERF_SAMPLE_TID)
		size += sizeof(data->tid) * 2;

       if (sample_type & PERF_SAMPLE_TIME)
		size += sizeof(data->time);

	if (sample_type & PERF_SAMPLE_ID)
		size += sizeof(data->id);

	if (sample_type & PERF_SAMPLE_STREAM_ID)
		size += sizeof(data->stream_id);

	if (sample_type & PERF_SAMPLE_CPU)
		size += sizeof(data->cpu) * 2;
1166 1167 1168

	if (sample_type & PERF_SAMPLE_IDENTIFIER)
		size += sizeof(data->id);
1169 1170 1171 1172
out:
	return size;
}

1173
bool evlist__valid_sample_id_all(struct evlist *evlist)
1174
{
1175
	struct evsel *first = evlist__first(evlist), *pos = first;
1176

1177
	evlist__for_each_entry_continue(evlist, pos) {
1178
		if (first->core.attr.sample_id_all != pos->core.attr.sample_id_all)
1179
			return false;
1180 1181
	}

1182 1183 1184
	return true;
}

1185
bool evlist__sample_id_all(struct evlist *evlist)
1186
{
1187
	struct evsel *first = evlist__first(evlist);
1188
	return first->core.attr.sample_id_all;
1189
}
1190

1191
void perf_evlist__set_selected(struct evlist *evlist,
1192
			       struct evsel *evsel)
1193 1194 1195
{
	evlist->selected = evsel;
}
1196

1197
void evlist__close(struct evlist *evlist)
1198
{
1199
	struct evsel *evsel;
1200 1201
	struct affinity affinity;
	int cpu, i;
1202

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	/*
	 * With perf record core.cpus is usually NULL.
	 * Use the old method to handle this for now.
	 */
	if (!evlist->core.cpus) {
		evlist__for_each_entry_reverse(evlist, evsel)
			evsel__close(evsel);
		return;
	}

	if (affinity__setup(&affinity) < 0)
		return;
	evlist__for_each_cpu(evlist, i, cpu) {
		affinity__set(&affinity, cpu);

		evlist__for_each_entry_reverse(evlist, evsel) {
			if (evsel__cpu_iter_skip(evsel, cpu))
			    continue;
			perf_evsel__close_cpu(&evsel->core, evsel->cpu_iter - 1);
		}
	}
	affinity__cleanup(&affinity);
	evlist__for_each_entry_reverse(evlist, evsel) {
		perf_evsel__free_fd(&evsel->core);
		perf_evsel__free_id(&evsel->core);
	}
1229 1230
}

1231
static int perf_evlist__create_syswide_maps(struct evlist *evlist)
1232
{
1233
	struct perf_cpu_map *cpus;
1234
	struct perf_thread_map *threads;
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
	int err = -ENOMEM;

	/*
	 * Try reading /sys/devices/system/cpu/online to get
	 * an all cpus map.
	 *
	 * FIXME: -ENOMEM is the best we can do here, the cpu_map
	 * code needs an overhaul to properly forward the
	 * error, and we may not want to do that fallback to a
	 * default cpu identity map :-\
	 */
1246
	cpus = perf_cpu_map__new(NULL);
1247
	if (!cpus)
1248 1249
		goto out;

1250
	threads = perf_thread_map__new_dummy();
1251 1252
	if (!threads)
		goto out_put;
1253

1254
	perf_evlist__set_maps(&evlist->core, cpus, threads);
1255 1256

	perf_thread_map__put(threads);
1257
out_put:
1258
	perf_cpu_map__put(cpus);
1259 1260
out:
	return err;
1261 1262
}

1263
int evlist__open(struct evlist *evlist)
1264
{
1265
	struct evsel *evsel;
1266
	int err;
1267

1268 1269 1270 1271
	/*
	 * Default: one fd per CPU, all threads, aka systemwide
	 * as sys_perf_event_open(cpu = -1, thread = -1) is EINVAL
	 */
1272
	if (evlist->core.threads == NULL && evlist->core.cpus == NULL) {
1273 1274 1275 1276 1277
		err = perf_evlist__create_syswide_maps(evlist);
		if (err < 0)
			goto out_err;
	}

1278
	evlist__update_id_pos(evlist);
1279

1280
	evlist__for_each_entry(evlist, evsel) {
1281
		err = evsel__open(evsel, evsel->core.cpus, evsel->core.threads);
1282 1283 1284 1285 1286 1287
		if (err < 0)
			goto out_err;
	}

	return 0;
out_err:
1288
	evlist__close(evlist);
1289
	errno = -err;
1290 1291
	return err;
}
1292

1293 1294
int evlist__prepare_workload(struct evlist *evlist, struct target *target, const char *argv[],
			     bool pipe_output, void (*exec_error)(int signo, siginfo_t *info, void *ucontext))
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
{
	int child_ready_pipe[2], go_pipe[2];
	char bf;

	if (pipe(child_ready_pipe) < 0) {
		perror("failed to create 'ready' pipe");
		return -1;
	}

	if (pipe(go_pipe) < 0) {
		perror("failed to create 'go' pipe");
		goto out_close_ready_pipe;
	}

	evlist->workload.pid = fork();
	if (evlist->workload.pid < 0) {
		perror("failed to fork");
		goto out_close_pipes;
	}

	if (!evlist->workload.pid) {
1316 1317
		int ret;

1318
		if (pipe_output)
1319 1320
			dup2(2, 1);

1321 1322
		signal(SIGTERM, SIG_DFL);

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
		close(child_ready_pipe[0]);
		close(go_pipe[1]);
		fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);

		/*
		 * Tell the parent we're ready to go
		 */
		close(child_ready_pipe[1]);

		/*
		 * Wait until the parent tells us to go.
		 */
1335 1336 1337 1338
		ret = read(go_pipe[0], &bf, 1);
		/*
		 * The parent will ask for the execvp() to be performed by
		 * writing exactly one byte, in workload.cork_fd, usually via
1339
		 * evlist__start_workload().
1340
		 *
1341
		 * For cancelling the workload without actually running it,
1342 1343 1344 1345 1346 1347 1348 1349 1350
		 * the parent will just close workload.cork_fd, without writing
		 * anything, i.e. read will return zero and we just exit()
		 * here.
		 */
		if (ret != 1) {
			if (ret == -1)
				perror("unable to read pipe");
			exit(ret);
		}
1351 1352 1353

		execvp(argv[0], (char **)argv);

1354
		if (exec_error) {
1355 1356 1357 1358 1359 1360 1361
			union sigval val;

			val.sival_int = errno;
			if (sigqueue(getppid(), SIGUSR1, val))
				perror(argv[0]);
		} else
			perror(argv[0]);
1362 1363 1364
		exit(-1);
	}

1365 1366 1367 1368 1369 1370 1371 1372
	if (exec_error) {
		struct sigaction act = {
			.sa_flags     = SA_SIGINFO,
			.sa_sigaction = exec_error,
		};
		sigaction(SIGUSR1, &act, NULL);
	}

1373
	if (target__none(target)) {
1374
		if (evlist->core.threads == NULL) {
1375 1376 1377 1378
			fprintf(stderr, "FATAL: evlist->threads need to be set at this point (%s:%d).\n",
				__func__, __LINE__);
			goto out_close_pipes;
		}
1379
		perf_thread_map__set_pid(evlist->core.threads, 0, evlist->workload.pid);
1380
	}
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391

	close(child_ready_pipe[1]);
	close(go_pipe[0]);
	/*
	 * wait for child to settle
	 */
	if (read(child_ready_pipe[0], &bf, 1) == -1) {
		perror("unable to read pipe");
		goto out_close_pipes;
	}

1392
	fcntl(go_pipe[1], F_SETFD, FD_CLOEXEC);
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
	evlist->workload.cork_fd = go_pipe[1];
	close(child_ready_pipe[0]);
	return 0;

out_close_pipes:
	close(go_pipe[0]);
	close(go_pipe[1]);
out_close_ready_pipe:
	close(child_ready_pipe[0]);
	close(child_ready_pipe[1]);
	return -1;
}

1406
int evlist__start_workload(struct evlist *evlist)
1407 1408
{
	if (evlist->workload.cork_fd > 0) {
1409
		char bf = 0;
1410
		int ret;
1411 1412 1413
		/*
		 * Remove the cork, let it rip!
		 */
1414 1415
		ret = write(evlist->workload.cork_fd, &bf, 1);
		if (ret < 0)
1416
			perror("unable to write to pipe");
1417 1418 1419

		close(evlist->workload.cork_fd);
		return ret;
1420 1421 1422 1423
	}

	return 0;
}
1424

1425
int evlist__parse_sample(struct evlist *evlist, union perf_event *event, struct perf_sample *sample)
1426
{
1427
	struct evsel *evsel = evlist__event2evsel(evlist, event);
1428 1429 1430

	if (!evsel)
		return -EFAULT;
1431
	return evsel__parse_sample(evsel, event, sample);
1432
}
1433

1434
int evlist__parse_sample_timestamp(struct evlist *evlist, union perf_event *event, u64 *timestamp)
1435
{
1436
	struct evsel *evsel = evlist__event2evsel(evlist, event);
1437 1438 1439

	if (!evsel)
		return -EFAULT;
1440
	return evsel__parse_sample_timestamp(evsel, event, timestamp);
1441 1442
}

1443
int evlist__strerror_open(struct evlist *evlist, int err, char *buf, size_t size)
1444 1445
{
	int printed, value;
1446
	char sbuf[STRERR_BUFSIZE], *emsg = str_error_r(err, sbuf, sizeof(sbuf));
1447 1448 1449 1450 1451 1452 1453 1454

	switch (err) {
	case EACCES:
	case EPERM:
		printed = scnprintf(buf, size,
				    "Error:\t%s.\n"
				    "Hint:\tCheck /proc/sys/kernel/perf_event_paranoid setting.", emsg);

1455
		value = perf_event_paranoid();
1456 1457 1458 1459 1460 1461 1462 1463

		printed += scnprintf(buf + printed, size - printed, "\nHint:\t");

		if (value >= 2) {
			printed += scnprintf(buf + printed, size - printed,
					     "For your workloads it needs to be <= 1\nHint:\t");
		}
		printed += scnprintf(buf + printed, size - printed,
1464
				     "For system wide tracing it needs to be set to -1.\n");
1465 1466

		printed += scnprintf(buf + printed, size - printed,
1467 1468
				    "Hint:\tTry: 'sudo sh -c \"echo -1 > /proc/sys/kernel/perf_event_paranoid\"'\n"
				    "Hint:\tThe current value is %d.", value);
1469
		break;
1470
	case EINVAL: {
1471
		struct evsel *first = evlist__first(evlist);
1472 1473 1474 1475 1476
		int max_freq;

		if (sysctl__read_int("kernel/perf_event_max_sample_rate", &max_freq) < 0)
			goto out_default;

1477
		if (first->core.attr.sample_freq < (u64)max_freq)
1478 1479 1480 1481 1482 1483
			goto out_default;

		printed = scnprintf(buf, size,
				    "Error:\t%s.\n"
				    "Hint:\tCheck /proc/sys/kernel/perf_event_max_sample_rate.\n"
				    "Hint:\tThe current value is %d and %" PRIu64 " is being requested.",
1484
				    emsg, max_freq, first->core.attr.sample_freq);
1485 1486
		break;
	}
1487
	default:
1488
out_default:
1489 1490 1491 1492 1493 1494
		scnprintf(buf, size, "%s", emsg);
		break;
	}

	return 0;
}
1495

1496
int evlist__strerror_mmap(struct evlist *evlist, int err, char *buf, size_t size)
1497
{
1498
	char sbuf[STRERR_BUFSIZE], *emsg = str_error_r(err, sbuf, sizeof(sbuf));
1499
	int pages_attempted = evlist->core.mmap_len / 1024, pages_max_per_user, printed = 0;
1500 1501 1502

	switch (err) {
	case EPERM:
1503
		sysctl__read_int("kernel/perf_event_mlock_kb", &pages_max_per_user);
1504 1505
		printed += scnprintf(buf + printed, size - printed,
				     "Error:\t%s.\n"
1506
				     "Hint:\tCheck /proc/sys/kernel/perf_event_mlock_kb (%d kB) setting.\n"
1507
				     "Hint:\tTried using %zd kB.\n",
1508
				     emsg, pages_max_per_user, pages_attempted);
1509 1510 1511 1512 1513 1514 1515 1516 1517

		if (pages_attempted >= pages_max_per_user) {
			printed += scnprintf(buf + printed, size - printed,
					     "Hint:\tTry 'sudo sh -c \"echo %d > /proc/sys/kernel/perf_event_mlock_kb\"', or\n",
					     pages_max_per_user + pages_attempted);
		}

		printed += scnprintf(buf + printed, size - printed,
				     "Hint:\tTry using a smaller -m/--mmap-pages value.");
1518 1519 1520 1521 1522 1523 1524 1525 1526
		break;
	default:
		scnprintf(buf, size, "%s", emsg);
		break;
	}

	return 0;
}

1527
void perf_evlist__to_front(struct evlist *evlist,
1528
			   struct evsel *move_evsel)
1529
{
1530
	struct evsel *evsel, *n;
1531 1532
	LIST_HEAD(move);

1533
	if (move_evsel == evlist__first(evlist))
1534 1535
		return;

1536
	evlist__for_each_entry_safe(evlist, n, evsel) {
1537
		if (evsel->leader == move_evsel->leader)
1538
			list_move_tail(&evsel->core.node, &move);
1539 1540
	}

1541
	list_splice(&move, &evlist->core.entries);
1542
}
1543

1544
struct evsel *evlist__get_tracking_event(struct evlist *evlist)
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
{
	struct evsel *evsel;

	evlist__for_each_entry(evlist, evsel) {
		if (evsel->tracking)
			return evsel;
	}

	return evlist__first(evlist);
}

1556
void evlist__set_tracking_event(struct evlist *evlist, struct evsel *tracking_evsel)
1557
{
1558
	struct evsel *evsel;
1559 1560 1561 1562

	if (tracking_evsel->tracking)
		return;

1563
	evlist__for_each_entry(evlist, evsel) {
1564 1565 1566 1567 1568 1569
		if (evsel != tracking_evsel)
			evsel->tracking = false;
	}

	tracking_evsel->tracking = true;
}
1570

1571
struct evsel *evlist__find_evsel_by_str(struct evlist *evlist, const char *str)
1572
{
1573
	struct evsel *evsel;
1574

1575
	evlist__for_each_entry(evlist, evsel) {
1576 1577 1578 1579 1580 1581 1582 1583
		if (!evsel->name)
			continue;
		if (strcmp(str, evsel->name) == 0)
			return evsel;
	}

	return NULL;
}
1584

1585
void evlist__toggle_bkw_mmap(struct evlist *evlist, enum bkw_mmap_state state)
1586 1587 1588 1589 1590 1591 1592 1593
{
	enum bkw_mmap_state old_state = evlist->bkw_mmap_state;
	enum action {
		NONE,
		PAUSE,
		RESUME,
	} action = NONE;

1594
	if (!evlist->overwrite_mmap)
1595 1596 1597 1598 1599
		return;

	switch (old_state) {
	case BKW_MMAP_NOTREADY: {
		if (state != BKW_MMAP_RUNNING)
1600
			goto state_err;
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
		break;
	}
	case BKW_MMAP_RUNNING: {
		if (state != BKW_MMAP_DATA_PENDING)
			goto state_err;
		action = PAUSE;
		break;
	}
	case BKW_MMAP_DATA_PENDING: {
		if (state != BKW_MMAP_EMPTY)
			goto state_err;
		break;
	}
	case BKW_MMAP_EMPTY: {
		if (state != BKW_MMAP_RUNNING)
			goto state_err;
		action = RESUME;
		break;
	}
	default:
		WARN_ONCE(1, "Shouldn't get there\n");
	}

	evlist->bkw_mmap_state = state;

	switch (action) {
	case PAUSE:
		perf_evlist__pause(evlist);
		break;
	case RESUME:
		perf_evlist__resume(evlist);
		break;
	case NONE:
	default:
		break;
	}

state_err:
	return;
}
1641

1642
bool perf_evlist__exclude_kernel(struct evlist *evlist)
1643
{
1644
	struct evsel *evsel;
1645 1646

	evlist__for_each_entry(evlist, evsel) {
1647
		if (!evsel->core.attr.exclude_kernel)
1648 1649 1650 1651 1652
			return false;
	}

	return true;
}
1653 1654 1655 1656 1657 1658

/*
 * Events in data file are not collect in groups, but we still want
 * the group display. Set the artificial group and set the leader's
 * forced_leader flag to notify the display code.
 */
1659
void perf_evlist__force_leader(struct evlist *evlist)
1660 1661
{
	if (!evlist->nr_groups) {
1662
		struct evsel *leader = evlist__first(evlist);
1663

1664
		evlist__set_leader(evlist);
1665 1666 1667
		leader->forced_leader = true;
	}
}
1668

1669
struct evsel *perf_evlist__reset_weak_group(struct evlist *evsel_list,
1670 1671
						 struct evsel *evsel,
						bool close)
1672
{
1673
	struct evsel *c2, *leader;
1674 1675 1676 1677
	bool is_open = true;

	leader = evsel->leader;
	pr_debug("Weak group for %s/%d failed\n",
1678
			leader->name, leader->core.nr_members);
1679 1680 1681 1682 1683 1684 1685 1686 1687

	/*
	 * for_each_group_member doesn't work here because it doesn't
	 * include the first entry.
	 */
	evlist__for_each_entry(evsel_list, c2) {
		if (c2 == evsel)
			is_open = false;
		if (c2->leader == leader) {
1688
			if (is_open && close)
1689
				perf_evsel__close(&c2->core);
1690
			c2->leader = c2;
1691
			c2->core.nr_members = 0;
1692 1693 1694 1695 1696
			/*
			 * Set this for all former members of the group
			 * to indicate they get reopened.
			 */
			c2->reset_group = true;
1697 1698 1699 1700
		}
	}
	return leader;
}
1701

1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
static int evlist__parse_control_fifo(const char *str, int *ctl_fd, int *ctl_fd_ack, bool *ctl_fd_close)
{
	char *s, *p;
	int ret = 0, fd;

	if (strncmp(str, "fifo:", 5))
		return -EINVAL;

	str += 5;
	if (!*str || *str == ',')
		return -EINVAL;

	s = strdup(str);
	if (!s)
		return -ENOMEM;

	p = strchr(s, ',');
	if (p)
		*p = '\0';

	/*
	 * O_RDWR avoids POLLHUPs which is necessary to allow the other
	 * end of a FIFO to be repeatedly opened and closed.
	 */
	fd = open(s, O_RDWR | O_NONBLOCK | O_CLOEXEC);
	if (fd < 0) {
		pr_err("Failed to open '%s'\n", s);
		ret = -errno;
		goto out_free;
	}
	*ctl_fd = fd;
	*ctl_fd_close = true;

	if (p && *++p) {
		/* O_RDWR | O_NONBLOCK means the other end need not be open */
		fd = open(p, O_RDWR | O_NONBLOCK | O_CLOEXEC);
		if (fd < 0) {
			pr_err("Failed to open '%s'\n", p);
			ret = -errno;
			goto out_free;
		}
		*ctl_fd_ack = fd;
	}

out_free:
	free(s);
	return ret;
}

int evlist__parse_control(const char *str, int *ctl_fd, int *ctl_fd_ack, bool *ctl_fd_close)
1752 1753 1754
{
	char *comma = NULL, *endptr = NULL;

1755 1756
	*ctl_fd_close = false;

1757
	if (strncmp(str, "fd:", 3))
1758
		return evlist__parse_control_fifo(str, ctl_fd, ctl_fd_ack, ctl_fd_close);
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776

	*ctl_fd = strtoul(&str[3], &endptr, 0);
	if (endptr == &str[3])
		return -EINVAL;

	comma = strchr(str, ',');
	if (comma) {
		if (endptr != comma)
			return -EINVAL;

		*ctl_fd_ack = strtoul(comma + 1, &endptr, 0);
		if (endptr == comma + 1 || *endptr != '\0')
			return -EINVAL;
	}

	return 0;
}

1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
void evlist__close_control(int ctl_fd, int ctl_fd_ack, bool *ctl_fd_close)
{
	if (*ctl_fd_close) {
		*ctl_fd_close = false;
		close(ctl_fd);
		if (ctl_fd_ack >= 0)
			close(ctl_fd_ack);
	}
}

1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
int evlist__initialize_ctlfd(struct evlist *evlist, int fd, int ack)
{
	if (fd == -1) {
		pr_debug("Control descriptor is not initialized\n");
		return 0;
	}

	evlist->ctl_fd.pos = perf_evlist__add_pollfd(&evlist->core, fd, NULL, POLLIN,
						     fdarray_flag__nonfilterable);
	if (evlist->ctl_fd.pos < 0) {
		evlist->ctl_fd.pos = -1;
		pr_err("Failed to add ctl fd entry: %m\n");
		return -1;
	}

	evlist->ctl_fd.fd = fd;
	evlist->ctl_fd.ack = ack;

	return 0;
}

bool evlist__ctlfd_initialized(struct evlist *evlist)
{
	return evlist->ctl_fd.pos >= 0;
}

int evlist__finalize_ctlfd(struct evlist *evlist)
{
	struct pollfd *entries = evlist->core.pollfd.entries;

	if (!evlist__ctlfd_initialized(evlist))
		return 0;

	entries[evlist->ctl_fd.pos].fd = -1;
	entries[evlist->ctl_fd.pos].events = 0;
	entries[evlist->ctl_fd.pos].revents = 0;

	evlist->ctl_fd.pos = -1;
	evlist->ctl_fd.ack = -1;
	evlist->ctl_fd.fd = -1;

	return 0;
}

static int evlist__ctlfd_recv(struct evlist *evlist, enum evlist_ctl_cmd *cmd,
			      char *cmd_data, size_t data_size)
{
	int err;
	char c;
	size_t bytes_read = 0;

1838
	*cmd = EVLIST_CTL_CMD_UNSUPPORTED;
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
	memset(cmd_data, 0, data_size);
	data_size--;

	do {
		err = read(evlist->ctl_fd.fd, &c, 1);
		if (err > 0) {
			if (c == '\n' || c == '\0')
				break;
			cmd_data[bytes_read++] = c;
			if (bytes_read == data_size)
				break;
1850 1851 1852 1853 1854 1855 1856
			continue;
		} else if (err == -1) {
			if (errno == EINTR)
				continue;
			if (errno == EAGAIN || errno == EWOULDBLOCK)
				err = 0;
			else
1857 1858
				pr_err("Failed to read from ctlfd %d: %m\n", evlist->ctl_fd.fd);
		}
1859
		break;
1860 1861 1862 1863 1864
	} while (1);

	pr_debug("Message from ctl_fd: \"%s%s\"\n", cmd_data,
		 bytes_read == data_size ? "" : c == '\n' ? "\\n" : "\\0");

1865
	if (bytes_read > 0) {
1866 1867 1868 1869 1870 1871
		if (!strncmp(cmd_data, EVLIST_CTL_CMD_ENABLE_TAG,
			     (sizeof(EVLIST_CTL_CMD_ENABLE_TAG)-1))) {
			*cmd = EVLIST_CTL_CMD_ENABLE;
		} else if (!strncmp(cmd_data, EVLIST_CTL_CMD_DISABLE_TAG,
				    (sizeof(EVLIST_CTL_CMD_DISABLE_TAG)-1))) {
			*cmd = EVLIST_CTL_CMD_DISABLE;
1872 1873 1874 1875
		} else if (!strncmp(cmd_data, EVLIST_CTL_CMD_SNAPSHOT_TAG,
				    (sizeof(EVLIST_CTL_CMD_SNAPSHOT_TAG)-1))) {
			*cmd = EVLIST_CTL_CMD_SNAPSHOT;
			pr_debug("is snapshot\n");
1876 1877 1878
		}
	}

1879
	return bytes_read ? (int)bytes_read : err;
1880 1881
}

1882
int evlist__ctlfd_ack(struct evlist *evlist)
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
{
	int err;

	if (evlist->ctl_fd.ack == -1)
		return 0;

	err = write(evlist->ctl_fd.ack, EVLIST_CTL_CMD_ACK_TAG,
		    sizeof(EVLIST_CTL_CMD_ACK_TAG));
	if (err == -1)
		pr_err("failed to write to ctl_ack_fd %d: %m\n", evlist->ctl_fd.ack);

	return err;
}

int evlist__ctlfd_process(struct evlist *evlist, enum evlist_ctl_cmd *cmd)
{
	int err = 0;
	char cmd_data[EVLIST_CTL_CMD_MAX_LEN];
	int ctlfd_pos = evlist->ctl_fd.pos;
	struct pollfd *entries = evlist->core.pollfd.entries;

	if (!evlist__ctlfd_initialized(evlist) || !entries[ctlfd_pos].revents)
		return 0;

	if (entries[ctlfd_pos].revents & POLLIN) {
		err = evlist__ctlfd_recv(evlist, cmd, cmd_data,
					 EVLIST_CTL_CMD_MAX_LEN);
		if (err > 0) {
			switch (*cmd) {
			case EVLIST_CTL_CMD_ENABLE:
				evlist__enable(evlist);
				break;
			case EVLIST_CTL_CMD_DISABLE:
				evlist__disable(evlist);
				break;
1918 1919
			case EVLIST_CTL_CMD_SNAPSHOT:
				break;
1920 1921 1922 1923 1924 1925
			case EVLIST_CTL_CMD_ACK:
			case EVLIST_CTL_CMD_UNSUPPORTED:
			default:
				pr_debug("ctlfd: unsupported %d\n", *cmd);
				break;
			}
1926 1927
			if (!(*cmd == EVLIST_CTL_CMD_ACK || *cmd == EVLIST_CTL_CMD_UNSUPPORTED ||
			      *cmd == EVLIST_CTL_CMD_SNAPSHOT))
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
				evlist__ctlfd_ack(evlist);
		}
	}

	if (entries[ctlfd_pos].revents & (POLLHUP | POLLERR))
		evlist__finalize_ctlfd(evlist);
	else
		entries[ctlfd_pos].revents = 0;

	return err;
}
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949

struct evsel *evlist__find_evsel(struct evlist *evlist, int idx)
{
	struct evsel *evsel;

	evlist__for_each_entry(evlist, evsel) {
		if (evsel->idx == idx)
			return evsel;
	}
	return NULL;
}