xref: /linux/tools/perf/util/auxtrace.c (revision f4bd0b4a9b21c609ede28cee2dcd16824c0489a8)
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 = 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 = 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 = 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->mem = true;
1337 	synth_opts->remote_access = true;
1338 
1339 	if (no_sample) {
1340 		synth_opts->period_type = PERF_ITRACE_PERIOD_INSTRUCTIONS;
1341 		synth_opts->period = 1;
1342 		synth_opts->calls = true;
1343 	} else {
1344 		synth_opts->instructions = true;
1345 		synth_opts->period_type = PERF_ITRACE_DEFAULT_PERIOD_TYPE;
1346 		synth_opts->period = PERF_ITRACE_DEFAULT_PERIOD;
1347 	}
1348 	synth_opts->callchain_sz = PERF_ITRACE_DEFAULT_CALLCHAIN_SZ;
1349 	synth_opts->last_branch_sz = PERF_ITRACE_DEFAULT_LAST_BRANCH_SZ;
1350 	synth_opts->initial_skip = 0;
1351 }
1352 
1353 static int get_flag(const char **ptr, unsigned int *flags)
1354 {
1355 	while (1) {
1356 		char c = **ptr;
1357 
1358 		if (c >= 'a' && c <= 'z') {
1359 			*flags |= 1 << (c - 'a');
1360 			++*ptr;
1361 			return 0;
1362 		} else if (c == ' ') {
1363 			++*ptr;
1364 			continue;
1365 		} else {
1366 			return -1;
1367 		}
1368 	}
1369 }
1370 
1371 static int get_flags(const char **ptr, unsigned int *plus_flags, unsigned int *minus_flags)
1372 {
1373 	while (1) {
1374 		switch (**ptr) {
1375 		case '+':
1376 			++*ptr;
1377 			if (get_flag(ptr, plus_flags))
1378 				return -1;
1379 			break;
1380 		case '-':
1381 			++*ptr;
1382 			if (get_flag(ptr, minus_flags))
1383 				return -1;
1384 			break;
1385 		case ' ':
1386 			++*ptr;
1387 			break;
1388 		default:
1389 			return 0;
1390 		}
1391 	}
1392 }
1393 
1394 /*
1395  * Please check tools/perf/Documentation/perf-script.txt for information
1396  * about the options parsed here, which is introduced after this cset,
1397  * when support in 'perf script' for these options is introduced.
1398  */
1399 int itrace_parse_synth_opts(const struct option *opt, const char *str,
1400 			    int unset)
1401 {
1402 	struct itrace_synth_opts *synth_opts = opt->value;
1403 	const char *p;
1404 	char *endptr;
1405 	bool period_type_set = false;
1406 	bool period_set = false;
1407 
1408 	synth_opts->set = true;
1409 
1410 	if (unset) {
1411 		synth_opts->dont_decode = true;
1412 		return 0;
1413 	}
1414 
1415 	if (!str) {
1416 		itrace_synth_opts__set_default(synth_opts,
1417 					       synth_opts->default_no_sample);
1418 		return 0;
1419 	}
1420 
1421 	for (p = str; *p;) {
1422 		switch (*p++) {
1423 		case 'i':
1424 			synth_opts->instructions = true;
1425 			while (*p == ' ' || *p == ',')
1426 				p += 1;
1427 			if (isdigit(*p)) {
1428 				synth_opts->period = strtoull(p, &endptr, 10);
1429 				period_set = true;
1430 				p = endptr;
1431 				while (*p == ' ' || *p == ',')
1432 					p += 1;
1433 				switch (*p++) {
1434 				case 'i':
1435 					synth_opts->period_type =
1436 						PERF_ITRACE_PERIOD_INSTRUCTIONS;
1437 					period_type_set = true;
1438 					break;
1439 				case 't':
1440 					synth_opts->period_type =
1441 						PERF_ITRACE_PERIOD_TICKS;
1442 					period_type_set = true;
1443 					break;
1444 				case 'm':
1445 					synth_opts->period *= 1000;
1446 					/* Fall through */
1447 				case 'u':
1448 					synth_opts->period *= 1000;
1449 					/* Fall through */
1450 				case 'n':
1451 					if (*p++ != 's')
1452 						goto out_err;
1453 					synth_opts->period_type =
1454 						PERF_ITRACE_PERIOD_NANOSECS;
1455 					period_type_set = true;
1456 					break;
1457 				case '\0':
1458 					goto out;
1459 				default:
1460 					goto out_err;
1461 				}
1462 			}
1463 			break;
1464 		case 'b':
1465 			synth_opts->branches = true;
1466 			break;
1467 		case 'x':
1468 			synth_opts->transactions = true;
1469 			break;
1470 		case 'w':
1471 			synth_opts->ptwrites = true;
1472 			break;
1473 		case 'p':
1474 			synth_opts->pwr_events = true;
1475 			break;
1476 		case 'o':
1477 			synth_opts->other_events = true;
1478 			break;
1479 		case 'e':
1480 			synth_opts->errors = true;
1481 			if (get_flags(&p, &synth_opts->error_plus_flags,
1482 				      &synth_opts->error_minus_flags))
1483 				goto out_err;
1484 			break;
1485 		case 'd':
1486 			synth_opts->log = true;
1487 			if (get_flags(&p, &synth_opts->log_plus_flags,
1488 				      &synth_opts->log_minus_flags))
1489 				goto out_err;
1490 			break;
1491 		case 'c':
1492 			synth_opts->branches = true;
1493 			synth_opts->calls = true;
1494 			break;
1495 		case 'r':
1496 			synth_opts->branches = true;
1497 			synth_opts->returns = true;
1498 			break;
1499 		case 'G':
1500 		case 'g':
1501 			if (p[-1] == 'G')
1502 				synth_opts->add_callchain = true;
1503 			else
1504 				synth_opts->callchain = true;
1505 			synth_opts->callchain_sz =
1506 					PERF_ITRACE_DEFAULT_CALLCHAIN_SZ;
1507 			while (*p == ' ' || *p == ',')
1508 				p += 1;
1509 			if (isdigit(*p)) {
1510 				unsigned int val;
1511 
1512 				val = strtoul(p, &endptr, 10);
1513 				p = endptr;
1514 				if (!val || val > PERF_ITRACE_MAX_CALLCHAIN_SZ)
1515 					goto out_err;
1516 				synth_opts->callchain_sz = val;
1517 			}
1518 			break;
1519 		case 'L':
1520 		case 'l':
1521 			if (p[-1] == 'L')
1522 				synth_opts->add_last_branch = true;
1523 			else
1524 				synth_opts->last_branch = true;
1525 			synth_opts->last_branch_sz =
1526 					PERF_ITRACE_DEFAULT_LAST_BRANCH_SZ;
1527 			while (*p == ' ' || *p == ',')
1528 				p += 1;
1529 			if (isdigit(*p)) {
1530 				unsigned int val;
1531 
1532 				val = strtoul(p, &endptr, 10);
1533 				p = endptr;
1534 				if (!val ||
1535 				    val > PERF_ITRACE_MAX_LAST_BRANCH_SZ)
1536 					goto out_err;
1537 				synth_opts->last_branch_sz = val;
1538 			}
1539 			break;
1540 		case 's':
1541 			synth_opts->initial_skip = strtoul(p, &endptr, 10);
1542 			if (p == endptr)
1543 				goto out_err;
1544 			p = endptr;
1545 			break;
1546 		case 'f':
1547 			synth_opts->flc = true;
1548 			break;
1549 		case 'm':
1550 			synth_opts->llc = true;
1551 			break;
1552 		case 't':
1553 			synth_opts->tlb = true;
1554 			break;
1555 		case 'a':
1556 			synth_opts->remote_access = true;
1557 			break;
1558 		case 'M':
1559 			synth_opts->mem = true;
1560 			break;
1561 		case 'q':
1562 			synth_opts->quick += 1;
1563 			break;
1564 		case ' ':
1565 		case ',':
1566 			break;
1567 		default:
1568 			goto out_err;
1569 		}
1570 	}
1571 out:
1572 	if (synth_opts->instructions) {
1573 		if (!period_type_set)
1574 			synth_opts->period_type =
1575 					PERF_ITRACE_DEFAULT_PERIOD_TYPE;
1576 		if (!period_set)
1577 			synth_opts->period = PERF_ITRACE_DEFAULT_PERIOD;
1578 	}
1579 
1580 	return 0;
1581 
1582 out_err:
1583 	pr_err("Bad Instruction Tracing options '%s'\n", str);
1584 	return -EINVAL;
1585 }
1586 
1587 static const char * const auxtrace_error_type_name[] = {
1588 	[PERF_AUXTRACE_ERROR_ITRACE] = "instruction trace",
1589 };
1590 
1591 static const char *auxtrace_error_name(int type)
1592 {
1593 	const char *error_type_name = NULL;
1594 
1595 	if (type < PERF_AUXTRACE_ERROR_MAX)
1596 		error_type_name = auxtrace_error_type_name[type];
1597 	if (!error_type_name)
1598 		error_type_name = "unknown AUX";
1599 	return error_type_name;
1600 }
1601 
1602 size_t perf_event__fprintf_auxtrace_error(union perf_event *event, FILE *fp)
1603 {
1604 	struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1605 	unsigned long long nsecs = e->time;
1606 	const char *msg = e->msg;
1607 	int ret;
1608 
1609 	ret = fprintf(fp, " %s error type %u",
1610 		      auxtrace_error_name(e->type), e->type);
1611 
1612 	if (e->fmt && nsecs) {
1613 		unsigned long secs = nsecs / NSEC_PER_SEC;
1614 
1615 		nsecs -= secs * NSEC_PER_SEC;
1616 		ret += fprintf(fp, " time %lu.%09llu", secs, nsecs);
1617 	} else {
1618 		ret += fprintf(fp, " time 0");
1619 	}
1620 
1621 	if (!e->fmt)
1622 		msg = (const char *)&e->time;
1623 
1624 	ret += fprintf(fp, " cpu %d pid %d tid %d ip %#"PRI_lx64" code %u: %s\n",
1625 		       e->cpu, e->pid, e->tid, e->ip, e->code, msg);
1626 	return ret;
1627 }
1628 
1629 void perf_session__auxtrace_error_inc(struct perf_session *session,
1630 				      union perf_event *event)
1631 {
1632 	struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1633 
1634 	if (e->type < PERF_AUXTRACE_ERROR_MAX)
1635 		session->evlist->stats.nr_auxtrace_errors[e->type] += 1;
1636 }
1637 
1638 void events_stats__auxtrace_error_warn(const struct events_stats *stats)
1639 {
1640 	int i;
1641 
1642 	for (i = 0; i < PERF_AUXTRACE_ERROR_MAX; i++) {
1643 		if (!stats->nr_auxtrace_errors[i])
1644 			continue;
1645 		ui__warning("%u %s errors\n",
1646 			    stats->nr_auxtrace_errors[i],
1647 			    auxtrace_error_name(i));
1648 	}
1649 }
1650 
1651 int perf_event__process_auxtrace_error(struct perf_session *session,
1652 				       union perf_event *event)
1653 {
1654 	if (auxtrace__dont_decode(session))
1655 		return 0;
1656 
1657 	perf_event__fprintf_auxtrace_error(event, stdout);
1658 	return 0;
1659 }
1660 
1661 static int __auxtrace_mmap__read(struct mmap *map,
1662 				 struct auxtrace_record *itr,
1663 				 struct perf_tool *tool, process_auxtrace_t fn,
1664 				 bool snapshot, size_t snapshot_size)
1665 {
1666 	struct auxtrace_mmap *mm = &map->auxtrace_mmap;
1667 	u64 head, old = mm->prev, offset, ref;
1668 	unsigned char *data = mm->base;
1669 	size_t size, head_off, old_off, len1, len2, padding;
1670 	union perf_event ev;
1671 	void *data1, *data2;
1672 
1673 	if (snapshot) {
1674 		head = auxtrace_mmap__read_snapshot_head(mm);
1675 		if (auxtrace_record__find_snapshot(itr, mm->idx, mm, data,
1676 						   &head, &old))
1677 			return -1;
1678 	} else {
1679 		head = auxtrace_mmap__read_head(mm);
1680 	}
1681 
1682 	if (old == head)
1683 		return 0;
1684 
1685 	pr_debug3("auxtrace idx %d old %#"PRIx64" head %#"PRIx64" diff %#"PRIx64"\n",
1686 		  mm->idx, old, head, head - old);
1687 
1688 	if (mm->mask) {
1689 		head_off = head & mm->mask;
1690 		old_off = old & mm->mask;
1691 	} else {
1692 		head_off = head % mm->len;
1693 		old_off = old % mm->len;
1694 	}
1695 
1696 	if (head_off > old_off)
1697 		size = head_off - old_off;
1698 	else
1699 		size = mm->len - (old_off - head_off);
1700 
1701 	if (snapshot && size > snapshot_size)
1702 		size = snapshot_size;
1703 
1704 	ref = auxtrace_record__reference(itr);
1705 
1706 	if (head > old || size <= head || mm->mask) {
1707 		offset = head - size;
1708 	} else {
1709 		/*
1710 		 * When the buffer size is not a power of 2, 'head' wraps at the
1711 		 * highest multiple of the buffer size, so we have to subtract
1712 		 * the remainder here.
1713 		 */
1714 		u64 rem = (0ULL - mm->len) % mm->len;
1715 
1716 		offset = head - size - rem;
1717 	}
1718 
1719 	if (size > head_off) {
1720 		len1 = size - head_off;
1721 		data1 = &data[mm->len - len1];
1722 		len2 = head_off;
1723 		data2 = &data[0];
1724 	} else {
1725 		len1 = size;
1726 		data1 = &data[head_off - len1];
1727 		len2 = 0;
1728 		data2 = NULL;
1729 	}
1730 
1731 	if (itr->alignment) {
1732 		unsigned int unwanted = len1 % itr->alignment;
1733 
1734 		len1 -= unwanted;
1735 		size -= unwanted;
1736 	}
1737 
1738 	/* padding must be written by fn() e.g. record__process_auxtrace() */
1739 	padding = size & (PERF_AUXTRACE_RECORD_ALIGNMENT - 1);
1740 	if (padding)
1741 		padding = PERF_AUXTRACE_RECORD_ALIGNMENT - padding;
1742 
1743 	memset(&ev, 0, sizeof(ev));
1744 	ev.auxtrace.header.type = PERF_RECORD_AUXTRACE;
1745 	ev.auxtrace.header.size = sizeof(ev.auxtrace);
1746 	ev.auxtrace.size = size + padding;
1747 	ev.auxtrace.offset = offset;
1748 	ev.auxtrace.reference = ref;
1749 	ev.auxtrace.idx = mm->idx;
1750 	ev.auxtrace.tid = mm->tid;
1751 	ev.auxtrace.cpu = mm->cpu;
1752 
1753 	if (fn(tool, map, &ev, data1, len1, data2, len2))
1754 		return -1;
1755 
1756 	mm->prev = head;
1757 
1758 	if (!snapshot) {
1759 		auxtrace_mmap__write_tail(mm, head);
1760 		if (itr->read_finish) {
1761 			int err;
1762 
1763 			err = itr->read_finish(itr, mm->idx);
1764 			if (err < 0)
1765 				return err;
1766 		}
1767 	}
1768 
1769 	return 1;
1770 }
1771 
1772 int auxtrace_mmap__read(struct mmap *map, struct auxtrace_record *itr,
1773 			struct perf_tool *tool, process_auxtrace_t fn)
1774 {
1775 	return __auxtrace_mmap__read(map, itr, tool, fn, false, 0);
1776 }
1777 
1778 int auxtrace_mmap__read_snapshot(struct mmap *map,
1779 				 struct auxtrace_record *itr,
1780 				 struct perf_tool *tool, process_auxtrace_t fn,
1781 				 size_t snapshot_size)
1782 {
1783 	return __auxtrace_mmap__read(map, itr, tool, fn, true, snapshot_size);
1784 }
1785 
1786 /**
1787  * struct auxtrace_cache - hash table to implement a cache
1788  * @hashtable: the hashtable
1789  * @sz: hashtable size (number of hlists)
1790  * @entry_size: size of an entry
1791  * @limit: limit the number of entries to this maximum, when reached the cache
1792  *         is dropped and caching begins again with an empty cache
1793  * @cnt: current number of entries
1794  * @bits: hashtable size (@sz = 2^@bits)
1795  */
1796 struct auxtrace_cache {
1797 	struct hlist_head *hashtable;
1798 	size_t sz;
1799 	size_t entry_size;
1800 	size_t limit;
1801 	size_t cnt;
1802 	unsigned int bits;
1803 };
1804 
1805 struct auxtrace_cache *auxtrace_cache__new(unsigned int bits, size_t entry_size,
1806 					   unsigned int limit_percent)
1807 {
1808 	struct auxtrace_cache *c;
1809 	struct hlist_head *ht;
1810 	size_t sz, i;
1811 
1812 	c = zalloc(sizeof(struct auxtrace_cache));
1813 	if (!c)
1814 		return NULL;
1815 
1816 	sz = 1UL << bits;
1817 
1818 	ht = calloc(sz, sizeof(struct hlist_head));
1819 	if (!ht)
1820 		goto out_free;
1821 
1822 	for (i = 0; i < sz; i++)
1823 		INIT_HLIST_HEAD(&ht[i]);
1824 
1825 	c->hashtable = ht;
1826 	c->sz = sz;
1827 	c->entry_size = entry_size;
1828 	c->limit = (c->sz * limit_percent) / 100;
1829 	c->bits = bits;
1830 
1831 	return c;
1832 
1833 out_free:
1834 	free(c);
1835 	return NULL;
1836 }
1837 
1838 static void auxtrace_cache__drop(struct auxtrace_cache *c)
1839 {
1840 	struct auxtrace_cache_entry *entry;
1841 	struct hlist_node *tmp;
1842 	size_t i;
1843 
1844 	if (!c)
1845 		return;
1846 
1847 	for (i = 0; i < c->sz; i++) {
1848 		hlist_for_each_entry_safe(entry, tmp, &c->hashtable[i], hash) {
1849 			hlist_del(&entry->hash);
1850 			auxtrace_cache__free_entry(c, entry);
1851 		}
1852 	}
1853 
1854 	c->cnt = 0;
1855 }
1856 
1857 void auxtrace_cache__free(struct auxtrace_cache *c)
1858 {
1859 	if (!c)
1860 		return;
1861 
1862 	auxtrace_cache__drop(c);
1863 	zfree(&c->hashtable);
1864 	free(c);
1865 }
1866 
1867 void *auxtrace_cache__alloc_entry(struct auxtrace_cache *c)
1868 {
1869 	return malloc(c->entry_size);
1870 }
1871 
1872 void auxtrace_cache__free_entry(struct auxtrace_cache *c __maybe_unused,
1873 				void *entry)
1874 {
1875 	free(entry);
1876 }
1877 
1878 int auxtrace_cache__add(struct auxtrace_cache *c, u32 key,
1879 			struct auxtrace_cache_entry *entry)
1880 {
1881 	if (c->limit && ++c->cnt > c->limit)
1882 		auxtrace_cache__drop(c);
1883 
1884 	entry->key = key;
1885 	hlist_add_head(&entry->hash, &c->hashtable[hash_32(key, c->bits)]);
1886 
1887 	return 0;
1888 }
1889 
1890 static struct auxtrace_cache_entry *auxtrace_cache__rm(struct auxtrace_cache *c,
1891 						       u32 key)
1892 {
1893 	struct auxtrace_cache_entry *entry;
1894 	struct hlist_head *hlist;
1895 	struct hlist_node *n;
1896 
1897 	if (!c)
1898 		return NULL;
1899 
1900 	hlist = &c->hashtable[hash_32(key, c->bits)];
1901 	hlist_for_each_entry_safe(entry, n, hlist, hash) {
1902 		if (entry->key == key) {
1903 			hlist_del(&entry->hash);
1904 			return entry;
1905 		}
1906 	}
1907 
1908 	return NULL;
1909 }
1910 
1911 void auxtrace_cache__remove(struct auxtrace_cache *c, u32 key)
1912 {
1913 	struct auxtrace_cache_entry *entry = auxtrace_cache__rm(c, key);
1914 
1915 	auxtrace_cache__free_entry(c, entry);
1916 }
1917 
1918 void *auxtrace_cache__lookup(struct auxtrace_cache *c, u32 key)
1919 {
1920 	struct auxtrace_cache_entry *entry;
1921 	struct hlist_head *hlist;
1922 
1923 	if (!c)
1924 		return NULL;
1925 
1926 	hlist = &c->hashtable[hash_32(key, c->bits)];
1927 	hlist_for_each_entry(entry, hlist, hash) {
1928 		if (entry->key == key)
1929 			return entry;
1930 	}
1931 
1932 	return NULL;
1933 }
1934 
1935 static void addr_filter__free_str(struct addr_filter *filt)
1936 {
1937 	zfree(&filt->str);
1938 	filt->action   = NULL;
1939 	filt->sym_from = NULL;
1940 	filt->sym_to   = NULL;
1941 	filt->filename = NULL;
1942 }
1943 
1944 static struct addr_filter *addr_filter__new(void)
1945 {
1946 	struct addr_filter *filt = zalloc(sizeof(*filt));
1947 
1948 	if (filt)
1949 		INIT_LIST_HEAD(&filt->list);
1950 
1951 	return filt;
1952 }
1953 
1954 static void addr_filter__free(struct addr_filter *filt)
1955 {
1956 	if (filt)
1957 		addr_filter__free_str(filt);
1958 	free(filt);
1959 }
1960 
1961 static void addr_filters__add(struct addr_filters *filts,
1962 			      struct addr_filter *filt)
1963 {
1964 	list_add_tail(&filt->list, &filts->head);
1965 	filts->cnt += 1;
1966 }
1967 
1968 static void addr_filters__del(struct addr_filters *filts,
1969 			      struct addr_filter *filt)
1970 {
1971 	list_del_init(&filt->list);
1972 	filts->cnt -= 1;
1973 }
1974 
1975 void addr_filters__init(struct addr_filters *filts)
1976 {
1977 	INIT_LIST_HEAD(&filts->head);
1978 	filts->cnt = 0;
1979 }
1980 
1981 void addr_filters__exit(struct addr_filters *filts)
1982 {
1983 	struct addr_filter *filt, *n;
1984 
1985 	list_for_each_entry_safe(filt, n, &filts->head, list) {
1986 		addr_filters__del(filts, filt);
1987 		addr_filter__free(filt);
1988 	}
1989 }
1990 
1991 static int parse_num_or_str(char **inp, u64 *num, const char **str,
1992 			    const char *str_delim)
1993 {
1994 	*inp += strspn(*inp, " ");
1995 
1996 	if (isdigit(**inp)) {
1997 		char *endptr;
1998 
1999 		if (!num)
2000 			return -EINVAL;
2001 		errno = 0;
2002 		*num = strtoull(*inp, &endptr, 0);
2003 		if (errno)
2004 			return -errno;
2005 		if (endptr == *inp)
2006 			return -EINVAL;
2007 		*inp = endptr;
2008 	} else {
2009 		size_t n;
2010 
2011 		if (!str)
2012 			return -EINVAL;
2013 		*inp += strspn(*inp, " ");
2014 		*str = *inp;
2015 		n = strcspn(*inp, str_delim);
2016 		if (!n)
2017 			return -EINVAL;
2018 		*inp += n;
2019 		if (**inp) {
2020 			**inp = '\0';
2021 			*inp += 1;
2022 		}
2023 	}
2024 	return 0;
2025 }
2026 
2027 static int parse_action(struct addr_filter *filt)
2028 {
2029 	if (!strcmp(filt->action, "filter")) {
2030 		filt->start = true;
2031 		filt->range = true;
2032 	} else if (!strcmp(filt->action, "start")) {
2033 		filt->start = true;
2034 	} else if (!strcmp(filt->action, "stop")) {
2035 		filt->start = false;
2036 	} else if (!strcmp(filt->action, "tracestop")) {
2037 		filt->start = false;
2038 		filt->range = true;
2039 		filt->action += 5; /* Change 'tracestop' to 'stop' */
2040 	} else {
2041 		return -EINVAL;
2042 	}
2043 	return 0;
2044 }
2045 
2046 static int parse_sym_idx(char **inp, int *idx)
2047 {
2048 	*idx = -1;
2049 
2050 	*inp += strspn(*inp, " ");
2051 
2052 	if (**inp != '#')
2053 		return 0;
2054 
2055 	*inp += 1;
2056 
2057 	if (**inp == 'g' || **inp == 'G') {
2058 		*inp += 1;
2059 		*idx = 0;
2060 	} else {
2061 		unsigned long num;
2062 		char *endptr;
2063 
2064 		errno = 0;
2065 		num = strtoul(*inp, &endptr, 0);
2066 		if (errno)
2067 			return -errno;
2068 		if (endptr == *inp || num > INT_MAX)
2069 			return -EINVAL;
2070 		*inp = endptr;
2071 		*idx = num;
2072 	}
2073 
2074 	return 0;
2075 }
2076 
2077 static int parse_addr_size(char **inp, u64 *num, const char **str, int *idx)
2078 {
2079 	int err = parse_num_or_str(inp, num, str, " ");
2080 
2081 	if (!err && *str)
2082 		err = parse_sym_idx(inp, idx);
2083 
2084 	return err;
2085 }
2086 
2087 static int parse_one_filter(struct addr_filter *filt, const char **filter_inp)
2088 {
2089 	char *fstr;
2090 	int err;
2091 
2092 	filt->str = fstr = strdup(*filter_inp);
2093 	if (!fstr)
2094 		return -ENOMEM;
2095 
2096 	err = parse_num_or_str(&fstr, NULL, &filt->action, " ");
2097 	if (err)
2098 		goto out_err;
2099 
2100 	err = parse_action(filt);
2101 	if (err)
2102 		goto out_err;
2103 
2104 	err = parse_addr_size(&fstr, &filt->addr, &filt->sym_from,
2105 			      &filt->sym_from_idx);
2106 	if (err)
2107 		goto out_err;
2108 
2109 	fstr += strspn(fstr, " ");
2110 
2111 	if (*fstr == '/') {
2112 		fstr += 1;
2113 		err = parse_addr_size(&fstr, &filt->size, &filt->sym_to,
2114 				      &filt->sym_to_idx);
2115 		if (err)
2116 			goto out_err;
2117 		filt->range = true;
2118 	}
2119 
2120 	fstr += strspn(fstr, " ");
2121 
2122 	if (*fstr == '@') {
2123 		fstr += 1;
2124 		err = parse_num_or_str(&fstr, NULL, &filt->filename, " ,");
2125 		if (err)
2126 			goto out_err;
2127 	}
2128 
2129 	fstr += strspn(fstr, " ,");
2130 
2131 	*filter_inp += fstr - filt->str;
2132 
2133 	return 0;
2134 
2135 out_err:
2136 	addr_filter__free_str(filt);
2137 
2138 	return err;
2139 }
2140 
2141 int addr_filters__parse_bare_filter(struct addr_filters *filts,
2142 				    const char *filter)
2143 {
2144 	struct addr_filter *filt;
2145 	const char *fstr = filter;
2146 	int err;
2147 
2148 	while (*fstr) {
2149 		filt = addr_filter__new();
2150 		err = parse_one_filter(filt, &fstr);
2151 		if (err) {
2152 			addr_filter__free(filt);
2153 			addr_filters__exit(filts);
2154 			return err;
2155 		}
2156 		addr_filters__add(filts, filt);
2157 	}
2158 
2159 	return 0;
2160 }
2161 
2162 struct sym_args {
2163 	const char	*name;
2164 	u64		start;
2165 	u64		size;
2166 	int		idx;
2167 	int		cnt;
2168 	bool		started;
2169 	bool		global;
2170 	bool		selected;
2171 	bool		duplicate;
2172 	bool		near;
2173 };
2174 
2175 static bool kern_sym_match(struct sym_args *args, const char *name, char type)
2176 {
2177 	/* A function with the same name, and global or the n'th found or any */
2178 	return kallsyms__is_function(type) &&
2179 	       !strcmp(name, args->name) &&
2180 	       ((args->global && isupper(type)) ||
2181 		(args->selected && ++(args->cnt) == args->idx) ||
2182 		(!args->global && !args->selected));
2183 }
2184 
2185 static int find_kern_sym_cb(void *arg, const char *name, char type, u64 start)
2186 {
2187 	struct sym_args *args = arg;
2188 
2189 	if (args->started) {
2190 		if (!args->size)
2191 			args->size = start - args->start;
2192 		if (args->selected) {
2193 			if (args->size)
2194 				return 1;
2195 		} else if (kern_sym_match(args, name, type)) {
2196 			args->duplicate = true;
2197 			return 1;
2198 		}
2199 	} else if (kern_sym_match(args, name, type)) {
2200 		args->started = true;
2201 		args->start = start;
2202 	}
2203 
2204 	return 0;
2205 }
2206 
2207 static int print_kern_sym_cb(void *arg, const char *name, char type, u64 start)
2208 {
2209 	struct sym_args *args = arg;
2210 
2211 	if (kern_sym_match(args, name, type)) {
2212 		pr_err("#%d\t0x%"PRIx64"\t%c\t%s\n",
2213 		       ++args->cnt, start, type, name);
2214 		args->near = true;
2215 	} else if (args->near) {
2216 		args->near = false;
2217 		pr_err("\t\twhich is near\t\t%s\n", name);
2218 	}
2219 
2220 	return 0;
2221 }
2222 
2223 static int sym_not_found_error(const char *sym_name, int idx)
2224 {
2225 	if (idx > 0) {
2226 		pr_err("N'th occurrence (N=%d) of symbol '%s' not found.\n",
2227 		       idx, sym_name);
2228 	} else if (!idx) {
2229 		pr_err("Global symbol '%s' not found.\n", sym_name);
2230 	} else {
2231 		pr_err("Symbol '%s' not found.\n", sym_name);
2232 	}
2233 	pr_err("Note that symbols must be functions.\n");
2234 
2235 	return -EINVAL;
2236 }
2237 
2238 static int find_kern_sym(const char *sym_name, u64 *start, u64 *size, int idx)
2239 {
2240 	struct sym_args args = {
2241 		.name = sym_name,
2242 		.idx = idx,
2243 		.global = !idx,
2244 		.selected = idx > 0,
2245 	};
2246 	int err;
2247 
2248 	*start = 0;
2249 	*size = 0;
2250 
2251 	err = kallsyms__parse("/proc/kallsyms", &args, find_kern_sym_cb);
2252 	if (err < 0) {
2253 		pr_err("Failed to parse /proc/kallsyms\n");
2254 		return err;
2255 	}
2256 
2257 	if (args.duplicate) {
2258 		pr_err("Multiple kernel symbols with name '%s'\n", sym_name);
2259 		args.cnt = 0;
2260 		kallsyms__parse("/proc/kallsyms", &args, print_kern_sym_cb);
2261 		pr_err("Disambiguate symbol name by inserting #n after the name e.g. %s #2\n",
2262 		       sym_name);
2263 		pr_err("Or select a global symbol by inserting #0 or #g or #G\n");
2264 		return -EINVAL;
2265 	}
2266 
2267 	if (!args.started) {
2268 		pr_err("Kernel symbol lookup: ");
2269 		return sym_not_found_error(sym_name, idx);
2270 	}
2271 
2272 	*start = args.start;
2273 	*size = args.size;
2274 
2275 	return 0;
2276 }
2277 
2278 static int find_entire_kern_cb(void *arg, const char *name __maybe_unused,
2279 			       char type, u64 start)
2280 {
2281 	struct sym_args *args = arg;
2282 
2283 	if (!kallsyms__is_function(type))
2284 		return 0;
2285 
2286 	if (!args->started) {
2287 		args->started = true;
2288 		args->start = start;
2289 	}
2290 	/* Don't know exactly where the kernel ends, so we add a page */
2291 	args->size = round_up(start, page_size) + page_size - args->start;
2292 
2293 	return 0;
2294 }
2295 
2296 static int addr_filter__entire_kernel(struct addr_filter *filt)
2297 {
2298 	struct sym_args args = { .started = false };
2299 	int err;
2300 
2301 	err = kallsyms__parse("/proc/kallsyms", &args, find_entire_kern_cb);
2302 	if (err < 0 || !args.started) {
2303 		pr_err("Failed to parse /proc/kallsyms\n");
2304 		return err;
2305 	}
2306 
2307 	filt->addr = args.start;
2308 	filt->size = args.size;
2309 
2310 	return 0;
2311 }
2312 
2313 static int check_end_after_start(struct addr_filter *filt, u64 start, u64 size)
2314 {
2315 	if (start + size >= filt->addr)
2316 		return 0;
2317 
2318 	if (filt->sym_from) {
2319 		pr_err("Symbol '%s' (0x%"PRIx64") comes before '%s' (0x%"PRIx64")\n",
2320 		       filt->sym_to, start, filt->sym_from, filt->addr);
2321 	} else {
2322 		pr_err("Symbol '%s' (0x%"PRIx64") comes before address 0x%"PRIx64")\n",
2323 		       filt->sym_to, start, filt->addr);
2324 	}
2325 
2326 	return -EINVAL;
2327 }
2328 
2329 static int addr_filter__resolve_kernel_syms(struct addr_filter *filt)
2330 {
2331 	bool no_size = false;
2332 	u64 start, size;
2333 	int err;
2334 
2335 	if (symbol_conf.kptr_restrict) {
2336 		pr_err("Kernel addresses are restricted. Unable to resolve kernel symbols.\n");
2337 		return -EINVAL;
2338 	}
2339 
2340 	if (filt->sym_from && !strcmp(filt->sym_from, "*"))
2341 		return addr_filter__entire_kernel(filt);
2342 
2343 	if (filt->sym_from) {
2344 		err = find_kern_sym(filt->sym_from, &start, &size,
2345 				    filt->sym_from_idx);
2346 		if (err)
2347 			return err;
2348 		filt->addr = start;
2349 		if (filt->range && !filt->size && !filt->sym_to) {
2350 			filt->size = size;
2351 			no_size = !size;
2352 		}
2353 	}
2354 
2355 	if (filt->sym_to) {
2356 		err = find_kern_sym(filt->sym_to, &start, &size,
2357 				    filt->sym_to_idx);
2358 		if (err)
2359 			return err;
2360 
2361 		err = check_end_after_start(filt, start, size);
2362 		if (err)
2363 			return err;
2364 		filt->size = start + size - filt->addr;
2365 		no_size = !size;
2366 	}
2367 
2368 	/* The very last symbol in kallsyms does not imply a particular size */
2369 	if (no_size) {
2370 		pr_err("Cannot determine size of symbol '%s'\n",
2371 		       filt->sym_to ? filt->sym_to : filt->sym_from);
2372 		return -EINVAL;
2373 	}
2374 
2375 	return 0;
2376 }
2377 
2378 static struct dso *load_dso(const char *name)
2379 {
2380 	struct map *map;
2381 	struct dso *dso;
2382 
2383 	map = dso__new_map(name);
2384 	if (!map)
2385 		return NULL;
2386 
2387 	if (map__load(map) < 0)
2388 		pr_err("File '%s' not found or has no symbols.\n", name);
2389 
2390 	dso = dso__get(map->dso);
2391 
2392 	map__put(map);
2393 
2394 	return dso;
2395 }
2396 
2397 static bool dso_sym_match(struct symbol *sym, const char *name, int *cnt,
2398 			  int idx)
2399 {
2400 	/* Same name, and global or the n'th found or any */
2401 	return !arch__compare_symbol_names(name, sym->name) &&
2402 	       ((!idx && sym->binding == STB_GLOBAL) ||
2403 		(idx > 0 && ++*cnt == idx) ||
2404 		idx < 0);
2405 }
2406 
2407 static void print_duplicate_syms(struct dso *dso, const char *sym_name)
2408 {
2409 	struct symbol *sym;
2410 	bool near = false;
2411 	int cnt = 0;
2412 
2413 	pr_err("Multiple symbols with name '%s'\n", sym_name);
2414 
2415 	sym = dso__first_symbol(dso);
2416 	while (sym) {
2417 		if (dso_sym_match(sym, sym_name, &cnt, -1)) {
2418 			pr_err("#%d\t0x%"PRIx64"\t%c\t%s\n",
2419 			       ++cnt, sym->start,
2420 			       sym->binding == STB_GLOBAL ? 'g' :
2421 			       sym->binding == STB_LOCAL  ? 'l' : 'w',
2422 			       sym->name);
2423 			near = true;
2424 		} else if (near) {
2425 			near = false;
2426 			pr_err("\t\twhich is near\t\t%s\n", sym->name);
2427 		}
2428 		sym = dso__next_symbol(sym);
2429 	}
2430 
2431 	pr_err("Disambiguate symbol name by inserting #n after the name e.g. %s #2\n",
2432 	       sym_name);
2433 	pr_err("Or select a global symbol by inserting #0 or #g or #G\n");
2434 }
2435 
2436 static int find_dso_sym(struct dso *dso, const char *sym_name, u64 *start,
2437 			u64 *size, int idx)
2438 {
2439 	struct symbol *sym;
2440 	int cnt = 0;
2441 
2442 	*start = 0;
2443 	*size = 0;
2444 
2445 	sym = dso__first_symbol(dso);
2446 	while (sym) {
2447 		if (*start) {
2448 			if (!*size)
2449 				*size = sym->start - *start;
2450 			if (idx > 0) {
2451 				if (*size)
2452 					return 1;
2453 			} else if (dso_sym_match(sym, sym_name, &cnt, idx)) {
2454 				print_duplicate_syms(dso, sym_name);
2455 				return -EINVAL;
2456 			}
2457 		} else if (dso_sym_match(sym, sym_name, &cnt, idx)) {
2458 			*start = sym->start;
2459 			*size = sym->end - sym->start;
2460 		}
2461 		sym = dso__next_symbol(sym);
2462 	}
2463 
2464 	if (!*start)
2465 		return sym_not_found_error(sym_name, idx);
2466 
2467 	return 0;
2468 }
2469 
2470 static int addr_filter__entire_dso(struct addr_filter *filt, struct dso *dso)
2471 {
2472 	if (dso__data_file_size(dso, NULL)) {
2473 		pr_err("Failed to determine filter for %s\nCannot determine file size.\n",
2474 		       filt->filename);
2475 		return -EINVAL;
2476 	}
2477 
2478 	filt->addr = 0;
2479 	filt->size = dso->data.file_size;
2480 
2481 	return 0;
2482 }
2483 
2484 static int addr_filter__resolve_syms(struct addr_filter *filt)
2485 {
2486 	u64 start, size;
2487 	struct dso *dso;
2488 	int err = 0;
2489 
2490 	if (!filt->sym_from && !filt->sym_to)
2491 		return 0;
2492 
2493 	if (!filt->filename)
2494 		return addr_filter__resolve_kernel_syms(filt);
2495 
2496 	dso = load_dso(filt->filename);
2497 	if (!dso) {
2498 		pr_err("Failed to load symbols from: %s\n", filt->filename);
2499 		return -EINVAL;
2500 	}
2501 
2502 	if (filt->sym_from && !strcmp(filt->sym_from, "*")) {
2503 		err = addr_filter__entire_dso(filt, dso);
2504 		goto put_dso;
2505 	}
2506 
2507 	if (filt->sym_from) {
2508 		err = find_dso_sym(dso, filt->sym_from, &start, &size,
2509 				   filt->sym_from_idx);
2510 		if (err)
2511 			goto put_dso;
2512 		filt->addr = start;
2513 		if (filt->range && !filt->size && !filt->sym_to)
2514 			filt->size = size;
2515 	}
2516 
2517 	if (filt->sym_to) {
2518 		err = find_dso_sym(dso, filt->sym_to, &start, &size,
2519 				   filt->sym_to_idx);
2520 		if (err)
2521 			goto put_dso;
2522 
2523 		err = check_end_after_start(filt, start, size);
2524 		if (err)
2525 			return err;
2526 
2527 		filt->size = start + size - filt->addr;
2528 	}
2529 
2530 put_dso:
2531 	dso__put(dso);
2532 
2533 	return err;
2534 }
2535 
2536 static char *addr_filter__to_str(struct addr_filter *filt)
2537 {
2538 	char filename_buf[PATH_MAX];
2539 	const char *at = "";
2540 	const char *fn = "";
2541 	char *filter;
2542 	int err;
2543 
2544 	if (filt->filename) {
2545 		at = "@";
2546 		fn = realpath(filt->filename, filename_buf);
2547 		if (!fn)
2548 			return NULL;
2549 	}
2550 
2551 	if (filt->range) {
2552 		err = asprintf(&filter, "%s 0x%"PRIx64"/0x%"PRIx64"%s%s",
2553 			       filt->action, filt->addr, filt->size, at, fn);
2554 	} else {
2555 		err = asprintf(&filter, "%s 0x%"PRIx64"%s%s",
2556 			       filt->action, filt->addr, at, fn);
2557 	}
2558 
2559 	return err < 0 ? NULL : filter;
2560 }
2561 
2562 static int parse_addr_filter(struct evsel *evsel, const char *filter,
2563 			     int max_nr)
2564 {
2565 	struct addr_filters filts;
2566 	struct addr_filter *filt;
2567 	int err;
2568 
2569 	addr_filters__init(&filts);
2570 
2571 	err = addr_filters__parse_bare_filter(&filts, filter);
2572 	if (err)
2573 		goto out_exit;
2574 
2575 	if (filts.cnt > max_nr) {
2576 		pr_err("Error: number of address filters (%d) exceeds maximum (%d)\n",
2577 		       filts.cnt, max_nr);
2578 		err = -EINVAL;
2579 		goto out_exit;
2580 	}
2581 
2582 	list_for_each_entry(filt, &filts.head, list) {
2583 		char *new_filter;
2584 
2585 		err = addr_filter__resolve_syms(filt);
2586 		if (err)
2587 			goto out_exit;
2588 
2589 		new_filter = addr_filter__to_str(filt);
2590 		if (!new_filter) {
2591 			err = -ENOMEM;
2592 			goto out_exit;
2593 		}
2594 
2595 		if (evsel__append_addr_filter(evsel, new_filter)) {
2596 			err = -ENOMEM;
2597 			goto out_exit;
2598 		}
2599 	}
2600 
2601 out_exit:
2602 	addr_filters__exit(&filts);
2603 
2604 	if (err) {
2605 		pr_err("Failed to parse address filter: '%s'\n", filter);
2606 		pr_err("Filter format is: filter|start|stop|tracestop <start symbol or address> [/ <end symbol or size>] [@<file name>]\n");
2607 		pr_err("Where multiple filters are separated by space or comma.\n");
2608 	}
2609 
2610 	return err;
2611 }
2612 
2613 static int evsel__nr_addr_filter(struct evsel *evsel)
2614 {
2615 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
2616 	int nr_addr_filters = 0;
2617 
2618 	if (!pmu)
2619 		return 0;
2620 
2621 	perf_pmu__scan_file(pmu, "nr_addr_filters", "%d", &nr_addr_filters);
2622 
2623 	return nr_addr_filters;
2624 }
2625 
2626 int auxtrace_parse_filters(struct evlist *evlist)
2627 {
2628 	struct evsel *evsel;
2629 	char *filter;
2630 	int err, max_nr;
2631 
2632 	evlist__for_each_entry(evlist, evsel) {
2633 		filter = evsel->filter;
2634 		max_nr = evsel__nr_addr_filter(evsel);
2635 		if (!filter || !max_nr)
2636 			continue;
2637 		evsel->filter = NULL;
2638 		err = parse_addr_filter(evsel, filter, max_nr);
2639 		free(filter);
2640 		if (err)
2641 			return err;
2642 		pr_debug("Address filter: %s\n", evsel->filter);
2643 	}
2644 
2645 	return 0;
2646 }
2647 
2648 int auxtrace__process_event(struct perf_session *session, union perf_event *event,
2649 			    struct perf_sample *sample, struct perf_tool *tool)
2650 {
2651 	if (!session->auxtrace)
2652 		return 0;
2653 
2654 	return session->auxtrace->process_event(session, event, sample, tool);
2655 }
2656 
2657 void auxtrace__dump_auxtrace_sample(struct perf_session *session,
2658 				    struct perf_sample *sample)
2659 {
2660 	if (!session->auxtrace || !session->auxtrace->dump_auxtrace_sample ||
2661 	    auxtrace__dont_decode(session))
2662 		return;
2663 
2664 	session->auxtrace->dump_auxtrace_sample(session, sample);
2665 }
2666 
2667 int auxtrace__flush_events(struct perf_session *session, struct perf_tool *tool)
2668 {
2669 	if (!session->auxtrace)
2670 		return 0;
2671 
2672 	return session->auxtrace->flush_events(session, tool);
2673 }
2674 
2675 void auxtrace__free_events(struct perf_session *session)
2676 {
2677 	if (!session->auxtrace)
2678 		return;
2679 
2680 	return session->auxtrace->free_events(session);
2681 }
2682 
2683 void auxtrace__free(struct perf_session *session)
2684 {
2685 	if (!session->auxtrace)
2686 		return;
2687 
2688 	return session->auxtrace->free(session);
2689 }
2690 
2691 bool auxtrace__evsel_is_auxtrace(struct perf_session *session,
2692 				 struct evsel *evsel)
2693 {
2694 	if (!session->auxtrace || !session->auxtrace->evsel_is_auxtrace)
2695 		return false;
2696 
2697 	return session->auxtrace->evsel_is_auxtrace(session, evsel);
2698 }
2699