xref: /linux/tools/perf/util/header.c (revision be59dba332e1e8edd3e88d991ba0e4795ae2bcb2)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <inttypes.h>
4 #include "string2.h"
5 #include <sys/param.h>
6 #include <sys/types.h>
7 #include <byteswap.h>
8 #include <unistd.h>
9 #include <regex.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <linux/compiler.h>
13 #include <linux/list.h>
14 #include <linux/kernel.h>
15 #include <linux/bitops.h>
16 #include <linux/string.h>
17 #include <linux/stringify.h>
18 #include <linux/zalloc.h>
19 #include <sys/stat.h>
20 #include <sys/utsname.h>
21 #include <linux/time64.h>
22 #include <dirent.h>
23 #ifdef HAVE_LIBBPF_SUPPORT
24 #include <bpf/libbpf.h>
25 #endif
26 #include <perf/cpumap.h>
27 #include <tools/libc_compat.h> // reallocarray
28 
29 #include "dso.h"
30 #include "evlist.h"
31 #include "evsel.h"
32 #include "util/evsel_fprintf.h"
33 #include "header.h"
34 #include "memswap.h"
35 #include "trace-event.h"
36 #include "session.h"
37 #include "symbol.h"
38 #include "debug.h"
39 #include "cpumap.h"
40 #include "pmu.h"
41 #include "pmus.h"
42 #include "vdso.h"
43 #include "strbuf.h"
44 #include "build-id.h"
45 #include "data.h"
46 #include <api/fs/fs.h>
47 #include <api/io_dir.h>
48 #include "asm/bug.h"
49 #include "tool.h"
50 #include "time-utils.h"
51 #include "units.h"
52 #include "util/util.h" // perf_exe()
53 #include "cputopo.h"
54 #include "bpf-event.h"
55 #include "bpf-utils.h"
56 #include "clockid.h"
57 
58 #include <linux/ctype.h>
59 #include <internal/lib.h>
60 
61 #ifdef HAVE_LIBTRACEEVENT
62 #include <event-parse.h>
63 #endif
64 
65 /*
66  * magic2 = "PERFILE2"
67  * must be a numerical value to let the endianness
68  * determine the memory layout. That way we are able
69  * to detect endianness when reading the perf.data file
70  * back.
71  *
72  * we check for legacy (PERFFILE) format.
73  */
74 static const char *__perf_magic1 = "PERFFILE";
75 static const u64 __perf_magic2    = 0x32454c4946524550ULL;
76 static const u64 __perf_magic2_sw = 0x50455246494c4532ULL;
77 
78 #define PERF_MAGIC	__perf_magic2
79 
80 const char perf_version_string[] = PERF_VERSION;
81 
82 struct perf_file_attr {
83 	struct perf_event_attr	attr;
84 	struct perf_file_section	ids;
85 };
86 
87 void perf_header__set_feat(struct perf_header *header, int feat)
88 {
89 	__set_bit(feat, header->adds_features);
90 }
91 
92 void perf_header__clear_feat(struct perf_header *header, int feat)
93 {
94 	__clear_bit(feat, header->adds_features);
95 }
96 
97 bool perf_header__has_feat(const struct perf_header *header, int feat)
98 {
99 	return test_bit(feat, header->adds_features);
100 }
101 
102 static int __do_write_fd(struct feat_fd *ff, const void *buf, size_t size)
103 {
104 	ssize_t ret = writen(ff->fd, buf, size);
105 
106 	if (ret != (ssize_t)size)
107 		return ret < 0 ? (int)ret : -1;
108 	return 0;
109 }
110 
111 static int __do_write_buf(struct feat_fd *ff,  const void *buf, size_t size)
112 {
113 	/* struct perf_event_header::size is u16 */
114 	const size_t max_size = 0xffff - sizeof(struct perf_event_header);
115 	size_t new_size = ff->size;
116 	void *addr;
117 
118 	if (size + ff->offset > max_size)
119 		return -E2BIG;
120 
121 	while (size > (new_size - ff->offset))
122 		new_size <<= 1;
123 	new_size = min(max_size, new_size);
124 
125 	if (ff->size < new_size) {
126 		addr = realloc(ff->buf, new_size);
127 		if (!addr)
128 			return -ENOMEM;
129 		ff->buf = addr;
130 		ff->size = new_size;
131 	}
132 
133 	memcpy(ff->buf + ff->offset, buf, size);
134 	ff->offset += size;
135 
136 	return 0;
137 }
138 
139 /* Return: 0 if succeeded, -ERR if failed. */
140 int do_write(struct feat_fd *ff, const void *buf, size_t size)
141 {
142 	if (!ff->buf)
143 		return __do_write_fd(ff, buf, size);
144 	return __do_write_buf(ff, buf, size);
145 }
146 
147 /* Return: 0 if succeeded, -ERR if failed. */
148 static int do_write_bitmap(struct feat_fd *ff, unsigned long *set, u64 size)
149 {
150 	u64 *p = (u64 *) set;
151 	int i, ret;
152 
153 	ret = do_write(ff, &size, sizeof(size));
154 	if (ret < 0)
155 		return ret;
156 
157 	for (i = 0; (u64) i < BITS_TO_U64(size); i++) {
158 		ret = do_write(ff, p + i, sizeof(*p));
159 		if (ret < 0)
160 			return ret;
161 	}
162 
163 	return 0;
164 }
165 
166 /* Return: 0 if succeeded, -ERR if failed. */
167 int write_padded(struct feat_fd *ff, const void *bf,
168 		 size_t count, size_t count_aligned)
169 {
170 	static const char zero_buf[NAME_ALIGN];
171 	int err = do_write(ff, bf, count);
172 
173 	if (!err)
174 		err = do_write(ff, zero_buf, count_aligned - count);
175 
176 	return err;
177 }
178 
179 #define string_size(str)						\
180 	(PERF_ALIGN((strlen(str) + 1), NAME_ALIGN) + sizeof(u32))
181 
182 /* Return: 0 if succeeded, -ERR if failed. */
183 static int do_write_string(struct feat_fd *ff, const char *str)
184 {
185 	u32 len, olen;
186 	int ret;
187 
188 	olen = strlen(str) + 1;
189 	len = PERF_ALIGN(olen, NAME_ALIGN);
190 
191 	/* write len, incl. \0 */
192 	ret = do_write(ff, &len, sizeof(len));
193 	if (ret < 0)
194 		return ret;
195 
196 	return write_padded(ff, str, olen, len);
197 }
198 
199 static int __do_read_fd(struct feat_fd *ff, void *addr, ssize_t size)
200 {
201 	ssize_t ret = readn(ff->fd, addr, size);
202 
203 	if (ret != size)
204 		return ret < 0 ? (int)ret : -1;
205 	return 0;
206 }
207 
208 static int __do_read_buf(struct feat_fd *ff, void *addr, ssize_t size)
209 {
210 	if (size > (ssize_t)ff->size - ff->offset)
211 		return -1;
212 
213 	memcpy(addr, ff->buf + ff->offset, size);
214 	ff->offset += size;
215 
216 	return 0;
217 
218 }
219 
220 static int __do_read(struct feat_fd *ff, void *addr, ssize_t size)
221 {
222 	if (!ff->buf)
223 		return __do_read_fd(ff, addr, size);
224 	return __do_read_buf(ff, addr, size);
225 }
226 
227 static int do_read_u32(struct feat_fd *ff, u32 *addr)
228 {
229 	int ret;
230 
231 	ret = __do_read(ff, addr, sizeof(*addr));
232 	if (ret)
233 		return ret;
234 
235 	if (ff->ph->needs_swap)
236 		*addr = bswap_32(*addr);
237 	return 0;
238 }
239 
240 static int do_read_u64(struct feat_fd *ff, u64 *addr)
241 {
242 	int ret;
243 
244 	ret = __do_read(ff, addr, sizeof(*addr));
245 	if (ret)
246 		return ret;
247 
248 	if (ff->ph->needs_swap)
249 		*addr = bswap_64(*addr);
250 	return 0;
251 }
252 
253 static char *do_read_string(struct feat_fd *ff)
254 {
255 	u32 len;
256 	char *buf;
257 
258 	if (do_read_u32(ff, &len))
259 		return NULL;
260 
261 	buf = malloc(len);
262 	if (!buf)
263 		return NULL;
264 
265 	if (!__do_read(ff, buf, len)) {
266 		/*
267 		 * strings are padded by zeroes
268 		 * thus the actual strlen of buf
269 		 * may be less than len
270 		 */
271 		return buf;
272 	}
273 
274 	free(buf);
275 	return NULL;
276 }
277 
278 /* Return: 0 if succeeded, -ERR if failed. */
279 static int do_read_bitmap(struct feat_fd *ff, unsigned long **pset, u64 *psize)
280 {
281 	unsigned long *set;
282 	u64 size, *p;
283 	int i, ret;
284 
285 	ret = do_read_u64(ff, &size);
286 	if (ret)
287 		return ret;
288 
289 	set = bitmap_zalloc(size);
290 	if (!set)
291 		return -ENOMEM;
292 
293 	p = (u64 *) set;
294 
295 	for (i = 0; (u64) i < BITS_TO_U64(size); i++) {
296 		ret = do_read_u64(ff, p + i);
297 		if (ret < 0) {
298 			free(set);
299 			return ret;
300 		}
301 	}
302 
303 	*pset  = set;
304 	*psize = size;
305 	return 0;
306 }
307 
308 #ifdef HAVE_LIBTRACEEVENT
309 static int write_tracing_data(struct feat_fd *ff,
310 			      struct evlist *evlist)
311 {
312 	if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
313 		return -1;
314 
315 	return read_tracing_data(ff->fd, &evlist->core.entries);
316 }
317 #endif
318 
319 static int write_build_id(struct feat_fd *ff,
320 			  struct evlist *evlist __maybe_unused)
321 {
322 	struct perf_session *session;
323 	int err;
324 
325 	session = container_of(ff->ph, struct perf_session, header);
326 
327 	if (!perf_session__read_build_ids(session, true))
328 		return -1;
329 
330 	if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
331 		return -1;
332 
333 	err = perf_session__write_buildid_table(session, ff);
334 	if (err < 0) {
335 		pr_debug("failed to write buildid table\n");
336 		return err;
337 	}
338 	perf_session__cache_build_ids(session);
339 
340 	return 0;
341 }
342 
343 static int write_hostname(struct feat_fd *ff,
344 			  struct evlist *evlist __maybe_unused)
345 {
346 	struct utsname uts;
347 	int ret;
348 
349 	ret = uname(&uts);
350 	if (ret < 0)
351 		return -1;
352 
353 	return do_write_string(ff, uts.nodename);
354 }
355 
356 static int write_osrelease(struct feat_fd *ff,
357 			   struct evlist *evlist __maybe_unused)
358 {
359 	struct utsname uts;
360 	int ret;
361 
362 	ret = uname(&uts);
363 	if (ret < 0)
364 		return -1;
365 
366 	return do_write_string(ff, uts.release);
367 }
368 
369 static int write_arch(struct feat_fd *ff,
370 		      struct evlist *evlist __maybe_unused)
371 {
372 	struct utsname uts;
373 	int ret;
374 
375 	ret = uname(&uts);
376 	if (ret < 0)
377 		return -1;
378 
379 	return do_write_string(ff, uts.machine);
380 }
381 
382 static int write_version(struct feat_fd *ff,
383 			 struct evlist *evlist __maybe_unused)
384 {
385 	return do_write_string(ff, perf_version_string);
386 }
387 
388 static int __write_cpudesc(struct feat_fd *ff, const char *cpuinfo_proc)
389 {
390 	FILE *file;
391 	char *buf = NULL;
392 	char *s, *p;
393 	const char *search = cpuinfo_proc;
394 	size_t len = 0;
395 	int ret = -1;
396 
397 	if (!search)
398 		return -1;
399 
400 	file = fopen("/proc/cpuinfo", "r");
401 	if (!file)
402 		return -1;
403 
404 	while (getline(&buf, &len, file) > 0) {
405 		ret = strncmp(buf, search, strlen(search));
406 		if (!ret)
407 			break;
408 	}
409 
410 	if (ret) {
411 		ret = -1;
412 		goto done;
413 	}
414 
415 	s = buf;
416 
417 	p = strchr(buf, ':');
418 	if (p && *(p+1) == ' ' && *(p+2))
419 		s = p + 2;
420 	p = strchr(s, '\n');
421 	if (p)
422 		*p = '\0';
423 
424 	/* squash extra space characters (branding string) */
425 	p = s;
426 	while (*p) {
427 		if (isspace(*p)) {
428 			char *r = p + 1;
429 			char *q = skip_spaces(r);
430 			*p = ' ';
431 			if (q != (p+1))
432 				while ((*r++ = *q++));
433 		}
434 		p++;
435 	}
436 	ret = do_write_string(ff, s);
437 done:
438 	free(buf);
439 	fclose(file);
440 	return ret;
441 }
442 
443 static int write_cpudesc(struct feat_fd *ff,
444 		       struct evlist *evlist __maybe_unused)
445 {
446 #if defined(__powerpc__) || defined(__hppa__) || defined(__sparc__)
447 #define CPUINFO_PROC	{ "cpu", }
448 #elif defined(__s390__)
449 #define CPUINFO_PROC	{ "vendor_id", }
450 #elif defined(__sh__)
451 #define CPUINFO_PROC	{ "cpu type", }
452 #elif defined(__alpha__) || defined(__mips__)
453 #define CPUINFO_PROC	{ "cpu model", }
454 #elif defined(__arm__)
455 #define CPUINFO_PROC	{ "model name", "Processor", }
456 #elif defined(__arc__)
457 #define CPUINFO_PROC	{ "Processor", }
458 #elif defined(__xtensa__)
459 #define CPUINFO_PROC	{ "core ID", }
460 #elif defined(__loongarch__)
461 #define CPUINFO_PROC	{ "Model Name", }
462 #else
463 #define CPUINFO_PROC	{ "model name", }
464 #endif
465 	const char *cpuinfo_procs[] = CPUINFO_PROC;
466 #undef CPUINFO_PROC
467 	unsigned int i;
468 
469 	for (i = 0; i < ARRAY_SIZE(cpuinfo_procs); i++) {
470 		int ret;
471 		ret = __write_cpudesc(ff, cpuinfo_procs[i]);
472 		if (ret >= 0)
473 			return ret;
474 	}
475 	return -1;
476 }
477 
478 
479 static int write_nrcpus(struct feat_fd *ff,
480 			struct evlist *evlist __maybe_unused)
481 {
482 	long nr;
483 	u32 nrc, nra;
484 	int ret;
485 
486 	nrc = cpu__max_present_cpu().cpu;
487 
488 	nr = sysconf(_SC_NPROCESSORS_ONLN);
489 	if (nr < 0)
490 		return -1;
491 
492 	nra = (u32)(nr & UINT_MAX);
493 
494 	ret = do_write(ff, &nrc, sizeof(nrc));
495 	if (ret < 0)
496 		return ret;
497 
498 	return do_write(ff, &nra, sizeof(nra));
499 }
500 
501 static int write_event_desc(struct feat_fd *ff,
502 			    struct evlist *evlist)
503 {
504 	struct evsel *evsel;
505 	u32 nre, nri, sz;
506 	int ret;
507 
508 	nre = evlist->core.nr_entries;
509 
510 	/*
511 	 * write number of events
512 	 */
513 	ret = do_write(ff, &nre, sizeof(nre));
514 	if (ret < 0)
515 		return ret;
516 
517 	/*
518 	 * size of perf_event_attr struct
519 	 */
520 	sz = (u32)sizeof(evsel->core.attr);
521 	ret = do_write(ff, &sz, sizeof(sz));
522 	if (ret < 0)
523 		return ret;
524 
525 	evlist__for_each_entry(evlist, evsel) {
526 		ret = do_write(ff, &evsel->core.attr, sz);
527 		if (ret < 0)
528 			return ret;
529 		/*
530 		 * write number of unique id per event
531 		 * there is one id per instance of an event
532 		 *
533 		 * copy into an nri to be independent of the
534 		 * type of ids,
535 		 */
536 		nri = evsel->core.ids;
537 		ret = do_write(ff, &nri, sizeof(nri));
538 		if (ret < 0)
539 			return ret;
540 
541 		/*
542 		 * write event string as passed on cmdline
543 		 */
544 		ret = do_write_string(ff, evsel__name(evsel));
545 		if (ret < 0)
546 			return ret;
547 		/*
548 		 * write unique ids for this event
549 		 */
550 		ret = do_write(ff, evsel->core.id, evsel->core.ids * sizeof(u64));
551 		if (ret < 0)
552 			return ret;
553 	}
554 	return 0;
555 }
556 
557 static int write_cmdline(struct feat_fd *ff,
558 			 struct evlist *evlist __maybe_unused)
559 {
560 	char pbuf[MAXPATHLEN], *buf;
561 	int i, ret, n;
562 
563 	/* actual path to perf binary */
564 	buf = perf_exe(pbuf, MAXPATHLEN);
565 
566 	/* account for binary path */
567 	n = perf_env.nr_cmdline + 1;
568 
569 	ret = do_write(ff, &n, sizeof(n));
570 	if (ret < 0)
571 		return ret;
572 
573 	ret = do_write_string(ff, buf);
574 	if (ret < 0)
575 		return ret;
576 
577 	for (i = 0 ; i < perf_env.nr_cmdline; i++) {
578 		ret = do_write_string(ff, perf_env.cmdline_argv[i]);
579 		if (ret < 0)
580 			return ret;
581 	}
582 	return 0;
583 }
584 
585 
586 static int write_cpu_topology(struct feat_fd *ff,
587 			      struct evlist *evlist __maybe_unused)
588 {
589 	struct cpu_topology *tp;
590 	u32 i;
591 	int ret, j;
592 
593 	tp = cpu_topology__new();
594 	if (!tp)
595 		return -1;
596 
597 	ret = do_write(ff, &tp->package_cpus_lists, sizeof(tp->package_cpus_lists));
598 	if (ret < 0)
599 		goto done;
600 
601 	for (i = 0; i < tp->package_cpus_lists; i++) {
602 		ret = do_write_string(ff, tp->package_cpus_list[i]);
603 		if (ret < 0)
604 			goto done;
605 	}
606 	ret = do_write(ff, &tp->core_cpus_lists, sizeof(tp->core_cpus_lists));
607 	if (ret < 0)
608 		goto done;
609 
610 	for (i = 0; i < tp->core_cpus_lists; i++) {
611 		ret = do_write_string(ff, tp->core_cpus_list[i]);
612 		if (ret < 0)
613 			break;
614 	}
615 
616 	ret = perf_env__read_cpu_topology_map(&perf_env);
617 	if (ret < 0)
618 		goto done;
619 
620 	for (j = 0; j < perf_env.nr_cpus_avail; j++) {
621 		ret = do_write(ff, &perf_env.cpu[j].core_id,
622 			       sizeof(perf_env.cpu[j].core_id));
623 		if (ret < 0)
624 			return ret;
625 		ret = do_write(ff, &perf_env.cpu[j].socket_id,
626 			       sizeof(perf_env.cpu[j].socket_id));
627 		if (ret < 0)
628 			return ret;
629 	}
630 
631 	if (!tp->die_cpus_lists)
632 		goto done;
633 
634 	ret = do_write(ff, &tp->die_cpus_lists, sizeof(tp->die_cpus_lists));
635 	if (ret < 0)
636 		goto done;
637 
638 	for (i = 0; i < tp->die_cpus_lists; i++) {
639 		ret = do_write_string(ff, tp->die_cpus_list[i]);
640 		if (ret < 0)
641 			goto done;
642 	}
643 
644 	for (j = 0; j < perf_env.nr_cpus_avail; j++) {
645 		ret = do_write(ff, &perf_env.cpu[j].die_id,
646 			       sizeof(perf_env.cpu[j].die_id));
647 		if (ret < 0)
648 			return ret;
649 	}
650 
651 done:
652 	cpu_topology__delete(tp);
653 	return ret;
654 }
655 
656 
657 
658 static int write_total_mem(struct feat_fd *ff,
659 			   struct evlist *evlist __maybe_unused)
660 {
661 	char *buf = NULL;
662 	FILE *fp;
663 	size_t len = 0;
664 	int ret = -1, n;
665 	uint64_t mem;
666 
667 	fp = fopen("/proc/meminfo", "r");
668 	if (!fp)
669 		return -1;
670 
671 	while (getline(&buf, &len, fp) > 0) {
672 		ret = strncmp(buf, "MemTotal:", 9);
673 		if (!ret)
674 			break;
675 	}
676 	if (!ret) {
677 		n = sscanf(buf, "%*s %"PRIu64, &mem);
678 		if (n == 1)
679 			ret = do_write(ff, &mem, sizeof(mem));
680 	} else
681 		ret = -1;
682 	free(buf);
683 	fclose(fp);
684 	return ret;
685 }
686 
687 static int write_numa_topology(struct feat_fd *ff,
688 			       struct evlist *evlist __maybe_unused)
689 {
690 	struct numa_topology *tp;
691 	int ret = -1;
692 	u32 i;
693 
694 	tp = numa_topology__new();
695 	if (!tp)
696 		return -ENOMEM;
697 
698 	ret = do_write(ff, &tp->nr, sizeof(u32));
699 	if (ret < 0)
700 		goto err;
701 
702 	for (i = 0; i < tp->nr; i++) {
703 		struct numa_topology_node *n = &tp->nodes[i];
704 
705 		ret = do_write(ff, &n->node, sizeof(u32));
706 		if (ret < 0)
707 			goto err;
708 
709 		ret = do_write(ff, &n->mem_total, sizeof(u64));
710 		if (ret)
711 			goto err;
712 
713 		ret = do_write(ff, &n->mem_free, sizeof(u64));
714 		if (ret)
715 			goto err;
716 
717 		ret = do_write_string(ff, n->cpus);
718 		if (ret < 0)
719 			goto err;
720 	}
721 
722 	ret = 0;
723 
724 err:
725 	numa_topology__delete(tp);
726 	return ret;
727 }
728 
729 /*
730  * File format:
731  *
732  * struct pmu_mappings {
733  *	u32	pmu_num;
734  *	struct pmu_map {
735  *		u32	type;
736  *		char	name[];
737  *	}[pmu_num];
738  * };
739  */
740 
741 static int write_pmu_mappings(struct feat_fd *ff,
742 			      struct evlist *evlist __maybe_unused)
743 {
744 	struct perf_pmu *pmu = NULL;
745 	u32 pmu_num = 0;
746 	int ret;
747 
748 	/*
749 	 * Do a first pass to count number of pmu to avoid lseek so this
750 	 * works in pipe mode as well.
751 	 */
752 	while ((pmu = perf_pmus__scan(pmu)))
753 		pmu_num++;
754 
755 	ret = do_write(ff, &pmu_num, sizeof(pmu_num));
756 	if (ret < 0)
757 		return ret;
758 
759 	while ((pmu = perf_pmus__scan(pmu))) {
760 		ret = do_write(ff, &pmu->type, sizeof(pmu->type));
761 		if (ret < 0)
762 			return ret;
763 
764 		ret = do_write_string(ff, pmu->name);
765 		if (ret < 0)
766 			return ret;
767 	}
768 
769 	return 0;
770 }
771 
772 /*
773  * File format:
774  *
775  * struct group_descs {
776  *	u32	nr_groups;
777  *	struct group_desc {
778  *		char	name[];
779  *		u32	leader_idx;
780  *		u32	nr_members;
781  *	}[nr_groups];
782  * };
783  */
784 static int write_group_desc(struct feat_fd *ff,
785 			    struct evlist *evlist)
786 {
787 	u32 nr_groups = evlist__nr_groups(evlist);
788 	struct evsel *evsel;
789 	int ret;
790 
791 	ret = do_write(ff, &nr_groups, sizeof(nr_groups));
792 	if (ret < 0)
793 		return ret;
794 
795 	evlist__for_each_entry(evlist, evsel) {
796 		if (evsel__is_group_leader(evsel) && evsel->core.nr_members > 1) {
797 			const char *name = evsel->group_name ?: "{anon_group}";
798 			u32 leader_idx = evsel->core.idx;
799 			u32 nr_members = evsel->core.nr_members;
800 
801 			ret = do_write_string(ff, name);
802 			if (ret < 0)
803 				return ret;
804 
805 			ret = do_write(ff, &leader_idx, sizeof(leader_idx));
806 			if (ret < 0)
807 				return ret;
808 
809 			ret = do_write(ff, &nr_members, sizeof(nr_members));
810 			if (ret < 0)
811 				return ret;
812 		}
813 	}
814 	return 0;
815 }
816 
817 /*
818  * Return the CPU id as a raw string.
819  *
820  * Each architecture should provide a more precise id string that
821  * can be use to match the architecture's "mapfile".
822  */
823 char * __weak get_cpuid_str(struct perf_cpu cpu __maybe_unused)
824 {
825 	return NULL;
826 }
827 
828 char *get_cpuid_allow_env_override(struct perf_cpu cpu)
829 {
830 	char *cpuid;
831 	static bool printed;
832 
833 	cpuid = getenv("PERF_CPUID");
834 	if (cpuid)
835 		cpuid = strdup(cpuid);
836 	if (!cpuid)
837 		cpuid = get_cpuid_str(cpu);
838 	if (!cpuid)
839 		return NULL;
840 
841 	if (!printed) {
842 		pr_debug("Using CPUID %s\n", cpuid);
843 		printed = true;
844 	}
845 	return cpuid;
846 }
847 
848 /* Return zero when the cpuid from the mapfile.csv matches the
849  * cpuid string generated on this platform.
850  * Otherwise return non-zero.
851  */
852 int __weak strcmp_cpuid_str(const char *mapcpuid, const char *cpuid)
853 {
854 	regex_t re;
855 	regmatch_t pmatch[1];
856 	int match;
857 
858 	if (regcomp(&re, mapcpuid, REG_EXTENDED) != 0) {
859 		/* Warn unable to generate match particular string. */
860 		pr_info("Invalid regular expression %s\n", mapcpuid);
861 		return 1;
862 	}
863 
864 	match = !regexec(&re, cpuid, 1, pmatch, 0);
865 	regfree(&re);
866 	if (match) {
867 		size_t match_len = (pmatch[0].rm_eo - pmatch[0].rm_so);
868 
869 		/* Verify the entire string matched. */
870 		if (match_len == strlen(cpuid))
871 			return 0;
872 	}
873 	return 1;
874 }
875 
876 /*
877  * default get_cpuid(): nothing gets recorded
878  * actual implementation must be in arch/$(SRCARCH)/util/header.c
879  */
880 int __weak get_cpuid(char *buffer __maybe_unused, size_t sz __maybe_unused,
881 		     struct perf_cpu cpu __maybe_unused)
882 {
883 	return ENOSYS; /* Not implemented */
884 }
885 
886 static int write_cpuid(struct feat_fd *ff, struct evlist *evlist)
887 {
888 	struct perf_cpu cpu = perf_cpu_map__min(evlist->core.all_cpus);
889 	char buffer[64];
890 	int ret;
891 
892 	ret = get_cpuid(buffer, sizeof(buffer), cpu);
893 	if (ret)
894 		return -1;
895 
896 	return do_write_string(ff, buffer);
897 }
898 
899 static int write_branch_stack(struct feat_fd *ff __maybe_unused,
900 			      struct evlist *evlist __maybe_unused)
901 {
902 	return 0;
903 }
904 
905 static int write_auxtrace(struct feat_fd *ff,
906 			  struct evlist *evlist __maybe_unused)
907 {
908 	struct perf_session *session;
909 	int err;
910 
911 	if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
912 		return -1;
913 
914 	session = container_of(ff->ph, struct perf_session, header);
915 
916 	err = auxtrace_index__write(ff->fd, &session->auxtrace_index);
917 	if (err < 0)
918 		pr_err("Failed to write auxtrace index\n");
919 	return err;
920 }
921 
922 static int write_clockid(struct feat_fd *ff,
923 			 struct evlist *evlist __maybe_unused)
924 {
925 	return do_write(ff, &ff->ph->env.clock.clockid_res_ns,
926 			sizeof(ff->ph->env.clock.clockid_res_ns));
927 }
928 
929 static int write_clock_data(struct feat_fd *ff,
930 			    struct evlist *evlist __maybe_unused)
931 {
932 	u64 *data64;
933 	u32 data32;
934 	int ret;
935 
936 	/* version */
937 	data32 = 1;
938 
939 	ret = do_write(ff, &data32, sizeof(data32));
940 	if (ret < 0)
941 		return ret;
942 
943 	/* clockid */
944 	data32 = ff->ph->env.clock.clockid;
945 
946 	ret = do_write(ff, &data32, sizeof(data32));
947 	if (ret < 0)
948 		return ret;
949 
950 	/* TOD ref time */
951 	data64 = &ff->ph->env.clock.tod_ns;
952 
953 	ret = do_write(ff, data64, sizeof(*data64));
954 	if (ret < 0)
955 		return ret;
956 
957 	/* clockid ref time */
958 	data64 = &ff->ph->env.clock.clockid_ns;
959 
960 	return do_write(ff, data64, sizeof(*data64));
961 }
962 
963 static int write_hybrid_topology(struct feat_fd *ff,
964 				 struct evlist *evlist __maybe_unused)
965 {
966 	struct hybrid_topology *tp;
967 	int ret;
968 	u32 i;
969 
970 	tp = hybrid_topology__new();
971 	if (!tp)
972 		return -ENOENT;
973 
974 	ret = do_write(ff, &tp->nr, sizeof(u32));
975 	if (ret < 0)
976 		goto err;
977 
978 	for (i = 0; i < tp->nr; i++) {
979 		struct hybrid_topology_node *n = &tp->nodes[i];
980 
981 		ret = do_write_string(ff, n->pmu_name);
982 		if (ret < 0)
983 			goto err;
984 
985 		ret = do_write_string(ff, n->cpus);
986 		if (ret < 0)
987 			goto err;
988 	}
989 
990 	ret = 0;
991 
992 err:
993 	hybrid_topology__delete(tp);
994 	return ret;
995 }
996 
997 static int write_dir_format(struct feat_fd *ff,
998 			    struct evlist *evlist __maybe_unused)
999 {
1000 	struct perf_session *session;
1001 	struct perf_data *data;
1002 
1003 	session = container_of(ff->ph, struct perf_session, header);
1004 	data = session->data;
1005 
1006 	if (WARN_ON(!perf_data__is_dir(data)))
1007 		return -1;
1008 
1009 	return do_write(ff, &data->dir.version, sizeof(data->dir.version));
1010 }
1011 
1012 #ifdef HAVE_LIBBPF_SUPPORT
1013 static int write_bpf_prog_info(struct feat_fd *ff,
1014 			       struct evlist *evlist __maybe_unused)
1015 {
1016 	struct perf_env *env = &ff->ph->env;
1017 	struct rb_root *root;
1018 	struct rb_node *next;
1019 	int ret;
1020 
1021 	down_read(&env->bpf_progs.lock);
1022 
1023 	ret = do_write(ff, &env->bpf_progs.infos_cnt,
1024 		       sizeof(env->bpf_progs.infos_cnt));
1025 	if (ret < 0)
1026 		goto out;
1027 
1028 	root = &env->bpf_progs.infos;
1029 	next = rb_first(root);
1030 	while (next) {
1031 		struct bpf_prog_info_node *node;
1032 		size_t len;
1033 
1034 		node = rb_entry(next, struct bpf_prog_info_node, rb_node);
1035 		next = rb_next(&node->rb_node);
1036 		len = sizeof(struct perf_bpil) +
1037 			node->info_linear->data_len;
1038 
1039 		/* before writing to file, translate address to offset */
1040 		bpil_addr_to_offs(node->info_linear);
1041 		ret = do_write(ff, node->info_linear, len);
1042 		/*
1043 		 * translate back to address even when do_write() fails,
1044 		 * so that this function never changes the data.
1045 		 */
1046 		bpil_offs_to_addr(node->info_linear);
1047 		if (ret < 0)
1048 			goto out;
1049 	}
1050 out:
1051 	up_read(&env->bpf_progs.lock);
1052 	return ret;
1053 }
1054 
1055 static int write_bpf_btf(struct feat_fd *ff,
1056 			 struct evlist *evlist __maybe_unused)
1057 {
1058 	struct perf_env *env = &ff->ph->env;
1059 	struct rb_root *root;
1060 	struct rb_node *next;
1061 	int ret;
1062 
1063 	down_read(&env->bpf_progs.lock);
1064 
1065 	ret = do_write(ff, &env->bpf_progs.btfs_cnt,
1066 		       sizeof(env->bpf_progs.btfs_cnt));
1067 
1068 	if (ret < 0)
1069 		goto out;
1070 
1071 	root = &env->bpf_progs.btfs;
1072 	next = rb_first(root);
1073 	while (next) {
1074 		struct btf_node *node;
1075 
1076 		node = rb_entry(next, struct btf_node, rb_node);
1077 		next = rb_next(&node->rb_node);
1078 		ret = do_write(ff, &node->id,
1079 			       sizeof(u32) * 2 + node->data_size);
1080 		if (ret < 0)
1081 			goto out;
1082 	}
1083 out:
1084 	up_read(&env->bpf_progs.lock);
1085 	return ret;
1086 }
1087 #endif // HAVE_LIBBPF_SUPPORT
1088 
1089 static int cpu_cache_level__sort(const void *a, const void *b)
1090 {
1091 	struct cpu_cache_level *cache_a = (struct cpu_cache_level *)a;
1092 	struct cpu_cache_level *cache_b = (struct cpu_cache_level *)b;
1093 
1094 	return cache_a->level - cache_b->level;
1095 }
1096 
1097 static bool cpu_cache_level__cmp(struct cpu_cache_level *a, struct cpu_cache_level *b)
1098 {
1099 	if (a->level != b->level)
1100 		return false;
1101 
1102 	if (a->line_size != b->line_size)
1103 		return false;
1104 
1105 	if (a->sets != b->sets)
1106 		return false;
1107 
1108 	if (a->ways != b->ways)
1109 		return false;
1110 
1111 	if (strcmp(a->type, b->type))
1112 		return false;
1113 
1114 	if (strcmp(a->size, b->size))
1115 		return false;
1116 
1117 	if (strcmp(a->map, b->map))
1118 		return false;
1119 
1120 	return true;
1121 }
1122 
1123 static int cpu_cache_level__read(struct cpu_cache_level *cache, u32 cpu, u16 level)
1124 {
1125 	char path[PATH_MAX], file[PATH_MAX];
1126 	struct stat st;
1127 	size_t len;
1128 
1129 	scnprintf(path, PATH_MAX, "devices/system/cpu/cpu%d/cache/index%d/", cpu, level);
1130 	scnprintf(file, PATH_MAX, "%s/%s", sysfs__mountpoint(), path);
1131 
1132 	if (stat(file, &st))
1133 		return 1;
1134 
1135 	scnprintf(file, PATH_MAX, "%s/level", path);
1136 	if (sysfs__read_int(file, (int *) &cache->level))
1137 		return -1;
1138 
1139 	scnprintf(file, PATH_MAX, "%s/coherency_line_size", path);
1140 	if (sysfs__read_int(file, (int *) &cache->line_size))
1141 		return -1;
1142 
1143 	scnprintf(file, PATH_MAX, "%s/number_of_sets", path);
1144 	if (sysfs__read_int(file, (int *) &cache->sets))
1145 		return -1;
1146 
1147 	scnprintf(file, PATH_MAX, "%s/ways_of_associativity", path);
1148 	if (sysfs__read_int(file, (int *) &cache->ways))
1149 		return -1;
1150 
1151 	scnprintf(file, PATH_MAX, "%s/type", path);
1152 	if (sysfs__read_str(file, &cache->type, &len))
1153 		return -1;
1154 
1155 	cache->type[len] = 0;
1156 	cache->type = strim(cache->type);
1157 
1158 	scnprintf(file, PATH_MAX, "%s/size", path);
1159 	if (sysfs__read_str(file, &cache->size, &len)) {
1160 		zfree(&cache->type);
1161 		return -1;
1162 	}
1163 
1164 	cache->size[len] = 0;
1165 	cache->size = strim(cache->size);
1166 
1167 	scnprintf(file, PATH_MAX, "%s/shared_cpu_list", path);
1168 	if (sysfs__read_str(file, &cache->map, &len)) {
1169 		zfree(&cache->size);
1170 		zfree(&cache->type);
1171 		return -1;
1172 	}
1173 
1174 	cache->map[len] = 0;
1175 	cache->map = strim(cache->map);
1176 	return 0;
1177 }
1178 
1179 static void cpu_cache_level__fprintf(FILE *out, struct cpu_cache_level *c)
1180 {
1181 	fprintf(out, "L%d %-15s %8s [%s]\n", c->level, c->type, c->size, c->map);
1182 }
1183 
1184 /*
1185  * Build caches levels for a particular CPU from the data in
1186  * /sys/devices/system/cpu/cpu<cpu>/cache/
1187  * The cache level data is stored in caches[] from index at
1188  * *cntp.
1189  */
1190 int build_caches_for_cpu(u32 cpu, struct cpu_cache_level caches[], u32 *cntp)
1191 {
1192 	u16 level;
1193 
1194 	for (level = 0; level < MAX_CACHE_LVL; level++) {
1195 		struct cpu_cache_level c;
1196 		int err;
1197 		u32 i;
1198 
1199 		err = cpu_cache_level__read(&c, cpu, level);
1200 		if (err < 0)
1201 			return err;
1202 
1203 		if (err == 1)
1204 			break;
1205 
1206 		for (i = 0; i < *cntp; i++) {
1207 			if (cpu_cache_level__cmp(&c, &caches[i]))
1208 				break;
1209 		}
1210 
1211 		if (i == *cntp) {
1212 			caches[*cntp] = c;
1213 			*cntp = *cntp + 1;
1214 		} else
1215 			cpu_cache_level__free(&c);
1216 	}
1217 
1218 	return 0;
1219 }
1220 
1221 static int build_caches(struct cpu_cache_level caches[], u32 *cntp)
1222 {
1223 	u32 nr, cpu, cnt = 0;
1224 
1225 	nr = cpu__max_cpu().cpu;
1226 
1227 	for (cpu = 0; cpu < nr; cpu++) {
1228 		int ret = build_caches_for_cpu(cpu, caches, &cnt);
1229 
1230 		if (ret)
1231 			return ret;
1232 	}
1233 	*cntp = cnt;
1234 	return 0;
1235 }
1236 
1237 static int write_cache(struct feat_fd *ff,
1238 		       struct evlist *evlist __maybe_unused)
1239 {
1240 	u32 max_caches = cpu__max_cpu().cpu * MAX_CACHE_LVL;
1241 	struct cpu_cache_level caches[max_caches];
1242 	u32 cnt = 0, i, version = 1;
1243 	int ret;
1244 
1245 	ret = build_caches(caches, &cnt);
1246 	if (ret)
1247 		goto out;
1248 
1249 	qsort(&caches, cnt, sizeof(struct cpu_cache_level), cpu_cache_level__sort);
1250 
1251 	ret = do_write(ff, &version, sizeof(u32));
1252 	if (ret < 0)
1253 		goto out;
1254 
1255 	ret = do_write(ff, &cnt, sizeof(u32));
1256 	if (ret < 0)
1257 		goto out;
1258 
1259 	for (i = 0; i < cnt; i++) {
1260 		struct cpu_cache_level *c = &caches[i];
1261 
1262 		#define _W(v)					\
1263 			ret = do_write(ff, &c->v, sizeof(u32));	\
1264 			if (ret < 0)				\
1265 				goto out;
1266 
1267 		_W(level)
1268 		_W(line_size)
1269 		_W(sets)
1270 		_W(ways)
1271 		#undef _W
1272 
1273 		#define _W(v)						\
1274 			ret = do_write_string(ff, (const char *) c->v);	\
1275 			if (ret < 0)					\
1276 				goto out;
1277 
1278 		_W(type)
1279 		_W(size)
1280 		_W(map)
1281 		#undef _W
1282 	}
1283 
1284 out:
1285 	for (i = 0; i < cnt; i++)
1286 		cpu_cache_level__free(&caches[i]);
1287 	return ret;
1288 }
1289 
1290 static int write_stat(struct feat_fd *ff __maybe_unused,
1291 		      struct evlist *evlist __maybe_unused)
1292 {
1293 	return 0;
1294 }
1295 
1296 static int write_sample_time(struct feat_fd *ff,
1297 			     struct evlist *evlist)
1298 {
1299 	int ret;
1300 
1301 	ret = do_write(ff, &evlist->first_sample_time,
1302 		       sizeof(evlist->first_sample_time));
1303 	if (ret < 0)
1304 		return ret;
1305 
1306 	return do_write(ff, &evlist->last_sample_time,
1307 			sizeof(evlist->last_sample_time));
1308 }
1309 
1310 
1311 static int memory_node__read(struct memory_node *n, unsigned long idx)
1312 {
1313 	unsigned int phys, size = 0;
1314 	char path[PATH_MAX];
1315 	struct io_dirent64 *ent;
1316 	struct io_dir dir;
1317 
1318 #define for_each_memory(mem, dir)					\
1319 	while ((ent = io_dir__readdir(&dir)) != NULL)			\
1320 		if (strcmp(ent->d_name, ".") &&				\
1321 		    strcmp(ent->d_name, "..") &&			\
1322 		    sscanf(ent->d_name, "memory%u", &mem) == 1)
1323 
1324 	scnprintf(path, PATH_MAX,
1325 		  "%s/devices/system/node/node%lu",
1326 		  sysfs__mountpoint(), idx);
1327 
1328 	io_dir__init(&dir, open(path, O_CLOEXEC | O_DIRECTORY | O_RDONLY));
1329 	if (dir.dirfd < 0) {
1330 		pr_warning("failed: can't open memory sysfs data '%s'\n", path);
1331 		return -1;
1332 	}
1333 
1334 	for_each_memory(phys, dir) {
1335 		size = max(phys, size);
1336 	}
1337 
1338 	size++;
1339 
1340 	n->set = bitmap_zalloc(size);
1341 	if (!n->set) {
1342 		close(dir.dirfd);
1343 		return -ENOMEM;
1344 	}
1345 
1346 	n->node = idx;
1347 	n->size = size;
1348 
1349 	io_dir__rewinddir(&dir);
1350 
1351 	for_each_memory(phys, dir) {
1352 		__set_bit(phys, n->set);
1353 	}
1354 
1355 	close(dir.dirfd);
1356 	return 0;
1357 }
1358 
1359 static void memory_node__delete_nodes(struct memory_node *nodesp, u64 cnt)
1360 {
1361 	for (u64 i = 0; i < cnt; i++)
1362 		bitmap_free(nodesp[i].set);
1363 
1364 	free(nodesp);
1365 }
1366 
1367 static int memory_node__sort(const void *a, const void *b)
1368 {
1369 	const struct memory_node *na = a;
1370 	const struct memory_node *nb = b;
1371 
1372 	return na->node - nb->node;
1373 }
1374 
1375 static int build_mem_topology(struct memory_node **nodesp, u64 *cntp)
1376 {
1377 	char path[PATH_MAX];
1378 	struct io_dirent64 *ent;
1379 	struct io_dir dir;
1380 	int ret = 0;
1381 	size_t cnt = 0, size = 0;
1382 	struct memory_node *nodes = NULL;
1383 
1384 	scnprintf(path, PATH_MAX, "%s/devices/system/node/",
1385 		  sysfs__mountpoint());
1386 
1387 	io_dir__init(&dir, open(path, O_CLOEXEC | O_DIRECTORY | O_RDONLY));
1388 	if (dir.dirfd < 0) {
1389 		pr_debug2("%s: couldn't read %s, does this arch have topology information?\n",
1390 			  __func__, path);
1391 		return -1;
1392 	}
1393 
1394 	while (!ret && (ent = io_dir__readdir(&dir))) {
1395 		unsigned int idx;
1396 		int r;
1397 
1398 		if (!strcmp(ent->d_name, ".") ||
1399 		    !strcmp(ent->d_name, ".."))
1400 			continue;
1401 
1402 		r = sscanf(ent->d_name, "node%u", &idx);
1403 		if (r != 1)
1404 			continue;
1405 
1406 		if (cnt >= size) {
1407 			struct memory_node *new_nodes =
1408 				reallocarray(nodes, cnt + 4, sizeof(*nodes));
1409 
1410 			if (!new_nodes) {
1411 				pr_err("Failed to write MEM_TOPOLOGY, size %zd nodes\n", size);
1412 				ret = -ENOMEM;
1413 				goto out;
1414 			}
1415 			nodes = new_nodes;
1416 			size += 4;
1417 		}
1418 		ret = memory_node__read(&nodes[cnt], idx);
1419 		if (!ret)
1420 			cnt += 1;
1421 	}
1422 out:
1423 	close(dir.dirfd);
1424 	if (!ret) {
1425 		*cntp = cnt;
1426 		*nodesp = nodes;
1427 		qsort(nodes, cnt, sizeof(nodes[0]), memory_node__sort);
1428 	} else
1429 		memory_node__delete_nodes(nodes, cnt);
1430 
1431 	return ret;
1432 }
1433 
1434 /*
1435  * The MEM_TOPOLOGY holds physical memory map for every
1436  * node in system. The format of data is as follows:
1437  *
1438  *  0 - version          | for future changes
1439  *  8 - block_size_bytes | /sys/devices/system/memory/block_size_bytes
1440  * 16 - count            | number of nodes
1441  *
1442  * For each node we store map of physical indexes for
1443  * each node:
1444  *
1445  * 32 - node id          | node index
1446  * 40 - size             | size of bitmap
1447  * 48 - bitmap           | bitmap of memory indexes that belongs to node
1448  */
1449 static int write_mem_topology(struct feat_fd *ff __maybe_unused,
1450 			      struct evlist *evlist __maybe_unused)
1451 {
1452 	struct memory_node *nodes = NULL;
1453 	u64 bsize, version = 1, i, nr = 0;
1454 	int ret;
1455 
1456 	ret = sysfs__read_xll("devices/system/memory/block_size_bytes",
1457 			      (unsigned long long *) &bsize);
1458 	if (ret)
1459 		return ret;
1460 
1461 	ret = build_mem_topology(&nodes, &nr);
1462 	if (ret)
1463 		return ret;
1464 
1465 	ret = do_write(ff, &version, sizeof(version));
1466 	if (ret < 0)
1467 		goto out;
1468 
1469 	ret = do_write(ff, &bsize, sizeof(bsize));
1470 	if (ret < 0)
1471 		goto out;
1472 
1473 	ret = do_write(ff, &nr, sizeof(nr));
1474 	if (ret < 0)
1475 		goto out;
1476 
1477 	for (i = 0; i < nr; i++) {
1478 		struct memory_node *n = &nodes[i];
1479 
1480 		#define _W(v)						\
1481 			ret = do_write(ff, &n->v, sizeof(n->v));	\
1482 			if (ret < 0)					\
1483 				goto out;
1484 
1485 		_W(node)
1486 		_W(size)
1487 
1488 		#undef _W
1489 
1490 		ret = do_write_bitmap(ff, n->set, n->size);
1491 		if (ret < 0)
1492 			goto out;
1493 	}
1494 
1495 out:
1496 	memory_node__delete_nodes(nodes, nr);
1497 	return ret;
1498 }
1499 
1500 static int write_compressed(struct feat_fd *ff __maybe_unused,
1501 			    struct evlist *evlist __maybe_unused)
1502 {
1503 	int ret;
1504 
1505 	ret = do_write(ff, &(ff->ph->env.comp_ver), sizeof(ff->ph->env.comp_ver));
1506 	if (ret)
1507 		return ret;
1508 
1509 	ret = do_write(ff, &(ff->ph->env.comp_type), sizeof(ff->ph->env.comp_type));
1510 	if (ret)
1511 		return ret;
1512 
1513 	ret = do_write(ff, &(ff->ph->env.comp_level), sizeof(ff->ph->env.comp_level));
1514 	if (ret)
1515 		return ret;
1516 
1517 	ret = do_write(ff, &(ff->ph->env.comp_ratio), sizeof(ff->ph->env.comp_ratio));
1518 	if (ret)
1519 		return ret;
1520 
1521 	return do_write(ff, &(ff->ph->env.comp_mmap_len), sizeof(ff->ph->env.comp_mmap_len));
1522 }
1523 
1524 static int __write_pmu_caps(struct feat_fd *ff, struct perf_pmu *pmu,
1525 			    bool write_pmu)
1526 {
1527 	struct perf_pmu_caps *caps = NULL;
1528 	int ret;
1529 
1530 	ret = do_write(ff, &pmu->nr_caps, sizeof(pmu->nr_caps));
1531 	if (ret < 0)
1532 		return ret;
1533 
1534 	list_for_each_entry(caps, &pmu->caps, list) {
1535 		ret = do_write_string(ff, caps->name);
1536 		if (ret < 0)
1537 			return ret;
1538 
1539 		ret = do_write_string(ff, caps->value);
1540 		if (ret < 0)
1541 			return ret;
1542 	}
1543 
1544 	if (write_pmu) {
1545 		ret = do_write_string(ff, pmu->name);
1546 		if (ret < 0)
1547 			return ret;
1548 	}
1549 
1550 	return ret;
1551 }
1552 
1553 static int write_cpu_pmu_caps(struct feat_fd *ff,
1554 			      struct evlist *evlist __maybe_unused)
1555 {
1556 	struct perf_pmu *cpu_pmu = perf_pmus__find("cpu");
1557 	int ret;
1558 
1559 	if (!cpu_pmu)
1560 		return -ENOENT;
1561 
1562 	ret = perf_pmu__caps_parse(cpu_pmu);
1563 	if (ret < 0)
1564 		return ret;
1565 
1566 	return __write_pmu_caps(ff, cpu_pmu, false);
1567 }
1568 
1569 static int write_pmu_caps(struct feat_fd *ff,
1570 			  struct evlist *evlist __maybe_unused)
1571 {
1572 	struct perf_pmu *pmu = NULL;
1573 	int nr_pmu = 0;
1574 	int ret;
1575 
1576 	while ((pmu = perf_pmus__scan(pmu))) {
1577 		if (!strcmp(pmu->name, "cpu")) {
1578 			/*
1579 			 * The "cpu" PMU is special and covered by
1580 			 * HEADER_CPU_PMU_CAPS. Note, core PMUs are
1581 			 * counted/written here for ARM, s390 and Intel hybrid.
1582 			 */
1583 			continue;
1584 		}
1585 		if (perf_pmu__caps_parse(pmu) <= 0)
1586 			continue;
1587 		nr_pmu++;
1588 	}
1589 
1590 	ret = do_write(ff, &nr_pmu, sizeof(nr_pmu));
1591 	if (ret < 0)
1592 		return ret;
1593 
1594 	if (!nr_pmu)
1595 		return 0;
1596 
1597 	/*
1598 	 * Note older perf tools assume core PMUs come first, this is a property
1599 	 * of perf_pmus__scan.
1600 	 */
1601 	pmu = NULL;
1602 	while ((pmu = perf_pmus__scan(pmu))) {
1603 		if (!strcmp(pmu->name, "cpu")) {
1604 			/* Skip as above. */
1605 			continue;
1606 		}
1607 		if (perf_pmu__caps_parse(pmu) <= 0)
1608 			continue;
1609 		ret = __write_pmu_caps(ff, pmu, true);
1610 		if (ret < 0)
1611 			return ret;
1612 	}
1613 	return 0;
1614 }
1615 
1616 static void print_hostname(struct feat_fd *ff, FILE *fp)
1617 {
1618 	fprintf(fp, "# hostname : %s\n", ff->ph->env.hostname);
1619 }
1620 
1621 static void print_osrelease(struct feat_fd *ff, FILE *fp)
1622 {
1623 	fprintf(fp, "# os release : %s\n", ff->ph->env.os_release);
1624 }
1625 
1626 static void print_arch(struct feat_fd *ff, FILE *fp)
1627 {
1628 	fprintf(fp, "# arch : %s\n", ff->ph->env.arch);
1629 }
1630 
1631 static void print_cpudesc(struct feat_fd *ff, FILE *fp)
1632 {
1633 	fprintf(fp, "# cpudesc : %s\n", ff->ph->env.cpu_desc);
1634 }
1635 
1636 static void print_nrcpus(struct feat_fd *ff, FILE *fp)
1637 {
1638 	fprintf(fp, "# nrcpus online : %u\n", ff->ph->env.nr_cpus_online);
1639 	fprintf(fp, "# nrcpus avail : %u\n", ff->ph->env.nr_cpus_avail);
1640 }
1641 
1642 static void print_version(struct feat_fd *ff, FILE *fp)
1643 {
1644 	fprintf(fp, "# perf version : %s\n", ff->ph->env.version);
1645 }
1646 
1647 static void print_cmdline(struct feat_fd *ff, FILE *fp)
1648 {
1649 	int nr, i;
1650 
1651 	nr = ff->ph->env.nr_cmdline;
1652 
1653 	fprintf(fp, "# cmdline : ");
1654 
1655 	for (i = 0; i < nr; i++) {
1656 		char *argv_i = strdup(ff->ph->env.cmdline_argv[i]);
1657 		if (!argv_i) {
1658 			fprintf(fp, "%s ", ff->ph->env.cmdline_argv[i]);
1659 		} else {
1660 			char *mem = argv_i;
1661 			do {
1662 				char *quote = strchr(argv_i, '\'');
1663 				if (!quote)
1664 					break;
1665 				*quote++ = '\0';
1666 				fprintf(fp, "%s\\\'", argv_i);
1667 				argv_i = quote;
1668 			} while (1);
1669 			fprintf(fp, "%s ", argv_i);
1670 			free(mem);
1671 		}
1672 	}
1673 	fputc('\n', fp);
1674 }
1675 
1676 static void print_cpu_topology(struct feat_fd *ff, FILE *fp)
1677 {
1678 	struct perf_header *ph = ff->ph;
1679 	int cpu_nr = ph->env.nr_cpus_avail;
1680 	int nr, i;
1681 	char *str;
1682 
1683 	nr = ph->env.nr_sibling_cores;
1684 	str = ph->env.sibling_cores;
1685 
1686 	for (i = 0; i < nr; i++) {
1687 		fprintf(fp, "# sibling sockets : %s\n", str);
1688 		str += strlen(str) + 1;
1689 	}
1690 
1691 	if (ph->env.nr_sibling_dies) {
1692 		nr = ph->env.nr_sibling_dies;
1693 		str = ph->env.sibling_dies;
1694 
1695 		for (i = 0; i < nr; i++) {
1696 			fprintf(fp, "# sibling dies    : %s\n", str);
1697 			str += strlen(str) + 1;
1698 		}
1699 	}
1700 
1701 	nr = ph->env.nr_sibling_threads;
1702 	str = ph->env.sibling_threads;
1703 
1704 	for (i = 0; i < nr; i++) {
1705 		fprintf(fp, "# sibling threads : %s\n", str);
1706 		str += strlen(str) + 1;
1707 	}
1708 
1709 	if (ph->env.nr_sibling_dies) {
1710 		if (ph->env.cpu != NULL) {
1711 			for (i = 0; i < cpu_nr; i++)
1712 				fprintf(fp, "# CPU %d: Core ID %d, "
1713 					    "Die ID %d, Socket ID %d\n",
1714 					    i, ph->env.cpu[i].core_id,
1715 					    ph->env.cpu[i].die_id,
1716 					    ph->env.cpu[i].socket_id);
1717 		} else
1718 			fprintf(fp, "# Core ID, Die ID and Socket ID "
1719 				    "information is not available\n");
1720 	} else {
1721 		if (ph->env.cpu != NULL) {
1722 			for (i = 0; i < cpu_nr; i++)
1723 				fprintf(fp, "# CPU %d: Core ID %d, "
1724 					    "Socket ID %d\n",
1725 					    i, ph->env.cpu[i].core_id,
1726 					    ph->env.cpu[i].socket_id);
1727 		} else
1728 			fprintf(fp, "# Core ID and Socket ID "
1729 				    "information is not available\n");
1730 	}
1731 }
1732 
1733 static void print_clockid(struct feat_fd *ff, FILE *fp)
1734 {
1735 	fprintf(fp, "# clockid frequency: %"PRIu64" MHz\n",
1736 		ff->ph->env.clock.clockid_res_ns * 1000);
1737 }
1738 
1739 static void print_clock_data(struct feat_fd *ff, FILE *fp)
1740 {
1741 	struct timespec clockid_ns;
1742 	char tstr[64], date[64];
1743 	struct timeval tod_ns;
1744 	clockid_t clockid;
1745 	struct tm ltime;
1746 	u64 ref;
1747 
1748 	if (!ff->ph->env.clock.enabled) {
1749 		fprintf(fp, "# reference time disabled\n");
1750 		return;
1751 	}
1752 
1753 	/* Compute TOD time. */
1754 	ref = ff->ph->env.clock.tod_ns;
1755 	tod_ns.tv_sec = ref / NSEC_PER_SEC;
1756 	ref -= tod_ns.tv_sec * NSEC_PER_SEC;
1757 	tod_ns.tv_usec = ref / NSEC_PER_USEC;
1758 
1759 	/* Compute clockid time. */
1760 	ref = ff->ph->env.clock.clockid_ns;
1761 	clockid_ns.tv_sec = ref / NSEC_PER_SEC;
1762 	ref -= clockid_ns.tv_sec * NSEC_PER_SEC;
1763 	clockid_ns.tv_nsec = ref;
1764 
1765 	clockid = ff->ph->env.clock.clockid;
1766 
1767 	if (localtime_r(&tod_ns.tv_sec, &ltime) == NULL)
1768 		snprintf(tstr, sizeof(tstr), "<error>");
1769 	else {
1770 		strftime(date, sizeof(date), "%F %T", &ltime);
1771 		scnprintf(tstr, sizeof(tstr), "%s.%06d",
1772 			  date, (int) tod_ns.tv_usec);
1773 	}
1774 
1775 	fprintf(fp, "# clockid: %s (%u)\n", clockid_name(clockid), clockid);
1776 	fprintf(fp, "# reference time: %s = %ld.%06d (TOD) = %ld.%09ld (%s)\n",
1777 		    tstr, (long) tod_ns.tv_sec, (int) tod_ns.tv_usec,
1778 		    (long) clockid_ns.tv_sec, clockid_ns.tv_nsec,
1779 		    clockid_name(clockid));
1780 }
1781 
1782 static void print_hybrid_topology(struct feat_fd *ff, FILE *fp)
1783 {
1784 	int i;
1785 	struct hybrid_node *n;
1786 
1787 	fprintf(fp, "# hybrid cpu system:\n");
1788 	for (i = 0; i < ff->ph->env.nr_hybrid_nodes; i++) {
1789 		n = &ff->ph->env.hybrid_nodes[i];
1790 		fprintf(fp, "# %s cpu list : %s\n", n->pmu_name, n->cpus);
1791 	}
1792 }
1793 
1794 static void print_dir_format(struct feat_fd *ff, FILE *fp)
1795 {
1796 	struct perf_session *session;
1797 	struct perf_data *data;
1798 
1799 	session = container_of(ff->ph, struct perf_session, header);
1800 	data = session->data;
1801 
1802 	fprintf(fp, "# directory data version : %"PRIu64"\n", data->dir.version);
1803 }
1804 
1805 #ifdef HAVE_LIBBPF_SUPPORT
1806 static void print_bpf_prog_info(struct feat_fd *ff, FILE *fp)
1807 {
1808 	struct perf_env *env = &ff->ph->env;
1809 	struct rb_root *root;
1810 	struct rb_node *next;
1811 
1812 	down_read(&env->bpf_progs.lock);
1813 
1814 	root = &env->bpf_progs.infos;
1815 	next = rb_first(root);
1816 
1817 	while (next) {
1818 		struct bpf_prog_info_node *node;
1819 
1820 		node = rb_entry(next, struct bpf_prog_info_node, rb_node);
1821 		next = rb_next(&node->rb_node);
1822 
1823 		__bpf_event__print_bpf_prog_info(&node->info_linear->info,
1824 						 env, fp);
1825 	}
1826 
1827 	up_read(&env->bpf_progs.lock);
1828 }
1829 
1830 static void print_bpf_btf(struct feat_fd *ff, FILE *fp)
1831 {
1832 	struct perf_env *env = &ff->ph->env;
1833 	struct rb_root *root;
1834 	struct rb_node *next;
1835 
1836 	down_read(&env->bpf_progs.lock);
1837 
1838 	root = &env->bpf_progs.btfs;
1839 	next = rb_first(root);
1840 
1841 	while (next) {
1842 		struct btf_node *node;
1843 
1844 		node = rb_entry(next, struct btf_node, rb_node);
1845 		next = rb_next(&node->rb_node);
1846 		fprintf(fp, "# btf info of id %u\n", node->id);
1847 	}
1848 
1849 	up_read(&env->bpf_progs.lock);
1850 }
1851 #endif // HAVE_LIBBPF_SUPPORT
1852 
1853 static void free_event_desc(struct evsel *events)
1854 {
1855 	struct evsel *evsel;
1856 
1857 	if (!events)
1858 		return;
1859 
1860 	for (evsel = events; evsel->core.attr.size; evsel++) {
1861 		zfree(&evsel->name);
1862 		zfree(&evsel->core.id);
1863 	}
1864 
1865 	free(events);
1866 }
1867 
1868 static bool perf_attr_check(struct perf_event_attr *attr)
1869 {
1870 	if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3) {
1871 		pr_warning("Reserved bits are set unexpectedly. "
1872 			   "Please update perf tool.\n");
1873 		return false;
1874 	}
1875 
1876 	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) {
1877 		pr_warning("Unknown sample type (0x%llx) is detected. "
1878 			   "Please update perf tool.\n",
1879 			   attr->sample_type);
1880 		return false;
1881 	}
1882 
1883 	if (attr->read_format & ~(PERF_FORMAT_MAX-1)) {
1884 		pr_warning("Unknown read format (0x%llx) is detected. "
1885 			   "Please update perf tool.\n",
1886 			   attr->read_format);
1887 		return false;
1888 	}
1889 
1890 	if ((attr->sample_type & PERF_SAMPLE_BRANCH_STACK) &&
1891 	    (attr->branch_sample_type & ~(PERF_SAMPLE_BRANCH_MAX-1))) {
1892 		pr_warning("Unknown branch sample type (0x%llx) is detected. "
1893 			   "Please update perf tool.\n",
1894 			   attr->branch_sample_type);
1895 
1896 		return false;
1897 	}
1898 
1899 	return true;
1900 }
1901 
1902 static struct evsel *read_event_desc(struct feat_fd *ff)
1903 {
1904 	struct evsel *evsel, *events = NULL;
1905 	u64 *id;
1906 	void *buf = NULL;
1907 	u32 nre, sz, nr, i, j;
1908 	size_t msz;
1909 
1910 	/* number of events */
1911 	if (do_read_u32(ff, &nre))
1912 		goto error;
1913 
1914 	if (do_read_u32(ff, &sz))
1915 		goto error;
1916 
1917 	/* buffer to hold on file attr struct */
1918 	buf = malloc(sz);
1919 	if (!buf)
1920 		goto error;
1921 
1922 	/* the last event terminates with evsel->core.attr.size == 0: */
1923 	events = calloc(nre + 1, sizeof(*events));
1924 	if (!events)
1925 		goto error;
1926 
1927 	msz = sizeof(evsel->core.attr);
1928 	if (sz < msz)
1929 		msz = sz;
1930 
1931 	for (i = 0, evsel = events; i < nre; evsel++, i++) {
1932 		evsel->core.idx = i;
1933 
1934 		/*
1935 		 * must read entire on-file attr struct to
1936 		 * sync up with layout.
1937 		 */
1938 		if (__do_read(ff, buf, sz))
1939 			goto error;
1940 
1941 		if (ff->ph->needs_swap)
1942 			perf_event__attr_swap(buf);
1943 
1944 		memcpy(&evsel->core.attr, buf, msz);
1945 
1946 		if (!perf_attr_check(&evsel->core.attr))
1947 			goto error;
1948 
1949 		if (do_read_u32(ff, &nr))
1950 			goto error;
1951 
1952 		if (ff->ph->needs_swap)
1953 			evsel->needs_swap = true;
1954 
1955 		evsel->name = do_read_string(ff);
1956 		if (!evsel->name)
1957 			goto error;
1958 
1959 		if (!nr)
1960 			continue;
1961 
1962 		id = calloc(nr, sizeof(*id));
1963 		if (!id)
1964 			goto error;
1965 		evsel->core.ids = nr;
1966 		evsel->core.id = id;
1967 
1968 		for (j = 0 ; j < nr; j++) {
1969 			if (do_read_u64(ff, id))
1970 				goto error;
1971 			id++;
1972 		}
1973 	}
1974 out:
1975 	free(buf);
1976 	return events;
1977 error:
1978 	free_event_desc(events);
1979 	events = NULL;
1980 	goto out;
1981 }
1982 
1983 static int __desc_attr__fprintf(FILE *fp, const char *name, const char *val,
1984 				void *priv __maybe_unused)
1985 {
1986 	return fprintf(fp, ", %s = %s", name, val);
1987 }
1988 
1989 static void print_event_desc(struct feat_fd *ff, FILE *fp)
1990 {
1991 	struct evsel *evsel, *events;
1992 	u32 j;
1993 	u64 *id;
1994 
1995 	if (ff->events)
1996 		events = ff->events;
1997 	else
1998 		events = read_event_desc(ff);
1999 
2000 	if (!events) {
2001 		fprintf(fp, "# event desc: not available or unable to read\n");
2002 		return;
2003 	}
2004 
2005 	for (evsel = events; evsel->core.attr.size; evsel++) {
2006 		fprintf(fp, "# event : name = %s, ", evsel->name);
2007 
2008 		if (evsel->core.ids) {
2009 			fprintf(fp, ", id = {");
2010 			for (j = 0, id = evsel->core.id; j < evsel->core.ids; j++, id++) {
2011 				if (j)
2012 					fputc(',', fp);
2013 				fprintf(fp, " %"PRIu64, *id);
2014 			}
2015 			fprintf(fp, " }");
2016 		}
2017 
2018 		perf_event_attr__fprintf(fp, &evsel->core.attr, __desc_attr__fprintf, NULL);
2019 
2020 		fputc('\n', fp);
2021 	}
2022 
2023 	free_event_desc(events);
2024 	ff->events = NULL;
2025 }
2026 
2027 static void print_total_mem(struct feat_fd *ff, FILE *fp)
2028 {
2029 	fprintf(fp, "# total memory : %llu kB\n", ff->ph->env.total_mem);
2030 }
2031 
2032 static void print_numa_topology(struct feat_fd *ff, FILE *fp)
2033 {
2034 	int i;
2035 	struct numa_node *n;
2036 
2037 	for (i = 0; i < ff->ph->env.nr_numa_nodes; i++) {
2038 		n = &ff->ph->env.numa_nodes[i];
2039 
2040 		fprintf(fp, "# node%u meminfo  : total = %"PRIu64" kB,"
2041 			    " free = %"PRIu64" kB\n",
2042 			n->node, n->mem_total, n->mem_free);
2043 
2044 		fprintf(fp, "# node%u cpu list : ", n->node);
2045 		cpu_map__fprintf(n->map, fp);
2046 	}
2047 }
2048 
2049 static void print_cpuid(struct feat_fd *ff, FILE *fp)
2050 {
2051 	fprintf(fp, "# cpuid : %s\n", ff->ph->env.cpuid);
2052 }
2053 
2054 static void print_branch_stack(struct feat_fd *ff __maybe_unused, FILE *fp)
2055 {
2056 	fprintf(fp, "# contains samples with branch stack\n");
2057 }
2058 
2059 static void print_auxtrace(struct feat_fd *ff __maybe_unused, FILE *fp)
2060 {
2061 	fprintf(fp, "# contains AUX area data (e.g. instruction trace)\n");
2062 }
2063 
2064 static void print_stat(struct feat_fd *ff __maybe_unused, FILE *fp)
2065 {
2066 	fprintf(fp, "# contains stat data\n");
2067 }
2068 
2069 static void print_cache(struct feat_fd *ff, FILE *fp __maybe_unused)
2070 {
2071 	int i;
2072 
2073 	fprintf(fp, "# CPU cache info:\n");
2074 	for (i = 0; i < ff->ph->env.caches_cnt; i++) {
2075 		fprintf(fp, "#  ");
2076 		cpu_cache_level__fprintf(fp, &ff->ph->env.caches[i]);
2077 	}
2078 }
2079 
2080 static void print_compressed(struct feat_fd *ff, FILE *fp)
2081 {
2082 	fprintf(fp, "# compressed : %s, level = %d, ratio = %d\n",
2083 		ff->ph->env.comp_type == PERF_COMP_ZSTD ? "Zstd" : "Unknown",
2084 		ff->ph->env.comp_level, ff->ph->env.comp_ratio);
2085 }
2086 
2087 static void __print_pmu_caps(FILE *fp, int nr_caps, char **caps, char *pmu_name)
2088 {
2089 	const char *delimiter = "";
2090 	int i;
2091 
2092 	if (!nr_caps) {
2093 		fprintf(fp, "# %s pmu capabilities: not available\n", pmu_name);
2094 		return;
2095 	}
2096 
2097 	fprintf(fp, "# %s pmu capabilities: ", pmu_name);
2098 	for (i = 0; i < nr_caps; i++) {
2099 		fprintf(fp, "%s%s", delimiter, caps[i]);
2100 		delimiter = ", ";
2101 	}
2102 
2103 	fprintf(fp, "\n");
2104 }
2105 
2106 static void print_cpu_pmu_caps(struct feat_fd *ff, FILE *fp)
2107 {
2108 	__print_pmu_caps(fp, ff->ph->env.nr_cpu_pmu_caps,
2109 			 ff->ph->env.cpu_pmu_caps, (char *)"cpu");
2110 }
2111 
2112 static void print_pmu_caps(struct feat_fd *ff, FILE *fp)
2113 {
2114 	struct pmu_caps *pmu_caps;
2115 
2116 	for (int i = 0; i < ff->ph->env.nr_pmus_with_caps; i++) {
2117 		pmu_caps = &ff->ph->env.pmu_caps[i];
2118 		__print_pmu_caps(fp, pmu_caps->nr_caps, pmu_caps->caps,
2119 				 pmu_caps->pmu_name);
2120 	}
2121 
2122 	if (strcmp(perf_env__arch(&ff->ph->env), "x86") == 0 &&
2123 	    perf_env__has_pmu_mapping(&ff->ph->env, "ibs_op")) {
2124 		char *max_precise = perf_env__find_pmu_cap(&ff->ph->env, "cpu", "max_precise");
2125 
2126 		if (max_precise != NULL && atoi(max_precise) == 0)
2127 			fprintf(fp, "# AMD systems uses ibs_op// PMU for some precise events, e.g.: cycles:p, see the 'perf list' man page for further details.\n");
2128 	}
2129 }
2130 
2131 static void print_pmu_mappings(struct feat_fd *ff, FILE *fp)
2132 {
2133 	const char *delimiter = "# pmu mappings: ";
2134 	char *str, *tmp;
2135 	u32 pmu_num;
2136 	u32 type;
2137 
2138 	pmu_num = ff->ph->env.nr_pmu_mappings;
2139 	if (!pmu_num) {
2140 		fprintf(fp, "# pmu mappings: not available\n");
2141 		return;
2142 	}
2143 
2144 	str = ff->ph->env.pmu_mappings;
2145 
2146 	while (pmu_num) {
2147 		type = strtoul(str, &tmp, 0);
2148 		if (*tmp != ':')
2149 			goto error;
2150 
2151 		str = tmp + 1;
2152 		fprintf(fp, "%s%s = %" PRIu32, delimiter, str, type);
2153 
2154 		delimiter = ", ";
2155 		str += strlen(str) + 1;
2156 		pmu_num--;
2157 	}
2158 
2159 	fprintf(fp, "\n");
2160 
2161 	if (!pmu_num)
2162 		return;
2163 error:
2164 	fprintf(fp, "# pmu mappings: unable to read\n");
2165 }
2166 
2167 static void print_group_desc(struct feat_fd *ff, FILE *fp)
2168 {
2169 	struct perf_session *session;
2170 	struct evsel *evsel;
2171 	u32 nr = 0;
2172 
2173 	session = container_of(ff->ph, struct perf_session, header);
2174 
2175 	evlist__for_each_entry(session->evlist, evsel) {
2176 		if (evsel__is_group_leader(evsel) && evsel->core.nr_members > 1) {
2177 			fprintf(fp, "# group: %s{%s", evsel->group_name ?: "", evsel__name(evsel));
2178 
2179 			nr = evsel->core.nr_members - 1;
2180 		} else if (nr) {
2181 			fprintf(fp, ",%s", evsel__name(evsel));
2182 
2183 			if (--nr == 0)
2184 				fprintf(fp, "}\n");
2185 		}
2186 	}
2187 }
2188 
2189 static void print_sample_time(struct feat_fd *ff, FILE *fp)
2190 {
2191 	struct perf_session *session;
2192 	char time_buf[32];
2193 	double d;
2194 
2195 	session = container_of(ff->ph, struct perf_session, header);
2196 
2197 	timestamp__scnprintf_usec(session->evlist->first_sample_time,
2198 				  time_buf, sizeof(time_buf));
2199 	fprintf(fp, "# time of first sample : %s\n", time_buf);
2200 
2201 	timestamp__scnprintf_usec(session->evlist->last_sample_time,
2202 				  time_buf, sizeof(time_buf));
2203 	fprintf(fp, "# time of last sample : %s\n", time_buf);
2204 
2205 	d = (double)(session->evlist->last_sample_time -
2206 		session->evlist->first_sample_time) / NSEC_PER_MSEC;
2207 
2208 	fprintf(fp, "# sample duration : %10.3f ms\n", d);
2209 }
2210 
2211 static void memory_node__fprintf(struct memory_node *n,
2212 				 unsigned long long bsize, FILE *fp)
2213 {
2214 	char buf_map[100], buf_size[50];
2215 	unsigned long long size;
2216 
2217 	size = bsize * bitmap_weight(n->set, n->size);
2218 	unit_number__scnprintf(buf_size, 50, size);
2219 
2220 	bitmap_scnprintf(n->set, n->size, buf_map, 100);
2221 	fprintf(fp, "#  %3" PRIu64 " [%s]: %s\n", n->node, buf_size, buf_map);
2222 }
2223 
2224 static void print_mem_topology(struct feat_fd *ff, FILE *fp)
2225 {
2226 	struct memory_node *nodes;
2227 	int i, nr;
2228 
2229 	nodes = ff->ph->env.memory_nodes;
2230 	nr    = ff->ph->env.nr_memory_nodes;
2231 
2232 	fprintf(fp, "# memory nodes (nr %d, block size 0x%llx):\n",
2233 		nr, ff->ph->env.memory_bsize);
2234 
2235 	for (i = 0; i < nr; i++) {
2236 		memory_node__fprintf(&nodes[i], ff->ph->env.memory_bsize, fp);
2237 	}
2238 }
2239 
2240 static int __event_process_build_id(struct perf_record_header_build_id *bev,
2241 				    char *filename,
2242 				    struct perf_session *session)
2243 {
2244 	int err = -1;
2245 	struct machine *machine;
2246 	u16 cpumode;
2247 	struct dso *dso;
2248 	enum dso_space_type dso_space;
2249 
2250 	machine = perf_session__findnew_machine(session, bev->pid);
2251 	if (!machine)
2252 		goto out;
2253 
2254 	cpumode = bev->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2255 
2256 	switch (cpumode) {
2257 	case PERF_RECORD_MISC_KERNEL:
2258 		dso_space = DSO_SPACE__KERNEL;
2259 		break;
2260 	case PERF_RECORD_MISC_GUEST_KERNEL:
2261 		dso_space = DSO_SPACE__KERNEL_GUEST;
2262 		break;
2263 	case PERF_RECORD_MISC_USER:
2264 	case PERF_RECORD_MISC_GUEST_USER:
2265 		dso_space = DSO_SPACE__USER;
2266 		break;
2267 	default:
2268 		goto out;
2269 	}
2270 
2271 	dso = machine__findnew_dso(machine, filename);
2272 	if (dso != NULL) {
2273 		char sbuild_id[SBUILD_ID_SIZE];
2274 		struct build_id bid;
2275 		size_t size = BUILD_ID_SIZE;
2276 
2277 		if (bev->header.misc & PERF_RECORD_MISC_BUILD_ID_SIZE)
2278 			size = bev->size;
2279 
2280 		build_id__init(&bid, bev->data, size);
2281 		dso__set_build_id(dso, &bid);
2282 		dso__set_header_build_id(dso, true);
2283 
2284 		if (dso_space != DSO_SPACE__USER) {
2285 			struct kmod_path m = { .name = NULL, };
2286 
2287 			if (!kmod_path__parse_name(&m, filename) && m.kmod)
2288 				dso__set_module_info(dso, &m, machine);
2289 
2290 			dso__set_kernel(dso, dso_space);
2291 			free(m.name);
2292 		}
2293 
2294 		build_id__sprintf(dso__bid(dso), sbuild_id);
2295 		pr_debug("build id event received for %s: %s [%zu]\n",
2296 			 dso__long_name(dso), sbuild_id, size);
2297 		dso__put(dso);
2298 	}
2299 
2300 	err = 0;
2301 out:
2302 	return err;
2303 }
2304 
2305 static int perf_header__read_build_ids_abi_quirk(struct perf_header *header,
2306 						 int input, u64 offset, u64 size)
2307 {
2308 	struct perf_session *session = container_of(header, struct perf_session, header);
2309 	struct {
2310 		struct perf_event_header   header;
2311 		u8			   build_id[PERF_ALIGN(BUILD_ID_SIZE, sizeof(u64))];
2312 		char			   filename[0];
2313 	} old_bev;
2314 	struct perf_record_header_build_id bev;
2315 	char filename[PATH_MAX];
2316 	u64 limit = offset + size;
2317 
2318 	while (offset < limit) {
2319 		ssize_t len;
2320 
2321 		if (readn(input, &old_bev, sizeof(old_bev)) != sizeof(old_bev))
2322 			return -1;
2323 
2324 		if (header->needs_swap)
2325 			perf_event_header__bswap(&old_bev.header);
2326 
2327 		len = old_bev.header.size - sizeof(old_bev);
2328 		if (readn(input, filename, len) != len)
2329 			return -1;
2330 
2331 		bev.header = old_bev.header;
2332 
2333 		/*
2334 		 * As the pid is the missing value, we need to fill
2335 		 * it properly. The header.misc value give us nice hint.
2336 		 */
2337 		bev.pid	= HOST_KERNEL_ID;
2338 		if (bev.header.misc == PERF_RECORD_MISC_GUEST_USER ||
2339 		    bev.header.misc == PERF_RECORD_MISC_GUEST_KERNEL)
2340 			bev.pid	= DEFAULT_GUEST_KERNEL_ID;
2341 
2342 		memcpy(bev.build_id, old_bev.build_id, sizeof(bev.build_id));
2343 		__event_process_build_id(&bev, filename, session);
2344 
2345 		offset += bev.header.size;
2346 	}
2347 
2348 	return 0;
2349 }
2350 
2351 static int perf_header__read_build_ids(struct perf_header *header,
2352 				       int input, u64 offset, u64 size)
2353 {
2354 	struct perf_session *session = container_of(header, struct perf_session, header);
2355 	struct perf_record_header_build_id bev;
2356 	char filename[PATH_MAX];
2357 	u64 limit = offset + size, orig_offset = offset;
2358 	int err = -1;
2359 
2360 	while (offset < limit) {
2361 		ssize_t len;
2362 
2363 		if (readn(input, &bev, sizeof(bev)) != sizeof(bev))
2364 			goto out;
2365 
2366 		if (header->needs_swap)
2367 			perf_event_header__bswap(&bev.header);
2368 
2369 		len = bev.header.size - sizeof(bev);
2370 		if (readn(input, filename, len) != len)
2371 			goto out;
2372 		/*
2373 		 * The a1645ce1 changeset:
2374 		 *
2375 		 * "perf: 'perf kvm' tool for monitoring guest performance from host"
2376 		 *
2377 		 * Added a field to struct perf_record_header_build_id that broke the file
2378 		 * format.
2379 		 *
2380 		 * Since the kernel build-id is the first entry, process the
2381 		 * table using the old format if the well known
2382 		 * '[kernel.kallsyms]' string for the kernel build-id has the
2383 		 * first 4 characters chopped off (where the pid_t sits).
2384 		 */
2385 		if (memcmp(filename, "nel.kallsyms]", 13) == 0) {
2386 			if (lseek(input, orig_offset, SEEK_SET) == (off_t)-1)
2387 				return -1;
2388 			return perf_header__read_build_ids_abi_quirk(header, input, offset, size);
2389 		}
2390 
2391 		__event_process_build_id(&bev, filename, session);
2392 
2393 		offset += bev.header.size;
2394 	}
2395 	err = 0;
2396 out:
2397 	return err;
2398 }
2399 
2400 /* Macro for features that simply need to read and store a string. */
2401 #define FEAT_PROCESS_STR_FUN(__feat, __feat_env) \
2402 static int process_##__feat(struct feat_fd *ff, void *data __maybe_unused) \
2403 {\
2404 	free(ff->ph->env.__feat_env);		     \
2405 	ff->ph->env.__feat_env = do_read_string(ff); \
2406 	return ff->ph->env.__feat_env ? 0 : -ENOMEM; \
2407 }
2408 
2409 FEAT_PROCESS_STR_FUN(hostname, hostname);
2410 FEAT_PROCESS_STR_FUN(osrelease, os_release);
2411 FEAT_PROCESS_STR_FUN(version, version);
2412 FEAT_PROCESS_STR_FUN(arch, arch);
2413 FEAT_PROCESS_STR_FUN(cpudesc, cpu_desc);
2414 FEAT_PROCESS_STR_FUN(cpuid, cpuid);
2415 
2416 #ifdef HAVE_LIBTRACEEVENT
2417 static int process_tracing_data(struct feat_fd *ff, void *data)
2418 {
2419 	ssize_t ret = trace_report(ff->fd, data, false);
2420 
2421 	return ret < 0 ? -1 : 0;
2422 }
2423 #endif
2424 
2425 static int process_build_id(struct feat_fd *ff, void *data __maybe_unused)
2426 {
2427 	if (perf_header__read_build_ids(ff->ph, ff->fd, ff->offset, ff->size))
2428 		pr_debug("Failed to read buildids, continuing...\n");
2429 	return 0;
2430 }
2431 
2432 static int process_nrcpus(struct feat_fd *ff, void *data __maybe_unused)
2433 {
2434 	int ret;
2435 	u32 nr_cpus_avail, nr_cpus_online;
2436 
2437 	ret = do_read_u32(ff, &nr_cpus_avail);
2438 	if (ret)
2439 		return ret;
2440 
2441 	ret = do_read_u32(ff, &nr_cpus_online);
2442 	if (ret)
2443 		return ret;
2444 	ff->ph->env.nr_cpus_avail = (int)nr_cpus_avail;
2445 	ff->ph->env.nr_cpus_online = (int)nr_cpus_online;
2446 	return 0;
2447 }
2448 
2449 static int process_total_mem(struct feat_fd *ff, void *data __maybe_unused)
2450 {
2451 	u64 total_mem;
2452 	int ret;
2453 
2454 	ret = do_read_u64(ff, &total_mem);
2455 	if (ret)
2456 		return -1;
2457 	ff->ph->env.total_mem = (unsigned long long)total_mem;
2458 	return 0;
2459 }
2460 
2461 static struct evsel *evlist__find_by_index(struct evlist *evlist, int idx)
2462 {
2463 	struct evsel *evsel;
2464 
2465 	evlist__for_each_entry(evlist, evsel) {
2466 		if (evsel->core.idx == idx)
2467 			return evsel;
2468 	}
2469 
2470 	return NULL;
2471 }
2472 
2473 static void evlist__set_event_name(struct evlist *evlist, struct evsel *event)
2474 {
2475 	struct evsel *evsel;
2476 
2477 	if (!event->name)
2478 		return;
2479 
2480 	evsel = evlist__find_by_index(evlist, event->core.idx);
2481 	if (!evsel)
2482 		return;
2483 
2484 	if (evsel->name)
2485 		return;
2486 
2487 	evsel->name = strdup(event->name);
2488 }
2489 
2490 static int
2491 process_event_desc(struct feat_fd *ff, void *data __maybe_unused)
2492 {
2493 	struct perf_session *session;
2494 	struct evsel *evsel, *events = read_event_desc(ff);
2495 
2496 	if (!events)
2497 		return 0;
2498 
2499 	session = container_of(ff->ph, struct perf_session, header);
2500 
2501 	if (session->data->is_pipe) {
2502 		/* Save events for reading later by print_event_desc,
2503 		 * since they can't be read again in pipe mode. */
2504 		ff->events = events;
2505 	}
2506 
2507 	for (evsel = events; evsel->core.attr.size; evsel++)
2508 		evlist__set_event_name(session->evlist, evsel);
2509 
2510 	if (!session->data->is_pipe)
2511 		free_event_desc(events);
2512 
2513 	return 0;
2514 }
2515 
2516 static int process_cmdline(struct feat_fd *ff, void *data __maybe_unused)
2517 {
2518 	char *str, *cmdline = NULL, **argv = NULL;
2519 	u32 nr, i, len = 0;
2520 
2521 	if (do_read_u32(ff, &nr))
2522 		return -1;
2523 
2524 	ff->ph->env.nr_cmdline = nr;
2525 
2526 	cmdline = zalloc(ff->size + nr + 1);
2527 	if (!cmdline)
2528 		return -1;
2529 
2530 	argv = zalloc(sizeof(char *) * (nr + 1));
2531 	if (!argv)
2532 		goto error;
2533 
2534 	for (i = 0; i < nr; i++) {
2535 		str = do_read_string(ff);
2536 		if (!str)
2537 			goto error;
2538 
2539 		argv[i] = cmdline + len;
2540 		memcpy(argv[i], str, strlen(str) + 1);
2541 		len += strlen(str) + 1;
2542 		free(str);
2543 	}
2544 	ff->ph->env.cmdline = cmdline;
2545 	ff->ph->env.cmdline_argv = (const char **) argv;
2546 	return 0;
2547 
2548 error:
2549 	free(argv);
2550 	free(cmdline);
2551 	return -1;
2552 }
2553 
2554 static int process_cpu_topology(struct feat_fd *ff, void *data __maybe_unused)
2555 {
2556 	u32 nr, i;
2557 	char *str = NULL;
2558 	struct strbuf sb;
2559 	int cpu_nr = ff->ph->env.nr_cpus_avail;
2560 	u64 size = 0;
2561 	struct perf_header *ph = ff->ph;
2562 
2563 	ph->env.cpu = calloc(cpu_nr, sizeof(*ph->env.cpu));
2564 	if (!ph->env.cpu)
2565 		return -1;
2566 
2567 	if (do_read_u32(ff, &nr))
2568 		goto free_cpu;
2569 
2570 	ph->env.nr_sibling_cores = nr;
2571 	size += sizeof(u32);
2572 	if (strbuf_init(&sb, 128) < 0)
2573 		goto free_cpu;
2574 
2575 	for (i = 0; i < nr; i++) {
2576 		str = do_read_string(ff);
2577 		if (!str)
2578 			goto error;
2579 
2580 		/* include a NULL character at the end */
2581 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
2582 			goto error;
2583 		size += string_size(str);
2584 		zfree(&str);
2585 	}
2586 	ph->env.sibling_cores = strbuf_detach(&sb, NULL);
2587 
2588 	if (do_read_u32(ff, &nr))
2589 		return -1;
2590 
2591 	ph->env.nr_sibling_threads = nr;
2592 	size += sizeof(u32);
2593 
2594 	for (i = 0; i < nr; i++) {
2595 		str = do_read_string(ff);
2596 		if (!str)
2597 			goto error;
2598 
2599 		/* include a NULL character at the end */
2600 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
2601 			goto error;
2602 		size += string_size(str);
2603 		zfree(&str);
2604 	}
2605 	ph->env.sibling_threads = strbuf_detach(&sb, NULL);
2606 
2607 	/*
2608 	 * The header may be from old perf,
2609 	 * which doesn't include core id and socket id information.
2610 	 */
2611 	if (ff->size <= size) {
2612 		zfree(&ph->env.cpu);
2613 		return 0;
2614 	}
2615 
2616 	for (i = 0; i < (u32)cpu_nr; i++) {
2617 		if (do_read_u32(ff, &nr))
2618 			goto free_cpu;
2619 
2620 		ph->env.cpu[i].core_id = nr;
2621 		size += sizeof(u32);
2622 
2623 		if (do_read_u32(ff, &nr))
2624 			goto free_cpu;
2625 
2626 		ph->env.cpu[i].socket_id = nr;
2627 		size += sizeof(u32);
2628 	}
2629 
2630 	/*
2631 	 * The header may be from old perf,
2632 	 * which doesn't include die information.
2633 	 */
2634 	if (ff->size <= size)
2635 		return 0;
2636 
2637 	if (do_read_u32(ff, &nr))
2638 		return -1;
2639 
2640 	ph->env.nr_sibling_dies = nr;
2641 	size += sizeof(u32);
2642 
2643 	for (i = 0; i < nr; i++) {
2644 		str = do_read_string(ff);
2645 		if (!str)
2646 			goto error;
2647 
2648 		/* include a NULL character at the end */
2649 		if (strbuf_add(&sb, str, strlen(str) + 1) < 0)
2650 			goto error;
2651 		size += string_size(str);
2652 		zfree(&str);
2653 	}
2654 	ph->env.sibling_dies = strbuf_detach(&sb, NULL);
2655 
2656 	for (i = 0; i < (u32)cpu_nr; i++) {
2657 		if (do_read_u32(ff, &nr))
2658 			goto free_cpu;
2659 
2660 		ph->env.cpu[i].die_id = nr;
2661 	}
2662 
2663 	return 0;
2664 
2665 error:
2666 	strbuf_release(&sb);
2667 	zfree(&str);
2668 free_cpu:
2669 	zfree(&ph->env.cpu);
2670 	return -1;
2671 }
2672 
2673 static int process_numa_topology(struct feat_fd *ff, void *data __maybe_unused)
2674 {
2675 	struct numa_node *nodes, *n;
2676 	u32 nr, i;
2677 	char *str;
2678 
2679 	/* nr nodes */
2680 	if (do_read_u32(ff, &nr))
2681 		return -1;
2682 
2683 	nodes = zalloc(sizeof(*nodes) * nr);
2684 	if (!nodes)
2685 		return -ENOMEM;
2686 
2687 	for (i = 0; i < nr; i++) {
2688 		n = &nodes[i];
2689 
2690 		/* node number */
2691 		if (do_read_u32(ff, &n->node))
2692 			goto error;
2693 
2694 		if (do_read_u64(ff, &n->mem_total))
2695 			goto error;
2696 
2697 		if (do_read_u64(ff, &n->mem_free))
2698 			goto error;
2699 
2700 		str = do_read_string(ff);
2701 		if (!str)
2702 			goto error;
2703 
2704 		n->map = perf_cpu_map__new(str);
2705 		free(str);
2706 		if (!n->map)
2707 			goto error;
2708 	}
2709 	ff->ph->env.nr_numa_nodes = nr;
2710 	ff->ph->env.numa_nodes = nodes;
2711 	return 0;
2712 
2713 error:
2714 	free(nodes);
2715 	return -1;
2716 }
2717 
2718 static int process_pmu_mappings(struct feat_fd *ff, void *data __maybe_unused)
2719 {
2720 	char *name;
2721 	u32 pmu_num;
2722 	u32 type;
2723 	struct strbuf sb;
2724 
2725 	if (do_read_u32(ff, &pmu_num))
2726 		return -1;
2727 
2728 	if (!pmu_num) {
2729 		pr_debug("pmu mappings not available\n");
2730 		return 0;
2731 	}
2732 
2733 	ff->ph->env.nr_pmu_mappings = pmu_num;
2734 	if (strbuf_init(&sb, 128) < 0)
2735 		return -1;
2736 
2737 	while (pmu_num) {
2738 		if (do_read_u32(ff, &type))
2739 			goto error;
2740 
2741 		name = do_read_string(ff);
2742 		if (!name)
2743 			goto error;
2744 
2745 		if (strbuf_addf(&sb, "%u:%s", type, name) < 0)
2746 			goto error;
2747 		/* include a NULL character at the end */
2748 		if (strbuf_add(&sb, "", 1) < 0)
2749 			goto error;
2750 
2751 		if (!strcmp(name, "msr"))
2752 			ff->ph->env.msr_pmu_type = type;
2753 
2754 		free(name);
2755 		pmu_num--;
2756 	}
2757 	/* AMD may set it by evlist__has_amd_ibs() from perf_session__new() */
2758 	free(ff->ph->env.pmu_mappings);
2759 	ff->ph->env.pmu_mappings = strbuf_detach(&sb, NULL);
2760 	return 0;
2761 
2762 error:
2763 	strbuf_release(&sb);
2764 	return -1;
2765 }
2766 
2767 static int process_group_desc(struct feat_fd *ff, void *data __maybe_unused)
2768 {
2769 	size_t ret = -1;
2770 	u32 i, nr, nr_groups;
2771 	struct perf_session *session;
2772 	struct evsel *evsel, *leader = NULL;
2773 	struct group_desc {
2774 		char *name;
2775 		u32 leader_idx;
2776 		u32 nr_members;
2777 	} *desc;
2778 
2779 	if (do_read_u32(ff, &nr_groups))
2780 		return -1;
2781 
2782 	ff->ph->env.nr_groups = nr_groups;
2783 	if (!nr_groups) {
2784 		pr_debug("group desc not available\n");
2785 		return 0;
2786 	}
2787 
2788 	desc = calloc(nr_groups, sizeof(*desc));
2789 	if (!desc)
2790 		return -1;
2791 
2792 	for (i = 0; i < nr_groups; i++) {
2793 		desc[i].name = do_read_string(ff);
2794 		if (!desc[i].name)
2795 			goto out_free;
2796 
2797 		if (do_read_u32(ff, &desc[i].leader_idx))
2798 			goto out_free;
2799 
2800 		if (do_read_u32(ff, &desc[i].nr_members))
2801 			goto out_free;
2802 	}
2803 
2804 	/*
2805 	 * Rebuild group relationship based on the group_desc
2806 	 */
2807 	session = container_of(ff->ph, struct perf_session, header);
2808 
2809 	i = nr = 0;
2810 	evlist__for_each_entry(session->evlist, evsel) {
2811 		if (i < nr_groups && evsel->core.idx == (int) desc[i].leader_idx) {
2812 			evsel__set_leader(evsel, evsel);
2813 			/* {anon_group} is a dummy name */
2814 			if (strcmp(desc[i].name, "{anon_group}")) {
2815 				evsel->group_name = desc[i].name;
2816 				desc[i].name = NULL;
2817 			}
2818 			evsel->core.nr_members = desc[i].nr_members;
2819 
2820 			if (i >= nr_groups || nr > 0) {
2821 				pr_debug("invalid group desc\n");
2822 				goto out_free;
2823 			}
2824 
2825 			leader = evsel;
2826 			nr = evsel->core.nr_members - 1;
2827 			i++;
2828 		} else if (nr) {
2829 			/* This is a group member */
2830 			evsel__set_leader(evsel, leader);
2831 
2832 			nr--;
2833 		}
2834 	}
2835 
2836 	if (i != nr_groups || nr != 0) {
2837 		pr_debug("invalid group desc\n");
2838 		goto out_free;
2839 	}
2840 
2841 	ret = 0;
2842 out_free:
2843 	for (i = 0; i < nr_groups; i++)
2844 		zfree(&desc[i].name);
2845 	free(desc);
2846 
2847 	return ret;
2848 }
2849 
2850 static int process_auxtrace(struct feat_fd *ff, void *data __maybe_unused)
2851 {
2852 	struct perf_session *session;
2853 	int err;
2854 
2855 	session = container_of(ff->ph, struct perf_session, header);
2856 
2857 	err = auxtrace_index__process(ff->fd, ff->size, session,
2858 				      ff->ph->needs_swap);
2859 	if (err < 0)
2860 		pr_err("Failed to process auxtrace index\n");
2861 	return err;
2862 }
2863 
2864 static int process_cache(struct feat_fd *ff, void *data __maybe_unused)
2865 {
2866 	struct cpu_cache_level *caches;
2867 	u32 cnt, i, version;
2868 
2869 	if (do_read_u32(ff, &version))
2870 		return -1;
2871 
2872 	if (version != 1)
2873 		return -1;
2874 
2875 	if (do_read_u32(ff, &cnt))
2876 		return -1;
2877 
2878 	caches = zalloc(sizeof(*caches) * cnt);
2879 	if (!caches)
2880 		return -1;
2881 
2882 	for (i = 0; i < cnt; i++) {
2883 		struct cpu_cache_level *c = &caches[i];
2884 
2885 		#define _R(v)						\
2886 			if (do_read_u32(ff, &c->v))			\
2887 				goto out_free_caches;			\
2888 
2889 		_R(level)
2890 		_R(line_size)
2891 		_R(sets)
2892 		_R(ways)
2893 		#undef _R
2894 
2895 		#define _R(v)					\
2896 			c->v = do_read_string(ff);		\
2897 			if (!c->v)				\
2898 				goto out_free_caches;		\
2899 
2900 		_R(type)
2901 		_R(size)
2902 		_R(map)
2903 		#undef _R
2904 	}
2905 
2906 	ff->ph->env.caches = caches;
2907 	ff->ph->env.caches_cnt = cnt;
2908 	return 0;
2909 out_free_caches:
2910 	for (i = 0; i < cnt; i++) {
2911 		free(caches[i].type);
2912 		free(caches[i].size);
2913 		free(caches[i].map);
2914 	}
2915 	free(caches);
2916 	return -1;
2917 }
2918 
2919 static int process_sample_time(struct feat_fd *ff, void *data __maybe_unused)
2920 {
2921 	struct perf_session *session;
2922 	u64 first_sample_time, last_sample_time;
2923 	int ret;
2924 
2925 	session = container_of(ff->ph, struct perf_session, header);
2926 
2927 	ret = do_read_u64(ff, &first_sample_time);
2928 	if (ret)
2929 		return -1;
2930 
2931 	ret = do_read_u64(ff, &last_sample_time);
2932 	if (ret)
2933 		return -1;
2934 
2935 	session->evlist->first_sample_time = first_sample_time;
2936 	session->evlist->last_sample_time = last_sample_time;
2937 	return 0;
2938 }
2939 
2940 static int process_mem_topology(struct feat_fd *ff,
2941 				void *data __maybe_unused)
2942 {
2943 	struct memory_node *nodes;
2944 	u64 version, i, nr, bsize;
2945 	int ret = -1;
2946 
2947 	if (do_read_u64(ff, &version))
2948 		return -1;
2949 
2950 	if (version != 1)
2951 		return -1;
2952 
2953 	if (do_read_u64(ff, &bsize))
2954 		return -1;
2955 
2956 	if (do_read_u64(ff, &nr))
2957 		return -1;
2958 
2959 	nodes = zalloc(sizeof(*nodes) * nr);
2960 	if (!nodes)
2961 		return -1;
2962 
2963 	for (i = 0; i < nr; i++) {
2964 		struct memory_node n;
2965 
2966 		#define _R(v)				\
2967 			if (do_read_u64(ff, &n.v))	\
2968 				goto out;		\
2969 
2970 		_R(node)
2971 		_R(size)
2972 
2973 		#undef _R
2974 
2975 		if (do_read_bitmap(ff, &n.set, &n.size))
2976 			goto out;
2977 
2978 		nodes[i] = n;
2979 	}
2980 
2981 	ff->ph->env.memory_bsize    = bsize;
2982 	ff->ph->env.memory_nodes    = nodes;
2983 	ff->ph->env.nr_memory_nodes = nr;
2984 	ret = 0;
2985 
2986 out:
2987 	if (ret)
2988 		free(nodes);
2989 	return ret;
2990 }
2991 
2992 static int process_clockid(struct feat_fd *ff,
2993 			   void *data __maybe_unused)
2994 {
2995 	if (do_read_u64(ff, &ff->ph->env.clock.clockid_res_ns))
2996 		return -1;
2997 
2998 	return 0;
2999 }
3000 
3001 static int process_clock_data(struct feat_fd *ff,
3002 			      void *_data __maybe_unused)
3003 {
3004 	u32 data32;
3005 	u64 data64;
3006 
3007 	/* version */
3008 	if (do_read_u32(ff, &data32))
3009 		return -1;
3010 
3011 	if (data32 != 1)
3012 		return -1;
3013 
3014 	/* clockid */
3015 	if (do_read_u32(ff, &data32))
3016 		return -1;
3017 
3018 	ff->ph->env.clock.clockid = data32;
3019 
3020 	/* TOD ref time */
3021 	if (do_read_u64(ff, &data64))
3022 		return -1;
3023 
3024 	ff->ph->env.clock.tod_ns = data64;
3025 
3026 	/* clockid ref time */
3027 	if (do_read_u64(ff, &data64))
3028 		return -1;
3029 
3030 	ff->ph->env.clock.clockid_ns = data64;
3031 	ff->ph->env.clock.enabled = true;
3032 	return 0;
3033 }
3034 
3035 static int process_hybrid_topology(struct feat_fd *ff,
3036 				   void *data __maybe_unused)
3037 {
3038 	struct hybrid_node *nodes, *n;
3039 	u32 nr, i;
3040 
3041 	/* nr nodes */
3042 	if (do_read_u32(ff, &nr))
3043 		return -1;
3044 
3045 	nodes = zalloc(sizeof(*nodes) * nr);
3046 	if (!nodes)
3047 		return -ENOMEM;
3048 
3049 	for (i = 0; i < nr; i++) {
3050 		n = &nodes[i];
3051 
3052 		n->pmu_name = do_read_string(ff);
3053 		if (!n->pmu_name)
3054 			goto error;
3055 
3056 		n->cpus = do_read_string(ff);
3057 		if (!n->cpus)
3058 			goto error;
3059 	}
3060 
3061 	ff->ph->env.nr_hybrid_nodes = nr;
3062 	ff->ph->env.hybrid_nodes = nodes;
3063 	return 0;
3064 
3065 error:
3066 	for (i = 0; i < nr; i++) {
3067 		free(nodes[i].pmu_name);
3068 		free(nodes[i].cpus);
3069 	}
3070 
3071 	free(nodes);
3072 	return -1;
3073 }
3074 
3075 static int process_dir_format(struct feat_fd *ff,
3076 			      void *_data __maybe_unused)
3077 {
3078 	struct perf_session *session;
3079 	struct perf_data *data;
3080 
3081 	session = container_of(ff->ph, struct perf_session, header);
3082 	data = session->data;
3083 
3084 	if (WARN_ON(!perf_data__is_dir(data)))
3085 		return -1;
3086 
3087 	return do_read_u64(ff, &data->dir.version);
3088 }
3089 
3090 #ifdef HAVE_LIBBPF_SUPPORT
3091 static int process_bpf_prog_info(struct feat_fd *ff, void *data __maybe_unused)
3092 {
3093 	struct bpf_prog_info_node *info_node;
3094 	struct perf_env *env = &ff->ph->env;
3095 	struct perf_bpil *info_linear;
3096 	u32 count, i;
3097 	int err = -1;
3098 
3099 	if (ff->ph->needs_swap) {
3100 		pr_warning("interpreting bpf_prog_info from systems with endianness is not yet supported\n");
3101 		return 0;
3102 	}
3103 
3104 	if (do_read_u32(ff, &count))
3105 		return -1;
3106 
3107 	down_write(&env->bpf_progs.lock);
3108 
3109 	for (i = 0; i < count; ++i) {
3110 		u32 info_len, data_len;
3111 
3112 		info_linear = NULL;
3113 		info_node = NULL;
3114 		if (do_read_u32(ff, &info_len))
3115 			goto out;
3116 		if (do_read_u32(ff, &data_len))
3117 			goto out;
3118 
3119 		if (info_len > sizeof(struct bpf_prog_info)) {
3120 			pr_warning("detected invalid bpf_prog_info\n");
3121 			goto out;
3122 		}
3123 
3124 		info_linear = malloc(sizeof(struct perf_bpil) +
3125 				     data_len);
3126 		if (!info_linear)
3127 			goto out;
3128 		info_linear->info_len = sizeof(struct bpf_prog_info);
3129 		info_linear->data_len = data_len;
3130 		if (do_read_u64(ff, (u64 *)(&info_linear->arrays)))
3131 			goto out;
3132 		if (__do_read(ff, &info_linear->info, info_len))
3133 			goto out;
3134 		if (info_len < sizeof(struct bpf_prog_info))
3135 			memset(((void *)(&info_linear->info)) + info_len, 0,
3136 			       sizeof(struct bpf_prog_info) - info_len);
3137 
3138 		if (__do_read(ff, info_linear->data, data_len))
3139 			goto out;
3140 
3141 		info_node = malloc(sizeof(struct bpf_prog_info_node));
3142 		if (!info_node)
3143 			goto out;
3144 
3145 		/* after reading from file, translate offset to address */
3146 		bpil_offs_to_addr(info_linear);
3147 		info_node->info_linear = info_linear;
3148 		info_node->metadata = NULL;
3149 		if (!__perf_env__insert_bpf_prog_info(env, info_node)) {
3150 			free(info_linear);
3151 			free(info_node);
3152 		}
3153 	}
3154 
3155 	up_write(&env->bpf_progs.lock);
3156 	return 0;
3157 out:
3158 	free(info_linear);
3159 	free(info_node);
3160 	up_write(&env->bpf_progs.lock);
3161 	return err;
3162 }
3163 
3164 static int process_bpf_btf(struct feat_fd *ff, void *data __maybe_unused)
3165 {
3166 	struct perf_env *env = &ff->ph->env;
3167 	struct btf_node *node = NULL;
3168 	u32 count, i;
3169 	int err = -1;
3170 
3171 	if (ff->ph->needs_swap) {
3172 		pr_warning("interpreting btf from systems with endianness is not yet supported\n");
3173 		return 0;
3174 	}
3175 
3176 	if (do_read_u32(ff, &count))
3177 		return -1;
3178 
3179 	down_write(&env->bpf_progs.lock);
3180 
3181 	for (i = 0; i < count; ++i) {
3182 		u32 id, data_size;
3183 
3184 		if (do_read_u32(ff, &id))
3185 			goto out;
3186 		if (do_read_u32(ff, &data_size))
3187 			goto out;
3188 
3189 		node = malloc(sizeof(struct btf_node) + data_size);
3190 		if (!node)
3191 			goto out;
3192 
3193 		node->id = id;
3194 		node->data_size = data_size;
3195 
3196 		if (__do_read(ff, node->data, data_size))
3197 			goto out;
3198 
3199 		if (!__perf_env__insert_btf(env, node))
3200 			free(node);
3201 		node = NULL;
3202 	}
3203 
3204 	err = 0;
3205 out:
3206 	up_write(&env->bpf_progs.lock);
3207 	free(node);
3208 	return err;
3209 }
3210 #endif // HAVE_LIBBPF_SUPPORT
3211 
3212 static int process_compressed(struct feat_fd *ff,
3213 			      void *data __maybe_unused)
3214 {
3215 	if (do_read_u32(ff, &(ff->ph->env.comp_ver)))
3216 		return -1;
3217 
3218 	if (do_read_u32(ff, &(ff->ph->env.comp_type)))
3219 		return -1;
3220 
3221 	if (do_read_u32(ff, &(ff->ph->env.comp_level)))
3222 		return -1;
3223 
3224 	if (do_read_u32(ff, &(ff->ph->env.comp_ratio)))
3225 		return -1;
3226 
3227 	if (do_read_u32(ff, &(ff->ph->env.comp_mmap_len)))
3228 		return -1;
3229 
3230 	return 0;
3231 }
3232 
3233 static int __process_pmu_caps(struct feat_fd *ff, int *nr_caps,
3234 			      char ***caps, unsigned int *max_branches,
3235 			      unsigned int *br_cntr_nr,
3236 			      unsigned int *br_cntr_width)
3237 {
3238 	char *name, *value, *ptr;
3239 	u32 nr_pmu_caps, i;
3240 
3241 	*nr_caps = 0;
3242 	*caps = NULL;
3243 
3244 	if (do_read_u32(ff, &nr_pmu_caps))
3245 		return -1;
3246 
3247 	if (!nr_pmu_caps)
3248 		return 0;
3249 
3250 	*caps = zalloc(sizeof(char *) * nr_pmu_caps);
3251 	if (!*caps)
3252 		return -1;
3253 
3254 	for (i = 0; i < nr_pmu_caps; i++) {
3255 		name = do_read_string(ff);
3256 		if (!name)
3257 			goto error;
3258 
3259 		value = do_read_string(ff);
3260 		if (!value)
3261 			goto free_name;
3262 
3263 		if (asprintf(&ptr, "%s=%s", name, value) < 0)
3264 			goto free_value;
3265 
3266 		(*caps)[i] = ptr;
3267 
3268 		if (!strcmp(name, "branches"))
3269 			*max_branches = atoi(value);
3270 
3271 		if (!strcmp(name, "branch_counter_nr"))
3272 			*br_cntr_nr = atoi(value);
3273 
3274 		if (!strcmp(name, "branch_counter_width"))
3275 			*br_cntr_width = atoi(value);
3276 
3277 		free(value);
3278 		free(name);
3279 	}
3280 	*nr_caps = nr_pmu_caps;
3281 	return 0;
3282 
3283 free_value:
3284 	free(value);
3285 free_name:
3286 	free(name);
3287 error:
3288 	for (; i > 0; i--)
3289 		free((*caps)[i - 1]);
3290 	free(*caps);
3291 	*caps = NULL;
3292 	*nr_caps = 0;
3293 	return -1;
3294 }
3295 
3296 static int process_cpu_pmu_caps(struct feat_fd *ff,
3297 				void *data __maybe_unused)
3298 {
3299 	int ret = __process_pmu_caps(ff, &ff->ph->env.nr_cpu_pmu_caps,
3300 				     &ff->ph->env.cpu_pmu_caps,
3301 				     &ff->ph->env.max_branches,
3302 				     &ff->ph->env.br_cntr_nr,
3303 				     &ff->ph->env.br_cntr_width);
3304 
3305 	if (!ret && !ff->ph->env.cpu_pmu_caps)
3306 		pr_debug("cpu pmu capabilities not available\n");
3307 	return ret;
3308 }
3309 
3310 static int process_pmu_caps(struct feat_fd *ff, void *data __maybe_unused)
3311 {
3312 	struct pmu_caps *pmu_caps;
3313 	u32 nr_pmu, i;
3314 	int ret;
3315 	int j;
3316 
3317 	if (do_read_u32(ff, &nr_pmu))
3318 		return -1;
3319 
3320 	if (!nr_pmu) {
3321 		pr_debug("pmu capabilities not available\n");
3322 		return 0;
3323 	}
3324 
3325 	pmu_caps = zalloc(sizeof(*pmu_caps) * nr_pmu);
3326 	if (!pmu_caps)
3327 		return -ENOMEM;
3328 
3329 	for (i = 0; i < nr_pmu; i++) {
3330 		ret = __process_pmu_caps(ff, &pmu_caps[i].nr_caps,
3331 					 &pmu_caps[i].caps,
3332 					 &pmu_caps[i].max_branches,
3333 					 &pmu_caps[i].br_cntr_nr,
3334 					 &pmu_caps[i].br_cntr_width);
3335 		if (ret)
3336 			goto err;
3337 
3338 		pmu_caps[i].pmu_name = do_read_string(ff);
3339 		if (!pmu_caps[i].pmu_name) {
3340 			ret = -1;
3341 			goto err;
3342 		}
3343 		if (!pmu_caps[i].nr_caps) {
3344 			pr_debug("%s pmu capabilities not available\n",
3345 				 pmu_caps[i].pmu_name);
3346 		}
3347 	}
3348 
3349 	ff->ph->env.nr_pmus_with_caps = nr_pmu;
3350 	ff->ph->env.pmu_caps = pmu_caps;
3351 	return 0;
3352 
3353 err:
3354 	for (i = 0; i < nr_pmu; i++) {
3355 		for (j = 0; j < pmu_caps[i].nr_caps; j++)
3356 			free(pmu_caps[i].caps[j]);
3357 		free(pmu_caps[i].caps);
3358 		free(pmu_caps[i].pmu_name);
3359 	}
3360 
3361 	free(pmu_caps);
3362 	return ret;
3363 }
3364 
3365 #define FEAT_OPR(n, func, __full_only) \
3366 	[HEADER_##n] = {					\
3367 		.name	    = __stringify(n),			\
3368 		.write	    = write_##func,			\
3369 		.print	    = print_##func,			\
3370 		.full_only  = __full_only,			\
3371 		.process    = process_##func,			\
3372 		.synthesize = true				\
3373 	}
3374 
3375 #define FEAT_OPN(n, func, __full_only) \
3376 	[HEADER_##n] = {					\
3377 		.name	    = __stringify(n),			\
3378 		.write	    = write_##func,			\
3379 		.print	    = print_##func,			\
3380 		.full_only  = __full_only,			\
3381 		.process    = process_##func			\
3382 	}
3383 
3384 /* feature_ops not implemented: */
3385 #define print_tracing_data	NULL
3386 #define print_build_id		NULL
3387 
3388 #define process_branch_stack	NULL
3389 #define process_stat		NULL
3390 
3391 // Only used in util/synthetic-events.c
3392 const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE];
3393 
3394 const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE] = {
3395 #ifdef HAVE_LIBTRACEEVENT
3396 	FEAT_OPN(TRACING_DATA,	tracing_data,	false),
3397 #endif
3398 	FEAT_OPN(BUILD_ID,	build_id,	false),
3399 	FEAT_OPR(HOSTNAME,	hostname,	false),
3400 	FEAT_OPR(OSRELEASE,	osrelease,	false),
3401 	FEAT_OPR(VERSION,	version,	false),
3402 	FEAT_OPR(ARCH,		arch,		false),
3403 	FEAT_OPR(NRCPUS,	nrcpus,		false),
3404 	FEAT_OPR(CPUDESC,	cpudesc,	false),
3405 	FEAT_OPR(CPUID,		cpuid,		false),
3406 	FEAT_OPR(TOTAL_MEM,	total_mem,	false),
3407 	FEAT_OPR(EVENT_DESC,	event_desc,	false),
3408 	FEAT_OPR(CMDLINE,	cmdline,	false),
3409 	FEAT_OPR(CPU_TOPOLOGY,	cpu_topology,	true),
3410 	FEAT_OPR(NUMA_TOPOLOGY,	numa_topology,	true),
3411 	FEAT_OPN(BRANCH_STACK,	branch_stack,	false),
3412 	FEAT_OPR(PMU_MAPPINGS,	pmu_mappings,	false),
3413 	FEAT_OPR(GROUP_DESC,	group_desc,	false),
3414 	FEAT_OPN(AUXTRACE,	auxtrace,	false),
3415 	FEAT_OPN(STAT,		stat,		false),
3416 	FEAT_OPN(CACHE,		cache,		true),
3417 	FEAT_OPR(SAMPLE_TIME,	sample_time,	false),
3418 	FEAT_OPR(MEM_TOPOLOGY,	mem_topology,	true),
3419 	FEAT_OPR(CLOCKID,	clockid,	false),
3420 	FEAT_OPN(DIR_FORMAT,	dir_format,	false),
3421 #ifdef HAVE_LIBBPF_SUPPORT
3422 	FEAT_OPR(BPF_PROG_INFO, bpf_prog_info,  false),
3423 	FEAT_OPR(BPF_BTF,       bpf_btf,        false),
3424 #endif
3425 	FEAT_OPR(COMPRESSED,	compressed,	false),
3426 	FEAT_OPR(CPU_PMU_CAPS,	cpu_pmu_caps,	false),
3427 	FEAT_OPR(CLOCK_DATA,	clock_data,	false),
3428 	FEAT_OPN(HYBRID_TOPOLOGY,	hybrid_topology,	true),
3429 	FEAT_OPR(PMU_CAPS,	pmu_caps,	false),
3430 };
3431 
3432 struct header_print_data {
3433 	FILE *fp;
3434 	bool full; /* extended list of headers */
3435 };
3436 
3437 static int perf_file_section__fprintf_info(struct perf_file_section *section,
3438 					   struct perf_header *ph,
3439 					   int feat, int fd, void *data)
3440 {
3441 	struct header_print_data *hd = data;
3442 	struct feat_fd ff;
3443 
3444 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
3445 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature "
3446 				"%d, continuing...\n", section->offset, feat);
3447 		return 0;
3448 	}
3449 	if (feat >= HEADER_LAST_FEATURE) {
3450 		pr_warning("unknown feature %d\n", feat);
3451 		return 0;
3452 	}
3453 	if (!feat_ops[feat].print)
3454 		return 0;
3455 
3456 	ff = (struct  feat_fd) {
3457 		.fd = fd,
3458 		.ph = ph,
3459 	};
3460 
3461 	if (!feat_ops[feat].full_only || hd->full)
3462 		feat_ops[feat].print(&ff, hd->fp);
3463 	else
3464 		fprintf(hd->fp, "# %s info available, use -I to display\n",
3465 			feat_ops[feat].name);
3466 
3467 	return 0;
3468 }
3469 
3470 int perf_header__fprintf_info(struct perf_session *session, FILE *fp, bool full)
3471 {
3472 	struct header_print_data hd;
3473 	struct perf_header *header = &session->header;
3474 	int fd = perf_data__fd(session->data);
3475 	struct stat st;
3476 	time_t stctime;
3477 	int ret, bit;
3478 
3479 	hd.fp = fp;
3480 	hd.full = full;
3481 
3482 	ret = fstat(fd, &st);
3483 	if (ret == -1)
3484 		return -1;
3485 
3486 	stctime = st.st_mtime;
3487 	fprintf(fp, "# captured on    : %s", ctime(&stctime));
3488 
3489 	fprintf(fp, "# header version : %u\n", header->version);
3490 	fprintf(fp, "# data offset    : %" PRIu64 "\n", header->data_offset);
3491 	fprintf(fp, "# data size      : %" PRIu64 "\n", header->data_size);
3492 	fprintf(fp, "# feat offset    : %" PRIu64 "\n", header->feat_offset);
3493 
3494 	perf_header__process_sections(header, fd, &hd,
3495 				      perf_file_section__fprintf_info);
3496 
3497 	if (session->data->is_pipe)
3498 		return 0;
3499 
3500 	fprintf(fp, "# missing features: ");
3501 	for_each_clear_bit(bit, header->adds_features, HEADER_LAST_FEATURE) {
3502 		if (bit)
3503 			fprintf(fp, "%s ", feat_ops[bit].name);
3504 	}
3505 
3506 	fprintf(fp, "\n");
3507 	return 0;
3508 }
3509 
3510 struct header_fw {
3511 	struct feat_writer	fw;
3512 	struct feat_fd		*ff;
3513 };
3514 
3515 static int feat_writer_cb(struct feat_writer *fw, void *buf, size_t sz)
3516 {
3517 	struct header_fw *h = container_of(fw, struct header_fw, fw);
3518 
3519 	return do_write(h->ff, buf, sz);
3520 }
3521 
3522 static int do_write_feat(struct feat_fd *ff, int type,
3523 			 struct perf_file_section **p,
3524 			 struct evlist *evlist,
3525 			 struct feat_copier *fc)
3526 {
3527 	int err;
3528 	int ret = 0;
3529 
3530 	if (perf_header__has_feat(ff->ph, type)) {
3531 		if (!feat_ops[type].write)
3532 			return -1;
3533 
3534 		if (WARN(ff->buf, "Error: calling %s in pipe-mode.\n", __func__))
3535 			return -1;
3536 
3537 		(*p)->offset = lseek(ff->fd, 0, SEEK_CUR);
3538 
3539 		/*
3540 		 * Hook to let perf inject copy features sections from the input
3541 		 * file.
3542 		 */
3543 		if (fc && fc->copy) {
3544 			struct header_fw h = {
3545 				.fw.write = feat_writer_cb,
3546 				.ff = ff,
3547 			};
3548 
3549 			/* ->copy() returns 0 if the feature was not copied */
3550 			err = fc->copy(fc, type, &h.fw);
3551 		} else {
3552 			err = 0;
3553 		}
3554 		if (!err)
3555 			err = feat_ops[type].write(ff, evlist);
3556 		if (err < 0) {
3557 			pr_debug("failed to write feature %s\n", feat_ops[type].name);
3558 
3559 			/* undo anything written */
3560 			lseek(ff->fd, (*p)->offset, SEEK_SET);
3561 
3562 			return -1;
3563 		}
3564 		(*p)->size = lseek(ff->fd, 0, SEEK_CUR) - (*p)->offset;
3565 		(*p)++;
3566 	}
3567 	return ret;
3568 }
3569 
3570 static int perf_header__adds_write(struct perf_header *header,
3571 				   struct evlist *evlist, int fd,
3572 				   struct feat_copier *fc)
3573 {
3574 	int nr_sections;
3575 	struct feat_fd ff = {
3576 		.fd  = fd,
3577 		.ph = header,
3578 	};
3579 	struct perf_file_section *feat_sec, *p;
3580 	int sec_size;
3581 	u64 sec_start;
3582 	int feat;
3583 	int err;
3584 
3585 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
3586 	if (!nr_sections)
3587 		return 0;
3588 
3589 	feat_sec = p = calloc(nr_sections, sizeof(*feat_sec));
3590 	if (feat_sec == NULL)
3591 		return -ENOMEM;
3592 
3593 	sec_size = sizeof(*feat_sec) * nr_sections;
3594 
3595 	sec_start = header->feat_offset;
3596 	lseek(fd, sec_start + sec_size, SEEK_SET);
3597 
3598 	for_each_set_bit(feat, header->adds_features, HEADER_FEAT_BITS) {
3599 		if (do_write_feat(&ff, feat, &p, evlist, fc))
3600 			perf_header__clear_feat(header, feat);
3601 	}
3602 
3603 	lseek(fd, sec_start, SEEK_SET);
3604 	/*
3605 	 * may write more than needed due to dropped feature, but
3606 	 * this is okay, reader will skip the missing entries
3607 	 */
3608 	err = do_write(&ff, feat_sec, sec_size);
3609 	if (err < 0)
3610 		pr_debug("failed to write feature section\n");
3611 	free(ff.buf); /* TODO: added to silence clang-tidy. */
3612 	free(feat_sec);
3613 	return err;
3614 }
3615 
3616 int perf_header__write_pipe(int fd)
3617 {
3618 	struct perf_pipe_file_header f_header;
3619 	struct feat_fd ff = {
3620 		.fd = fd,
3621 	};
3622 	int err;
3623 
3624 	f_header = (struct perf_pipe_file_header){
3625 		.magic	   = PERF_MAGIC,
3626 		.size	   = sizeof(f_header),
3627 	};
3628 
3629 	err = do_write(&ff, &f_header, sizeof(f_header));
3630 	if (err < 0) {
3631 		pr_debug("failed to write perf pipe header\n");
3632 		return err;
3633 	}
3634 	free(ff.buf);
3635 	return 0;
3636 }
3637 
3638 static int perf_session__do_write_header(struct perf_session *session,
3639 					 struct evlist *evlist,
3640 					 int fd, bool at_exit,
3641 					 struct feat_copier *fc,
3642 					 bool write_attrs_after_data)
3643 {
3644 	struct perf_file_header f_header;
3645 	struct perf_header *header = &session->header;
3646 	struct evsel *evsel;
3647 	struct feat_fd ff = {
3648 		.fd = fd,
3649 	};
3650 	u64 attr_offset = sizeof(f_header), attr_size = 0;
3651 	int err;
3652 
3653 	if (write_attrs_after_data && at_exit) {
3654 		/*
3655 		 * Write features at the end of the file first so that
3656 		 * attributes may come after them.
3657 		 */
3658 		if (!header->data_offset && header->data_size) {
3659 			pr_err("File contains data but offset unknown\n");
3660 			err = -1;
3661 			goto err_out;
3662 		}
3663 		header->feat_offset = header->data_offset + header->data_size;
3664 		err = perf_header__adds_write(header, evlist, fd, fc);
3665 		if (err < 0)
3666 			goto err_out;
3667 		attr_offset = lseek(fd, 0, SEEK_CUR);
3668 	} else {
3669 		lseek(fd, attr_offset, SEEK_SET);
3670 	}
3671 
3672 	evlist__for_each_entry(session->evlist, evsel) {
3673 		evsel->id_offset = attr_offset;
3674 		/* Avoid writing at the end of the file until the session is exiting. */
3675 		if (!write_attrs_after_data || at_exit) {
3676 			err = do_write(&ff, evsel->core.id, evsel->core.ids * sizeof(u64));
3677 			if (err < 0) {
3678 				pr_debug("failed to write perf header\n");
3679 				goto err_out;
3680 			}
3681 		}
3682 		attr_offset += evsel->core.ids * sizeof(u64);
3683 	}
3684 
3685 	evlist__for_each_entry(evlist, evsel) {
3686 		if (evsel->core.attr.size < sizeof(evsel->core.attr)) {
3687 			/*
3688 			 * We are likely in "perf inject" and have read
3689 			 * from an older file. Update attr size so that
3690 			 * reader gets the right offset to the ids.
3691 			 */
3692 			evsel->core.attr.size = sizeof(evsel->core.attr);
3693 		}
3694 		/* Avoid writing at the end of the file until the session is exiting. */
3695 		if (!write_attrs_after_data || at_exit) {
3696 			struct perf_file_attr f_attr = {
3697 				.attr = evsel->core.attr,
3698 				.ids  = {
3699 					.offset = evsel->id_offset,
3700 					.size   = evsel->core.ids * sizeof(u64),
3701 				}
3702 			};
3703 			err = do_write(&ff, &f_attr, sizeof(f_attr));
3704 			if (err < 0) {
3705 				pr_debug("failed to write perf header attribute\n");
3706 				goto err_out;
3707 			}
3708 		}
3709 		attr_size += sizeof(struct perf_file_attr);
3710 	}
3711 
3712 	if (!header->data_offset) {
3713 		if (write_attrs_after_data)
3714 			header->data_offset = sizeof(f_header);
3715 		else
3716 			header->data_offset = attr_offset + attr_size;
3717 	}
3718 	header->feat_offset = header->data_offset + header->data_size;
3719 
3720 	if (!write_attrs_after_data && at_exit) {
3721 		/* Write features now feat_offset is known. */
3722 		err = perf_header__adds_write(header, evlist, fd, fc);
3723 		if (err < 0)
3724 			goto err_out;
3725 	}
3726 
3727 	f_header = (struct perf_file_header){
3728 		.magic	   = PERF_MAGIC,
3729 		.size	   = sizeof(f_header),
3730 		.attr_size = sizeof(struct perf_file_attr),
3731 		.attrs = {
3732 			.offset = attr_offset,
3733 			.size   = attr_size,
3734 		},
3735 		.data = {
3736 			.offset = header->data_offset,
3737 			.size	= header->data_size,
3738 		},
3739 		/* event_types is ignored, store zeros */
3740 	};
3741 
3742 	memcpy(&f_header.adds_features, &header->adds_features, sizeof(header->adds_features));
3743 
3744 	lseek(fd, 0, SEEK_SET);
3745 	err = do_write(&ff, &f_header, sizeof(f_header));
3746 	if (err < 0) {
3747 		pr_debug("failed to write perf header\n");
3748 		goto err_out;
3749 	} else {
3750 		lseek(fd, 0, SEEK_END);
3751 		err = 0;
3752 	}
3753 err_out:
3754 	free(ff.buf);
3755 	return err;
3756 }
3757 
3758 int perf_session__write_header(struct perf_session *session,
3759 			       struct evlist *evlist,
3760 			       int fd, bool at_exit)
3761 {
3762 	return perf_session__do_write_header(session, evlist, fd, at_exit, /*fc=*/NULL,
3763 					     /*write_attrs_after_data=*/false);
3764 }
3765 
3766 size_t perf_session__data_offset(const struct evlist *evlist)
3767 {
3768 	struct evsel *evsel;
3769 	size_t data_offset;
3770 
3771 	data_offset = sizeof(struct perf_file_header);
3772 	evlist__for_each_entry(evlist, evsel) {
3773 		data_offset += evsel->core.ids * sizeof(u64);
3774 	}
3775 	data_offset += evlist->core.nr_entries * sizeof(struct perf_file_attr);
3776 
3777 	return data_offset;
3778 }
3779 
3780 int perf_session__inject_header(struct perf_session *session,
3781 				struct evlist *evlist,
3782 				int fd,
3783 				struct feat_copier *fc,
3784 				bool write_attrs_after_data)
3785 {
3786 	return perf_session__do_write_header(session, evlist, fd, true, fc,
3787 					     write_attrs_after_data);
3788 }
3789 
3790 static int perf_header__getbuffer64(struct perf_header *header,
3791 				    int fd, void *buf, size_t size)
3792 {
3793 	if (readn(fd, buf, size) <= 0)
3794 		return -1;
3795 
3796 	if (header->needs_swap)
3797 		mem_bswap_64(buf, size);
3798 
3799 	return 0;
3800 }
3801 
3802 int perf_header__process_sections(struct perf_header *header, int fd,
3803 				  void *data,
3804 				  int (*process)(struct perf_file_section *section,
3805 						 struct perf_header *ph,
3806 						 int feat, int fd, void *data))
3807 {
3808 	struct perf_file_section *feat_sec, *sec;
3809 	int nr_sections;
3810 	int sec_size;
3811 	int feat;
3812 	int err;
3813 
3814 	nr_sections = bitmap_weight(header->adds_features, HEADER_FEAT_BITS);
3815 	if (!nr_sections)
3816 		return 0;
3817 
3818 	feat_sec = sec = calloc(nr_sections, sizeof(*feat_sec));
3819 	if (!feat_sec)
3820 		return -1;
3821 
3822 	sec_size = sizeof(*feat_sec) * nr_sections;
3823 
3824 	lseek(fd, header->feat_offset, SEEK_SET);
3825 
3826 	err = perf_header__getbuffer64(header, fd, feat_sec, sec_size);
3827 	if (err < 0)
3828 		goto out_free;
3829 
3830 	for_each_set_bit(feat, header->adds_features, HEADER_LAST_FEATURE) {
3831 		err = process(sec++, header, feat, fd, data);
3832 		if (err < 0)
3833 			goto out_free;
3834 	}
3835 	err = 0;
3836 out_free:
3837 	free(feat_sec);
3838 	return err;
3839 }
3840 
3841 static const int attr_file_abi_sizes[] = {
3842 	[0] = PERF_ATTR_SIZE_VER0,
3843 	[1] = PERF_ATTR_SIZE_VER1,
3844 	[2] = PERF_ATTR_SIZE_VER2,
3845 	[3] = PERF_ATTR_SIZE_VER3,
3846 	[4] = PERF_ATTR_SIZE_VER4,
3847 	0,
3848 };
3849 
3850 /*
3851  * In the legacy file format, the magic number is not used to encode endianness.
3852  * hdr_sz was used to encode endianness. But given that hdr_sz can vary based
3853  * on ABI revisions, we need to try all combinations for all endianness to
3854  * detect the endianness.
3855  */
3856 static int try_all_file_abis(uint64_t hdr_sz, struct perf_header *ph)
3857 {
3858 	uint64_t ref_size, attr_size;
3859 	int i;
3860 
3861 	for (i = 0 ; attr_file_abi_sizes[i]; i++) {
3862 		ref_size = attr_file_abi_sizes[i]
3863 			 + sizeof(struct perf_file_section);
3864 		if (hdr_sz != ref_size) {
3865 			attr_size = bswap_64(hdr_sz);
3866 			if (attr_size != ref_size)
3867 				continue;
3868 
3869 			ph->needs_swap = true;
3870 		}
3871 		pr_debug("ABI%d perf.data file detected, need_swap=%d\n",
3872 			 i,
3873 			 ph->needs_swap);
3874 		return 0;
3875 	}
3876 	/* could not determine endianness */
3877 	return -1;
3878 }
3879 
3880 #define PERF_PIPE_HDR_VER0	16
3881 
3882 static const size_t attr_pipe_abi_sizes[] = {
3883 	[0] = PERF_PIPE_HDR_VER0,
3884 	0,
3885 };
3886 
3887 /*
3888  * In the legacy pipe format, there is an implicit assumption that endianness
3889  * between host recording the samples, and host parsing the samples is the
3890  * same. This is not always the case given that the pipe output may always be
3891  * redirected into a file and analyzed on a different machine with possibly a
3892  * different endianness and perf_event ABI revisions in the perf tool itself.
3893  */
3894 static int try_all_pipe_abis(uint64_t hdr_sz, struct perf_header *ph)
3895 {
3896 	u64 attr_size;
3897 	int i;
3898 
3899 	for (i = 0 ; attr_pipe_abi_sizes[i]; i++) {
3900 		if (hdr_sz != attr_pipe_abi_sizes[i]) {
3901 			attr_size = bswap_64(hdr_sz);
3902 			if (attr_size != hdr_sz)
3903 				continue;
3904 
3905 			ph->needs_swap = true;
3906 		}
3907 		pr_debug("Pipe ABI%d perf.data file detected\n", i);
3908 		return 0;
3909 	}
3910 	return -1;
3911 }
3912 
3913 bool is_perf_magic(u64 magic)
3914 {
3915 	if (!memcmp(&magic, __perf_magic1, sizeof(magic))
3916 		|| magic == __perf_magic2
3917 		|| magic == __perf_magic2_sw)
3918 		return true;
3919 
3920 	return false;
3921 }
3922 
3923 static int check_magic_endian(u64 magic, uint64_t hdr_sz,
3924 			      bool is_pipe, struct perf_header *ph)
3925 {
3926 	int ret;
3927 
3928 	/* check for legacy format */
3929 	ret = memcmp(&magic, __perf_magic1, sizeof(magic));
3930 	if (ret == 0) {
3931 		ph->version = PERF_HEADER_VERSION_1;
3932 		pr_debug("legacy perf.data format\n");
3933 		if (is_pipe)
3934 			return try_all_pipe_abis(hdr_sz, ph);
3935 
3936 		return try_all_file_abis(hdr_sz, ph);
3937 	}
3938 	/*
3939 	 * the new magic number serves two purposes:
3940 	 * - unique number to identify actual perf.data files
3941 	 * - encode endianness of file
3942 	 */
3943 	ph->version = PERF_HEADER_VERSION_2;
3944 
3945 	/* check magic number with one endianness */
3946 	if (magic == __perf_magic2)
3947 		return 0;
3948 
3949 	/* check magic number with opposite endianness */
3950 	if (magic != __perf_magic2_sw)
3951 		return -1;
3952 
3953 	ph->needs_swap = true;
3954 
3955 	return 0;
3956 }
3957 
3958 int perf_file_header__read(struct perf_file_header *header,
3959 			   struct perf_header *ph, int fd)
3960 {
3961 	ssize_t ret;
3962 
3963 	lseek(fd, 0, SEEK_SET);
3964 
3965 	ret = readn(fd, header, sizeof(*header));
3966 	if (ret <= 0)
3967 		return -1;
3968 
3969 	if (check_magic_endian(header->magic,
3970 			       header->attr_size, false, ph) < 0) {
3971 		pr_debug("magic/endian check failed\n");
3972 		return -1;
3973 	}
3974 
3975 	if (ph->needs_swap) {
3976 		mem_bswap_64(header, offsetof(struct perf_file_header,
3977 			     adds_features));
3978 	}
3979 
3980 	if (header->size > header->attrs.offset) {
3981 		pr_err("Perf file header corrupt: header overlaps attrs\n");
3982 		return -1;
3983 	}
3984 
3985 	if (header->size > header->data.offset) {
3986 		pr_err("Perf file header corrupt: header overlaps data\n");
3987 		return -1;
3988 	}
3989 
3990 	if ((header->attrs.offset <= header->data.offset &&
3991 	     header->attrs.offset + header->attrs.size > header->data.offset) ||
3992 	    (header->attrs.offset > header->data.offset &&
3993 	     header->data.offset + header->data.size > header->attrs.offset)) {
3994 		pr_err("Perf file header corrupt: Attributes and data overlap\n");
3995 		return -1;
3996 	}
3997 
3998 	if (header->size != sizeof(*header)) {
3999 		/* Support the previous format */
4000 		if (header->size == offsetof(typeof(*header), adds_features))
4001 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
4002 		else
4003 			return -1;
4004 	} else if (ph->needs_swap) {
4005 		/*
4006 		 * feature bitmap is declared as an array of unsigned longs --
4007 		 * not good since its size can differ between the host that
4008 		 * generated the data file and the host analyzing the file.
4009 		 *
4010 		 * We need to handle endianness, but we don't know the size of
4011 		 * the unsigned long where the file was generated. Take a best
4012 		 * guess at determining it: try 64-bit swap first (ie., file
4013 		 * created on a 64-bit host), and check if the hostname feature
4014 		 * bit is set (this feature bit is forced on as of fbe96f2).
4015 		 * If the bit is not, undo the 64-bit swap and try a 32-bit
4016 		 * swap. If the hostname bit is still not set (e.g., older data
4017 		 * file), punt and fallback to the original behavior --
4018 		 * clearing all feature bits and setting buildid.
4019 		 */
4020 		mem_bswap_64(&header->adds_features,
4021 			    BITS_TO_U64(HEADER_FEAT_BITS));
4022 
4023 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
4024 			/* unswap as u64 */
4025 			mem_bswap_64(&header->adds_features,
4026 				    BITS_TO_U64(HEADER_FEAT_BITS));
4027 
4028 			/* unswap as u32 */
4029 			mem_bswap_32(&header->adds_features,
4030 				    BITS_TO_U32(HEADER_FEAT_BITS));
4031 		}
4032 
4033 		if (!test_bit(HEADER_HOSTNAME, header->adds_features)) {
4034 			bitmap_zero(header->adds_features, HEADER_FEAT_BITS);
4035 			__set_bit(HEADER_BUILD_ID, header->adds_features);
4036 		}
4037 	}
4038 
4039 	memcpy(&ph->adds_features, &header->adds_features,
4040 	       sizeof(ph->adds_features));
4041 
4042 	ph->data_offset  = header->data.offset;
4043 	ph->data_size	 = header->data.size;
4044 	ph->feat_offset  = header->data.offset + header->data.size;
4045 	return 0;
4046 }
4047 
4048 static int perf_file_section__process(struct perf_file_section *section,
4049 				      struct perf_header *ph,
4050 				      int feat, int fd, void *data)
4051 {
4052 	struct feat_fd fdd = {
4053 		.fd	= fd,
4054 		.ph	= ph,
4055 		.size	= section->size,
4056 		.offset	= section->offset,
4057 	};
4058 
4059 	if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
4060 		pr_debug("Failed to lseek to %" PRIu64 " offset for feature "
4061 			  "%d, continuing...\n", section->offset, feat);
4062 		return 0;
4063 	}
4064 
4065 	if (feat >= HEADER_LAST_FEATURE) {
4066 		pr_debug("unknown feature %d, continuing...\n", feat);
4067 		return 0;
4068 	}
4069 
4070 	if (!feat_ops[feat].process)
4071 		return 0;
4072 
4073 	return feat_ops[feat].process(&fdd, data);
4074 }
4075 
4076 static int perf_file_header__read_pipe(struct perf_pipe_file_header *header,
4077 				       struct perf_header *ph,
4078 				       struct perf_data *data)
4079 {
4080 	ssize_t ret;
4081 
4082 	ret = perf_data__read(data, header, sizeof(*header));
4083 	if (ret <= 0)
4084 		return -1;
4085 
4086 	if (check_magic_endian(header->magic, header->size, true, ph) < 0) {
4087 		pr_debug("endian/magic failed\n");
4088 		return -1;
4089 	}
4090 
4091 	if (ph->needs_swap)
4092 		header->size = bswap_64(header->size);
4093 
4094 	return 0;
4095 }
4096 
4097 static int perf_header__read_pipe(struct perf_session *session)
4098 {
4099 	struct perf_header *header = &session->header;
4100 	struct perf_pipe_file_header f_header;
4101 
4102 	if (perf_file_header__read_pipe(&f_header, header, session->data) < 0) {
4103 		pr_debug("incompatible file format\n");
4104 		return -EINVAL;
4105 	}
4106 
4107 	return f_header.size == sizeof(f_header) ? 0 : -1;
4108 }
4109 
4110 static int read_attr(int fd, struct perf_header *ph,
4111 		     struct perf_file_attr *f_attr)
4112 {
4113 	struct perf_event_attr *attr = &f_attr->attr;
4114 	size_t sz, left;
4115 	size_t our_sz = sizeof(f_attr->attr);
4116 	ssize_t ret;
4117 
4118 	memset(f_attr, 0, sizeof(*f_attr));
4119 
4120 	/* read minimal guaranteed structure */
4121 	ret = readn(fd, attr, PERF_ATTR_SIZE_VER0);
4122 	if (ret <= 0) {
4123 		pr_debug("cannot read %d bytes of header attr\n",
4124 			 PERF_ATTR_SIZE_VER0);
4125 		return -1;
4126 	}
4127 
4128 	/* on file perf_event_attr size */
4129 	sz = attr->size;
4130 
4131 	if (ph->needs_swap)
4132 		sz = bswap_32(sz);
4133 
4134 	if (sz == 0) {
4135 		/* assume ABI0 */
4136 		sz =  PERF_ATTR_SIZE_VER0;
4137 	} else if (sz > our_sz) {
4138 		pr_debug("file uses a more recent and unsupported ABI"
4139 			 " (%zu bytes extra)\n", sz - our_sz);
4140 		return -1;
4141 	}
4142 	/* what we have not yet read and that we know about */
4143 	left = sz - PERF_ATTR_SIZE_VER0;
4144 	if (left) {
4145 		void *ptr = attr;
4146 		ptr += PERF_ATTR_SIZE_VER0;
4147 
4148 		ret = readn(fd, ptr, left);
4149 	}
4150 	/* read perf_file_section, ids are read in caller */
4151 	ret = readn(fd, &f_attr->ids, sizeof(f_attr->ids));
4152 
4153 	return ret <= 0 ? -1 : 0;
4154 }
4155 
4156 #ifdef HAVE_LIBTRACEEVENT
4157 static int evsel__prepare_tracepoint_event(struct evsel *evsel, struct tep_handle *pevent)
4158 {
4159 	struct tep_event *event;
4160 	char bf[128];
4161 
4162 	/* already prepared */
4163 	if (evsel->tp_format)
4164 		return 0;
4165 
4166 	if (pevent == NULL) {
4167 		pr_debug("broken or missing trace data\n");
4168 		return -1;
4169 	}
4170 
4171 	event = tep_find_event(pevent, evsel->core.attr.config);
4172 	if (event == NULL) {
4173 		pr_debug("cannot find event format for %d\n", (int)evsel->core.attr.config);
4174 		return -1;
4175 	}
4176 
4177 	if (!evsel->name) {
4178 		snprintf(bf, sizeof(bf), "%s:%s", event->system, event->name);
4179 		evsel->name = strdup(bf);
4180 		if (evsel->name == NULL)
4181 			return -1;
4182 	}
4183 
4184 	evsel->tp_format = event;
4185 	return 0;
4186 }
4187 
4188 static int evlist__prepare_tracepoint_events(struct evlist *evlist, struct tep_handle *pevent)
4189 {
4190 	struct evsel *pos;
4191 
4192 	evlist__for_each_entry(evlist, pos) {
4193 		if (pos->core.attr.type == PERF_TYPE_TRACEPOINT &&
4194 		    evsel__prepare_tracepoint_event(pos, pevent))
4195 			return -1;
4196 	}
4197 
4198 	return 0;
4199 }
4200 #endif
4201 
4202 int perf_session__read_header(struct perf_session *session)
4203 {
4204 	struct perf_data *data = session->data;
4205 	struct perf_header *header = &session->header;
4206 	struct perf_file_header	f_header;
4207 	struct perf_file_attr	f_attr;
4208 	u64			f_id;
4209 	int nr_attrs, nr_ids, i, j, err;
4210 	int fd = perf_data__fd(data);
4211 
4212 	session->evlist = evlist__new();
4213 	if (session->evlist == NULL)
4214 		return -ENOMEM;
4215 
4216 	session->evlist->env = &header->env;
4217 	session->machines.host.env = &header->env;
4218 
4219 	/*
4220 	 * We can read 'pipe' data event from regular file,
4221 	 * check for the pipe header regardless of source.
4222 	 */
4223 	err = perf_header__read_pipe(session);
4224 	if (!err || perf_data__is_pipe(data)) {
4225 		data->is_pipe = true;
4226 		return err;
4227 	}
4228 
4229 	if (perf_file_header__read(&f_header, header, fd) < 0)
4230 		return -EINVAL;
4231 
4232 	if (header->needs_swap && data->in_place_update) {
4233 		pr_err("In-place update not supported when byte-swapping is required\n");
4234 		return -EINVAL;
4235 	}
4236 
4237 	/*
4238 	 * Sanity check that perf.data was written cleanly; data size is
4239 	 * initialized to 0 and updated only if the on_exit function is run.
4240 	 * If data size is still 0 then the file contains only partial
4241 	 * information.  Just warn user and process it as much as it can.
4242 	 */
4243 	if (f_header.data.size == 0) {
4244 		pr_warning("WARNING: The %s file's data size field is 0 which is unexpected.\n"
4245 			   "Was the 'perf record' command properly terminated?\n",
4246 			   data->file.path);
4247 	}
4248 
4249 	if (f_header.attr_size == 0) {
4250 		pr_err("ERROR: The %s file's attr size field is 0 which is unexpected.\n"
4251 		       "Was the 'perf record' command properly terminated?\n",
4252 		       data->file.path);
4253 		return -EINVAL;
4254 	}
4255 
4256 	nr_attrs = f_header.attrs.size / f_header.attr_size;
4257 	lseek(fd, f_header.attrs.offset, SEEK_SET);
4258 
4259 	for (i = 0; i < nr_attrs; i++) {
4260 		struct evsel *evsel;
4261 		off_t tmp;
4262 
4263 		if (read_attr(fd, header, &f_attr) < 0)
4264 			goto out_errno;
4265 
4266 		if (header->needs_swap) {
4267 			f_attr.ids.size   = bswap_64(f_attr.ids.size);
4268 			f_attr.ids.offset = bswap_64(f_attr.ids.offset);
4269 			perf_event__attr_swap(&f_attr.attr);
4270 		}
4271 
4272 		tmp = lseek(fd, 0, SEEK_CUR);
4273 		evsel = evsel__new(&f_attr.attr);
4274 
4275 		if (evsel == NULL)
4276 			goto out_delete_evlist;
4277 
4278 		evsel->needs_swap = header->needs_swap;
4279 		/*
4280 		 * Do it before so that if perf_evsel__alloc_id fails, this
4281 		 * entry gets purged too at evlist__delete().
4282 		 */
4283 		evlist__add(session->evlist, evsel);
4284 
4285 		nr_ids = f_attr.ids.size / sizeof(u64);
4286 		/*
4287 		 * We don't have the cpu and thread maps on the header, so
4288 		 * for allocating the perf_sample_id table we fake 1 cpu and
4289 		 * hattr->ids threads.
4290 		 */
4291 		if (perf_evsel__alloc_id(&evsel->core, 1, nr_ids))
4292 			goto out_delete_evlist;
4293 
4294 		lseek(fd, f_attr.ids.offset, SEEK_SET);
4295 
4296 		for (j = 0; j < nr_ids; j++) {
4297 			if (perf_header__getbuffer64(header, fd, &f_id, sizeof(f_id)))
4298 				goto out_errno;
4299 
4300 			perf_evlist__id_add(&session->evlist->core, &evsel->core, 0, j, f_id);
4301 		}
4302 
4303 		lseek(fd, tmp, SEEK_SET);
4304 	}
4305 
4306 #ifdef HAVE_LIBTRACEEVENT
4307 	perf_header__process_sections(header, fd, &session->tevent,
4308 				      perf_file_section__process);
4309 
4310 	if (evlist__prepare_tracepoint_events(session->evlist, session->tevent.pevent))
4311 		goto out_delete_evlist;
4312 #else
4313 	perf_header__process_sections(header, fd, NULL, perf_file_section__process);
4314 #endif
4315 
4316 	return 0;
4317 out_errno:
4318 	return -errno;
4319 
4320 out_delete_evlist:
4321 	evlist__delete(session->evlist);
4322 	session->evlist = NULL;
4323 	return -ENOMEM;
4324 }
4325 
4326 int perf_event__process_feature(struct perf_session *session,
4327 				union perf_event *event)
4328 {
4329 	const struct perf_tool *tool = session->tool;
4330 	struct feat_fd ff = { .fd = 0 };
4331 	struct perf_record_header_feature *fe = (struct perf_record_header_feature *)event;
4332 	int type = fe->header.type;
4333 	u64 feat = fe->feat_id;
4334 	int ret = 0;
4335 
4336 	if (type < 0 || type >= PERF_RECORD_HEADER_MAX) {
4337 		pr_warning("invalid record type %d in pipe-mode\n", type);
4338 		return 0;
4339 	}
4340 	if (feat == HEADER_RESERVED || feat >= HEADER_LAST_FEATURE) {
4341 		pr_warning("invalid record type %d in pipe-mode\n", type);
4342 		return -1;
4343 	}
4344 
4345 	if (!feat_ops[feat].process)
4346 		return 0;
4347 
4348 	ff.buf  = (void *)fe->data;
4349 	ff.size = event->header.size - sizeof(*fe);
4350 	ff.ph = &session->header;
4351 
4352 	if (feat_ops[feat].process(&ff, NULL)) {
4353 		ret = -1;
4354 		goto out;
4355 	}
4356 
4357 	if (!feat_ops[feat].print || !tool->show_feat_hdr)
4358 		goto out;
4359 
4360 	if (!feat_ops[feat].full_only ||
4361 	    tool->show_feat_hdr >= SHOW_FEAT_HEADER_FULL_INFO) {
4362 		feat_ops[feat].print(&ff, stdout);
4363 	} else {
4364 		fprintf(stdout, "# %s info available, use -I to display\n",
4365 			feat_ops[feat].name);
4366 	}
4367 out:
4368 	free_event_desc(ff.events);
4369 	return ret;
4370 }
4371 
4372 size_t perf_event__fprintf_event_update(union perf_event *event, FILE *fp)
4373 {
4374 	struct perf_record_event_update *ev = &event->event_update;
4375 	struct perf_cpu_map *map;
4376 	size_t ret;
4377 
4378 	ret = fprintf(fp, "\n... id:    %" PRI_lu64 "\n", ev->id);
4379 
4380 	switch (ev->type) {
4381 	case PERF_EVENT_UPDATE__SCALE:
4382 		ret += fprintf(fp, "... scale: %f\n", ev->scale.scale);
4383 		break;
4384 	case PERF_EVENT_UPDATE__UNIT:
4385 		ret += fprintf(fp, "... unit:  %s\n", ev->unit);
4386 		break;
4387 	case PERF_EVENT_UPDATE__NAME:
4388 		ret += fprintf(fp, "... name:  %s\n", ev->name);
4389 		break;
4390 	case PERF_EVENT_UPDATE__CPUS:
4391 		ret += fprintf(fp, "... ");
4392 
4393 		map = cpu_map__new_data(&ev->cpus.cpus);
4394 		if (map) {
4395 			ret += cpu_map__fprintf(map, fp);
4396 			perf_cpu_map__put(map);
4397 		} else
4398 			ret += fprintf(fp, "failed to get cpus\n");
4399 		break;
4400 	default:
4401 		ret += fprintf(fp, "... unknown type\n");
4402 		break;
4403 	}
4404 
4405 	return ret;
4406 }
4407 
4408 int perf_event__process_attr(const struct perf_tool *tool __maybe_unused,
4409 			     union perf_event *event,
4410 			     struct evlist **pevlist)
4411 {
4412 	u32 i, n_ids;
4413 	u64 *ids;
4414 	struct evsel *evsel;
4415 	struct evlist *evlist = *pevlist;
4416 
4417 	if (evlist == NULL) {
4418 		*pevlist = evlist = evlist__new();
4419 		if (evlist == NULL)
4420 			return -ENOMEM;
4421 	}
4422 
4423 	evsel = evsel__new(&event->attr.attr);
4424 	if (evsel == NULL)
4425 		return -ENOMEM;
4426 
4427 	evlist__add(evlist, evsel);
4428 
4429 	n_ids = event->header.size - sizeof(event->header) - event->attr.attr.size;
4430 	n_ids = n_ids / sizeof(u64);
4431 	/*
4432 	 * We don't have the cpu and thread maps on the header, so
4433 	 * for allocating the perf_sample_id table we fake 1 cpu and
4434 	 * hattr->ids threads.
4435 	 */
4436 	if (perf_evsel__alloc_id(&evsel->core, 1, n_ids))
4437 		return -ENOMEM;
4438 
4439 	ids = perf_record_header_attr_id(event);
4440 	for (i = 0; i < n_ids; i++) {
4441 		perf_evlist__id_add(&evlist->core, &evsel->core, 0, i, ids[i]);
4442 	}
4443 
4444 	return 0;
4445 }
4446 
4447 int perf_event__process_event_update(const struct perf_tool *tool __maybe_unused,
4448 				     union perf_event *event,
4449 				     struct evlist **pevlist)
4450 {
4451 	struct perf_record_event_update *ev = &event->event_update;
4452 	struct evlist *evlist;
4453 	struct evsel *evsel;
4454 	struct perf_cpu_map *map;
4455 
4456 	if (dump_trace)
4457 		perf_event__fprintf_event_update(event, stdout);
4458 
4459 	if (!pevlist || *pevlist == NULL)
4460 		return -EINVAL;
4461 
4462 	evlist = *pevlist;
4463 
4464 	evsel = evlist__id2evsel(evlist, ev->id);
4465 	if (evsel == NULL)
4466 		return -EINVAL;
4467 
4468 	switch (ev->type) {
4469 	case PERF_EVENT_UPDATE__UNIT:
4470 		free((char *)evsel->unit);
4471 		evsel->unit = strdup(ev->unit);
4472 		break;
4473 	case PERF_EVENT_UPDATE__NAME:
4474 		free(evsel->name);
4475 		evsel->name = strdup(ev->name);
4476 		break;
4477 	case PERF_EVENT_UPDATE__SCALE:
4478 		evsel->scale = ev->scale.scale;
4479 		break;
4480 	case PERF_EVENT_UPDATE__CPUS:
4481 		map = cpu_map__new_data(&ev->cpus.cpus);
4482 		if (map) {
4483 			perf_cpu_map__put(evsel->core.own_cpus);
4484 			evsel->core.own_cpus = map;
4485 		} else
4486 			pr_err("failed to get event_update cpus\n");
4487 	default:
4488 		break;
4489 	}
4490 
4491 	return 0;
4492 }
4493 
4494 #ifdef HAVE_LIBTRACEEVENT
4495 int perf_event__process_tracing_data(struct perf_session *session,
4496 				     union perf_event *event)
4497 {
4498 	ssize_t size_read, padding, size = event->tracing_data.size;
4499 	int fd = perf_data__fd(session->data);
4500 	char buf[BUFSIZ];
4501 
4502 	/*
4503 	 * The pipe fd is already in proper place and in any case
4504 	 * we can't move it, and we'd screw the case where we read
4505 	 * 'pipe' data from regular file. The trace_report reads
4506 	 * data from 'fd' so we need to set it directly behind the
4507 	 * event, where the tracing data starts.
4508 	 */
4509 	if (!perf_data__is_pipe(session->data)) {
4510 		off_t offset = lseek(fd, 0, SEEK_CUR);
4511 
4512 		/* setup for reading amidst mmap */
4513 		lseek(fd, offset + sizeof(struct perf_record_header_tracing_data),
4514 		      SEEK_SET);
4515 	}
4516 
4517 	size_read = trace_report(fd, &session->tevent, session->trace_event_repipe);
4518 	padding = PERF_ALIGN(size_read, sizeof(u64)) - size_read;
4519 
4520 	if (readn(fd, buf, padding) < 0) {
4521 		pr_err("%s: reading input file", __func__);
4522 		return -1;
4523 	}
4524 	if (session->trace_event_repipe) {
4525 		int retw = write(STDOUT_FILENO, buf, padding);
4526 		if (retw <= 0 || retw != padding) {
4527 			pr_err("%s: repiping tracing data padding", __func__);
4528 			return -1;
4529 		}
4530 	}
4531 
4532 	if (size_read + padding != size) {
4533 		pr_err("%s: tracing data size mismatch", __func__);
4534 		return -1;
4535 	}
4536 
4537 	evlist__prepare_tracepoint_events(session->evlist, session->tevent.pevent);
4538 
4539 	return size_read + padding;
4540 }
4541 #endif
4542 
4543 int perf_event__process_build_id(struct perf_session *session,
4544 				 union perf_event *event)
4545 {
4546 	__event_process_build_id(&event->build_id,
4547 				 event->build_id.filename,
4548 				 session);
4549 	return 0;
4550 }
4551