Merge tag 'leds-5.12-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/pavel...
[linux-2.6-microblaze.git] / tools / perf / util / synthetic-events.c
1 // SPDX-License-Identifier: GPL-2.0-only 
2
3 #include "util/debug.h"
4 #include "util/dso.h"
5 #include "util/event.h"
6 #include "util/evlist.h"
7 #include "util/machine.h"
8 #include "util/map.h"
9 #include "util/map_symbol.h"
10 #include "util/branch.h"
11 #include "util/memswap.h"
12 #include "util/namespaces.h"
13 #include "util/session.h"
14 #include "util/stat.h"
15 #include "util/symbol.h"
16 #include "util/synthetic-events.h"
17 #include "util/target.h"
18 #include "util/time-utils.h"
19 #include "util/cgroup.h"
20 #include <linux/bitops.h>
21 #include <linux/kernel.h>
22 #include <linux/string.h>
23 #include <linux/zalloc.h>
24 #include <linux/perf_event.h>
25 #include <asm/bug.h>
26 #include <perf/evsel.h>
27 #include <perf/cpumap.h>
28 #include <internal/lib.h> // page_size
29 #include <internal/threadmap.h>
30 #include <perf/threadmap.h>
31 #include <symbol/kallsyms.h>
32 #include <dirent.h>
33 #include <errno.h>
34 #include <inttypes.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <uapi/linux/mman.h> /* To get things like MAP_HUGETLB even on older libc headers */
38 #include <api/fs/fs.h>
39 #include <api/io.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <fcntl.h>
43 #include <unistd.h>
44
45 #define DEFAULT_PROC_MAP_PARSE_TIMEOUT 500
46
47 unsigned int proc_map_timeout = DEFAULT_PROC_MAP_PARSE_TIMEOUT;
48
49 int perf_tool__process_synth_event(struct perf_tool *tool,
50                                    union perf_event *event,
51                                    struct machine *machine,
52                                    perf_event__handler_t process)
53 {
54         struct perf_sample synth_sample = {
55                 .pid       = -1,
56                 .tid       = -1,
57                 .time      = -1,
58                 .stream_id = -1,
59                 .cpu       = -1,
60                 .period    = 1,
61                 .cpumode   = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK,
62         };
63
64         return process(tool, event, &synth_sample, machine);
65 };
66
67 /*
68  * Assumes that the first 4095 bytes of /proc/pid/stat contains
69  * the comm, tgid and ppid.
70  */
71 static int perf_event__get_comm_ids(pid_t pid, pid_t tid, char *comm, size_t len,
72                                     pid_t *tgid, pid_t *ppid, bool *kernel)
73 {
74         char bf[4096];
75         int fd;
76         size_t size = 0;
77         ssize_t n;
78         char *name, *tgids, *ppids, *vmpeak, *threads;
79
80         *tgid = -1;
81         *ppid = -1;
82
83         if (pid)
84                 snprintf(bf, sizeof(bf), "/proc/%d/task/%d/status", pid, tid);
85         else
86                 snprintf(bf, sizeof(bf), "/proc/%d/status", tid);
87
88         fd = open(bf, O_RDONLY);
89         if (fd < 0) {
90                 pr_debug("couldn't open %s\n", bf);
91                 return -1;
92         }
93
94         n = read(fd, bf, sizeof(bf) - 1);
95         close(fd);
96         if (n <= 0) {
97                 pr_warning("Couldn't get COMM, tigd and ppid for pid %d\n",
98                            tid);
99                 return -1;
100         }
101         bf[n] = '\0';
102
103         name = strstr(bf, "Name:");
104         tgids = strstr(name ?: bf, "Tgid:");
105         ppids = strstr(tgids ?: bf, "PPid:");
106         vmpeak = strstr(ppids ?: bf, "VmPeak:");
107
108         if (vmpeak)
109                 threads = NULL;
110         else
111                 threads = strstr(ppids ?: bf, "Threads:");
112
113         if (name) {
114                 char *nl;
115
116                 name = skip_spaces(name + 5);  /* strlen("Name:") */
117                 nl = strchr(name, '\n');
118                 if (nl)
119                         *nl = '\0';
120
121                 size = strlen(name);
122                 if (size >= len)
123                         size = len - 1;
124                 memcpy(comm, name, size);
125                 comm[size] = '\0';
126         } else {
127                 pr_debug("Name: string not found for pid %d\n", tid);
128         }
129
130         if (tgids) {
131                 tgids += 5;  /* strlen("Tgid:") */
132                 *tgid = atoi(tgids);
133         } else {
134                 pr_debug("Tgid: string not found for pid %d\n", tid);
135         }
136
137         if (ppids) {
138                 ppids += 5;  /* strlen("PPid:") */
139                 *ppid = atoi(ppids);
140         } else {
141                 pr_debug("PPid: string not found for pid %d\n", tid);
142         }
143
144         if (!vmpeak && threads)
145                 *kernel = true;
146         else
147                 *kernel = false;
148
149         return 0;
150 }
151
152 static int perf_event__prepare_comm(union perf_event *event, pid_t pid, pid_t tid,
153                                     struct machine *machine,
154                                     pid_t *tgid, pid_t *ppid, bool *kernel)
155 {
156         size_t size;
157
158         *ppid = -1;
159
160         memset(&event->comm, 0, sizeof(event->comm));
161
162         if (machine__is_host(machine)) {
163                 if (perf_event__get_comm_ids(pid, tid, event->comm.comm,
164                                              sizeof(event->comm.comm),
165                                              tgid, ppid, kernel) != 0) {
166                         return -1;
167                 }
168         } else {
169                 *tgid = machine->pid;
170         }
171
172         if (*tgid < 0)
173                 return -1;
174
175         event->comm.pid = *tgid;
176         event->comm.header.type = PERF_RECORD_COMM;
177
178         size = strlen(event->comm.comm) + 1;
179         size = PERF_ALIGN(size, sizeof(u64));
180         memset(event->comm.comm + size, 0, machine->id_hdr_size);
181         event->comm.header.size = (sizeof(event->comm) -
182                                 (sizeof(event->comm.comm) - size) +
183                                 machine->id_hdr_size);
184         event->comm.tid = tid;
185
186         return 0;
187 }
188
189 pid_t perf_event__synthesize_comm(struct perf_tool *tool,
190                                          union perf_event *event, pid_t pid,
191                                          perf_event__handler_t process,
192                                          struct machine *machine)
193 {
194         pid_t tgid, ppid;
195         bool kernel_thread;
196
197         if (perf_event__prepare_comm(event, 0, pid, machine, &tgid, &ppid,
198                                      &kernel_thread) != 0)
199                 return -1;
200
201         if (perf_tool__process_synth_event(tool, event, machine, process) != 0)
202                 return -1;
203
204         return tgid;
205 }
206
207 static void perf_event__get_ns_link_info(pid_t pid, const char *ns,
208                                          struct perf_ns_link_info *ns_link_info)
209 {
210         struct stat64 st;
211         char proc_ns[128];
212
213         sprintf(proc_ns, "/proc/%u/ns/%s", pid, ns);
214         if (stat64(proc_ns, &st) == 0) {
215                 ns_link_info->dev = st.st_dev;
216                 ns_link_info->ino = st.st_ino;
217         }
218 }
219
220 int perf_event__synthesize_namespaces(struct perf_tool *tool,
221                                       union perf_event *event,
222                                       pid_t pid, pid_t tgid,
223                                       perf_event__handler_t process,
224                                       struct machine *machine)
225 {
226         u32 idx;
227         struct perf_ns_link_info *ns_link_info;
228
229         if (!tool || !tool->namespace_events)
230                 return 0;
231
232         memset(&event->namespaces, 0, (sizeof(event->namespaces) +
233                (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
234                machine->id_hdr_size));
235
236         event->namespaces.pid = tgid;
237         event->namespaces.tid = pid;
238
239         event->namespaces.nr_namespaces = NR_NAMESPACES;
240
241         ns_link_info = event->namespaces.link_info;
242
243         for (idx = 0; idx < event->namespaces.nr_namespaces; idx++)
244                 perf_event__get_ns_link_info(pid, perf_ns__name(idx),
245                                              &ns_link_info[idx]);
246
247         event->namespaces.header.type = PERF_RECORD_NAMESPACES;
248
249         event->namespaces.header.size = (sizeof(event->namespaces) +
250                         (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
251                         machine->id_hdr_size);
252
253         if (perf_tool__process_synth_event(tool, event, machine, process) != 0)
254                 return -1;
255
256         return 0;
257 }
258
259 static int perf_event__synthesize_fork(struct perf_tool *tool,
260                                        union perf_event *event,
261                                        pid_t pid, pid_t tgid, pid_t ppid,
262                                        perf_event__handler_t process,
263                                        struct machine *machine)
264 {
265         memset(&event->fork, 0, sizeof(event->fork) + machine->id_hdr_size);
266
267         /*
268          * for main thread set parent to ppid from status file. For other
269          * threads set parent pid to main thread. ie., assume main thread
270          * spawns all threads in a process
271         */
272         if (tgid == pid) {
273                 event->fork.ppid = ppid;
274                 event->fork.ptid = ppid;
275         } else {
276                 event->fork.ppid = tgid;
277                 event->fork.ptid = tgid;
278         }
279         event->fork.pid  = tgid;
280         event->fork.tid  = pid;
281         event->fork.header.type = PERF_RECORD_FORK;
282         event->fork.header.misc = PERF_RECORD_MISC_FORK_EXEC;
283
284         event->fork.header.size = (sizeof(event->fork) + machine->id_hdr_size);
285
286         if (perf_tool__process_synth_event(tool, event, machine, process) != 0)
287                 return -1;
288
289         return 0;
290 }
291
292 static bool read_proc_maps_line(struct io *io, __u64 *start, __u64 *end,
293                                 u32 *prot, u32 *flags, __u64 *offset,
294                                 u32 *maj, u32 *min,
295                                 __u64 *inode,
296                                 ssize_t pathname_size, char *pathname)
297 {
298         __u64 temp;
299         int ch;
300         char *start_pathname = pathname;
301
302         if (io__get_hex(io, start) != '-')
303                 return false;
304         if (io__get_hex(io, end) != ' ')
305                 return false;
306
307         /* map protection and flags bits */
308         *prot = 0;
309         ch = io__get_char(io);
310         if (ch == 'r')
311                 *prot |= PROT_READ;
312         else if (ch != '-')
313                 return false;
314         ch = io__get_char(io);
315         if (ch == 'w')
316                 *prot |= PROT_WRITE;
317         else if (ch != '-')
318                 return false;
319         ch = io__get_char(io);
320         if (ch == 'x')
321                 *prot |= PROT_EXEC;
322         else if (ch != '-')
323                 return false;
324         ch = io__get_char(io);
325         if (ch == 's')
326                 *flags = MAP_SHARED;
327         else if (ch == 'p')
328                 *flags = MAP_PRIVATE;
329         else
330                 return false;
331         if (io__get_char(io) != ' ')
332                 return false;
333
334         if (io__get_hex(io, offset) != ' ')
335                 return false;
336
337         if (io__get_hex(io, &temp) != ':')
338                 return false;
339         *maj = temp;
340         if (io__get_hex(io, &temp) != ' ')
341                 return false;
342         *min = temp;
343
344         ch = io__get_dec(io, inode);
345         if (ch != ' ') {
346                 *pathname = '\0';
347                 return ch == '\n';
348         }
349         do {
350                 ch = io__get_char(io);
351         } while (ch == ' ');
352         while (true) {
353                 if (ch < 0)
354                         return false;
355                 if (ch == '\0' || ch == '\n' ||
356                     (pathname + 1 - start_pathname) >= pathname_size) {
357                         *pathname = '\0';
358                         return true;
359                 }
360                 *pathname++ = ch;
361                 ch = io__get_char(io);
362         }
363 }
364
365 static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
366                                              bool is_kernel)
367 {
368         struct build_id bid;
369         int rc;
370
371         if (is_kernel)
372                 rc = sysfs__read_build_id("/sys/kernel/notes", &bid);
373         else
374                 rc = filename__read_build_id(event->filename, &bid) > 0 ? 0 : -1;
375
376         if (rc == 0) {
377                 memcpy(event->build_id, bid.data, sizeof(bid.data));
378                 event->build_id_size = (u8) bid.size;
379                 event->header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
380                 event->__reserved_1 = 0;
381                 event->__reserved_2 = 0;
382         } else {
383                 if (event->filename[0] == '/') {
384                         pr_debug2("Failed to read build ID for %s\n",
385                                   event->filename);
386                 }
387         }
388 }
389
390 int perf_event__synthesize_mmap_events(struct perf_tool *tool,
391                                        union perf_event *event,
392                                        pid_t pid, pid_t tgid,
393                                        perf_event__handler_t process,
394                                        struct machine *machine,
395                                        bool mmap_data)
396 {
397         unsigned long long t;
398         char bf[BUFSIZ];
399         struct io io;
400         bool truncation = false;
401         unsigned long long timeout = proc_map_timeout * 1000000ULL;
402         int rc = 0;
403         const char *hugetlbfs_mnt = hugetlbfs__mountpoint();
404         int hugetlbfs_mnt_len = hugetlbfs_mnt ? strlen(hugetlbfs_mnt) : 0;
405
406         if (machine__is_default_guest(machine))
407                 return 0;
408
409         snprintf(bf, sizeof(bf), "%s/proc/%d/task/%d/maps",
410                 machine->root_dir, pid, pid);
411
412         io.fd = open(bf, O_RDONLY, 0);
413         if (io.fd < 0) {
414                 /*
415                  * We raced with a task exiting - just return:
416                  */
417                 pr_debug("couldn't open %s\n", bf);
418                 return -1;
419         }
420         io__init(&io, io.fd, bf, sizeof(bf));
421
422         event->header.type = PERF_RECORD_MMAP2;
423         t = rdclock();
424
425         while (!io.eof) {
426                 static const char anonstr[] = "//anon";
427                 size_t size;
428
429                 /* ensure null termination since stack will be reused. */
430                 event->mmap2.filename[0] = '\0';
431
432                 /* 00400000-0040c000 r-xp 00000000 fd:01 41038  /bin/cat */
433                 if (!read_proc_maps_line(&io,
434                                         &event->mmap2.start,
435                                         &event->mmap2.len,
436                                         &event->mmap2.prot,
437                                         &event->mmap2.flags,
438                                         &event->mmap2.pgoff,
439                                         &event->mmap2.maj,
440                                         &event->mmap2.min,
441                                         &event->mmap2.ino,
442                                         sizeof(event->mmap2.filename),
443                                         event->mmap2.filename))
444                         continue;
445
446                 if ((rdclock() - t) > timeout) {
447                         pr_warning("Reading %s/proc/%d/task/%d/maps time out. "
448                                    "You may want to increase "
449                                    "the time limit by --proc-map-timeout\n",
450                                    machine->root_dir, pid, pid);
451                         truncation = true;
452                         goto out;
453                 }
454
455                 event->mmap2.ino_generation = 0;
456
457                 /*
458                  * Just like the kernel, see __perf_event_mmap in kernel/perf_event.c
459                  */
460                 if (machine__is_host(machine))
461                         event->header.misc = PERF_RECORD_MISC_USER;
462                 else
463                         event->header.misc = PERF_RECORD_MISC_GUEST_USER;
464
465                 if ((event->mmap2.prot & PROT_EXEC) == 0) {
466                         if (!mmap_data || (event->mmap2.prot & PROT_READ) == 0)
467                                 continue;
468
469                         event->header.misc |= PERF_RECORD_MISC_MMAP_DATA;
470                 }
471
472 out:
473                 if (truncation)
474                         event->header.misc |= PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT;
475
476                 if (!strcmp(event->mmap2.filename, ""))
477                         strcpy(event->mmap2.filename, anonstr);
478
479                 if (hugetlbfs_mnt_len &&
480                     !strncmp(event->mmap2.filename, hugetlbfs_mnt,
481                              hugetlbfs_mnt_len)) {
482                         strcpy(event->mmap2.filename, anonstr);
483                         event->mmap2.flags |= MAP_HUGETLB;
484                 }
485
486                 size = strlen(event->mmap2.filename) + 1;
487                 size = PERF_ALIGN(size, sizeof(u64));
488                 event->mmap2.len -= event->mmap.start;
489                 event->mmap2.header.size = (sizeof(event->mmap2) -
490                                         (sizeof(event->mmap2.filename) - size));
491                 memset(event->mmap2.filename + size, 0, machine->id_hdr_size);
492                 event->mmap2.header.size += machine->id_hdr_size;
493                 event->mmap2.pid = tgid;
494                 event->mmap2.tid = pid;
495
496                 if (symbol_conf.buildid_mmap2)
497                         perf_record_mmap2__read_build_id(&event->mmap2, false);
498
499                 if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
500                         rc = -1;
501                         break;
502                 }
503
504                 if (truncation)
505                         break;
506         }
507
508         close(io.fd);
509         return rc;
510 }
511
512 #ifdef HAVE_FILE_HANDLE
513 static int perf_event__synthesize_cgroup(struct perf_tool *tool,
514                                          union perf_event *event,
515                                          char *path, size_t mount_len,
516                                          perf_event__handler_t process,
517                                          struct machine *machine)
518 {
519         size_t event_size = sizeof(event->cgroup) - sizeof(event->cgroup.path);
520         size_t path_len = strlen(path) - mount_len + 1;
521         struct {
522                 struct file_handle fh;
523                 uint64_t cgroup_id;
524         } handle;
525         int mount_id;
526
527         while (path_len % sizeof(u64))
528                 path[mount_len + path_len++] = '\0';
529
530         memset(&event->cgroup, 0, event_size);
531
532         event->cgroup.header.type = PERF_RECORD_CGROUP;
533         event->cgroup.header.size = event_size + path_len + machine->id_hdr_size;
534
535         handle.fh.handle_bytes = sizeof(handle.cgroup_id);
536         if (name_to_handle_at(AT_FDCWD, path, &handle.fh, &mount_id, 0) < 0) {
537                 pr_debug("stat failed: %s\n", path);
538                 return -1;
539         }
540
541         event->cgroup.id = handle.cgroup_id;
542         strncpy(event->cgroup.path, path + mount_len, path_len);
543         memset(event->cgroup.path + path_len, 0, machine->id_hdr_size);
544
545         if (perf_tool__process_synth_event(tool, event, machine, process) < 0) {
546                 pr_debug("process synth event failed\n");
547                 return -1;
548         }
549
550         return 0;
551 }
552
553 static int perf_event__walk_cgroup_tree(struct perf_tool *tool,
554                                         union perf_event *event,
555                                         char *path, size_t mount_len,
556                                         perf_event__handler_t process,
557                                         struct machine *machine)
558 {
559         size_t pos = strlen(path);
560         DIR *d;
561         struct dirent *dent;
562         int ret = 0;
563
564         if (perf_event__synthesize_cgroup(tool, event, path, mount_len,
565                                           process, machine) < 0)
566                 return -1;
567
568         d = opendir(path);
569         if (d == NULL) {
570                 pr_debug("failed to open directory: %s\n", path);
571                 return -1;
572         }
573
574         while ((dent = readdir(d)) != NULL) {
575                 if (dent->d_type != DT_DIR)
576                         continue;
577                 if (!strcmp(dent->d_name, ".") ||
578                     !strcmp(dent->d_name, ".."))
579                         continue;
580
581                 /* any sane path should be less than PATH_MAX */
582                 if (strlen(path) + strlen(dent->d_name) + 1 >= PATH_MAX)
583                         continue;
584
585                 if (path[pos - 1] != '/')
586                         strcat(path, "/");
587                 strcat(path, dent->d_name);
588
589                 ret = perf_event__walk_cgroup_tree(tool, event, path,
590                                                    mount_len, process, machine);
591                 if (ret < 0)
592                         break;
593
594                 path[pos] = '\0';
595         }
596
597         closedir(d);
598         return ret;
599 }
600
601 int perf_event__synthesize_cgroups(struct perf_tool *tool,
602                                    perf_event__handler_t process,
603                                    struct machine *machine)
604 {
605         union perf_event event;
606         char cgrp_root[PATH_MAX];
607         size_t mount_len;  /* length of mount point in the path */
608
609         if (!tool || !tool->cgroup_events)
610                 return 0;
611
612         if (cgroupfs_find_mountpoint(cgrp_root, PATH_MAX, "perf_event") < 0) {
613                 pr_debug("cannot find cgroup mount point\n");
614                 return -1;
615         }
616
617         mount_len = strlen(cgrp_root);
618         /* make sure the path starts with a slash (after mount point) */
619         strcat(cgrp_root, "/");
620
621         if (perf_event__walk_cgroup_tree(tool, &event, cgrp_root, mount_len,
622                                          process, machine) < 0)
623                 return -1;
624
625         return 0;
626 }
627 #else
628 int perf_event__synthesize_cgroups(struct perf_tool *tool __maybe_unused,
629                                    perf_event__handler_t process __maybe_unused,
630                                    struct machine *machine __maybe_unused)
631 {
632         return -1;
633 }
634 #endif
635
636 int perf_event__synthesize_modules(struct perf_tool *tool, perf_event__handler_t process,
637                                    struct machine *machine)
638 {
639         int rc = 0;
640         struct map *pos;
641         struct maps *maps = machine__kernel_maps(machine);
642         union perf_event *event;
643         size_t size = symbol_conf.buildid_mmap2 ?
644                         sizeof(event->mmap2) : sizeof(event->mmap);
645
646         event = zalloc(size + machine->id_hdr_size);
647         if (event == NULL) {
648                 pr_debug("Not enough memory synthesizing mmap event "
649                          "for kernel modules\n");
650                 return -1;
651         }
652
653         /*
654          * kernel uses 0 for user space maps, see kernel/perf_event.c
655          * __perf_event_mmap
656          */
657         if (machine__is_host(machine))
658                 event->header.misc = PERF_RECORD_MISC_KERNEL;
659         else
660                 event->header.misc = PERF_RECORD_MISC_GUEST_KERNEL;
661
662         maps__for_each_entry(maps, pos) {
663                 if (!__map__is_kmodule(pos))
664                         continue;
665
666                 if (symbol_conf.buildid_mmap2) {
667                         size = PERF_ALIGN(pos->dso->long_name_len + 1, sizeof(u64));
668                         event->mmap2.header.type = PERF_RECORD_MMAP2;
669                         event->mmap2.header.size = (sizeof(event->mmap2) -
670                                                 (sizeof(event->mmap2.filename) - size));
671                         memset(event->mmap2.filename + size, 0, machine->id_hdr_size);
672                         event->mmap2.header.size += machine->id_hdr_size;
673                         event->mmap2.start = pos->start;
674                         event->mmap2.len   = pos->end - pos->start;
675                         event->mmap2.pid   = machine->pid;
676
677                         memcpy(event->mmap2.filename, pos->dso->long_name,
678                                pos->dso->long_name_len + 1);
679
680                         perf_record_mmap2__read_build_id(&event->mmap2, false);
681                 } else {
682                         size = PERF_ALIGN(pos->dso->long_name_len + 1, sizeof(u64));
683                         event->mmap.header.type = PERF_RECORD_MMAP;
684                         event->mmap.header.size = (sizeof(event->mmap) -
685                                                 (sizeof(event->mmap.filename) - size));
686                         memset(event->mmap.filename + size, 0, machine->id_hdr_size);
687                         event->mmap.header.size += machine->id_hdr_size;
688                         event->mmap.start = pos->start;
689                         event->mmap.len   = pos->end - pos->start;
690                         event->mmap.pid   = machine->pid;
691
692                         memcpy(event->mmap.filename, pos->dso->long_name,
693                                pos->dso->long_name_len + 1);
694                 }
695
696                 if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
697                         rc = -1;
698                         break;
699                 }
700         }
701
702         free(event);
703         return rc;
704 }
705
706 static int filter_task(const struct dirent *dirent)
707 {
708         return isdigit(dirent->d_name[0]);
709 }
710
711 static int __event__synthesize_thread(union perf_event *comm_event,
712                                       union perf_event *mmap_event,
713                                       union perf_event *fork_event,
714                                       union perf_event *namespaces_event,
715                                       pid_t pid, int full, perf_event__handler_t process,
716                                       struct perf_tool *tool, struct machine *machine, bool mmap_data)
717 {
718         char filename[PATH_MAX];
719         struct dirent **dirent;
720         pid_t tgid, ppid;
721         int rc = 0;
722         int i, n;
723
724         /* special case: only send one comm event using passed in pid */
725         if (!full) {
726                 tgid = perf_event__synthesize_comm(tool, comm_event, pid,
727                                                    process, machine);
728
729                 if (tgid == -1)
730                         return -1;
731
732                 if (perf_event__synthesize_namespaces(tool, namespaces_event, pid,
733                                                       tgid, process, machine) < 0)
734                         return -1;
735
736                 /*
737                  * send mmap only for thread group leader
738                  * see thread__init_maps()
739                  */
740                 if (pid == tgid &&
741                     perf_event__synthesize_mmap_events(tool, mmap_event, pid, tgid,
742                                                        process, machine, mmap_data))
743                         return -1;
744
745                 return 0;
746         }
747
748         if (machine__is_default_guest(machine))
749                 return 0;
750
751         snprintf(filename, sizeof(filename), "%s/proc/%d/task",
752                  machine->root_dir, pid);
753
754         n = scandir(filename, &dirent, filter_task, alphasort);
755         if (n < 0)
756                 return n;
757
758         for (i = 0; i < n; i++) {
759                 char *end;
760                 pid_t _pid;
761                 bool kernel_thread;
762
763                 _pid = strtol(dirent[i]->d_name, &end, 10);
764                 if (*end)
765                         continue;
766
767                 rc = -1;
768                 if (perf_event__prepare_comm(comm_event, pid, _pid, machine,
769                                              &tgid, &ppid, &kernel_thread) != 0)
770                         break;
771
772                 if (perf_event__synthesize_fork(tool, fork_event, _pid, tgid,
773                                                 ppid, process, machine) < 0)
774                         break;
775
776                 if (perf_event__synthesize_namespaces(tool, namespaces_event, _pid,
777                                                       tgid, process, machine) < 0)
778                         break;
779
780                 /*
781                  * Send the prepared comm event
782                  */
783                 if (perf_tool__process_synth_event(tool, comm_event, machine, process) != 0)
784                         break;
785
786                 rc = 0;
787                 if (_pid == pid && !kernel_thread) {
788                         /* process the parent's maps too */
789                         rc = perf_event__synthesize_mmap_events(tool, mmap_event, pid, tgid,
790                                                 process, machine, mmap_data);
791                         if (rc)
792                                 break;
793                 }
794         }
795
796         for (i = 0; i < n; i++)
797                 zfree(&dirent[i]);
798         free(dirent);
799
800         return rc;
801 }
802
803 int perf_event__synthesize_thread_map(struct perf_tool *tool,
804                                       struct perf_thread_map *threads,
805                                       perf_event__handler_t process,
806                                       struct machine *machine,
807                                       bool mmap_data)
808 {
809         union perf_event *comm_event, *mmap_event, *fork_event;
810         union perf_event *namespaces_event;
811         int err = -1, thread, j;
812
813         comm_event = malloc(sizeof(comm_event->comm) + machine->id_hdr_size);
814         if (comm_event == NULL)
815                 goto out;
816
817         mmap_event = malloc(sizeof(mmap_event->mmap2) + machine->id_hdr_size);
818         if (mmap_event == NULL)
819                 goto out_free_comm;
820
821         fork_event = malloc(sizeof(fork_event->fork) + machine->id_hdr_size);
822         if (fork_event == NULL)
823                 goto out_free_mmap;
824
825         namespaces_event = malloc(sizeof(namespaces_event->namespaces) +
826                                   (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
827                                   machine->id_hdr_size);
828         if (namespaces_event == NULL)
829                 goto out_free_fork;
830
831         err = 0;
832         for (thread = 0; thread < threads->nr; ++thread) {
833                 if (__event__synthesize_thread(comm_event, mmap_event,
834                                                fork_event, namespaces_event,
835                                                perf_thread_map__pid(threads, thread), 0,
836                                                process, tool, machine,
837                                                mmap_data)) {
838                         err = -1;
839                         break;
840                 }
841
842                 /*
843                  * comm.pid is set to thread group id by
844                  * perf_event__synthesize_comm
845                  */
846                 if ((int) comm_event->comm.pid != perf_thread_map__pid(threads, thread)) {
847                         bool need_leader = true;
848
849                         /* is thread group leader in thread_map? */
850                         for (j = 0; j < threads->nr; ++j) {
851                                 if ((int) comm_event->comm.pid == perf_thread_map__pid(threads, j)) {
852                                         need_leader = false;
853                                         break;
854                                 }
855                         }
856
857                         /* if not, generate events for it */
858                         if (need_leader &&
859                             __event__synthesize_thread(comm_event, mmap_event,
860                                                        fork_event, namespaces_event,
861                                                        comm_event->comm.pid, 0,
862                                                        process, tool, machine,
863                                                        mmap_data)) {
864                                 err = -1;
865                                 break;
866                         }
867                 }
868         }
869         free(namespaces_event);
870 out_free_fork:
871         free(fork_event);
872 out_free_mmap:
873         free(mmap_event);
874 out_free_comm:
875         free(comm_event);
876 out:
877         return err;
878 }
879
880 static int __perf_event__synthesize_threads(struct perf_tool *tool,
881                                             perf_event__handler_t process,
882                                             struct machine *machine,
883                                             bool mmap_data,
884                                             struct dirent **dirent,
885                                             int start,
886                                             int num)
887 {
888         union perf_event *comm_event, *mmap_event, *fork_event;
889         union perf_event *namespaces_event;
890         int err = -1;
891         char *end;
892         pid_t pid;
893         int i;
894
895         comm_event = malloc(sizeof(comm_event->comm) + machine->id_hdr_size);
896         if (comm_event == NULL)
897                 goto out;
898
899         mmap_event = malloc(sizeof(mmap_event->mmap2) + machine->id_hdr_size);
900         if (mmap_event == NULL)
901                 goto out_free_comm;
902
903         fork_event = malloc(sizeof(fork_event->fork) + machine->id_hdr_size);
904         if (fork_event == NULL)
905                 goto out_free_mmap;
906
907         namespaces_event = malloc(sizeof(namespaces_event->namespaces) +
908                                   (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) +
909                                   machine->id_hdr_size);
910         if (namespaces_event == NULL)
911                 goto out_free_fork;
912
913         for (i = start; i < start + num; i++) {
914                 if (!isdigit(dirent[i]->d_name[0]))
915                         continue;
916
917                 pid = (pid_t)strtol(dirent[i]->d_name, &end, 10);
918                 /* only interested in proper numerical dirents */
919                 if (*end)
920                         continue;
921                 /*
922                  * We may race with exiting thread, so don't stop just because
923                  * one thread couldn't be synthesized.
924                  */
925                 __event__synthesize_thread(comm_event, mmap_event, fork_event,
926                                            namespaces_event, pid, 1, process,
927                                            tool, machine, mmap_data);
928         }
929         err = 0;
930
931         free(namespaces_event);
932 out_free_fork:
933         free(fork_event);
934 out_free_mmap:
935         free(mmap_event);
936 out_free_comm:
937         free(comm_event);
938 out:
939         return err;
940 }
941
942 struct synthesize_threads_arg {
943         struct perf_tool *tool;
944         perf_event__handler_t process;
945         struct machine *machine;
946         bool mmap_data;
947         struct dirent **dirent;
948         int num;
949         int start;
950 };
951
952 static void *synthesize_threads_worker(void *arg)
953 {
954         struct synthesize_threads_arg *args = arg;
955
956         __perf_event__synthesize_threads(args->tool, args->process,
957                                          args->machine, args->mmap_data,
958                                          args->dirent,
959                                          args->start, args->num);
960         return NULL;
961 }
962
963 int perf_event__synthesize_threads(struct perf_tool *tool,
964                                    perf_event__handler_t process,
965                                    struct machine *machine,
966                                    bool mmap_data,
967                                    unsigned int nr_threads_synthesize)
968 {
969         struct synthesize_threads_arg *args = NULL;
970         pthread_t *synthesize_threads = NULL;
971         char proc_path[PATH_MAX];
972         struct dirent **dirent;
973         int num_per_thread;
974         int m, n, i, j;
975         int thread_nr;
976         int base = 0;
977         int err = -1;
978
979
980         if (machine__is_default_guest(machine))
981                 return 0;
982
983         snprintf(proc_path, sizeof(proc_path), "%s/proc", machine->root_dir);
984         n = scandir(proc_path, &dirent, filter_task, alphasort);
985         if (n < 0)
986                 return err;
987
988         if (nr_threads_synthesize == UINT_MAX)
989                 thread_nr = sysconf(_SC_NPROCESSORS_ONLN);
990         else
991                 thread_nr = nr_threads_synthesize;
992
993         if (thread_nr <= 1) {
994                 err = __perf_event__synthesize_threads(tool, process,
995                                                        machine, mmap_data,
996                                                        dirent, base, n);
997                 goto free_dirent;
998         }
999         if (thread_nr > n)
1000                 thread_nr = n;
1001
1002         synthesize_threads = calloc(sizeof(pthread_t), thread_nr);
1003         if (synthesize_threads == NULL)
1004                 goto free_dirent;
1005
1006         args = calloc(sizeof(*args), thread_nr);
1007         if (args == NULL)
1008                 goto free_threads;
1009
1010         num_per_thread = n / thread_nr;
1011         m = n % thread_nr;
1012         for (i = 0; i < thread_nr; i++) {
1013                 args[i].tool = tool;
1014                 args[i].process = process;
1015                 args[i].machine = machine;
1016                 args[i].mmap_data = mmap_data;
1017                 args[i].dirent = dirent;
1018         }
1019         for (i = 0; i < m; i++) {
1020                 args[i].num = num_per_thread + 1;
1021                 args[i].start = i * args[i].num;
1022         }
1023         if (i != 0)
1024                 base = args[i-1].start + args[i-1].num;
1025         for (j = i; j < thread_nr; j++) {
1026                 args[j].num = num_per_thread;
1027                 args[j].start = base + (j - i) * args[i].num;
1028         }
1029
1030         for (i = 0; i < thread_nr; i++) {
1031                 if (pthread_create(&synthesize_threads[i], NULL,
1032                                    synthesize_threads_worker, &args[i]))
1033                         goto out_join;
1034         }
1035         err = 0;
1036 out_join:
1037         for (i = 0; i < thread_nr; i++)
1038                 pthread_join(synthesize_threads[i], NULL);
1039         free(args);
1040 free_threads:
1041         free(synthesize_threads);
1042 free_dirent:
1043         for (i = 0; i < n; i++)
1044                 zfree(&dirent[i]);
1045         free(dirent);
1046
1047         return err;
1048 }
1049
1050 int __weak perf_event__synthesize_extra_kmaps(struct perf_tool *tool __maybe_unused,
1051                                               perf_event__handler_t process __maybe_unused,
1052                                               struct machine *machine __maybe_unused)
1053 {
1054         return 0;
1055 }
1056
1057 static int __perf_event__synthesize_kernel_mmap(struct perf_tool *tool,
1058                                                 perf_event__handler_t process,
1059                                                 struct machine *machine)
1060 {
1061         union perf_event *event;
1062         size_t size = symbol_conf.buildid_mmap2 ?
1063                         sizeof(event->mmap2) : sizeof(event->mmap);
1064         struct map *map = machine__kernel_map(machine);
1065         struct kmap *kmap;
1066         int err;
1067
1068         if (map == NULL)
1069                 return -1;
1070
1071         kmap = map__kmap(map);
1072         if (!kmap->ref_reloc_sym)
1073                 return -1;
1074
1075         /*
1076          * We should get this from /sys/kernel/sections/.text, but till that is
1077          * available use this, and after it is use this as a fallback for older
1078          * kernels.
1079          */
1080         event = zalloc(size + machine->id_hdr_size);
1081         if (event == NULL) {
1082                 pr_debug("Not enough memory synthesizing mmap event "
1083                          "for kernel modules\n");
1084                 return -1;
1085         }
1086
1087         if (machine__is_host(machine)) {
1088                 /*
1089                  * kernel uses PERF_RECORD_MISC_USER for user space maps,
1090                  * see kernel/perf_event.c __perf_event_mmap
1091                  */
1092                 event->header.misc = PERF_RECORD_MISC_KERNEL;
1093         } else {
1094                 event->header.misc = PERF_RECORD_MISC_GUEST_KERNEL;
1095         }
1096
1097         if (symbol_conf.buildid_mmap2) {
1098                 size = snprintf(event->mmap2.filename, sizeof(event->mmap2.filename),
1099                                 "%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;
1100                 size = PERF_ALIGN(size, sizeof(u64));
1101                 event->mmap2.header.type = PERF_RECORD_MMAP2;
1102                 event->mmap2.header.size = (sizeof(event->mmap2) -
1103                                 (sizeof(event->mmap2.filename) - size) + machine->id_hdr_size);
1104                 event->mmap2.pgoff = kmap->ref_reloc_sym->addr;
1105                 event->mmap2.start = map->start;
1106                 event->mmap2.len   = map->end - event->mmap.start;
1107                 event->mmap2.pid   = machine->pid;
1108
1109                 perf_record_mmap2__read_build_id(&event->mmap2, true);
1110         } else {
1111                 size = snprintf(event->mmap.filename, sizeof(event->mmap.filename),
1112                                 "%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;
1113                 size = PERF_ALIGN(size, sizeof(u64));
1114                 event->mmap.header.type = PERF_RECORD_MMAP;
1115                 event->mmap.header.size = (sizeof(event->mmap) -
1116                                 (sizeof(event->mmap.filename) - size) + machine->id_hdr_size);
1117                 event->mmap.pgoff = kmap->ref_reloc_sym->addr;
1118                 event->mmap.start = map->start;
1119                 event->mmap.len   = map->end - event->mmap.start;
1120                 event->mmap.pid   = machine->pid;
1121         }
1122
1123         err = perf_tool__process_synth_event(tool, event, machine, process);
1124         free(event);
1125
1126         return err;
1127 }
1128
1129 int perf_event__synthesize_kernel_mmap(struct perf_tool *tool,
1130                                        perf_event__handler_t process,
1131                                        struct machine *machine)
1132 {
1133         int err;
1134
1135         err = __perf_event__synthesize_kernel_mmap(tool, process, machine);
1136         if (err < 0)
1137                 return err;
1138
1139         return perf_event__synthesize_extra_kmaps(tool, process, machine);
1140 }
1141
1142 int perf_event__synthesize_thread_map2(struct perf_tool *tool,
1143                                       struct perf_thread_map *threads,
1144                                       perf_event__handler_t process,
1145                                       struct machine *machine)
1146 {
1147         union perf_event *event;
1148         int i, err, size;
1149
1150         size  = sizeof(event->thread_map);
1151         size += threads->nr * sizeof(event->thread_map.entries[0]);
1152
1153         event = zalloc(size);
1154         if (!event)
1155                 return -ENOMEM;
1156
1157         event->header.type = PERF_RECORD_THREAD_MAP;
1158         event->header.size = size;
1159         event->thread_map.nr = threads->nr;
1160
1161         for (i = 0; i < threads->nr; i++) {
1162                 struct perf_record_thread_map_entry *entry = &event->thread_map.entries[i];
1163                 char *comm = perf_thread_map__comm(threads, i);
1164
1165                 if (!comm)
1166                         comm = (char *) "";
1167
1168                 entry->pid = perf_thread_map__pid(threads, i);
1169                 strncpy((char *) &entry->comm, comm, sizeof(entry->comm));
1170         }
1171
1172         err = process(tool, event, NULL, machine);
1173
1174         free(event);
1175         return err;
1176 }
1177
1178 static void synthesize_cpus(struct cpu_map_entries *cpus,
1179                             struct perf_cpu_map *map)
1180 {
1181         int i;
1182
1183         cpus->nr = map->nr;
1184
1185         for (i = 0; i < map->nr; i++)
1186                 cpus->cpu[i] = map->map[i];
1187 }
1188
1189 static void synthesize_mask(struct perf_record_record_cpu_map *mask,
1190                             struct perf_cpu_map *map, int max)
1191 {
1192         int i;
1193
1194         mask->nr = BITS_TO_LONGS(max);
1195         mask->long_size = sizeof(long);
1196
1197         for (i = 0; i < map->nr; i++)
1198                 set_bit(map->map[i], mask->mask);
1199 }
1200
1201 static size_t cpus_size(struct perf_cpu_map *map)
1202 {
1203         return sizeof(struct cpu_map_entries) + map->nr * sizeof(u16);
1204 }
1205
1206 static size_t mask_size(struct perf_cpu_map *map, int *max)
1207 {
1208         int i;
1209
1210         *max = 0;
1211
1212         for (i = 0; i < map->nr; i++) {
1213                 /* bit possition of the cpu is + 1 */
1214                 int bit = map->map[i] + 1;
1215
1216                 if (bit > *max)
1217                         *max = bit;
1218         }
1219
1220         return sizeof(struct perf_record_record_cpu_map) + BITS_TO_LONGS(*max) * sizeof(long);
1221 }
1222
1223 void *cpu_map_data__alloc(struct perf_cpu_map *map, size_t *size, u16 *type, int *max)
1224 {
1225         size_t size_cpus, size_mask;
1226         bool is_dummy = perf_cpu_map__empty(map);
1227
1228         /*
1229          * Both array and mask data have variable size based
1230          * on the number of cpus and their actual values.
1231          * The size of the 'struct perf_record_cpu_map_data' is:
1232          *
1233          *   array = size of 'struct cpu_map_entries' +
1234          *           number of cpus * sizeof(u64)
1235          *
1236          *   mask  = size of 'struct perf_record_record_cpu_map' +
1237          *           maximum cpu bit converted to size of longs
1238          *
1239          * and finaly + the size of 'struct perf_record_cpu_map_data'.
1240          */
1241         size_cpus = cpus_size(map);
1242         size_mask = mask_size(map, max);
1243
1244         if (is_dummy || (size_cpus < size_mask)) {
1245                 *size += size_cpus;
1246                 *type  = PERF_CPU_MAP__CPUS;
1247         } else {
1248                 *size += size_mask;
1249                 *type  = PERF_CPU_MAP__MASK;
1250         }
1251
1252         *size += sizeof(struct perf_record_cpu_map_data);
1253         *size = PERF_ALIGN(*size, sizeof(u64));
1254         return zalloc(*size);
1255 }
1256
1257 void cpu_map_data__synthesize(struct perf_record_cpu_map_data *data, struct perf_cpu_map *map,
1258                               u16 type, int max)
1259 {
1260         data->type = type;
1261
1262         switch (type) {
1263         case PERF_CPU_MAP__CPUS:
1264                 synthesize_cpus((struct cpu_map_entries *) data->data, map);
1265                 break;
1266         case PERF_CPU_MAP__MASK:
1267                 synthesize_mask((struct perf_record_record_cpu_map *)data->data, map, max);
1268         default:
1269                 break;
1270         }
1271 }
1272
1273 static struct perf_record_cpu_map *cpu_map_event__new(struct perf_cpu_map *map)
1274 {
1275         size_t size = sizeof(struct perf_record_cpu_map);
1276         struct perf_record_cpu_map *event;
1277         int max;
1278         u16 type;
1279
1280         event = cpu_map_data__alloc(map, &size, &type, &max);
1281         if (!event)
1282                 return NULL;
1283
1284         event->header.type = PERF_RECORD_CPU_MAP;
1285         event->header.size = size;
1286         event->data.type   = type;
1287
1288         cpu_map_data__synthesize(&event->data, map, type, max);
1289         return event;
1290 }
1291
1292 int perf_event__synthesize_cpu_map(struct perf_tool *tool,
1293                                    struct perf_cpu_map *map,
1294                                    perf_event__handler_t process,
1295                                    struct machine *machine)
1296 {
1297         struct perf_record_cpu_map *event;
1298         int err;
1299
1300         event = cpu_map_event__new(map);
1301         if (!event)
1302                 return -ENOMEM;
1303
1304         err = process(tool, (union perf_event *) event, NULL, machine);
1305
1306         free(event);
1307         return err;
1308 }
1309
1310 int perf_event__synthesize_stat_config(struct perf_tool *tool,
1311                                        struct perf_stat_config *config,
1312                                        perf_event__handler_t process,
1313                                        struct machine *machine)
1314 {
1315         struct perf_record_stat_config *event;
1316         int size, i = 0, err;
1317
1318         size  = sizeof(*event);
1319         size += (PERF_STAT_CONFIG_TERM__MAX * sizeof(event->data[0]));
1320
1321         event = zalloc(size);
1322         if (!event)
1323                 return -ENOMEM;
1324
1325         event->header.type = PERF_RECORD_STAT_CONFIG;
1326         event->header.size = size;
1327         event->nr          = PERF_STAT_CONFIG_TERM__MAX;
1328
1329 #define ADD(__term, __val)                                      \
1330         event->data[i].tag = PERF_STAT_CONFIG_TERM__##__term;   \
1331         event->data[i].val = __val;                             \
1332         i++;
1333
1334         ADD(AGGR_MODE,  config->aggr_mode)
1335         ADD(INTERVAL,   config->interval)
1336         ADD(SCALE,      config->scale)
1337
1338         WARN_ONCE(i != PERF_STAT_CONFIG_TERM__MAX,
1339                   "stat config terms unbalanced\n");
1340 #undef ADD
1341
1342         err = process(tool, (union perf_event *) event, NULL, machine);
1343
1344         free(event);
1345         return err;
1346 }
1347
1348 int perf_event__synthesize_stat(struct perf_tool *tool,
1349                                 u32 cpu, u32 thread, u64 id,
1350                                 struct perf_counts_values *count,
1351                                 perf_event__handler_t process,
1352                                 struct machine *machine)
1353 {
1354         struct perf_record_stat event;
1355
1356         event.header.type = PERF_RECORD_STAT;
1357         event.header.size = sizeof(event);
1358         event.header.misc = 0;
1359
1360         event.id        = id;
1361         event.cpu       = cpu;
1362         event.thread    = thread;
1363         event.val       = count->val;
1364         event.ena       = count->ena;
1365         event.run       = count->run;
1366
1367         return process(tool, (union perf_event *) &event, NULL, machine);
1368 }
1369
1370 int perf_event__synthesize_stat_round(struct perf_tool *tool,
1371                                       u64 evtime, u64 type,
1372                                       perf_event__handler_t process,
1373                                       struct machine *machine)
1374 {
1375         struct perf_record_stat_round event;
1376
1377         event.header.type = PERF_RECORD_STAT_ROUND;
1378         event.header.size = sizeof(event);
1379         event.header.misc = 0;
1380
1381         event.time = evtime;
1382         event.type = type;
1383
1384         return process(tool, (union perf_event *) &event, NULL, machine);
1385 }
1386
1387 size_t perf_event__sample_event_size(const struct perf_sample *sample, u64 type, u64 read_format)
1388 {
1389         size_t sz, result = sizeof(struct perf_record_sample);
1390
1391         if (type & PERF_SAMPLE_IDENTIFIER)
1392                 result += sizeof(u64);
1393
1394         if (type & PERF_SAMPLE_IP)
1395                 result += sizeof(u64);
1396
1397         if (type & PERF_SAMPLE_TID)
1398                 result += sizeof(u64);
1399
1400         if (type & PERF_SAMPLE_TIME)
1401                 result += sizeof(u64);
1402
1403         if (type & PERF_SAMPLE_ADDR)
1404                 result += sizeof(u64);
1405
1406         if (type & PERF_SAMPLE_ID)
1407                 result += sizeof(u64);
1408
1409         if (type & PERF_SAMPLE_STREAM_ID)
1410                 result += sizeof(u64);
1411
1412         if (type & PERF_SAMPLE_CPU)
1413                 result += sizeof(u64);
1414
1415         if (type & PERF_SAMPLE_PERIOD)
1416                 result += sizeof(u64);
1417
1418         if (type & PERF_SAMPLE_READ) {
1419                 result += sizeof(u64);
1420                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1421                         result += sizeof(u64);
1422                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1423                         result += sizeof(u64);
1424                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1425                 if (read_format & PERF_FORMAT_GROUP) {
1426                         sz = sample->read.group.nr *
1427                              sizeof(struct sample_read_value);
1428                         result += sz;
1429                 } else {
1430                         result += sizeof(u64);
1431                 }
1432         }
1433
1434         if (type & PERF_SAMPLE_CALLCHAIN) {
1435                 sz = (sample->callchain->nr + 1) * sizeof(u64);
1436                 result += sz;
1437         }
1438
1439         if (type & PERF_SAMPLE_RAW) {
1440                 result += sizeof(u32);
1441                 result += sample->raw_size;
1442         }
1443
1444         if (type & PERF_SAMPLE_BRANCH_STACK) {
1445                 sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1446                 /* nr, hw_idx */
1447                 sz += 2 * sizeof(u64);
1448                 result += sz;
1449         }
1450
1451         if (type & PERF_SAMPLE_REGS_USER) {
1452                 if (sample->user_regs.abi) {
1453                         result += sizeof(u64);
1454                         sz = hweight64(sample->user_regs.mask) * sizeof(u64);
1455                         result += sz;
1456                 } else {
1457                         result += sizeof(u64);
1458                 }
1459         }
1460
1461         if (type & PERF_SAMPLE_STACK_USER) {
1462                 sz = sample->user_stack.size;
1463                 result += sizeof(u64);
1464                 if (sz) {
1465                         result += sz;
1466                         result += sizeof(u64);
1467                 }
1468         }
1469
1470         if (type & PERF_SAMPLE_WEIGHT_TYPE)
1471                 result += sizeof(u64);
1472
1473         if (type & PERF_SAMPLE_DATA_SRC)
1474                 result += sizeof(u64);
1475
1476         if (type & PERF_SAMPLE_TRANSACTION)
1477                 result += sizeof(u64);
1478
1479         if (type & PERF_SAMPLE_REGS_INTR) {
1480                 if (sample->intr_regs.abi) {
1481                         result += sizeof(u64);
1482                         sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
1483                         result += sz;
1484                 } else {
1485                         result += sizeof(u64);
1486                 }
1487         }
1488
1489         if (type & PERF_SAMPLE_PHYS_ADDR)
1490                 result += sizeof(u64);
1491
1492         if (type & PERF_SAMPLE_CGROUP)
1493                 result += sizeof(u64);
1494
1495         if (type & PERF_SAMPLE_DATA_PAGE_SIZE)
1496                 result += sizeof(u64);
1497
1498         if (type & PERF_SAMPLE_CODE_PAGE_SIZE)
1499                 result += sizeof(u64);
1500
1501         if (type & PERF_SAMPLE_AUX) {
1502                 result += sizeof(u64);
1503                 result += sample->aux_sample.size;
1504         }
1505
1506         return result;
1507 }
1508
1509 void __weak arch_perf_synthesize_sample_weight(const struct perf_sample *data,
1510                                                __u64 *array, u64 type __maybe_unused)
1511 {
1512         *array = data->weight;
1513 }
1514
1515 int perf_event__synthesize_sample(union perf_event *event, u64 type, u64 read_format,
1516                                   const struct perf_sample *sample)
1517 {
1518         __u64 *array;
1519         size_t sz;
1520         /*
1521          * used for cross-endian analysis. See git commit 65014ab3
1522          * for why this goofiness is needed.
1523          */
1524         union u64_swap u;
1525
1526         array = event->sample.array;
1527
1528         if (type & PERF_SAMPLE_IDENTIFIER) {
1529                 *array = sample->id;
1530                 array++;
1531         }
1532
1533         if (type & PERF_SAMPLE_IP) {
1534                 *array = sample->ip;
1535                 array++;
1536         }
1537
1538         if (type & PERF_SAMPLE_TID) {
1539                 u.val32[0] = sample->pid;
1540                 u.val32[1] = sample->tid;
1541                 *array = u.val64;
1542                 array++;
1543         }
1544
1545         if (type & PERF_SAMPLE_TIME) {
1546                 *array = sample->time;
1547                 array++;
1548         }
1549
1550         if (type & PERF_SAMPLE_ADDR) {
1551                 *array = sample->addr;
1552                 array++;
1553         }
1554
1555         if (type & PERF_SAMPLE_ID) {
1556                 *array = sample->id;
1557                 array++;
1558         }
1559
1560         if (type & PERF_SAMPLE_STREAM_ID) {
1561                 *array = sample->stream_id;
1562                 array++;
1563         }
1564
1565         if (type & PERF_SAMPLE_CPU) {
1566                 u.val32[0] = sample->cpu;
1567                 u.val32[1] = 0;
1568                 *array = u.val64;
1569                 array++;
1570         }
1571
1572         if (type & PERF_SAMPLE_PERIOD) {
1573                 *array = sample->period;
1574                 array++;
1575         }
1576
1577         if (type & PERF_SAMPLE_READ) {
1578                 if (read_format & PERF_FORMAT_GROUP)
1579                         *array = sample->read.group.nr;
1580                 else
1581                         *array = sample->read.one.value;
1582                 array++;
1583
1584                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1585                         *array = sample->read.time_enabled;
1586                         array++;
1587                 }
1588
1589                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1590                         *array = sample->read.time_running;
1591                         array++;
1592                 }
1593
1594                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1595                 if (read_format & PERF_FORMAT_GROUP) {
1596                         sz = sample->read.group.nr *
1597                              sizeof(struct sample_read_value);
1598                         memcpy(array, sample->read.group.values, sz);
1599                         array = (void *)array + sz;
1600                 } else {
1601                         *array = sample->read.one.id;
1602                         array++;
1603                 }
1604         }
1605
1606         if (type & PERF_SAMPLE_CALLCHAIN) {
1607                 sz = (sample->callchain->nr + 1) * sizeof(u64);
1608                 memcpy(array, sample->callchain, sz);
1609                 array = (void *)array + sz;
1610         }
1611
1612         if (type & PERF_SAMPLE_RAW) {
1613                 u.val32[0] = sample->raw_size;
1614                 *array = u.val64;
1615                 array = (void *)array + sizeof(u32);
1616
1617                 memcpy(array, sample->raw_data, sample->raw_size);
1618                 array = (void *)array + sample->raw_size;
1619         }
1620
1621         if (type & PERF_SAMPLE_BRANCH_STACK) {
1622                 sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1623                 /* nr, hw_idx */
1624                 sz += 2 * sizeof(u64);
1625                 memcpy(array, sample->branch_stack, sz);
1626                 array = (void *)array + sz;
1627         }
1628
1629         if (type & PERF_SAMPLE_REGS_USER) {
1630                 if (sample->user_regs.abi) {
1631                         *array++ = sample->user_regs.abi;
1632                         sz = hweight64(sample->user_regs.mask) * sizeof(u64);
1633                         memcpy(array, sample->user_regs.regs, sz);
1634                         array = (void *)array + sz;
1635                 } else {
1636                         *array++ = 0;
1637                 }
1638         }
1639
1640         if (type & PERF_SAMPLE_STACK_USER) {
1641                 sz = sample->user_stack.size;
1642                 *array++ = sz;
1643                 if (sz) {
1644                         memcpy(array, sample->user_stack.data, sz);
1645                         array = (void *)array + sz;
1646                         *array++ = sz;
1647                 }
1648         }
1649
1650         if (type & PERF_SAMPLE_WEIGHT_TYPE) {
1651                 arch_perf_synthesize_sample_weight(sample, array, type);
1652                 array++;
1653         }
1654
1655         if (type & PERF_SAMPLE_DATA_SRC) {
1656                 *array = sample->data_src;
1657                 array++;
1658         }
1659
1660         if (type & PERF_SAMPLE_TRANSACTION) {
1661                 *array = sample->transaction;
1662                 array++;
1663         }
1664
1665         if (type & PERF_SAMPLE_REGS_INTR) {
1666                 if (sample->intr_regs.abi) {
1667                         *array++ = sample->intr_regs.abi;
1668                         sz = hweight64(sample->intr_regs.mask) * sizeof(u64);
1669                         memcpy(array, sample->intr_regs.regs, sz);
1670                         array = (void *)array + sz;
1671                 } else {
1672                         *array++ = 0;
1673                 }
1674         }
1675
1676         if (type & PERF_SAMPLE_PHYS_ADDR) {
1677                 *array = sample->phys_addr;
1678                 array++;
1679         }
1680
1681         if (type & PERF_SAMPLE_CGROUP) {
1682                 *array = sample->cgroup;
1683                 array++;
1684         }
1685
1686         if (type & PERF_SAMPLE_DATA_PAGE_SIZE) {
1687                 *array = sample->data_page_size;
1688                 array++;
1689         }
1690
1691         if (type & PERF_SAMPLE_CODE_PAGE_SIZE) {
1692                 *array = sample->code_page_size;
1693                 array++;
1694         }
1695
1696         if (type & PERF_SAMPLE_AUX) {
1697                 sz = sample->aux_sample.size;
1698                 *array++ = sz;
1699                 memcpy(array, sample->aux_sample.data, sz);
1700                 array = (void *)array + sz;
1701         }
1702
1703         return 0;
1704 }
1705
1706 int perf_event__synthesize_id_index(struct perf_tool *tool, perf_event__handler_t process,
1707                                     struct evlist *evlist, struct machine *machine)
1708 {
1709         union perf_event *ev;
1710         struct evsel *evsel;
1711         size_t nr = 0, i = 0, sz, max_nr, n;
1712         int err;
1713
1714         pr_debug2("Synthesizing id index\n");
1715
1716         max_nr = (UINT16_MAX - sizeof(struct perf_record_id_index)) /
1717                  sizeof(struct id_index_entry);
1718
1719         evlist__for_each_entry(evlist, evsel)
1720                 nr += evsel->core.ids;
1721
1722         n = nr > max_nr ? max_nr : nr;
1723         sz = sizeof(struct perf_record_id_index) + n * sizeof(struct id_index_entry);
1724         ev = zalloc(sz);
1725         if (!ev)
1726                 return -ENOMEM;
1727
1728         ev->id_index.header.type = PERF_RECORD_ID_INDEX;
1729         ev->id_index.header.size = sz;
1730         ev->id_index.nr = n;
1731
1732         evlist__for_each_entry(evlist, evsel) {
1733                 u32 j;
1734
1735                 for (j = 0; j < evsel->core.ids; j++) {
1736                         struct id_index_entry *e;
1737                         struct perf_sample_id *sid;
1738
1739                         if (i >= n) {
1740                                 err = process(tool, ev, NULL, machine);
1741                                 if (err)
1742                                         goto out_err;
1743                                 nr -= n;
1744                                 i = 0;
1745                         }
1746
1747                         e = &ev->id_index.entries[i++];
1748
1749                         e->id = evsel->core.id[j];
1750
1751                         sid = evlist__id2sid(evlist, e->id);
1752                         if (!sid) {
1753                                 free(ev);
1754                                 return -ENOENT;
1755                         }
1756
1757                         e->idx = sid->idx;
1758                         e->cpu = sid->cpu;
1759                         e->tid = sid->tid;
1760                 }
1761         }
1762
1763         sz = sizeof(struct perf_record_id_index) + nr * sizeof(struct id_index_entry);
1764         ev->id_index.header.size = sz;
1765         ev->id_index.nr = nr;
1766
1767         err = process(tool, ev, NULL, machine);
1768 out_err:
1769         free(ev);
1770
1771         return err;
1772 }
1773
1774 int __machine__synthesize_threads(struct machine *machine, struct perf_tool *tool,
1775                                   struct target *target, struct perf_thread_map *threads,
1776                                   perf_event__handler_t process, bool data_mmap,
1777                                   unsigned int nr_threads_synthesize)
1778 {
1779         if (target__has_task(target))
1780                 return perf_event__synthesize_thread_map(tool, threads, process, machine, data_mmap);
1781         else if (target__has_cpu(target))
1782                 return perf_event__synthesize_threads(tool, process,
1783                                                       machine, data_mmap,
1784                                                       nr_threads_synthesize);
1785         /* command specified */
1786         return 0;
1787 }
1788
1789 int machine__synthesize_threads(struct machine *machine, struct target *target,
1790                                 struct perf_thread_map *threads, bool data_mmap,
1791                                 unsigned int nr_threads_synthesize)
1792 {
1793         return __machine__synthesize_threads(machine, NULL, target, threads,
1794                                              perf_event__process, data_mmap,
1795                                              nr_threads_synthesize);
1796 }
1797
1798 static struct perf_record_event_update *event_update_event__new(size_t size, u64 type, u64 id)
1799 {
1800         struct perf_record_event_update *ev;
1801
1802         size += sizeof(*ev);
1803         size  = PERF_ALIGN(size, sizeof(u64));
1804
1805         ev = zalloc(size);
1806         if (ev) {
1807                 ev->header.type = PERF_RECORD_EVENT_UPDATE;
1808                 ev->header.size = (u16)size;
1809                 ev->type        = type;
1810                 ev->id          = id;
1811         }
1812         return ev;
1813 }
1814
1815 int perf_event__synthesize_event_update_unit(struct perf_tool *tool, struct evsel *evsel,
1816                                              perf_event__handler_t process)
1817 {
1818         size_t size = strlen(evsel->unit);
1819         struct perf_record_event_update *ev;
1820         int err;
1821
1822         ev = event_update_event__new(size + 1, PERF_EVENT_UPDATE__UNIT, evsel->core.id[0]);
1823         if (ev == NULL)
1824                 return -ENOMEM;
1825
1826         strlcpy(ev->data, evsel->unit, size + 1);
1827         err = process(tool, (union perf_event *)ev, NULL, NULL);
1828         free(ev);
1829         return err;
1830 }
1831
1832 int perf_event__synthesize_event_update_scale(struct perf_tool *tool, struct evsel *evsel,
1833                                               perf_event__handler_t process)
1834 {
1835         struct perf_record_event_update *ev;
1836         struct perf_record_event_update_scale *ev_data;
1837         int err;
1838
1839         ev = event_update_event__new(sizeof(*ev_data), PERF_EVENT_UPDATE__SCALE, evsel->core.id[0]);
1840         if (ev == NULL)
1841                 return -ENOMEM;
1842
1843         ev_data = (struct perf_record_event_update_scale *)ev->data;
1844         ev_data->scale = evsel->scale;
1845         err = process(tool, (union perf_event *)ev, NULL, NULL);
1846         free(ev);
1847         return err;
1848 }
1849
1850 int perf_event__synthesize_event_update_name(struct perf_tool *tool, struct evsel *evsel,
1851                                              perf_event__handler_t process)
1852 {
1853         struct perf_record_event_update *ev;
1854         size_t len = strlen(evsel->name);
1855         int err;
1856
1857         ev = event_update_event__new(len + 1, PERF_EVENT_UPDATE__NAME, evsel->core.id[0]);
1858         if (ev == NULL)
1859                 return -ENOMEM;
1860
1861         strlcpy(ev->data, evsel->name, len + 1);
1862         err = process(tool, (union perf_event *)ev, NULL, NULL);
1863         free(ev);
1864         return err;
1865 }
1866
1867 int perf_event__synthesize_event_update_cpus(struct perf_tool *tool, struct evsel *evsel,
1868                                              perf_event__handler_t process)
1869 {
1870         size_t size = sizeof(struct perf_record_event_update);
1871         struct perf_record_event_update *ev;
1872         int max, err;
1873         u16 type;
1874
1875         if (!evsel->core.own_cpus)
1876                 return 0;
1877
1878         ev = cpu_map_data__alloc(evsel->core.own_cpus, &size, &type, &max);
1879         if (!ev)
1880                 return -ENOMEM;
1881
1882         ev->header.type = PERF_RECORD_EVENT_UPDATE;
1883         ev->header.size = (u16)size;
1884         ev->type        = PERF_EVENT_UPDATE__CPUS;
1885         ev->id          = evsel->core.id[0];
1886
1887         cpu_map_data__synthesize((struct perf_record_cpu_map_data *)ev->data,
1888                                  evsel->core.own_cpus, type, max);
1889
1890         err = process(tool, (union perf_event *)ev, NULL, NULL);
1891         free(ev);
1892         return err;
1893 }
1894
1895 int perf_event__synthesize_attrs(struct perf_tool *tool, struct evlist *evlist,
1896                                  perf_event__handler_t process)
1897 {
1898         struct evsel *evsel;
1899         int err = 0;
1900
1901         evlist__for_each_entry(evlist, evsel) {
1902                 err = perf_event__synthesize_attr(tool, &evsel->core.attr, evsel->core.ids,
1903                                                   evsel->core.id, process);
1904                 if (err) {
1905                         pr_debug("failed to create perf header attribute\n");
1906                         return err;
1907                 }
1908         }
1909
1910         return err;
1911 }
1912
1913 static bool has_unit(struct evsel *evsel)
1914 {
1915         return evsel->unit && *evsel->unit;
1916 }
1917
1918 static bool has_scale(struct evsel *evsel)
1919 {
1920         return evsel->scale != 1;
1921 }
1922
1923 int perf_event__synthesize_extra_attr(struct perf_tool *tool, struct evlist *evsel_list,
1924                                       perf_event__handler_t process, bool is_pipe)
1925 {
1926         struct evsel *evsel;
1927         int err;
1928
1929         /*
1930          * Synthesize other events stuff not carried within
1931          * attr event - unit, scale, name
1932          */
1933         evlist__for_each_entry(evsel_list, evsel) {
1934                 if (!evsel->supported)
1935                         continue;
1936
1937                 /*
1938                  * Synthesize unit and scale only if it's defined.
1939                  */
1940                 if (has_unit(evsel)) {
1941                         err = perf_event__synthesize_event_update_unit(tool, evsel, process);
1942                         if (err < 0) {
1943                                 pr_err("Couldn't synthesize evsel unit.\n");
1944                                 return err;
1945                         }
1946                 }
1947
1948                 if (has_scale(evsel)) {
1949                         err = perf_event__synthesize_event_update_scale(tool, evsel, process);
1950                         if (err < 0) {
1951                                 pr_err("Couldn't synthesize evsel evsel.\n");
1952                                 return err;
1953                         }
1954                 }
1955
1956                 if (evsel->core.own_cpus) {
1957                         err = perf_event__synthesize_event_update_cpus(tool, evsel, process);
1958                         if (err < 0) {
1959                                 pr_err("Couldn't synthesize evsel cpus.\n");
1960                                 return err;
1961                         }
1962                 }
1963
1964                 /*
1965                  * Name is needed only for pipe output,
1966                  * perf.data carries event names.
1967                  */
1968                 if (is_pipe) {
1969                         err = perf_event__synthesize_event_update_name(tool, evsel, process);
1970                         if (err < 0) {
1971                                 pr_err("Couldn't synthesize evsel name.\n");
1972                                 return err;
1973                         }
1974                 }
1975         }
1976         return 0;
1977 }
1978
1979 int perf_event__synthesize_attr(struct perf_tool *tool, struct perf_event_attr *attr,
1980                                 u32 ids, u64 *id, perf_event__handler_t process)
1981 {
1982         union perf_event *ev;
1983         size_t size;
1984         int err;
1985
1986         size = sizeof(struct perf_event_attr);
1987         size = PERF_ALIGN(size, sizeof(u64));
1988         size += sizeof(struct perf_event_header);
1989         size += ids * sizeof(u64);
1990
1991         ev = zalloc(size);
1992
1993         if (ev == NULL)
1994                 return -ENOMEM;
1995
1996         ev->attr.attr = *attr;
1997         memcpy(ev->attr.id, id, ids * sizeof(u64));
1998
1999         ev->attr.header.type = PERF_RECORD_HEADER_ATTR;
2000         ev->attr.header.size = (u16)size;
2001
2002         if (ev->attr.header.size == size)
2003                 err = process(tool, ev, NULL, NULL);
2004         else
2005                 err = -E2BIG;
2006
2007         free(ev);
2008
2009         return err;
2010 }
2011
2012 int perf_event__synthesize_tracing_data(struct perf_tool *tool, int fd, struct evlist *evlist,
2013                                         perf_event__handler_t process)
2014 {
2015         union perf_event ev;
2016         struct tracing_data *tdata;
2017         ssize_t size = 0, aligned_size = 0, padding;
2018         struct feat_fd ff;
2019
2020         /*
2021          * We are going to store the size of the data followed
2022          * by the data contents. Since the fd descriptor is a pipe,
2023          * we cannot seek back to store the size of the data once
2024          * we know it. Instead we:
2025          *
2026          * - write the tracing data to the temp file
2027          * - get/write the data size to pipe
2028          * - write the tracing data from the temp file
2029          *   to the pipe
2030          */
2031         tdata = tracing_data_get(&evlist->core.entries, fd, true);
2032         if (!tdata)
2033                 return -1;
2034
2035         memset(&ev, 0, sizeof(ev));
2036
2037         ev.tracing_data.header.type = PERF_RECORD_HEADER_TRACING_DATA;
2038         size = tdata->size;
2039         aligned_size = PERF_ALIGN(size, sizeof(u64));
2040         padding = aligned_size - size;
2041         ev.tracing_data.header.size = sizeof(ev.tracing_data);
2042         ev.tracing_data.size = aligned_size;
2043
2044         process(tool, &ev, NULL, NULL);
2045
2046         /*
2047          * The put function will copy all the tracing data
2048          * stored in temp file to the pipe.
2049          */
2050         tracing_data_put(tdata);
2051
2052         ff = (struct feat_fd){ .fd = fd };
2053         if (write_padded(&ff, NULL, 0, padding))
2054                 return -1;
2055
2056         return aligned_size;
2057 }
2058
2059 int perf_event__synthesize_build_id(struct perf_tool *tool, struct dso *pos, u16 misc,
2060                                     perf_event__handler_t process, struct machine *machine)
2061 {
2062         union perf_event ev;
2063         size_t len;
2064
2065         if (!pos->hit)
2066                 return 0;
2067
2068         memset(&ev, 0, sizeof(ev));
2069
2070         len = pos->long_name_len + 1;
2071         len = PERF_ALIGN(len, NAME_ALIGN);
2072         memcpy(&ev.build_id.build_id, pos->bid.data, sizeof(pos->bid.data));
2073         ev.build_id.header.type = PERF_RECORD_HEADER_BUILD_ID;
2074         ev.build_id.header.misc = misc;
2075         ev.build_id.pid = machine->pid;
2076         ev.build_id.header.size = sizeof(ev.build_id) + len;
2077         memcpy(&ev.build_id.filename, pos->long_name, pos->long_name_len);
2078
2079         return process(tool, &ev, NULL, machine);
2080 }
2081
2082 int perf_event__synthesize_stat_events(struct perf_stat_config *config, struct perf_tool *tool,
2083                                        struct evlist *evlist, perf_event__handler_t process, bool attrs)
2084 {
2085         int err;
2086
2087         if (attrs) {
2088                 err = perf_event__synthesize_attrs(tool, evlist, process);
2089                 if (err < 0) {
2090                         pr_err("Couldn't synthesize attrs.\n");
2091                         return err;
2092                 }
2093         }
2094
2095         err = perf_event__synthesize_extra_attr(tool, evlist, process, attrs);
2096         err = perf_event__synthesize_thread_map2(tool, evlist->core.threads, process, NULL);
2097         if (err < 0) {
2098                 pr_err("Couldn't synthesize thread map.\n");
2099                 return err;
2100         }
2101
2102         err = perf_event__synthesize_cpu_map(tool, evlist->core.cpus, process, NULL);
2103         if (err < 0) {
2104                 pr_err("Couldn't synthesize thread map.\n");
2105                 return err;
2106         }
2107
2108         err = perf_event__synthesize_stat_config(tool, config, process, NULL);
2109         if (err < 0) {
2110                 pr_err("Couldn't synthesize config.\n");
2111                 return err;
2112         }
2113
2114         return 0;
2115 }
2116
2117 extern const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE];
2118
2119 int perf_event__synthesize_features(struct perf_tool *tool, struct perf_session *session,
2120                                     struct evlist *evlist, perf_event__handler_t process)
2121 {
2122         struct perf_header *header = &session->header;
2123         struct perf_record_header_feature *fe;
2124         struct feat_fd ff;
2125         size_t sz, sz_hdr;
2126         int feat, ret;
2127
2128         sz_hdr = sizeof(fe->header);
2129         sz = sizeof(union perf_event);
2130         /* get a nice alignment */
2131         sz = PERF_ALIGN(sz, page_size);
2132
2133         memset(&ff, 0, sizeof(ff));
2134
2135         ff.buf = malloc(sz);
2136         if (!ff.buf)
2137                 return -ENOMEM;
2138
2139         ff.size = sz - sz_hdr;
2140         ff.ph = &session->header;
2141
2142         for_each_set_bit(feat, header->adds_features, HEADER_FEAT_BITS) {
2143                 if (!feat_ops[feat].synthesize) {
2144                         pr_debug("No record header feature for header :%d\n", feat);
2145                         continue;
2146                 }
2147
2148                 ff.offset = sizeof(*fe);
2149
2150                 ret = feat_ops[feat].write(&ff, evlist);
2151                 if (ret || ff.offset <= (ssize_t)sizeof(*fe)) {
2152                         pr_debug("Error writing feature\n");
2153                         continue;
2154                 }
2155                 /* ff.buf may have changed due to realloc in do_write() */
2156                 fe = ff.buf;
2157                 memset(fe, 0, sizeof(*fe));
2158
2159                 fe->feat_id = feat;
2160                 fe->header.type = PERF_RECORD_HEADER_FEATURE;
2161                 fe->header.size = ff.offset;
2162
2163                 ret = process(tool, ff.buf, NULL, NULL);
2164                 if (ret) {
2165                         free(ff.buf);
2166                         return ret;
2167                 }
2168         }
2169
2170         /* Send HEADER_LAST_FEATURE mark. */
2171         fe = ff.buf;
2172         fe->feat_id     = HEADER_LAST_FEATURE;
2173         fe->header.type = PERF_RECORD_HEADER_FEATURE;
2174         fe->header.size = sizeof(*fe);
2175
2176         ret = process(tool, ff.buf, NULL, NULL);
2177
2178         free(ff.buf);
2179         return ret;
2180 }