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