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