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