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