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