}
 
 static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event,
+                                            struct machine *machine,
                                             bool is_kernel)
 {
        struct build_id bid;
        struct nsinfo *nsi;
        struct nscookie nc;
+       struct dso *dso = NULL;
+       struct dso_id id;
        int rc;
 
        if (is_kernel) {
                goto out;
        }
 
+       id.maj = event->maj;
+       id.min = event->min;
+       id.ino = event->ino;
+       id.ino_generation = event->ino_generation;
+
+       dso = dsos__findnew_id(&machine->dsos, event->filename, &id);
+       if (dso && dso->has_build_id) {
+               bid = dso->bid;
+               rc = 0;
+               goto out;
+       }
+
        nsi = nsinfo__new(event->pid);
        nsinfo__mountns_enter(nsi, &nc);
 
                event->header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
                event->__reserved_1 = 0;
                event->__reserved_2 = 0;
+
+               if (dso && !dso->has_build_id)
+                       dso__set_build_id(dso, &bid);
        } else {
                if (event->filename[0] == '/') {
                        pr_debug2("Failed to read build ID for %s\n",
                                  event->filename);
                }
        }
+       dso__put(dso);
 }
 
 int perf_event__synthesize_mmap_events(struct perf_tool *tool,
                event->mmap2.tid = pid;
 
                if (symbol_conf.buildid_mmap2)
-                       perf_record_mmap2__read_build_id(&event->mmap2, false);
+                       perf_record_mmap2__read_build_id(&event->mmap2, machine, false);
 
                if (perf_tool__process_synth_event(tool, event, machine, process) != 0) {
                        rc = -1;
                        memcpy(event->mmap2.filename, pos->dso->long_name,
                               pos->dso->long_name_len + 1);
 
-                       perf_record_mmap2__read_build_id(&event->mmap2, false);
+                       perf_record_mmap2__read_build_id(&event->mmap2, machine, false);
                } else {
                        size = PERF_ALIGN(pos->dso->long_name_len + 1, sizeof(u64));
                        event->mmap.header.type = PERF_RECORD_MMAP;
                event->mmap2.len   = map->end - event->mmap.start;
                event->mmap2.pid   = machine->pid;
 
-               perf_record_mmap2__read_build_id(&event->mmap2, true);
+               perf_record_mmap2__read_build_id(&event->mmap2, machine, true);
        } else {
                size = snprintf(event->mmap.filename, sizeof(event->mmap.filename),
                                "%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1;