xref: /openbmc/linux/tools/perf/util/auxtrace.c (revision 068c38ad)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * auxtrace.c: AUX area trace support
4  * Copyright (c) 2013-2015, Intel Corporation.
5  */
6 
7 #include <inttypes.h>
8 #include <sys/types.h>
9 #include <sys/mman.h>
10 #include <stdbool.h>
11 #include <string.h>
12 #include <limits.h>
13 #include <errno.h>
14 
15 #include <linux/kernel.h>
16 #include <linux/perf_event.h>
17 #include <linux/types.h>
18 #include <linux/bitops.h>
19 #include <linux/log2.h>
20 #include <linux/string.h>
21 #include <linux/time64.h>
22 
23 #include <sys/param.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <linux/list.h>
27 #include <linux/zalloc.h>
28 
29 #include "config.h"
30 #include "evlist.h"
31 #include "dso.h"
32 #include "map.h"
33 #include "pmu.h"
34 #include "evsel.h"
35 #include "evsel_config.h"
36 #include "symbol.h"
37 #include "util/perf_api_probe.h"
38 #include "util/synthetic-events.h"
39 #include "thread_map.h"
40 #include "asm/bug.h"
41 #include "auxtrace.h"
42 
43 #include <linux/hash.h>
44 
45 #include "event.h"
46 #include "record.h"
47 #include "session.h"
48 #include "debug.h"
49 #include <subcmd/parse-options.h>
50 
51 #include "cs-etm.h"
52 #include "intel-pt.h"
53 #include "intel-bts.h"
54 #include "arm-spe.h"
55 #include "hisi-ptt.h"
56 #include "s390-cpumsf.h"
57 #include "util/mmap.h"
58 
59 #include <linux/ctype.h>
60 #include "symbol/kallsyms.h"
61 #include <internal/lib.h>
62 
63 /*
64  * Make a group from 'leader' to 'last', requiring that the events were not
65  * already grouped to a different leader.
66  */
67 static int evlist__regroup(struct evlist *evlist, struct evsel *leader, struct evsel *last)
68 {
69 	struct evsel *evsel;
70 	bool grp;
71 
72 	if (!evsel__is_group_leader(leader))
73 		return -EINVAL;
74 
75 	grp = false;
76 	evlist__for_each_entry(evlist, evsel) {
77 		if (grp) {
78 			if (!(evsel__leader(evsel) == leader ||
79 			     (evsel__leader(evsel) == evsel &&
80 			      evsel->core.nr_members <= 1)))
81 				return -EINVAL;
82 		} else if (evsel == leader) {
83 			grp = true;
84 		}
85 		if (evsel == last)
86 			break;
87 	}
88 
89 	grp = false;
90 	evlist__for_each_entry(evlist, evsel) {
91 		if (grp) {
92 			if (!evsel__has_leader(evsel, leader)) {
93 				evsel__set_leader(evsel, leader);
94 				if (leader->core.nr_members < 1)
95 					leader->core.nr_members = 1;
96 				leader->core.nr_members += 1;
97 			}
98 		} else if (evsel == leader) {
99 			grp = true;
100 		}
101 		if (evsel == last)
102 			break;
103 	}
104 
105 	return 0;
106 }
107 
108 static bool auxtrace__dont_decode(struct perf_session *session)
109 {
110 	return !session->itrace_synth_opts ||
111 	       session->itrace_synth_opts->dont_decode;
112 }
113 
114 int auxtrace_mmap__mmap(struct auxtrace_mmap *mm,
115 			struct auxtrace_mmap_params *mp,
116 			void *userpg, int fd)
117 {
118 	struct perf_event_mmap_page *pc = userpg;
119 
120 	WARN_ONCE(mm->base, "Uninitialized auxtrace_mmap\n");
121 
122 	mm->userpg = userpg;
123 	mm->mask = mp->mask;
124 	mm->len = mp->len;
125 	mm->prev = 0;
126 	mm->idx = mp->idx;
127 	mm->tid = mp->tid;
128 	mm->cpu = mp->cpu.cpu;
129 
130 	if (!mp->len || !mp->mmap_needed) {
131 		mm->base = NULL;
132 		return 0;
133 	}
134 
135 	pc->aux_offset = mp->offset;
136 	pc->aux_size = mp->len;
137 
138 	mm->base = mmap(NULL, mp->len, mp->prot, MAP_SHARED, fd, mp->offset);
139 	if (mm->base == MAP_FAILED) {
140 		pr_debug2("failed to mmap AUX area\n");
141 		mm->base = NULL;
142 		return -1;
143 	}
144 
145 	return 0;
146 }
147 
148 void auxtrace_mmap__munmap(struct auxtrace_mmap *mm)
149 {
150 	if (mm->base) {
151 		munmap(mm->base, mm->len);
152 		mm->base = NULL;
153 	}
154 }
155 
156 void auxtrace_mmap_params__init(struct auxtrace_mmap_params *mp,
157 				off_t auxtrace_offset,
158 				unsigned int auxtrace_pages,
159 				bool auxtrace_overwrite)
160 {
161 	if (auxtrace_pages) {
162 		mp->offset = auxtrace_offset;
163 		mp->len = auxtrace_pages * (size_t)page_size;
164 		mp->mask = is_power_of_2(mp->len) ? mp->len - 1 : 0;
165 		mp->prot = PROT_READ | (auxtrace_overwrite ? 0 : PROT_WRITE);
166 		pr_debug2("AUX area mmap length %zu\n", mp->len);
167 	} else {
168 		mp->len = 0;
169 	}
170 }
171 
172 void auxtrace_mmap_params__set_idx(struct auxtrace_mmap_params *mp,
173 				   struct evlist *evlist,
174 				   struct evsel *evsel, int idx)
175 {
176 	bool per_cpu = !perf_cpu_map__empty(evlist->core.user_requested_cpus);
177 
178 	mp->mmap_needed = evsel->needs_auxtrace_mmap;
179 
180 	if (!mp->mmap_needed)
181 		return;
182 
183 	mp->idx = idx;
184 
185 	if (per_cpu) {
186 		mp->cpu = perf_cpu_map__cpu(evlist->core.all_cpus, idx);
187 		if (evlist->core.threads)
188 			mp->tid = perf_thread_map__pid(evlist->core.threads, 0);
189 		else
190 			mp->tid = -1;
191 	} else {
192 		mp->cpu.cpu = -1;
193 		mp->tid = perf_thread_map__pid(evlist->core.threads, idx);
194 	}
195 }
196 
197 #define AUXTRACE_INIT_NR_QUEUES	32
198 
199 static struct auxtrace_queue *auxtrace_alloc_queue_array(unsigned int nr_queues)
200 {
201 	struct auxtrace_queue *queue_array;
202 	unsigned int max_nr_queues, i;
203 
204 	max_nr_queues = UINT_MAX / sizeof(struct auxtrace_queue);
205 	if (nr_queues > max_nr_queues)
206 		return NULL;
207 
208 	queue_array = calloc(nr_queues, sizeof(struct auxtrace_queue));
209 	if (!queue_array)
210 		return NULL;
211 
212 	for (i = 0; i < nr_queues; i++) {
213 		INIT_LIST_HEAD(&queue_array[i].head);
214 		queue_array[i].priv = NULL;
215 	}
216 
217 	return queue_array;
218 }
219 
220 int auxtrace_queues__init(struct auxtrace_queues *queues)
221 {
222 	queues->nr_queues = AUXTRACE_INIT_NR_QUEUES;
223 	queues->queue_array = auxtrace_alloc_queue_array(queues->nr_queues);
224 	if (!queues->queue_array)
225 		return -ENOMEM;
226 	return 0;
227 }
228 
229 static int auxtrace_queues__grow(struct auxtrace_queues *queues,
230 				 unsigned int new_nr_queues)
231 {
232 	unsigned int nr_queues = queues->nr_queues;
233 	struct auxtrace_queue *queue_array;
234 	unsigned int i;
235 
236 	if (!nr_queues)
237 		nr_queues = AUXTRACE_INIT_NR_QUEUES;
238 
239 	while (nr_queues && nr_queues < new_nr_queues)
240 		nr_queues <<= 1;
241 
242 	if (nr_queues < queues->nr_queues || nr_queues < new_nr_queues)
243 		return -EINVAL;
244 
245 	queue_array = auxtrace_alloc_queue_array(nr_queues);
246 	if (!queue_array)
247 		return -ENOMEM;
248 
249 	for (i = 0; i < queues->nr_queues; i++) {
250 		list_splice_tail(&queues->queue_array[i].head,
251 				 &queue_array[i].head);
252 		queue_array[i].tid = queues->queue_array[i].tid;
253 		queue_array[i].cpu = queues->queue_array[i].cpu;
254 		queue_array[i].set = queues->queue_array[i].set;
255 		queue_array[i].priv = queues->queue_array[i].priv;
256 	}
257 
258 	queues->nr_queues = nr_queues;
259 	queues->queue_array = queue_array;
260 
261 	return 0;
262 }
263 
264 static void *auxtrace_copy_data(u64 size, struct perf_session *session)
265 {
266 	int fd = perf_data__fd(session->data);
267 	void *p;
268 	ssize_t ret;
269 
270 	if (size > SSIZE_MAX)
271 		return NULL;
272 
273 	p = malloc(size);
274 	if (!p)
275 		return NULL;
276 
277 	ret = readn(fd, p, size);
278 	if (ret != (ssize_t)size) {
279 		free(p);
280 		return NULL;
281 	}
282 
283 	return p;
284 }
285 
286 static int auxtrace_queues__queue_buffer(struct auxtrace_queues *queues,
287 					 unsigned int idx,
288 					 struct auxtrace_buffer *buffer)
289 {
290 	struct auxtrace_queue *queue;
291 	int err;
292 
293 	if (idx >= queues->nr_queues) {
294 		err = auxtrace_queues__grow(queues, idx + 1);
295 		if (err)
296 			return err;
297 	}
298 
299 	queue = &queues->queue_array[idx];
300 
301 	if (!queue->set) {
302 		queue->set = true;
303 		queue->tid = buffer->tid;
304 		queue->cpu = buffer->cpu.cpu;
305 	}
306 
307 	buffer->buffer_nr = queues->next_buffer_nr++;
308 
309 	list_add_tail(&buffer->list, &queue->head);
310 
311 	queues->new_data = true;
312 	queues->populated = true;
313 
314 	return 0;
315 }
316 
317 /* Limit buffers to 32MiB on 32-bit */
318 #define BUFFER_LIMIT_FOR_32_BIT (32 * 1024 * 1024)
319 
320 static int auxtrace_queues__split_buffer(struct auxtrace_queues *queues,
321 					 unsigned int idx,
322 					 struct auxtrace_buffer *buffer)
323 {
324 	u64 sz = buffer->size;
325 	bool consecutive = false;
326 	struct auxtrace_buffer *b;
327 	int err;
328 
329 	while (sz > BUFFER_LIMIT_FOR_32_BIT) {
330 		b = memdup(buffer, sizeof(struct auxtrace_buffer));
331 		if (!b)
332 			return -ENOMEM;
333 		b->size = BUFFER_LIMIT_FOR_32_BIT;
334 		b->consecutive = consecutive;
335 		err = auxtrace_queues__queue_buffer(queues, idx, b);
336 		if (err) {
337 			auxtrace_buffer__free(b);
338 			return err;
339 		}
340 		buffer->data_offset += BUFFER_LIMIT_FOR_32_BIT;
341 		sz -= BUFFER_LIMIT_FOR_32_BIT;
342 		consecutive = true;
343 	}
344 
345 	buffer->size = sz;
346 	buffer->consecutive = consecutive;
347 
348 	return 0;
349 }
350 
351 static bool filter_cpu(struct perf_session *session, struct perf_cpu cpu)
352 {
353 	unsigned long *cpu_bitmap = session->itrace_synth_opts->cpu_bitmap;
354 
355 	return cpu_bitmap && cpu.cpu != -1 && !test_bit(cpu.cpu, cpu_bitmap);
356 }
357 
358 static int auxtrace_queues__add_buffer(struct auxtrace_queues *queues,
359 				       struct perf_session *session,
360 				       unsigned int idx,
361 				       struct auxtrace_buffer *buffer,
362 				       struct auxtrace_buffer **buffer_ptr)
363 {
364 	int err = -ENOMEM;
365 
366 	if (filter_cpu(session, buffer->cpu))
367 		return 0;
368 
369 	buffer = memdup(buffer, sizeof(*buffer));
370 	if (!buffer)
371 		return -ENOMEM;
372 
373 	if (session->one_mmap) {
374 		buffer->data = buffer->data_offset - session->one_mmap_offset +
375 			       session->one_mmap_addr;
376 	} else if (perf_data__is_pipe(session->data)) {
377 		buffer->data = auxtrace_copy_data(buffer->size, session);
378 		if (!buffer->data)
379 			goto out_free;
380 		buffer->data_needs_freeing = true;
381 	} else if (BITS_PER_LONG == 32 &&
382 		   buffer->size > BUFFER_LIMIT_FOR_32_BIT) {
383 		err = auxtrace_queues__split_buffer(queues, idx, buffer);
384 		if (err)
385 			goto out_free;
386 	}
387 
388 	err = auxtrace_queues__queue_buffer(queues, idx, buffer);
389 	if (err)
390 		goto out_free;
391 
392 	/* FIXME: Doesn't work for split buffer */
393 	if (buffer_ptr)
394 		*buffer_ptr = buffer;
395 
396 	return 0;
397 
398 out_free:
399 	auxtrace_buffer__free(buffer);
400 	return err;
401 }
402 
403 int auxtrace_queues__add_event(struct auxtrace_queues *queues,
404 			       struct perf_session *session,
405 			       union perf_event *event, off_t data_offset,
406 			       struct auxtrace_buffer **buffer_ptr)
407 {
408 	struct auxtrace_buffer buffer = {
409 		.pid = -1,
410 		.tid = event->auxtrace.tid,
411 		.cpu = { event->auxtrace.cpu },
412 		.data_offset = data_offset,
413 		.offset = event->auxtrace.offset,
414 		.reference = event->auxtrace.reference,
415 		.size = event->auxtrace.size,
416 	};
417 	unsigned int idx = event->auxtrace.idx;
418 
419 	return auxtrace_queues__add_buffer(queues, session, idx, &buffer,
420 					   buffer_ptr);
421 }
422 
423 static int auxtrace_queues__add_indexed_event(struct auxtrace_queues *queues,
424 					      struct perf_session *session,
425 					      off_t file_offset, size_t sz)
426 {
427 	union perf_event *event;
428 	int err;
429 	char buf[PERF_SAMPLE_MAX_SIZE];
430 
431 	err = perf_session__peek_event(session, file_offset, buf,
432 				       PERF_SAMPLE_MAX_SIZE, &event, NULL);
433 	if (err)
434 		return err;
435 
436 	if (event->header.type == PERF_RECORD_AUXTRACE) {
437 		if (event->header.size < sizeof(struct perf_record_auxtrace) ||
438 		    event->header.size != sz) {
439 			err = -EINVAL;
440 			goto out;
441 		}
442 		file_offset += event->header.size;
443 		err = auxtrace_queues__add_event(queues, session, event,
444 						 file_offset, NULL);
445 	}
446 out:
447 	return err;
448 }
449 
450 void auxtrace_queues__free(struct auxtrace_queues *queues)
451 {
452 	unsigned int i;
453 
454 	for (i = 0; i < queues->nr_queues; i++) {
455 		while (!list_empty(&queues->queue_array[i].head)) {
456 			struct auxtrace_buffer *buffer;
457 
458 			buffer = list_entry(queues->queue_array[i].head.next,
459 					    struct auxtrace_buffer, list);
460 			list_del_init(&buffer->list);
461 			auxtrace_buffer__free(buffer);
462 		}
463 	}
464 
465 	zfree(&queues->queue_array);
466 	queues->nr_queues = 0;
467 }
468 
469 static void auxtrace_heapify(struct auxtrace_heap_item *heap_array,
470 			     unsigned int pos, unsigned int queue_nr,
471 			     u64 ordinal)
472 {
473 	unsigned int parent;
474 
475 	while (pos) {
476 		parent = (pos - 1) >> 1;
477 		if (heap_array[parent].ordinal <= ordinal)
478 			break;
479 		heap_array[pos] = heap_array[parent];
480 		pos = parent;
481 	}
482 	heap_array[pos].queue_nr = queue_nr;
483 	heap_array[pos].ordinal = ordinal;
484 }
485 
486 int auxtrace_heap__add(struct auxtrace_heap *heap, unsigned int queue_nr,
487 		       u64 ordinal)
488 {
489 	struct auxtrace_heap_item *heap_array;
490 
491 	if (queue_nr >= heap->heap_sz) {
492 		unsigned int heap_sz = AUXTRACE_INIT_NR_QUEUES;
493 
494 		while (heap_sz <= queue_nr)
495 			heap_sz <<= 1;
496 		heap_array = realloc(heap->heap_array,
497 				     heap_sz * sizeof(struct auxtrace_heap_item));
498 		if (!heap_array)
499 			return -ENOMEM;
500 		heap->heap_array = heap_array;
501 		heap->heap_sz = heap_sz;
502 	}
503 
504 	auxtrace_heapify(heap->heap_array, heap->heap_cnt++, queue_nr, ordinal);
505 
506 	return 0;
507 }
508 
509 void auxtrace_heap__free(struct auxtrace_heap *heap)
510 {
511 	zfree(&heap->heap_array);
512 	heap->heap_cnt = 0;
513 	heap->heap_sz = 0;
514 }
515 
516 void auxtrace_heap__pop(struct auxtrace_heap *heap)
517 {
518 	unsigned int pos, last, heap_cnt = heap->heap_cnt;
519 	struct auxtrace_heap_item *heap_array;
520 
521 	if (!heap_cnt)
522 		return;
523 
524 	heap->heap_cnt -= 1;
525 
526 	heap_array = heap->heap_array;
527 
528 	pos = 0;
529 	while (1) {
530 		unsigned int left, right;
531 
532 		left = (pos << 1) + 1;
533 		if (left >= heap_cnt)
534 			break;
535 		right = left + 1;
536 		if (right >= heap_cnt) {
537 			heap_array[pos] = heap_array[left];
538 			return;
539 		}
540 		if (heap_array[left].ordinal < heap_array[right].ordinal) {
541 			heap_array[pos] = heap_array[left];
542 			pos = left;
543 		} else {
544 			heap_array[pos] = heap_array[right];
545 			pos = right;
546 		}
547 	}
548 
549 	last = heap_cnt - 1;
550 	auxtrace_heapify(heap_array, pos, heap_array[last].queue_nr,
551 			 heap_array[last].ordinal);
552 }
553 
554 size_t auxtrace_record__info_priv_size(struct auxtrace_record *itr,
555 				       struct evlist *evlist)
556 {
557 	if (itr)
558 		return itr->info_priv_size(itr, evlist);
559 	return 0;
560 }
561 
562 static int auxtrace_not_supported(void)
563 {
564 	pr_err("AUX area tracing is not supported on this architecture\n");
565 	return -EINVAL;
566 }
567 
568 int auxtrace_record__info_fill(struct auxtrace_record *itr,
569 			       struct perf_session *session,
570 			       struct perf_record_auxtrace_info *auxtrace_info,
571 			       size_t priv_size)
572 {
573 	if (itr)
574 		return itr->info_fill(itr, session, auxtrace_info, priv_size);
575 	return auxtrace_not_supported();
576 }
577 
578 void auxtrace_record__free(struct auxtrace_record *itr)
579 {
580 	if (itr)
581 		itr->free(itr);
582 }
583 
584 int auxtrace_record__snapshot_start(struct auxtrace_record *itr)
585 {
586 	if (itr && itr->snapshot_start)
587 		return itr->snapshot_start(itr);
588 	return 0;
589 }
590 
591 int auxtrace_record__snapshot_finish(struct auxtrace_record *itr, bool on_exit)
592 {
593 	if (!on_exit && itr && itr->snapshot_finish)
594 		return itr->snapshot_finish(itr);
595 	return 0;
596 }
597 
598 int auxtrace_record__find_snapshot(struct auxtrace_record *itr, int idx,
599 				   struct auxtrace_mmap *mm,
600 				   unsigned char *data, u64 *head, u64 *old)
601 {
602 	if (itr && itr->find_snapshot)
603 		return itr->find_snapshot(itr, idx, mm, data, head, old);
604 	return 0;
605 }
606 
607 int auxtrace_record__options(struct auxtrace_record *itr,
608 			     struct evlist *evlist,
609 			     struct record_opts *opts)
610 {
611 	if (itr) {
612 		itr->evlist = evlist;
613 		return itr->recording_options(itr, evlist, opts);
614 	}
615 	return 0;
616 }
617 
618 u64 auxtrace_record__reference(struct auxtrace_record *itr)
619 {
620 	if (itr)
621 		return itr->reference(itr);
622 	return 0;
623 }
624 
625 int auxtrace_parse_snapshot_options(struct auxtrace_record *itr,
626 				    struct record_opts *opts, const char *str)
627 {
628 	if (!str)
629 		return 0;
630 
631 	/* PMU-agnostic options */
632 	switch (*str) {
633 	case 'e':
634 		opts->auxtrace_snapshot_on_exit = true;
635 		str++;
636 		break;
637 	default:
638 		break;
639 	}
640 
641 	if (itr && itr->parse_snapshot_options)
642 		return itr->parse_snapshot_options(itr, opts, str);
643 
644 	pr_err("No AUX area tracing to snapshot\n");
645 	return -EINVAL;
646 }
647 
648 static int evlist__enable_event_idx(struct evlist *evlist, struct evsel *evsel, int idx)
649 {
650 	bool per_cpu_mmaps = !perf_cpu_map__empty(evlist->core.user_requested_cpus);
651 
652 	if (per_cpu_mmaps) {
653 		struct perf_cpu evlist_cpu = perf_cpu_map__cpu(evlist->core.all_cpus, idx);
654 		int cpu_map_idx = perf_cpu_map__idx(evsel->core.cpus, evlist_cpu);
655 
656 		if (cpu_map_idx == -1)
657 			return -EINVAL;
658 		return perf_evsel__enable_cpu(&evsel->core, cpu_map_idx);
659 	}
660 
661 	return perf_evsel__enable_thread(&evsel->core, idx);
662 }
663 
664 int auxtrace_record__read_finish(struct auxtrace_record *itr, int idx)
665 {
666 	struct evsel *evsel;
667 
668 	if (!itr->evlist || !itr->pmu)
669 		return -EINVAL;
670 
671 	evlist__for_each_entry(itr->evlist, evsel) {
672 		if (evsel->core.attr.type == itr->pmu->type) {
673 			if (evsel->disabled)
674 				return 0;
675 			return evlist__enable_event_idx(itr->evlist, evsel, idx);
676 		}
677 	}
678 	return -EINVAL;
679 }
680 
681 /*
682  * Event record size is 16-bit which results in a maximum size of about 64KiB.
683  * Allow about 4KiB for the rest of the sample record, to give a maximum
684  * AUX area sample size of 60KiB.
685  */
686 #define MAX_AUX_SAMPLE_SIZE (60 * 1024)
687 
688 /* Arbitrary default size if no other default provided */
689 #define DEFAULT_AUX_SAMPLE_SIZE (4 * 1024)
690 
691 static int auxtrace_validate_aux_sample_size(struct evlist *evlist,
692 					     struct record_opts *opts)
693 {
694 	struct evsel *evsel;
695 	bool has_aux_leader = false;
696 	u32 sz;
697 
698 	evlist__for_each_entry(evlist, evsel) {
699 		sz = evsel->core.attr.aux_sample_size;
700 		if (evsel__is_group_leader(evsel)) {
701 			has_aux_leader = evsel__is_aux_event(evsel);
702 			if (sz) {
703 				if (has_aux_leader)
704 					pr_err("Cannot add AUX area sampling to an AUX area event\n");
705 				else
706 					pr_err("Cannot add AUX area sampling to a group leader\n");
707 				return -EINVAL;
708 			}
709 		}
710 		if (sz > MAX_AUX_SAMPLE_SIZE) {
711 			pr_err("AUX area sample size %u too big, max. %d\n",
712 			       sz, MAX_AUX_SAMPLE_SIZE);
713 			return -EINVAL;
714 		}
715 		if (sz) {
716 			if (!has_aux_leader) {
717 				pr_err("Cannot add AUX area sampling because group leader is not an AUX area event\n");
718 				return -EINVAL;
719 			}
720 			evsel__set_sample_bit(evsel, AUX);
721 			opts->auxtrace_sample_mode = true;
722 		} else {
723 			evsel__reset_sample_bit(evsel, AUX);
724 		}
725 	}
726 
727 	if (!opts->auxtrace_sample_mode) {
728 		pr_err("AUX area sampling requires an AUX area event group leader plus other events to which to add samples\n");
729 		return -EINVAL;
730 	}
731 
732 	if (!perf_can_aux_sample()) {
733 		pr_err("AUX area sampling is not supported by kernel\n");
734 		return -EINVAL;
735 	}
736 
737 	return 0;
738 }
739 
740 int auxtrace_parse_sample_options(struct auxtrace_record *itr,
741 				  struct evlist *evlist,
742 				  struct record_opts *opts, const char *str)
743 {
744 	struct evsel_config_term *term;
745 	struct evsel *aux_evsel;
746 	bool has_aux_sample_size = false;
747 	bool has_aux_leader = false;
748 	struct evsel *evsel;
749 	char *endptr;
750 	unsigned long sz;
751 
752 	if (!str)
753 		goto no_opt;
754 
755 	if (!itr) {
756 		pr_err("No AUX area event to sample\n");
757 		return -EINVAL;
758 	}
759 
760 	sz = strtoul(str, &endptr, 0);
761 	if (*endptr || sz > UINT_MAX) {
762 		pr_err("Bad AUX area sampling option: '%s'\n", str);
763 		return -EINVAL;
764 	}
765 
766 	if (!sz)
767 		sz = itr->default_aux_sample_size;
768 
769 	if (!sz)
770 		sz = DEFAULT_AUX_SAMPLE_SIZE;
771 
772 	/* Set aux_sample_size based on --aux-sample option */
773 	evlist__for_each_entry(evlist, evsel) {
774 		if (evsel__is_group_leader(evsel)) {
775 			has_aux_leader = evsel__is_aux_event(evsel);
776 		} else if (has_aux_leader) {
777 			evsel->core.attr.aux_sample_size = sz;
778 		}
779 	}
780 no_opt:
781 	aux_evsel = NULL;
782 	/* Override with aux_sample_size from config term */
783 	evlist__for_each_entry(evlist, evsel) {
784 		if (evsel__is_aux_event(evsel))
785 			aux_evsel = evsel;
786 		term = evsel__get_config_term(evsel, AUX_SAMPLE_SIZE);
787 		if (term) {
788 			has_aux_sample_size = true;
789 			evsel->core.attr.aux_sample_size = term->val.aux_sample_size;
790 			/* If possible, group with the AUX event */
791 			if (aux_evsel && evsel->core.attr.aux_sample_size)
792 				evlist__regroup(evlist, aux_evsel, evsel);
793 		}
794 	}
795 
796 	if (!str && !has_aux_sample_size)
797 		return 0;
798 
799 	if (!itr) {
800 		pr_err("No AUX area event to sample\n");
801 		return -EINVAL;
802 	}
803 
804 	return auxtrace_validate_aux_sample_size(evlist, opts);
805 }
806 
807 void auxtrace_regroup_aux_output(struct evlist *evlist)
808 {
809 	struct evsel *evsel, *aux_evsel = NULL;
810 	struct evsel_config_term *term;
811 
812 	evlist__for_each_entry(evlist, evsel) {
813 		if (evsel__is_aux_event(evsel))
814 			aux_evsel = evsel;
815 		term = evsel__get_config_term(evsel, AUX_OUTPUT);
816 		/* If possible, group with the AUX event */
817 		if (term && aux_evsel)
818 			evlist__regroup(evlist, aux_evsel, evsel);
819 	}
820 }
821 
822 struct auxtrace_record *__weak
823 auxtrace_record__init(struct evlist *evlist __maybe_unused, int *err)
824 {
825 	*err = 0;
826 	return NULL;
827 }
828 
829 static int auxtrace_index__alloc(struct list_head *head)
830 {
831 	struct auxtrace_index *auxtrace_index;
832 
833 	auxtrace_index = malloc(sizeof(struct auxtrace_index));
834 	if (!auxtrace_index)
835 		return -ENOMEM;
836 
837 	auxtrace_index->nr = 0;
838 	INIT_LIST_HEAD(&auxtrace_index->list);
839 
840 	list_add_tail(&auxtrace_index->list, head);
841 
842 	return 0;
843 }
844 
845 void auxtrace_index__free(struct list_head *head)
846 {
847 	struct auxtrace_index *auxtrace_index, *n;
848 
849 	list_for_each_entry_safe(auxtrace_index, n, head, list) {
850 		list_del_init(&auxtrace_index->list);
851 		free(auxtrace_index);
852 	}
853 }
854 
855 static struct auxtrace_index *auxtrace_index__last(struct list_head *head)
856 {
857 	struct auxtrace_index *auxtrace_index;
858 	int err;
859 
860 	if (list_empty(head)) {
861 		err = auxtrace_index__alloc(head);
862 		if (err)
863 			return NULL;
864 	}
865 
866 	auxtrace_index = list_entry(head->prev, struct auxtrace_index, list);
867 
868 	if (auxtrace_index->nr >= PERF_AUXTRACE_INDEX_ENTRY_COUNT) {
869 		err = auxtrace_index__alloc(head);
870 		if (err)
871 			return NULL;
872 		auxtrace_index = list_entry(head->prev, struct auxtrace_index,
873 					    list);
874 	}
875 
876 	return auxtrace_index;
877 }
878 
879 int auxtrace_index__auxtrace_event(struct list_head *head,
880 				   union perf_event *event, off_t file_offset)
881 {
882 	struct auxtrace_index *auxtrace_index;
883 	size_t nr;
884 
885 	auxtrace_index = auxtrace_index__last(head);
886 	if (!auxtrace_index)
887 		return -ENOMEM;
888 
889 	nr = auxtrace_index->nr;
890 	auxtrace_index->entries[nr].file_offset = file_offset;
891 	auxtrace_index->entries[nr].sz = event->header.size;
892 	auxtrace_index->nr += 1;
893 
894 	return 0;
895 }
896 
897 static int auxtrace_index__do_write(int fd,
898 				    struct auxtrace_index *auxtrace_index)
899 {
900 	struct auxtrace_index_entry ent;
901 	size_t i;
902 
903 	for (i = 0; i < auxtrace_index->nr; i++) {
904 		ent.file_offset = auxtrace_index->entries[i].file_offset;
905 		ent.sz = auxtrace_index->entries[i].sz;
906 		if (writen(fd, &ent, sizeof(ent)) != sizeof(ent))
907 			return -errno;
908 	}
909 	return 0;
910 }
911 
912 int auxtrace_index__write(int fd, struct list_head *head)
913 {
914 	struct auxtrace_index *auxtrace_index;
915 	u64 total = 0;
916 	int err;
917 
918 	list_for_each_entry(auxtrace_index, head, list)
919 		total += auxtrace_index->nr;
920 
921 	if (writen(fd, &total, sizeof(total)) != sizeof(total))
922 		return -errno;
923 
924 	list_for_each_entry(auxtrace_index, head, list) {
925 		err = auxtrace_index__do_write(fd, auxtrace_index);
926 		if (err)
927 			return err;
928 	}
929 
930 	return 0;
931 }
932 
933 static int auxtrace_index__process_entry(int fd, struct list_head *head,
934 					 bool needs_swap)
935 {
936 	struct auxtrace_index *auxtrace_index;
937 	struct auxtrace_index_entry ent;
938 	size_t nr;
939 
940 	if (readn(fd, &ent, sizeof(ent)) != sizeof(ent))
941 		return -1;
942 
943 	auxtrace_index = auxtrace_index__last(head);
944 	if (!auxtrace_index)
945 		return -1;
946 
947 	nr = auxtrace_index->nr;
948 	if (needs_swap) {
949 		auxtrace_index->entries[nr].file_offset =
950 						bswap_64(ent.file_offset);
951 		auxtrace_index->entries[nr].sz = bswap_64(ent.sz);
952 	} else {
953 		auxtrace_index->entries[nr].file_offset = ent.file_offset;
954 		auxtrace_index->entries[nr].sz = ent.sz;
955 	}
956 
957 	auxtrace_index->nr = nr + 1;
958 
959 	return 0;
960 }
961 
962 int auxtrace_index__process(int fd, u64 size, struct perf_session *session,
963 			    bool needs_swap)
964 {
965 	struct list_head *head = &session->auxtrace_index;
966 	u64 nr;
967 
968 	if (readn(fd, &nr, sizeof(u64)) != sizeof(u64))
969 		return -1;
970 
971 	if (needs_swap)
972 		nr = bswap_64(nr);
973 
974 	if (sizeof(u64) + nr * sizeof(struct auxtrace_index_entry) > size)
975 		return -1;
976 
977 	while (nr--) {
978 		int err;
979 
980 		err = auxtrace_index__process_entry(fd, head, needs_swap);
981 		if (err)
982 			return -1;
983 	}
984 
985 	return 0;
986 }
987 
988 static int auxtrace_queues__process_index_entry(struct auxtrace_queues *queues,
989 						struct perf_session *session,
990 						struct auxtrace_index_entry *ent)
991 {
992 	return auxtrace_queues__add_indexed_event(queues, session,
993 						  ent->file_offset, ent->sz);
994 }
995 
996 int auxtrace_queues__process_index(struct auxtrace_queues *queues,
997 				   struct perf_session *session)
998 {
999 	struct auxtrace_index *auxtrace_index;
1000 	struct auxtrace_index_entry *ent;
1001 	size_t i;
1002 	int err;
1003 
1004 	if (auxtrace__dont_decode(session))
1005 		return 0;
1006 
1007 	list_for_each_entry(auxtrace_index, &session->auxtrace_index, list) {
1008 		for (i = 0; i < auxtrace_index->nr; i++) {
1009 			ent = &auxtrace_index->entries[i];
1010 			err = auxtrace_queues__process_index_entry(queues,
1011 								   session,
1012 								   ent);
1013 			if (err)
1014 				return err;
1015 		}
1016 	}
1017 	return 0;
1018 }
1019 
1020 struct auxtrace_buffer *auxtrace_buffer__next(struct auxtrace_queue *queue,
1021 					      struct auxtrace_buffer *buffer)
1022 {
1023 	if (buffer) {
1024 		if (list_is_last(&buffer->list, &queue->head))
1025 			return NULL;
1026 		return list_entry(buffer->list.next, struct auxtrace_buffer,
1027 				  list);
1028 	} else {
1029 		if (list_empty(&queue->head))
1030 			return NULL;
1031 		return list_entry(queue->head.next, struct auxtrace_buffer,
1032 				  list);
1033 	}
1034 }
1035 
1036 struct auxtrace_queue *auxtrace_queues__sample_queue(struct auxtrace_queues *queues,
1037 						     struct perf_sample *sample,
1038 						     struct perf_session *session)
1039 {
1040 	struct perf_sample_id *sid;
1041 	unsigned int idx;
1042 	u64 id;
1043 
1044 	id = sample->id;
1045 	if (!id)
1046 		return NULL;
1047 
1048 	sid = evlist__id2sid(session->evlist, id);
1049 	if (!sid)
1050 		return NULL;
1051 
1052 	idx = sid->idx;
1053 
1054 	if (idx >= queues->nr_queues)
1055 		return NULL;
1056 
1057 	return &queues->queue_array[idx];
1058 }
1059 
1060 int auxtrace_queues__add_sample(struct auxtrace_queues *queues,
1061 				struct perf_session *session,
1062 				struct perf_sample *sample, u64 data_offset,
1063 				u64 reference)
1064 {
1065 	struct auxtrace_buffer buffer = {
1066 		.pid = -1,
1067 		.data_offset = data_offset,
1068 		.reference = reference,
1069 		.size = sample->aux_sample.size,
1070 	};
1071 	struct perf_sample_id *sid;
1072 	u64 id = sample->id;
1073 	unsigned int idx;
1074 
1075 	if (!id)
1076 		return -EINVAL;
1077 
1078 	sid = evlist__id2sid(session->evlist, id);
1079 	if (!sid)
1080 		return -ENOENT;
1081 
1082 	idx = sid->idx;
1083 	buffer.tid = sid->tid;
1084 	buffer.cpu = sid->cpu;
1085 
1086 	return auxtrace_queues__add_buffer(queues, session, idx, &buffer, NULL);
1087 }
1088 
1089 struct queue_data {
1090 	bool samples;
1091 	bool events;
1092 };
1093 
1094 static int auxtrace_queue_data_cb(struct perf_session *session,
1095 				  union perf_event *event, u64 offset,
1096 				  void *data)
1097 {
1098 	struct queue_data *qd = data;
1099 	struct perf_sample sample;
1100 	int err;
1101 
1102 	if (qd->events && event->header.type == PERF_RECORD_AUXTRACE) {
1103 		if (event->header.size < sizeof(struct perf_record_auxtrace))
1104 			return -EINVAL;
1105 		offset += event->header.size;
1106 		return session->auxtrace->queue_data(session, NULL, event,
1107 						     offset);
1108 	}
1109 
1110 	if (!qd->samples || event->header.type != PERF_RECORD_SAMPLE)
1111 		return 0;
1112 
1113 	err = evlist__parse_sample(session->evlist, event, &sample);
1114 	if (err)
1115 		return err;
1116 
1117 	if (!sample.aux_sample.size)
1118 		return 0;
1119 
1120 	offset += sample.aux_sample.data - (void *)event;
1121 
1122 	return session->auxtrace->queue_data(session, &sample, NULL, offset);
1123 }
1124 
1125 int auxtrace_queue_data(struct perf_session *session, bool samples, bool events)
1126 {
1127 	struct queue_data qd = {
1128 		.samples = samples,
1129 		.events = events,
1130 	};
1131 
1132 	if (auxtrace__dont_decode(session))
1133 		return 0;
1134 
1135 	if (!session->auxtrace || !session->auxtrace->queue_data)
1136 		return -EINVAL;
1137 
1138 	return perf_session__peek_events(session, session->header.data_offset,
1139 					 session->header.data_size,
1140 					 auxtrace_queue_data_cb, &qd);
1141 }
1142 
1143 void *auxtrace_buffer__get_data_rw(struct auxtrace_buffer *buffer, int fd, bool rw)
1144 {
1145 	int prot = rw ? PROT_READ | PROT_WRITE : PROT_READ;
1146 	size_t adj = buffer->data_offset & (page_size - 1);
1147 	size_t size = buffer->size + adj;
1148 	off_t file_offset = buffer->data_offset - adj;
1149 	void *addr;
1150 
1151 	if (buffer->data)
1152 		return buffer->data;
1153 
1154 	addr = mmap(NULL, size, prot, MAP_SHARED, fd, file_offset);
1155 	if (addr == MAP_FAILED)
1156 		return NULL;
1157 
1158 	buffer->mmap_addr = addr;
1159 	buffer->mmap_size = size;
1160 
1161 	buffer->data = addr + adj;
1162 
1163 	return buffer->data;
1164 }
1165 
1166 void auxtrace_buffer__put_data(struct auxtrace_buffer *buffer)
1167 {
1168 	if (!buffer->data || !buffer->mmap_addr)
1169 		return;
1170 	munmap(buffer->mmap_addr, buffer->mmap_size);
1171 	buffer->mmap_addr = NULL;
1172 	buffer->mmap_size = 0;
1173 	buffer->data = NULL;
1174 	buffer->use_data = NULL;
1175 }
1176 
1177 void auxtrace_buffer__drop_data(struct auxtrace_buffer *buffer)
1178 {
1179 	auxtrace_buffer__put_data(buffer);
1180 	if (buffer->data_needs_freeing) {
1181 		buffer->data_needs_freeing = false;
1182 		zfree(&buffer->data);
1183 		buffer->use_data = NULL;
1184 		buffer->size = 0;
1185 	}
1186 }
1187 
1188 void auxtrace_buffer__free(struct auxtrace_buffer *buffer)
1189 {
1190 	auxtrace_buffer__drop_data(buffer);
1191 	free(buffer);
1192 }
1193 
1194 void auxtrace_synth_guest_error(struct perf_record_auxtrace_error *auxtrace_error, int type,
1195 				int code, int cpu, pid_t pid, pid_t tid, u64 ip,
1196 				const char *msg, u64 timestamp,
1197 				pid_t machine_pid, int vcpu)
1198 {
1199 	size_t size;
1200 
1201 	memset(auxtrace_error, 0, sizeof(struct perf_record_auxtrace_error));
1202 
1203 	auxtrace_error->header.type = PERF_RECORD_AUXTRACE_ERROR;
1204 	auxtrace_error->type = type;
1205 	auxtrace_error->code = code;
1206 	auxtrace_error->cpu = cpu;
1207 	auxtrace_error->pid = pid;
1208 	auxtrace_error->tid = tid;
1209 	auxtrace_error->fmt = 1;
1210 	auxtrace_error->ip = ip;
1211 	auxtrace_error->time = timestamp;
1212 	strlcpy(auxtrace_error->msg, msg, MAX_AUXTRACE_ERROR_MSG);
1213 	if (machine_pid) {
1214 		auxtrace_error->fmt = 2;
1215 		auxtrace_error->machine_pid = machine_pid;
1216 		auxtrace_error->vcpu = vcpu;
1217 		size = sizeof(*auxtrace_error);
1218 	} else {
1219 		size = (void *)auxtrace_error->msg - (void *)auxtrace_error +
1220 		       strlen(auxtrace_error->msg) + 1;
1221 	}
1222 	auxtrace_error->header.size = PERF_ALIGN(size, sizeof(u64));
1223 }
1224 
1225 void auxtrace_synth_error(struct perf_record_auxtrace_error *auxtrace_error, int type,
1226 			  int code, int cpu, pid_t pid, pid_t tid, u64 ip,
1227 			  const char *msg, u64 timestamp)
1228 {
1229 	auxtrace_synth_guest_error(auxtrace_error, type, code, cpu, pid, tid,
1230 				   ip, msg, timestamp, 0, -1);
1231 }
1232 
1233 int perf_event__synthesize_auxtrace_info(struct auxtrace_record *itr,
1234 					 struct perf_tool *tool,
1235 					 struct perf_session *session,
1236 					 perf_event__handler_t process)
1237 {
1238 	union perf_event *ev;
1239 	size_t priv_size;
1240 	int err;
1241 
1242 	pr_debug2("Synthesizing auxtrace information\n");
1243 	priv_size = auxtrace_record__info_priv_size(itr, session->evlist);
1244 	ev = zalloc(sizeof(struct perf_record_auxtrace_info) + priv_size);
1245 	if (!ev)
1246 		return -ENOMEM;
1247 
1248 	ev->auxtrace_info.header.type = PERF_RECORD_AUXTRACE_INFO;
1249 	ev->auxtrace_info.header.size = sizeof(struct perf_record_auxtrace_info) +
1250 					priv_size;
1251 	err = auxtrace_record__info_fill(itr, session, &ev->auxtrace_info,
1252 					 priv_size);
1253 	if (err)
1254 		goto out_free;
1255 
1256 	err = process(tool, ev, NULL, NULL);
1257 out_free:
1258 	free(ev);
1259 	return err;
1260 }
1261 
1262 static void unleader_evsel(struct evlist *evlist, struct evsel *leader)
1263 {
1264 	struct evsel *new_leader = NULL;
1265 	struct evsel *evsel;
1266 
1267 	/* Find new leader for the group */
1268 	evlist__for_each_entry(evlist, evsel) {
1269 		if (!evsel__has_leader(evsel, leader) || evsel == leader)
1270 			continue;
1271 		if (!new_leader)
1272 			new_leader = evsel;
1273 		evsel__set_leader(evsel, new_leader);
1274 	}
1275 
1276 	/* Update group information */
1277 	if (new_leader) {
1278 		zfree(&new_leader->group_name);
1279 		new_leader->group_name = leader->group_name;
1280 		leader->group_name = NULL;
1281 
1282 		new_leader->core.nr_members = leader->core.nr_members - 1;
1283 		leader->core.nr_members = 1;
1284 	}
1285 }
1286 
1287 static void unleader_auxtrace(struct perf_session *session)
1288 {
1289 	struct evsel *evsel;
1290 
1291 	evlist__for_each_entry(session->evlist, evsel) {
1292 		if (auxtrace__evsel_is_auxtrace(session, evsel) &&
1293 		    evsel__is_group_leader(evsel)) {
1294 			unleader_evsel(session->evlist, evsel);
1295 		}
1296 	}
1297 }
1298 
1299 int perf_event__process_auxtrace_info(struct perf_session *session,
1300 				      union perf_event *event)
1301 {
1302 	enum auxtrace_type type = event->auxtrace_info.type;
1303 	int err;
1304 
1305 	if (dump_trace)
1306 		fprintf(stdout, " type: %u\n", type);
1307 
1308 	switch (type) {
1309 	case PERF_AUXTRACE_INTEL_PT:
1310 		err = intel_pt_process_auxtrace_info(event, session);
1311 		break;
1312 	case PERF_AUXTRACE_INTEL_BTS:
1313 		err = intel_bts_process_auxtrace_info(event, session);
1314 		break;
1315 	case PERF_AUXTRACE_ARM_SPE:
1316 		err = arm_spe_process_auxtrace_info(event, session);
1317 		break;
1318 	case PERF_AUXTRACE_CS_ETM:
1319 		err = cs_etm__process_auxtrace_info(event, session);
1320 		break;
1321 	case PERF_AUXTRACE_S390_CPUMSF:
1322 		err = s390_cpumsf_process_auxtrace_info(event, session);
1323 		break;
1324 	case PERF_AUXTRACE_HISI_PTT:
1325 		err = hisi_ptt_process_auxtrace_info(event, session);
1326 		break;
1327 	case PERF_AUXTRACE_UNKNOWN:
1328 	default:
1329 		return -EINVAL;
1330 	}
1331 
1332 	if (err)
1333 		return err;
1334 
1335 	unleader_auxtrace(session);
1336 
1337 	return 0;
1338 }
1339 
1340 s64 perf_event__process_auxtrace(struct perf_session *session,
1341 				 union perf_event *event)
1342 {
1343 	s64 err;
1344 
1345 	if (dump_trace)
1346 		fprintf(stdout, " size: %#"PRI_lx64"  offset: %#"PRI_lx64"  ref: %#"PRI_lx64"  idx: %u  tid: %d  cpu: %d\n",
1347 			event->auxtrace.size, event->auxtrace.offset,
1348 			event->auxtrace.reference, event->auxtrace.idx,
1349 			event->auxtrace.tid, event->auxtrace.cpu);
1350 
1351 	if (auxtrace__dont_decode(session))
1352 		return event->auxtrace.size;
1353 
1354 	if (!session->auxtrace || event->header.type != PERF_RECORD_AUXTRACE)
1355 		return -EINVAL;
1356 
1357 	err = session->auxtrace->process_auxtrace_event(session, event, session->tool);
1358 	if (err < 0)
1359 		return err;
1360 
1361 	return event->auxtrace.size;
1362 }
1363 
1364 #define PERF_ITRACE_DEFAULT_PERIOD_TYPE		PERF_ITRACE_PERIOD_NANOSECS
1365 #define PERF_ITRACE_DEFAULT_PERIOD		100000
1366 #define PERF_ITRACE_DEFAULT_CALLCHAIN_SZ	16
1367 #define PERF_ITRACE_MAX_CALLCHAIN_SZ		1024
1368 #define PERF_ITRACE_DEFAULT_LAST_BRANCH_SZ	64
1369 #define PERF_ITRACE_MAX_LAST_BRANCH_SZ		1024
1370 
1371 void itrace_synth_opts__set_default(struct itrace_synth_opts *synth_opts,
1372 				    bool no_sample)
1373 {
1374 	synth_opts->branches = true;
1375 	synth_opts->transactions = true;
1376 	synth_opts->ptwrites = true;
1377 	synth_opts->pwr_events = true;
1378 	synth_opts->other_events = true;
1379 	synth_opts->intr_events = true;
1380 	synth_opts->errors = true;
1381 	synth_opts->flc = true;
1382 	synth_opts->llc = true;
1383 	synth_opts->tlb = true;
1384 	synth_opts->mem = true;
1385 	synth_opts->remote_access = true;
1386 
1387 	if (no_sample) {
1388 		synth_opts->period_type = PERF_ITRACE_PERIOD_INSTRUCTIONS;
1389 		synth_opts->period = 1;
1390 		synth_opts->calls = true;
1391 	} else {
1392 		synth_opts->instructions = true;
1393 		synth_opts->period_type = PERF_ITRACE_DEFAULT_PERIOD_TYPE;
1394 		synth_opts->period = PERF_ITRACE_DEFAULT_PERIOD;
1395 	}
1396 	synth_opts->callchain_sz = PERF_ITRACE_DEFAULT_CALLCHAIN_SZ;
1397 	synth_opts->last_branch_sz = PERF_ITRACE_DEFAULT_LAST_BRANCH_SZ;
1398 	synth_opts->initial_skip = 0;
1399 }
1400 
1401 static int get_flag(const char **ptr, unsigned int *flags)
1402 {
1403 	while (1) {
1404 		char c = **ptr;
1405 
1406 		if (c >= 'a' && c <= 'z') {
1407 			*flags |= 1 << (c - 'a');
1408 			++*ptr;
1409 			return 0;
1410 		} else if (c == ' ') {
1411 			++*ptr;
1412 			continue;
1413 		} else {
1414 			return -1;
1415 		}
1416 	}
1417 }
1418 
1419 static int get_flags(const char **ptr, unsigned int *plus_flags, unsigned int *minus_flags)
1420 {
1421 	while (1) {
1422 		switch (**ptr) {
1423 		case '+':
1424 			++*ptr;
1425 			if (get_flag(ptr, plus_flags))
1426 				return -1;
1427 			break;
1428 		case '-':
1429 			++*ptr;
1430 			if (get_flag(ptr, minus_flags))
1431 				return -1;
1432 			break;
1433 		case ' ':
1434 			++*ptr;
1435 			break;
1436 		default:
1437 			return 0;
1438 		}
1439 	}
1440 }
1441 
1442 #define ITRACE_DFLT_LOG_ON_ERROR_SZ 16384
1443 
1444 static unsigned int itrace_log_on_error_size(void)
1445 {
1446 	unsigned int sz = 0;
1447 
1448 	perf_config_scan("itrace.debug-log-buffer-size", "%u", &sz);
1449 	return sz ?: ITRACE_DFLT_LOG_ON_ERROR_SZ;
1450 }
1451 
1452 /*
1453  * Please check tools/perf/Documentation/perf-script.txt for information
1454  * about the options parsed here, which is introduced after this cset,
1455  * when support in 'perf script' for these options is introduced.
1456  */
1457 int itrace_do_parse_synth_opts(struct itrace_synth_opts *synth_opts,
1458 			       const char *str, int unset)
1459 {
1460 	const char *p;
1461 	char *endptr;
1462 	bool period_type_set = false;
1463 	bool period_set = false;
1464 
1465 	synth_opts->set = true;
1466 
1467 	if (unset) {
1468 		synth_opts->dont_decode = true;
1469 		return 0;
1470 	}
1471 
1472 	if (!str) {
1473 		itrace_synth_opts__set_default(synth_opts,
1474 					       synth_opts->default_no_sample);
1475 		return 0;
1476 	}
1477 
1478 	for (p = str; *p;) {
1479 		switch (*p++) {
1480 		case 'i':
1481 			synth_opts->instructions = true;
1482 			while (*p == ' ' || *p == ',')
1483 				p += 1;
1484 			if (isdigit(*p)) {
1485 				synth_opts->period = strtoull(p, &endptr, 10);
1486 				period_set = true;
1487 				p = endptr;
1488 				while (*p == ' ' || *p == ',')
1489 					p += 1;
1490 				switch (*p++) {
1491 				case 'i':
1492 					synth_opts->period_type =
1493 						PERF_ITRACE_PERIOD_INSTRUCTIONS;
1494 					period_type_set = true;
1495 					break;
1496 				case 't':
1497 					synth_opts->period_type =
1498 						PERF_ITRACE_PERIOD_TICKS;
1499 					period_type_set = true;
1500 					break;
1501 				case 'm':
1502 					synth_opts->period *= 1000;
1503 					/* Fall through */
1504 				case 'u':
1505 					synth_opts->period *= 1000;
1506 					/* Fall through */
1507 				case 'n':
1508 					if (*p++ != 's')
1509 						goto out_err;
1510 					synth_opts->period_type =
1511 						PERF_ITRACE_PERIOD_NANOSECS;
1512 					period_type_set = true;
1513 					break;
1514 				case '\0':
1515 					goto out;
1516 				default:
1517 					goto out_err;
1518 				}
1519 			}
1520 			break;
1521 		case 'b':
1522 			synth_opts->branches = true;
1523 			break;
1524 		case 'x':
1525 			synth_opts->transactions = true;
1526 			break;
1527 		case 'w':
1528 			synth_opts->ptwrites = true;
1529 			break;
1530 		case 'p':
1531 			synth_opts->pwr_events = true;
1532 			break;
1533 		case 'o':
1534 			synth_opts->other_events = true;
1535 			break;
1536 		case 'I':
1537 			synth_opts->intr_events = true;
1538 			break;
1539 		case 'e':
1540 			synth_opts->errors = true;
1541 			if (get_flags(&p, &synth_opts->error_plus_flags,
1542 				      &synth_opts->error_minus_flags))
1543 				goto out_err;
1544 			break;
1545 		case 'd':
1546 			synth_opts->log = true;
1547 			if (get_flags(&p, &synth_opts->log_plus_flags,
1548 				      &synth_opts->log_minus_flags))
1549 				goto out_err;
1550 			if (synth_opts->log_plus_flags & AUXTRACE_LOG_FLG_ON_ERROR)
1551 				synth_opts->log_on_error_size = itrace_log_on_error_size();
1552 			break;
1553 		case 'c':
1554 			synth_opts->branches = true;
1555 			synth_opts->calls = true;
1556 			break;
1557 		case 'r':
1558 			synth_opts->branches = true;
1559 			synth_opts->returns = true;
1560 			break;
1561 		case 'G':
1562 		case 'g':
1563 			if (p[-1] == 'G')
1564 				synth_opts->add_callchain = true;
1565 			else
1566 				synth_opts->callchain = true;
1567 			synth_opts->callchain_sz =
1568 					PERF_ITRACE_DEFAULT_CALLCHAIN_SZ;
1569 			while (*p == ' ' || *p == ',')
1570 				p += 1;
1571 			if (isdigit(*p)) {
1572 				unsigned int val;
1573 
1574 				val = strtoul(p, &endptr, 10);
1575 				p = endptr;
1576 				if (!val || val > PERF_ITRACE_MAX_CALLCHAIN_SZ)
1577 					goto out_err;
1578 				synth_opts->callchain_sz = val;
1579 			}
1580 			break;
1581 		case 'L':
1582 		case 'l':
1583 			if (p[-1] == 'L')
1584 				synth_opts->add_last_branch = true;
1585 			else
1586 				synth_opts->last_branch = true;
1587 			synth_opts->last_branch_sz =
1588 					PERF_ITRACE_DEFAULT_LAST_BRANCH_SZ;
1589 			while (*p == ' ' || *p == ',')
1590 				p += 1;
1591 			if (isdigit(*p)) {
1592 				unsigned int val;
1593 
1594 				val = strtoul(p, &endptr, 10);
1595 				p = endptr;
1596 				if (!val ||
1597 				    val > PERF_ITRACE_MAX_LAST_BRANCH_SZ)
1598 					goto out_err;
1599 				synth_opts->last_branch_sz = val;
1600 			}
1601 			break;
1602 		case 's':
1603 			synth_opts->initial_skip = strtoul(p, &endptr, 10);
1604 			if (p == endptr)
1605 				goto out_err;
1606 			p = endptr;
1607 			break;
1608 		case 'f':
1609 			synth_opts->flc = true;
1610 			break;
1611 		case 'm':
1612 			synth_opts->llc = true;
1613 			break;
1614 		case 't':
1615 			synth_opts->tlb = true;
1616 			break;
1617 		case 'a':
1618 			synth_opts->remote_access = true;
1619 			break;
1620 		case 'M':
1621 			synth_opts->mem = true;
1622 			break;
1623 		case 'q':
1624 			synth_opts->quick += 1;
1625 			break;
1626 		case 'A':
1627 			synth_opts->approx_ipc = true;
1628 			break;
1629 		case 'Z':
1630 			synth_opts->timeless_decoding = true;
1631 			break;
1632 		case ' ':
1633 		case ',':
1634 			break;
1635 		default:
1636 			goto out_err;
1637 		}
1638 	}
1639 out:
1640 	if (synth_opts->instructions) {
1641 		if (!period_type_set)
1642 			synth_opts->period_type =
1643 					PERF_ITRACE_DEFAULT_PERIOD_TYPE;
1644 		if (!period_set)
1645 			synth_opts->period = PERF_ITRACE_DEFAULT_PERIOD;
1646 	}
1647 
1648 	return 0;
1649 
1650 out_err:
1651 	pr_err("Bad Instruction Tracing options '%s'\n", str);
1652 	return -EINVAL;
1653 }
1654 
1655 int itrace_parse_synth_opts(const struct option *opt, const char *str, int unset)
1656 {
1657 	return itrace_do_parse_synth_opts(opt->value, str, unset);
1658 }
1659 
1660 static const char * const auxtrace_error_type_name[] = {
1661 	[PERF_AUXTRACE_ERROR_ITRACE] = "instruction trace",
1662 };
1663 
1664 static const char *auxtrace_error_name(int type)
1665 {
1666 	const char *error_type_name = NULL;
1667 
1668 	if (type < PERF_AUXTRACE_ERROR_MAX)
1669 		error_type_name = auxtrace_error_type_name[type];
1670 	if (!error_type_name)
1671 		error_type_name = "unknown AUX";
1672 	return error_type_name;
1673 }
1674 
1675 size_t perf_event__fprintf_auxtrace_error(union perf_event *event, FILE *fp)
1676 {
1677 	struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1678 	unsigned long long nsecs = e->time;
1679 	const char *msg = e->msg;
1680 	int ret;
1681 
1682 	ret = fprintf(fp, " %s error type %u",
1683 		      auxtrace_error_name(e->type), e->type);
1684 
1685 	if (e->fmt && nsecs) {
1686 		unsigned long secs = nsecs / NSEC_PER_SEC;
1687 
1688 		nsecs -= secs * NSEC_PER_SEC;
1689 		ret += fprintf(fp, " time %lu.%09llu", secs, nsecs);
1690 	} else {
1691 		ret += fprintf(fp, " time 0");
1692 	}
1693 
1694 	if (!e->fmt)
1695 		msg = (const char *)&e->time;
1696 
1697 	if (e->fmt >= 2 && e->machine_pid)
1698 		ret += fprintf(fp, " machine_pid %d vcpu %d", e->machine_pid, e->vcpu);
1699 
1700 	ret += fprintf(fp, " cpu %d pid %d tid %d ip %#"PRI_lx64" code %u: %s\n",
1701 		       e->cpu, e->pid, e->tid, e->ip, e->code, msg);
1702 	return ret;
1703 }
1704 
1705 void perf_session__auxtrace_error_inc(struct perf_session *session,
1706 				      union perf_event *event)
1707 {
1708 	struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1709 
1710 	if (e->type < PERF_AUXTRACE_ERROR_MAX)
1711 		session->evlist->stats.nr_auxtrace_errors[e->type] += 1;
1712 }
1713 
1714 void events_stats__auxtrace_error_warn(const struct events_stats *stats)
1715 {
1716 	int i;
1717 
1718 	for (i = 0; i < PERF_AUXTRACE_ERROR_MAX; i++) {
1719 		if (!stats->nr_auxtrace_errors[i])
1720 			continue;
1721 		ui__warning("%u %s errors\n",
1722 			    stats->nr_auxtrace_errors[i],
1723 			    auxtrace_error_name(i));
1724 	}
1725 }
1726 
1727 int perf_event__process_auxtrace_error(struct perf_session *session,
1728 				       union perf_event *event)
1729 {
1730 	if (auxtrace__dont_decode(session))
1731 		return 0;
1732 
1733 	perf_event__fprintf_auxtrace_error(event, stdout);
1734 	return 0;
1735 }
1736 
1737 /*
1738  * In the compat mode kernel runs in 64-bit and perf tool runs in 32-bit mode,
1739  * 32-bit perf tool cannot access 64-bit value atomically, which might lead to
1740  * the issues caused by the below sequence on multiple CPUs: when perf tool
1741  * accesses either the load operation or the store operation for 64-bit value,
1742  * on some architectures the operation is divided into two instructions, one
1743  * is for accessing the low 32-bit value and another is for the high 32-bit;
1744  * thus these two user operations can give the kernel chances to access the
1745  * 64-bit value, and thus leads to the unexpected load values.
1746  *
1747  *   kernel (64-bit)                        user (32-bit)
1748  *
1749  *   if (LOAD ->aux_tail) { --,             LOAD ->aux_head_lo
1750  *       STORE $aux_data      |       ,--->
1751  *       FLUSH $aux_data      |       |     LOAD ->aux_head_hi
1752  *       STORE ->aux_head   --|-------`     smp_rmb()
1753  *   }                        |             LOAD $data
1754  *                            |             smp_mb()
1755  *                            |             STORE ->aux_tail_lo
1756  *                            `----------->
1757  *                                          STORE ->aux_tail_hi
1758  *
1759  * For this reason, it's impossible for the perf tool to work correctly when
1760  * the AUX head or tail is bigger than 4GB (more than 32 bits length); and we
1761  * can not simply limit the AUX ring buffer to less than 4GB, the reason is
1762  * the pointers can be increased monotonically, whatever the buffer size it is,
1763  * at the end the head and tail can be bigger than 4GB and carry out to the
1764  * high 32-bit.
1765  *
1766  * To mitigate the issues and improve the user experience, we can allow the
1767  * perf tool working in certain conditions and bail out with error if detect
1768  * any overflow cannot be handled.
1769  *
1770  * For reading the AUX head, it reads out the values for three times, and
1771  * compares the high 4 bytes of the values between the first time and the last
1772  * time, if there has no change for high 4 bytes injected by the kernel during
1773  * the user reading sequence, it's safe for use the second value.
1774  *
1775  * When compat_auxtrace_mmap__write_tail() detects any carrying in the high
1776  * 32 bits, it means there have two store operations in user space and it cannot
1777  * promise the atomicity for 64-bit write, so return '-1' in this case to tell
1778  * the caller an overflow error has happened.
1779  */
1780 u64 __weak compat_auxtrace_mmap__read_head(struct auxtrace_mmap *mm)
1781 {
1782 	struct perf_event_mmap_page *pc = mm->userpg;
1783 	u64 first, second, last;
1784 	u64 mask = (u64)(UINT32_MAX) << 32;
1785 
1786 	do {
1787 		first = READ_ONCE(pc->aux_head);
1788 		/* Ensure all reads are done after we read the head */
1789 		smp_rmb();
1790 		second = READ_ONCE(pc->aux_head);
1791 		/* Ensure all reads are done after we read the head */
1792 		smp_rmb();
1793 		last = READ_ONCE(pc->aux_head);
1794 	} while ((first & mask) != (last & mask));
1795 
1796 	return second;
1797 }
1798 
1799 int __weak compat_auxtrace_mmap__write_tail(struct auxtrace_mmap *mm, u64 tail)
1800 {
1801 	struct perf_event_mmap_page *pc = mm->userpg;
1802 	u64 mask = (u64)(UINT32_MAX) << 32;
1803 
1804 	if (tail & mask)
1805 		return -1;
1806 
1807 	/* Ensure all reads are done before we write the tail out */
1808 	smp_mb();
1809 	WRITE_ONCE(pc->aux_tail, tail);
1810 	return 0;
1811 }
1812 
1813 static int __auxtrace_mmap__read(struct mmap *map,
1814 				 struct auxtrace_record *itr,
1815 				 struct perf_tool *tool, process_auxtrace_t fn,
1816 				 bool snapshot, size_t snapshot_size)
1817 {
1818 	struct auxtrace_mmap *mm = &map->auxtrace_mmap;
1819 	u64 head, old = mm->prev, offset, ref;
1820 	unsigned char *data = mm->base;
1821 	size_t size, head_off, old_off, len1, len2, padding;
1822 	union perf_event ev;
1823 	void *data1, *data2;
1824 	int kernel_is_64_bit = perf_env__kernel_is_64_bit(evsel__env(NULL));
1825 
1826 	head = auxtrace_mmap__read_head(mm, kernel_is_64_bit);
1827 
1828 	if (snapshot &&
1829 	    auxtrace_record__find_snapshot(itr, mm->idx, mm, data, &head, &old))
1830 		return -1;
1831 
1832 	if (old == head)
1833 		return 0;
1834 
1835 	pr_debug3("auxtrace idx %d old %#"PRIx64" head %#"PRIx64" diff %#"PRIx64"\n",
1836 		  mm->idx, old, head, head - old);
1837 
1838 	if (mm->mask) {
1839 		head_off = head & mm->mask;
1840 		old_off = old & mm->mask;
1841 	} else {
1842 		head_off = head % mm->len;
1843 		old_off = old % mm->len;
1844 	}
1845 
1846 	if (head_off > old_off)
1847 		size = head_off - old_off;
1848 	else
1849 		size = mm->len - (old_off - head_off);
1850 
1851 	if (snapshot && size > snapshot_size)
1852 		size = snapshot_size;
1853 
1854 	ref = auxtrace_record__reference(itr);
1855 
1856 	if (head > old || size <= head || mm->mask) {
1857 		offset = head - size;
1858 	} else {
1859 		/*
1860 		 * When the buffer size is not a power of 2, 'head' wraps at the
1861 		 * highest multiple of the buffer size, so we have to subtract
1862 		 * the remainder here.
1863 		 */
1864 		u64 rem = (0ULL - mm->len) % mm->len;
1865 
1866 		offset = head - size - rem;
1867 	}
1868 
1869 	if (size > head_off) {
1870 		len1 = size - head_off;
1871 		data1 = &data[mm->len - len1];
1872 		len2 = head_off;
1873 		data2 = &data[0];
1874 	} else {
1875 		len1 = size;
1876 		data1 = &data[head_off - len1];
1877 		len2 = 0;
1878 		data2 = NULL;
1879 	}
1880 
1881 	if (itr->alignment) {
1882 		unsigned int unwanted = len1 % itr->alignment;
1883 
1884 		len1 -= unwanted;
1885 		size -= unwanted;
1886 	}
1887 
1888 	/* padding must be written by fn() e.g. record__process_auxtrace() */
1889 	padding = size & (PERF_AUXTRACE_RECORD_ALIGNMENT - 1);
1890 	if (padding)
1891 		padding = PERF_AUXTRACE_RECORD_ALIGNMENT - padding;
1892 
1893 	memset(&ev, 0, sizeof(ev));
1894 	ev.auxtrace.header.type = PERF_RECORD_AUXTRACE;
1895 	ev.auxtrace.header.size = sizeof(ev.auxtrace);
1896 	ev.auxtrace.size = size + padding;
1897 	ev.auxtrace.offset = offset;
1898 	ev.auxtrace.reference = ref;
1899 	ev.auxtrace.idx = mm->idx;
1900 	ev.auxtrace.tid = mm->tid;
1901 	ev.auxtrace.cpu = mm->cpu;
1902 
1903 	if (fn(tool, map, &ev, data1, len1, data2, len2))
1904 		return -1;
1905 
1906 	mm->prev = head;
1907 
1908 	if (!snapshot) {
1909 		int err;
1910 
1911 		err = auxtrace_mmap__write_tail(mm, head, kernel_is_64_bit);
1912 		if (err < 0)
1913 			return err;
1914 
1915 		if (itr->read_finish) {
1916 			err = itr->read_finish(itr, mm->idx);
1917 			if (err < 0)
1918 				return err;
1919 		}
1920 	}
1921 
1922 	return 1;
1923 }
1924 
1925 int auxtrace_mmap__read(struct mmap *map, struct auxtrace_record *itr,
1926 			struct perf_tool *tool, process_auxtrace_t fn)
1927 {
1928 	return __auxtrace_mmap__read(map, itr, tool, fn, false, 0);
1929 }
1930 
1931 int auxtrace_mmap__read_snapshot(struct mmap *map,
1932 				 struct auxtrace_record *itr,
1933 				 struct perf_tool *tool, process_auxtrace_t fn,
1934 				 size_t snapshot_size)
1935 {
1936 	return __auxtrace_mmap__read(map, itr, tool, fn, true, snapshot_size);
1937 }
1938 
1939 /**
1940  * struct auxtrace_cache - hash table to implement a cache
1941  * @hashtable: the hashtable
1942  * @sz: hashtable size (number of hlists)
1943  * @entry_size: size of an entry
1944  * @limit: limit the number of entries to this maximum, when reached the cache
1945  *         is dropped and caching begins again with an empty cache
1946  * @cnt: current number of entries
1947  * @bits: hashtable size (@sz = 2^@bits)
1948  */
1949 struct auxtrace_cache {
1950 	struct hlist_head *hashtable;
1951 	size_t sz;
1952 	size_t entry_size;
1953 	size_t limit;
1954 	size_t cnt;
1955 	unsigned int bits;
1956 };
1957 
1958 struct auxtrace_cache *auxtrace_cache__new(unsigned int bits, size_t entry_size,
1959 					   unsigned int limit_percent)
1960 {
1961 	struct auxtrace_cache *c;
1962 	struct hlist_head *ht;
1963 	size_t sz, i;
1964 
1965 	c = zalloc(sizeof(struct auxtrace_cache));
1966 	if (!c)
1967 		return NULL;
1968 
1969 	sz = 1UL << bits;
1970 
1971 	ht = calloc(sz, sizeof(struct hlist_head));
1972 	if (!ht)
1973 		goto out_free;
1974 
1975 	for (i = 0; i < sz; i++)
1976 		INIT_HLIST_HEAD(&ht[i]);
1977 
1978 	c->hashtable = ht;
1979 	c->sz = sz;
1980 	c->entry_size = entry_size;
1981 	c->limit = (c->sz * limit_percent) / 100;
1982 	c->bits = bits;
1983 
1984 	return c;
1985 
1986 out_free:
1987 	free(c);
1988 	return NULL;
1989 }
1990 
1991 static void auxtrace_cache__drop(struct auxtrace_cache *c)
1992 {
1993 	struct auxtrace_cache_entry *entry;
1994 	struct hlist_node *tmp;
1995 	size_t i;
1996 
1997 	if (!c)
1998 		return;
1999 
2000 	for (i = 0; i < c->sz; i++) {
2001 		hlist_for_each_entry_safe(entry, tmp, &c->hashtable[i], hash) {
2002 			hlist_del(&entry->hash);
2003 			auxtrace_cache__free_entry(c, entry);
2004 		}
2005 	}
2006 
2007 	c->cnt = 0;
2008 }
2009 
2010 void auxtrace_cache__free(struct auxtrace_cache *c)
2011 {
2012 	if (!c)
2013 		return;
2014 
2015 	auxtrace_cache__drop(c);
2016 	zfree(&c->hashtable);
2017 	free(c);
2018 }
2019 
2020 void *auxtrace_cache__alloc_entry(struct auxtrace_cache *c)
2021 {
2022 	return malloc(c->entry_size);
2023 }
2024 
2025 void auxtrace_cache__free_entry(struct auxtrace_cache *c __maybe_unused,
2026 				void *entry)
2027 {
2028 	free(entry);
2029 }
2030 
2031 int auxtrace_cache__add(struct auxtrace_cache *c, u32 key,
2032 			struct auxtrace_cache_entry *entry)
2033 {
2034 	if (c->limit && ++c->cnt > c->limit)
2035 		auxtrace_cache__drop(c);
2036 
2037 	entry->key = key;
2038 	hlist_add_head(&entry->hash, &c->hashtable[hash_32(key, c->bits)]);
2039 
2040 	return 0;
2041 }
2042 
2043 static struct auxtrace_cache_entry *auxtrace_cache__rm(struct auxtrace_cache *c,
2044 						       u32 key)
2045 {
2046 	struct auxtrace_cache_entry *entry;
2047 	struct hlist_head *hlist;
2048 	struct hlist_node *n;
2049 
2050 	if (!c)
2051 		return NULL;
2052 
2053 	hlist = &c->hashtable[hash_32(key, c->bits)];
2054 	hlist_for_each_entry_safe(entry, n, hlist, hash) {
2055 		if (entry->key == key) {
2056 			hlist_del(&entry->hash);
2057 			return entry;
2058 		}
2059 	}
2060 
2061 	return NULL;
2062 }
2063 
2064 void auxtrace_cache__remove(struct auxtrace_cache *c, u32 key)
2065 {
2066 	struct auxtrace_cache_entry *entry = auxtrace_cache__rm(c, key);
2067 
2068 	auxtrace_cache__free_entry(c, entry);
2069 }
2070 
2071 void *auxtrace_cache__lookup(struct auxtrace_cache *c, u32 key)
2072 {
2073 	struct auxtrace_cache_entry *entry;
2074 	struct hlist_head *hlist;
2075 
2076 	if (!c)
2077 		return NULL;
2078 
2079 	hlist = &c->hashtable[hash_32(key, c->bits)];
2080 	hlist_for_each_entry(entry, hlist, hash) {
2081 		if (entry->key == key)
2082 			return entry;
2083 	}
2084 
2085 	return NULL;
2086 }
2087 
2088 static void addr_filter__free_str(struct addr_filter *filt)
2089 {
2090 	zfree(&filt->str);
2091 	filt->action   = NULL;
2092 	filt->sym_from = NULL;
2093 	filt->sym_to   = NULL;
2094 	filt->filename = NULL;
2095 }
2096 
2097 static struct addr_filter *addr_filter__new(void)
2098 {
2099 	struct addr_filter *filt = zalloc(sizeof(*filt));
2100 
2101 	if (filt)
2102 		INIT_LIST_HEAD(&filt->list);
2103 
2104 	return filt;
2105 }
2106 
2107 static void addr_filter__free(struct addr_filter *filt)
2108 {
2109 	if (filt)
2110 		addr_filter__free_str(filt);
2111 	free(filt);
2112 }
2113 
2114 static void addr_filters__add(struct addr_filters *filts,
2115 			      struct addr_filter *filt)
2116 {
2117 	list_add_tail(&filt->list, &filts->head);
2118 	filts->cnt += 1;
2119 }
2120 
2121 static void addr_filters__del(struct addr_filters *filts,
2122 			      struct addr_filter *filt)
2123 {
2124 	list_del_init(&filt->list);
2125 	filts->cnt -= 1;
2126 }
2127 
2128 void addr_filters__init(struct addr_filters *filts)
2129 {
2130 	INIT_LIST_HEAD(&filts->head);
2131 	filts->cnt = 0;
2132 }
2133 
2134 void addr_filters__exit(struct addr_filters *filts)
2135 {
2136 	struct addr_filter *filt, *n;
2137 
2138 	list_for_each_entry_safe(filt, n, &filts->head, list) {
2139 		addr_filters__del(filts, filt);
2140 		addr_filter__free(filt);
2141 	}
2142 }
2143 
2144 static int parse_num_or_str(char **inp, u64 *num, const char **str,
2145 			    const char *str_delim)
2146 {
2147 	*inp += strspn(*inp, " ");
2148 
2149 	if (isdigit(**inp)) {
2150 		char *endptr;
2151 
2152 		if (!num)
2153 			return -EINVAL;
2154 		errno = 0;
2155 		*num = strtoull(*inp, &endptr, 0);
2156 		if (errno)
2157 			return -errno;
2158 		if (endptr == *inp)
2159 			return -EINVAL;
2160 		*inp = endptr;
2161 	} else {
2162 		size_t n;
2163 
2164 		if (!str)
2165 			return -EINVAL;
2166 		*inp += strspn(*inp, " ");
2167 		*str = *inp;
2168 		n = strcspn(*inp, str_delim);
2169 		if (!n)
2170 			return -EINVAL;
2171 		*inp += n;
2172 		if (**inp) {
2173 			**inp = '\0';
2174 			*inp += 1;
2175 		}
2176 	}
2177 	return 0;
2178 }
2179 
2180 static int parse_action(struct addr_filter *filt)
2181 {
2182 	if (!strcmp(filt->action, "filter")) {
2183 		filt->start = true;
2184 		filt->range = true;
2185 	} else if (!strcmp(filt->action, "start")) {
2186 		filt->start = true;
2187 	} else if (!strcmp(filt->action, "stop")) {
2188 		filt->start = false;
2189 	} else if (!strcmp(filt->action, "tracestop")) {
2190 		filt->start = false;
2191 		filt->range = true;
2192 		filt->action += 5; /* Change 'tracestop' to 'stop' */
2193 	} else {
2194 		return -EINVAL;
2195 	}
2196 	return 0;
2197 }
2198 
2199 static int parse_sym_idx(char **inp, int *idx)
2200 {
2201 	*idx = -1;
2202 
2203 	*inp += strspn(*inp, " ");
2204 
2205 	if (**inp != '#')
2206 		return 0;
2207 
2208 	*inp += 1;
2209 
2210 	if (**inp == 'g' || **inp == 'G') {
2211 		*inp += 1;
2212 		*idx = 0;
2213 	} else {
2214 		unsigned long num;
2215 		char *endptr;
2216 
2217 		errno = 0;
2218 		num = strtoul(*inp, &endptr, 0);
2219 		if (errno)
2220 			return -errno;
2221 		if (endptr == *inp || num > INT_MAX)
2222 			return -EINVAL;
2223 		*inp = endptr;
2224 		*idx = num;
2225 	}
2226 
2227 	return 0;
2228 }
2229 
2230 static int parse_addr_size(char **inp, u64 *num, const char **str, int *idx)
2231 {
2232 	int err = parse_num_or_str(inp, num, str, " ");
2233 
2234 	if (!err && *str)
2235 		err = parse_sym_idx(inp, idx);
2236 
2237 	return err;
2238 }
2239 
2240 static int parse_one_filter(struct addr_filter *filt, const char **filter_inp)
2241 {
2242 	char *fstr;
2243 	int err;
2244 
2245 	filt->str = fstr = strdup(*filter_inp);
2246 	if (!fstr)
2247 		return -ENOMEM;
2248 
2249 	err = parse_num_or_str(&fstr, NULL, &filt->action, " ");
2250 	if (err)
2251 		goto out_err;
2252 
2253 	err = parse_action(filt);
2254 	if (err)
2255 		goto out_err;
2256 
2257 	err = parse_addr_size(&fstr, &filt->addr, &filt->sym_from,
2258 			      &filt->sym_from_idx);
2259 	if (err)
2260 		goto out_err;
2261 
2262 	fstr += strspn(fstr, " ");
2263 
2264 	if (*fstr == '/') {
2265 		fstr += 1;
2266 		err = parse_addr_size(&fstr, &filt->size, &filt->sym_to,
2267 				      &filt->sym_to_idx);
2268 		if (err)
2269 			goto out_err;
2270 		filt->range = true;
2271 	}
2272 
2273 	fstr += strspn(fstr, " ");
2274 
2275 	if (*fstr == '@') {
2276 		fstr += 1;
2277 		err = parse_num_or_str(&fstr, NULL, &filt->filename, " ,");
2278 		if (err)
2279 			goto out_err;
2280 	}
2281 
2282 	fstr += strspn(fstr, " ,");
2283 
2284 	*filter_inp += fstr - filt->str;
2285 
2286 	return 0;
2287 
2288 out_err:
2289 	addr_filter__free_str(filt);
2290 
2291 	return err;
2292 }
2293 
2294 int addr_filters__parse_bare_filter(struct addr_filters *filts,
2295 				    const char *filter)
2296 {
2297 	struct addr_filter *filt;
2298 	const char *fstr = filter;
2299 	int err;
2300 
2301 	while (*fstr) {
2302 		filt = addr_filter__new();
2303 		err = parse_one_filter(filt, &fstr);
2304 		if (err) {
2305 			addr_filter__free(filt);
2306 			addr_filters__exit(filts);
2307 			return err;
2308 		}
2309 		addr_filters__add(filts, filt);
2310 	}
2311 
2312 	return 0;
2313 }
2314 
2315 struct sym_args {
2316 	const char	*name;
2317 	u64		start;
2318 	u64		size;
2319 	int		idx;
2320 	int		cnt;
2321 	bool		started;
2322 	bool		global;
2323 	bool		selected;
2324 	bool		duplicate;
2325 	bool		near;
2326 };
2327 
2328 static bool kern_sym_name_match(const char *kname, const char *name)
2329 {
2330 	size_t n = strlen(name);
2331 
2332 	return !strcmp(kname, name) ||
2333 	       (!strncmp(kname, name, n) && kname[n] == '\t');
2334 }
2335 
2336 static bool kern_sym_match(struct sym_args *args, const char *name, char type)
2337 {
2338 	/* A function with the same name, and global or the n'th found or any */
2339 	return kallsyms__is_function(type) &&
2340 	       kern_sym_name_match(name, args->name) &&
2341 	       ((args->global && isupper(type)) ||
2342 		(args->selected && ++(args->cnt) == args->idx) ||
2343 		(!args->global && !args->selected));
2344 }
2345 
2346 static int find_kern_sym_cb(void *arg, const char *name, char type, u64 start)
2347 {
2348 	struct sym_args *args = arg;
2349 
2350 	if (args->started) {
2351 		if (!args->size)
2352 			args->size = start - args->start;
2353 		if (args->selected) {
2354 			if (args->size)
2355 				return 1;
2356 		} else if (kern_sym_match(args, name, type)) {
2357 			args->duplicate = true;
2358 			return 1;
2359 		}
2360 	} else if (kern_sym_match(args, name, type)) {
2361 		args->started = true;
2362 		args->start = start;
2363 	}
2364 
2365 	return 0;
2366 }
2367 
2368 static int print_kern_sym_cb(void *arg, const char *name, char type, u64 start)
2369 {
2370 	struct sym_args *args = arg;
2371 
2372 	if (kern_sym_match(args, name, type)) {
2373 		pr_err("#%d\t0x%"PRIx64"\t%c\t%s\n",
2374 		       ++args->cnt, start, type, name);
2375 		args->near = true;
2376 	} else if (args->near) {
2377 		args->near = false;
2378 		pr_err("\t\twhich is near\t\t%s\n", name);
2379 	}
2380 
2381 	return 0;
2382 }
2383 
2384 static int sym_not_found_error(const char *sym_name, int idx)
2385 {
2386 	if (idx > 0) {
2387 		pr_err("N'th occurrence (N=%d) of symbol '%s' not found.\n",
2388 		       idx, sym_name);
2389 	} else if (!idx) {
2390 		pr_err("Global symbol '%s' not found.\n", sym_name);
2391 	} else {
2392 		pr_err("Symbol '%s' not found.\n", sym_name);
2393 	}
2394 	pr_err("Note that symbols must be functions.\n");
2395 
2396 	return -EINVAL;
2397 }
2398 
2399 static int find_kern_sym(const char *sym_name, u64 *start, u64 *size, int idx)
2400 {
2401 	struct sym_args args = {
2402 		.name = sym_name,
2403 		.idx = idx,
2404 		.global = !idx,
2405 		.selected = idx > 0,
2406 	};
2407 	int err;
2408 
2409 	*start = 0;
2410 	*size = 0;
2411 
2412 	err = kallsyms__parse("/proc/kallsyms", &args, find_kern_sym_cb);
2413 	if (err < 0) {
2414 		pr_err("Failed to parse /proc/kallsyms\n");
2415 		return err;
2416 	}
2417 
2418 	if (args.duplicate) {
2419 		pr_err("Multiple kernel symbols with name '%s'\n", sym_name);
2420 		args.cnt = 0;
2421 		kallsyms__parse("/proc/kallsyms", &args, print_kern_sym_cb);
2422 		pr_err("Disambiguate symbol name by inserting #n after the name e.g. %s #2\n",
2423 		       sym_name);
2424 		pr_err("Or select a global symbol by inserting #0 or #g or #G\n");
2425 		return -EINVAL;
2426 	}
2427 
2428 	if (!args.started) {
2429 		pr_err("Kernel symbol lookup: ");
2430 		return sym_not_found_error(sym_name, idx);
2431 	}
2432 
2433 	*start = args.start;
2434 	*size = args.size;
2435 
2436 	return 0;
2437 }
2438 
2439 static int find_entire_kern_cb(void *arg, const char *name __maybe_unused,
2440 			       char type, u64 start)
2441 {
2442 	struct sym_args *args = arg;
2443 
2444 	if (!kallsyms__is_function(type))
2445 		return 0;
2446 
2447 	if (!args->started) {
2448 		args->started = true;
2449 		args->start = start;
2450 	}
2451 	/* Don't know exactly where the kernel ends, so we add a page */
2452 	args->size = round_up(start, page_size) + page_size - args->start;
2453 
2454 	return 0;
2455 }
2456 
2457 static int addr_filter__entire_kernel(struct addr_filter *filt)
2458 {
2459 	struct sym_args args = { .started = false };
2460 	int err;
2461 
2462 	err = kallsyms__parse("/proc/kallsyms", &args, find_entire_kern_cb);
2463 	if (err < 0 || !args.started) {
2464 		pr_err("Failed to parse /proc/kallsyms\n");
2465 		return err;
2466 	}
2467 
2468 	filt->addr = args.start;
2469 	filt->size = args.size;
2470 
2471 	return 0;
2472 }
2473 
2474 static int check_end_after_start(struct addr_filter *filt, u64 start, u64 size)
2475 {
2476 	if (start + size >= filt->addr)
2477 		return 0;
2478 
2479 	if (filt->sym_from) {
2480 		pr_err("Symbol '%s' (0x%"PRIx64") comes before '%s' (0x%"PRIx64")\n",
2481 		       filt->sym_to, start, filt->sym_from, filt->addr);
2482 	} else {
2483 		pr_err("Symbol '%s' (0x%"PRIx64") comes before address 0x%"PRIx64")\n",
2484 		       filt->sym_to, start, filt->addr);
2485 	}
2486 
2487 	return -EINVAL;
2488 }
2489 
2490 static int addr_filter__resolve_kernel_syms(struct addr_filter *filt)
2491 {
2492 	bool no_size = false;
2493 	u64 start, size;
2494 	int err;
2495 
2496 	if (symbol_conf.kptr_restrict) {
2497 		pr_err("Kernel addresses are restricted. Unable to resolve kernel symbols.\n");
2498 		return -EINVAL;
2499 	}
2500 
2501 	if (filt->sym_from && !strcmp(filt->sym_from, "*"))
2502 		return addr_filter__entire_kernel(filt);
2503 
2504 	if (filt->sym_from) {
2505 		err = find_kern_sym(filt->sym_from, &start, &size,
2506 				    filt->sym_from_idx);
2507 		if (err)
2508 			return err;
2509 		filt->addr = start;
2510 		if (filt->range && !filt->size && !filt->sym_to) {
2511 			filt->size = size;
2512 			no_size = !size;
2513 		}
2514 	}
2515 
2516 	if (filt->sym_to) {
2517 		err = find_kern_sym(filt->sym_to, &start, &size,
2518 				    filt->sym_to_idx);
2519 		if (err)
2520 			return err;
2521 
2522 		err = check_end_after_start(filt, start, size);
2523 		if (err)
2524 			return err;
2525 		filt->size = start + size - filt->addr;
2526 		no_size = !size;
2527 	}
2528 
2529 	/* The very last symbol in kallsyms does not imply a particular size */
2530 	if (no_size) {
2531 		pr_err("Cannot determine size of symbol '%s'\n",
2532 		       filt->sym_to ? filt->sym_to : filt->sym_from);
2533 		return -EINVAL;
2534 	}
2535 
2536 	return 0;
2537 }
2538 
2539 static struct dso *load_dso(const char *name)
2540 {
2541 	struct map *map;
2542 	struct dso *dso;
2543 
2544 	map = dso__new_map(name);
2545 	if (!map)
2546 		return NULL;
2547 
2548 	if (map__load(map) < 0)
2549 		pr_err("File '%s' not found or has no symbols.\n", name);
2550 
2551 	dso = dso__get(map->dso);
2552 
2553 	map__put(map);
2554 
2555 	return dso;
2556 }
2557 
2558 static bool dso_sym_match(struct symbol *sym, const char *name, int *cnt,
2559 			  int idx)
2560 {
2561 	/* Same name, and global or the n'th found or any */
2562 	return !arch__compare_symbol_names(name, sym->name) &&
2563 	       ((!idx && sym->binding == STB_GLOBAL) ||
2564 		(idx > 0 && ++*cnt == idx) ||
2565 		idx < 0);
2566 }
2567 
2568 static void print_duplicate_syms(struct dso *dso, const char *sym_name)
2569 {
2570 	struct symbol *sym;
2571 	bool near = false;
2572 	int cnt = 0;
2573 
2574 	pr_err("Multiple symbols with name '%s'\n", sym_name);
2575 
2576 	sym = dso__first_symbol(dso);
2577 	while (sym) {
2578 		if (dso_sym_match(sym, sym_name, &cnt, -1)) {
2579 			pr_err("#%d\t0x%"PRIx64"\t%c\t%s\n",
2580 			       ++cnt, sym->start,
2581 			       sym->binding == STB_GLOBAL ? 'g' :
2582 			       sym->binding == STB_LOCAL  ? 'l' : 'w',
2583 			       sym->name);
2584 			near = true;
2585 		} else if (near) {
2586 			near = false;
2587 			pr_err("\t\twhich is near\t\t%s\n", sym->name);
2588 		}
2589 		sym = dso__next_symbol(sym);
2590 	}
2591 
2592 	pr_err("Disambiguate symbol name by inserting #n after the name e.g. %s #2\n",
2593 	       sym_name);
2594 	pr_err("Or select a global symbol by inserting #0 or #g or #G\n");
2595 }
2596 
2597 static int find_dso_sym(struct dso *dso, const char *sym_name, u64 *start,
2598 			u64 *size, int idx)
2599 {
2600 	struct symbol *sym;
2601 	int cnt = 0;
2602 
2603 	*start = 0;
2604 	*size = 0;
2605 
2606 	sym = dso__first_symbol(dso);
2607 	while (sym) {
2608 		if (*start) {
2609 			if (!*size)
2610 				*size = sym->start - *start;
2611 			if (idx > 0) {
2612 				if (*size)
2613 					return 1;
2614 			} else if (dso_sym_match(sym, sym_name, &cnt, idx)) {
2615 				print_duplicate_syms(dso, sym_name);
2616 				return -EINVAL;
2617 			}
2618 		} else if (dso_sym_match(sym, sym_name, &cnt, idx)) {
2619 			*start = sym->start;
2620 			*size = sym->end - sym->start;
2621 		}
2622 		sym = dso__next_symbol(sym);
2623 	}
2624 
2625 	if (!*start)
2626 		return sym_not_found_error(sym_name, idx);
2627 
2628 	return 0;
2629 }
2630 
2631 static int addr_filter__entire_dso(struct addr_filter *filt, struct dso *dso)
2632 {
2633 	if (dso__data_file_size(dso, NULL)) {
2634 		pr_err("Failed to determine filter for %s\nCannot determine file size.\n",
2635 		       filt->filename);
2636 		return -EINVAL;
2637 	}
2638 
2639 	filt->addr = 0;
2640 	filt->size = dso->data.file_size;
2641 
2642 	return 0;
2643 }
2644 
2645 static int addr_filter__resolve_syms(struct addr_filter *filt)
2646 {
2647 	u64 start, size;
2648 	struct dso *dso;
2649 	int err = 0;
2650 
2651 	if (!filt->sym_from && !filt->sym_to)
2652 		return 0;
2653 
2654 	if (!filt->filename)
2655 		return addr_filter__resolve_kernel_syms(filt);
2656 
2657 	dso = load_dso(filt->filename);
2658 	if (!dso) {
2659 		pr_err("Failed to load symbols from: %s\n", filt->filename);
2660 		return -EINVAL;
2661 	}
2662 
2663 	if (filt->sym_from && !strcmp(filt->sym_from, "*")) {
2664 		err = addr_filter__entire_dso(filt, dso);
2665 		goto put_dso;
2666 	}
2667 
2668 	if (filt->sym_from) {
2669 		err = find_dso_sym(dso, filt->sym_from, &start, &size,
2670 				   filt->sym_from_idx);
2671 		if (err)
2672 			goto put_dso;
2673 		filt->addr = start;
2674 		if (filt->range && !filt->size && !filt->sym_to)
2675 			filt->size = size;
2676 	}
2677 
2678 	if (filt->sym_to) {
2679 		err = find_dso_sym(dso, filt->sym_to, &start, &size,
2680 				   filt->sym_to_idx);
2681 		if (err)
2682 			goto put_dso;
2683 
2684 		err = check_end_after_start(filt, start, size);
2685 		if (err)
2686 			return err;
2687 
2688 		filt->size = start + size - filt->addr;
2689 	}
2690 
2691 put_dso:
2692 	dso__put(dso);
2693 
2694 	return err;
2695 }
2696 
2697 static char *addr_filter__to_str(struct addr_filter *filt)
2698 {
2699 	char filename_buf[PATH_MAX];
2700 	const char *at = "";
2701 	const char *fn = "";
2702 	char *filter;
2703 	int err;
2704 
2705 	if (filt->filename) {
2706 		at = "@";
2707 		fn = realpath(filt->filename, filename_buf);
2708 		if (!fn)
2709 			return NULL;
2710 	}
2711 
2712 	if (filt->range) {
2713 		err = asprintf(&filter, "%s 0x%"PRIx64"/0x%"PRIx64"%s%s",
2714 			       filt->action, filt->addr, filt->size, at, fn);
2715 	} else {
2716 		err = asprintf(&filter, "%s 0x%"PRIx64"%s%s",
2717 			       filt->action, filt->addr, at, fn);
2718 	}
2719 
2720 	return err < 0 ? NULL : filter;
2721 }
2722 
2723 static int parse_addr_filter(struct evsel *evsel, const char *filter,
2724 			     int max_nr)
2725 {
2726 	struct addr_filters filts;
2727 	struct addr_filter *filt;
2728 	int err;
2729 
2730 	addr_filters__init(&filts);
2731 
2732 	err = addr_filters__parse_bare_filter(&filts, filter);
2733 	if (err)
2734 		goto out_exit;
2735 
2736 	if (filts.cnt > max_nr) {
2737 		pr_err("Error: number of address filters (%d) exceeds maximum (%d)\n",
2738 		       filts.cnt, max_nr);
2739 		err = -EINVAL;
2740 		goto out_exit;
2741 	}
2742 
2743 	list_for_each_entry(filt, &filts.head, list) {
2744 		char *new_filter;
2745 
2746 		err = addr_filter__resolve_syms(filt);
2747 		if (err)
2748 			goto out_exit;
2749 
2750 		new_filter = addr_filter__to_str(filt);
2751 		if (!new_filter) {
2752 			err = -ENOMEM;
2753 			goto out_exit;
2754 		}
2755 
2756 		if (evsel__append_addr_filter(evsel, new_filter)) {
2757 			err = -ENOMEM;
2758 			goto out_exit;
2759 		}
2760 	}
2761 
2762 out_exit:
2763 	addr_filters__exit(&filts);
2764 
2765 	if (err) {
2766 		pr_err("Failed to parse address filter: '%s'\n", filter);
2767 		pr_err("Filter format is: filter|start|stop|tracestop <start symbol or address> [/ <end symbol or size>] [@<file name>]\n");
2768 		pr_err("Where multiple filters are separated by space or comma.\n");
2769 	}
2770 
2771 	return err;
2772 }
2773 
2774 static int evsel__nr_addr_filter(struct evsel *evsel)
2775 {
2776 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
2777 	int nr_addr_filters = 0;
2778 
2779 	if (!pmu)
2780 		return 0;
2781 
2782 	perf_pmu__scan_file(pmu, "nr_addr_filters", "%d", &nr_addr_filters);
2783 
2784 	return nr_addr_filters;
2785 }
2786 
2787 int auxtrace_parse_filters(struct evlist *evlist)
2788 {
2789 	struct evsel *evsel;
2790 	char *filter;
2791 	int err, max_nr;
2792 
2793 	evlist__for_each_entry(evlist, evsel) {
2794 		filter = evsel->filter;
2795 		max_nr = evsel__nr_addr_filter(evsel);
2796 		if (!filter || !max_nr)
2797 			continue;
2798 		evsel->filter = NULL;
2799 		err = parse_addr_filter(evsel, filter, max_nr);
2800 		free(filter);
2801 		if (err)
2802 			return err;
2803 		pr_debug("Address filter: %s\n", evsel->filter);
2804 	}
2805 
2806 	return 0;
2807 }
2808 
2809 int auxtrace__process_event(struct perf_session *session, union perf_event *event,
2810 			    struct perf_sample *sample, struct perf_tool *tool)
2811 {
2812 	if (!session->auxtrace)
2813 		return 0;
2814 
2815 	return session->auxtrace->process_event(session, event, sample, tool);
2816 }
2817 
2818 void auxtrace__dump_auxtrace_sample(struct perf_session *session,
2819 				    struct perf_sample *sample)
2820 {
2821 	if (!session->auxtrace || !session->auxtrace->dump_auxtrace_sample ||
2822 	    auxtrace__dont_decode(session))
2823 		return;
2824 
2825 	session->auxtrace->dump_auxtrace_sample(session, sample);
2826 }
2827 
2828 int auxtrace__flush_events(struct perf_session *session, struct perf_tool *tool)
2829 {
2830 	if (!session->auxtrace)
2831 		return 0;
2832 
2833 	return session->auxtrace->flush_events(session, tool);
2834 }
2835 
2836 void auxtrace__free_events(struct perf_session *session)
2837 {
2838 	if (!session->auxtrace)
2839 		return;
2840 
2841 	return session->auxtrace->free_events(session);
2842 }
2843 
2844 void auxtrace__free(struct perf_session *session)
2845 {
2846 	if (!session->auxtrace)
2847 		return;
2848 
2849 	return session->auxtrace->free(session);
2850 }
2851 
2852 bool auxtrace__evsel_is_auxtrace(struct perf_session *session,
2853 				 struct evsel *evsel)
2854 {
2855 	if (!session->auxtrace || !session->auxtrace->evsel_is_auxtrace)
2856 		return false;
2857 
2858 	return session->auxtrace->evsel_is_auxtrace(session, evsel);
2859 }
2860