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