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