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