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