1 /* Copyright (C) 2019 The Android Open Source Project
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <gtest/gtest.h>
17 #include <inttypes.h>
18 #include <linux/dma-buf.h>
19 #include <poll.h>
20 #include <string.h>
21 #include <sys/mman.h>
22 #include <sys/types.h>
23 
24 #include <filesystem>
25 #include <fstream>
26 #include <string>
27 #include <unordered_map>
28 #include <vector>
29 
30 #include <android-base/file.h>
31 #include <android-base/logging.h>
32 #include <android-base/stringprintf.h>
33 #include <android-base/strings.h>
34 #include <android-base/unique_fd.h>
35 #include <ion/ion.h>
36 #include <unistd.h>
37 
38 #include <dmabufinfo/dmabuf_sysfs_stats.h>
39 #include <dmabufinfo/dmabufinfo.h>
40 
41 using namespace ::android::dmabufinfo;
42 using namespace ::android::base;
43 
44 namespace fs = std::filesystem;
45 
46 #define MAX_HEAP_NAME 32
47 #define ION_HEAP_ANY_MASK (0x7fffffff)
48 
49 struct ion_heap_data {
50     char name[MAX_HEAP_NAME];
51     __u32 type;
52     __u32 heap_id;
53     __u32 reserved0;
54     __u32 reserved1;
55     __u32 reserved2;
56 };
57 
58 #ifndef DMA_BUF_SET_NAME
59 #define DMA_BUF_SET_NAME _IOW(DMA_BUF_BASE, 5, const char*)
60 #endif
61 
62 class fd_sharer {
63   public:
64     fd_sharer();
~fd_sharer()65     ~fd_sharer() { kill(); }
66 
ok() const67     bool ok() const { return child_pid > 0; }
68     bool sendfd(int fd);
69     bool kill();
pid() const70     pid_t pid() const { return child_pid; }
71 
72   private:
73     unique_fd parent_fd, child_fd;
74     pid_t child_pid;
75 
76     void run();
77 };
78 
fd_sharer()79 fd_sharer::fd_sharer() : parent_fd{}, child_fd{}, child_pid{-1} {
80     bool sp_ok = android::base::Socketpair(SOCK_STREAM, &parent_fd, &child_fd);
81     if (!sp_ok) return;
82 
83     child_pid = fork();
84     if (child_pid < 0) return;
85 
86     if (child_pid == 0) run();
87 }
88 
kill()89 bool fd_sharer::kill() {
90     int err = ::kill(child_pid, SIGKILL);
91     if (err < 0) return false;
92 
93     return ::waitpid(child_pid, nullptr, 0) == child_pid;
94 }
95 
run()96 void fd_sharer::run() {
97     while (true) {
98         int fd;
99         char unused = 0;
100 
101         iovec iov{};
102         iov.iov_base = &unused;
103         iov.iov_len = sizeof(unused);
104 
105         msghdr msg{};
106         msg.msg_iov = &iov;
107         msg.msg_iovlen = 1;
108 
109         char cmsg_buf[CMSG_SPACE(sizeof(fd))];
110         msg.msg_control = cmsg_buf;
111         msg.msg_controllen = sizeof(cmsg_buf);
112 
113         cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
114         cmsg->cmsg_level = SOL_SOCKET;
115         cmsg->cmsg_type = SCM_RIGHTS;
116         cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
117 
118         ssize_t s = TEMP_FAILURE_RETRY(recvmsg(child_fd, &msg, 0));
119         if (s == -1) break;
120 
121         s = TEMP_FAILURE_RETRY(write(child_fd, &unused, sizeof(unused)));
122         if (s == -1) break;
123     }
124 }
125 
sendfd(int fd)126 bool fd_sharer::sendfd(int fd) {
127     char unused = 0;
128 
129     iovec iov{};
130     iov.iov_base = &unused;
131     iov.iov_len = sizeof(unused);
132 
133     msghdr msg{};
134     msg.msg_iov = &iov;
135     msg.msg_iovlen = 1;
136 
137     char cmsg_buf[CMSG_SPACE(sizeof(fd))];
138     msg.msg_control = cmsg_buf;
139     msg.msg_controllen = sizeof(cmsg_buf);
140 
141     cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
142     cmsg->cmsg_level = SOL_SOCKET;
143     cmsg->cmsg_type = SCM_RIGHTS;
144     cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
145 
146     int* fd_buf = reinterpret_cast<int*>(CMSG_DATA(cmsg));
147     *fd_buf = fd;
148 
149     ssize_t s = TEMP_FAILURE_RETRY(sendmsg(parent_fd, &msg, 0));
150     if (s == -1) return false;
151 
152     // The target process installs the fd into its fd table during recvmsg().
153     // So if we return now, there's a brief window between sendfd() finishing
154     // and libmemoryinfo actually seeing that the buffer has been shared.  This
155     // window is just large enough to break tests.
156     //
157     // To work around this, wait for the target process to respond with a dummy
158     // byte, with a timeout of 1 s.
159     pollfd p{};
160     p.fd = parent_fd;
161     p.events = POLL_IN;
162     int ready = poll(&p, 1, 1000);
163     if (ready != 1) return false;
164 
165     s = TEMP_FAILURE_RETRY(read(parent_fd, &unused, sizeof(unused)));
166     if (s == -1) return false;
167 
168     return true;
169 }
170 
171 #define EXPECT_ONE_BUF_EQ(_bufptr, _name, _fdrefs, _maprefs, _expname, _count, _size) \
172     do {                                                                              \
173         EXPECT_EQ(_bufptr->name(), _name);                                            \
174         EXPECT_EQ(_bufptr->fdrefs().size(), _fdrefs);                                 \
175         EXPECT_EQ(_bufptr->maprefs().size(), _maprefs);                               \
176         EXPECT_EQ(_bufptr->exporter(), _expname);                                     \
177         EXPECT_EQ(_bufptr->count(), _count);                                          \
178         EXPECT_EQ(_bufptr->size(), _size);                                            \
179     } while (0)
180 
181 #define EXPECT_PID_IN_FDREFS(_bufptr, _pid, _expect)                         \
182     do {                                                                     \
183         const std::unordered_map<pid_t, int>& _fdrefs = _bufptr->fdrefs();   \
184         auto _ref = _fdrefs.find(_pid);                                      \
185         EXPECT_EQ((_ref != _fdrefs.end()), _expect);                         \
186     } while (0)
187 
188 #define EXPECT_PID_IN_MAPREFS(_bufptr, _pid, _expect)                        \
189     do {                                                                     \
190         const std::unordered_map<pid_t, int>& _maprefs = _bufptr->maprefs(); \
191         auto _ref = _maprefs.find(_pid);                                     \
192         EXPECT_EQ((_ref != _maprefs.end()), _expect);                        \
193     } while (0)
194 
195 class DmaBufSysfsStatsParser : public ::testing::Test {
196   public:
SetUp()197     virtual void SetUp() {
198         fs::current_path(fs::temp_directory_path());
199         buffer_stats_path = fs::current_path() / "buffers";
200         ASSERT_TRUE(fs::create_directory(buffer_stats_path));
201     }
TearDown()202     virtual void TearDown() { fs::remove_all(buffer_stats_path); }
203 
204     std::filesystem::path buffer_stats_path;
205 };
206 
TEST_F(DmaBufSysfsStatsParser,TestReadDmaBufSysfsStats)207 TEST_F(DmaBufSysfsStatsParser, TestReadDmaBufSysfsStats) {
208     using android::base::StringPrintf;
209 
210     for (unsigned int inode_number = 74831; inode_number < 74841; inode_number++) {
211         auto buffer_path = buffer_stats_path / StringPrintf("%u", inode_number);
212         ASSERT_TRUE(fs::create_directories(buffer_path));
213 
214         auto buffer_size_path = buffer_path / "size";
215         const std::string buffer_size = "4096";
216         ASSERT_TRUE(android::base::WriteStringToFile(buffer_size, buffer_size_path));
217 
218         auto exp_name_path = buffer_path / "exporter_name";
219         const std::string exp_name = "system";
220         ASSERT_TRUE(android::base::WriteStringToFile(exp_name, exp_name_path));
221     }
222 
223     DmabufSysfsStats stats;
224     ASSERT_TRUE(GetDmabufSysfsStats(&stats, buffer_stats_path.c_str()));
225 
226     auto buffer_stats = stats.buffer_stats();
227     ASSERT_EQ(buffer_stats.size(), 10UL);
228 
229     auto buf_info = buffer_stats[0];
230     EXPECT_EQ(buf_info.inode, 74831UL);
231     EXPECT_EQ(buf_info.exp_name, "system");
232     EXPECT_EQ(buf_info.size, 4096UL);
233 
234     auto exporter_stats = stats.exporter_info();
235     ASSERT_EQ(exporter_stats.size(), 1UL);
236     auto exp_info = exporter_stats.find("system");
237     ASSERT_TRUE(exp_info != exporter_stats.end());
238     EXPECT_EQ(exp_info->second.size, 40960UL);
239     EXPECT_EQ(exp_info->second.buffer_count, 10UL);
240 
241     auto total_size = stats.total_size();
242     EXPECT_EQ(total_size, 40960UL);
243 
244     auto total_count = stats.total_count();
245     EXPECT_EQ(total_count, 10UL);
246 
247     uint64_t total_exported;
248     EXPECT_TRUE(GetDmabufTotalExportedKb(&total_exported, buffer_stats_path.c_str()));
249     EXPECT_EQ(total_exported, 40UL);
250 }
251 
252 class DmaBufProcessStatsTest : public ::testing::Test {
253   public:
SetUp()254     virtual void SetUp() {
255         fs::current_path(fs::temp_directory_path());
256         dmabuf_sysfs_path = fs::current_path() / "buffers";
257         procfs_path = fs::current_path() / "proc";
258         ASSERT_TRUE(fs::create_directory(dmabuf_sysfs_path));
259         ASSERT_TRUE(fs::create_directory(procfs_path));
260         pid_path = procfs_path / android::base::StringPrintf("%d", pid);
261         ASSERT_TRUE(fs::create_directories(pid_path));
262         pid_fdinfo_path = pid_path / "fdinfo";
263         ASSERT_TRUE(fs::create_directories(pid_fdinfo_path));
264     }
TearDown()265     virtual void TearDown() {
266         fs::remove_all(dmabuf_sysfs_path);
267         fs::remove_all(procfs_path);
268     }
269 
AddFdInfo(unsigned int inode,unsigned int size,bool is_dmabuf)270     void AddFdInfo(unsigned int inode, unsigned int size, bool is_dmabuf) {
271         std::string dmabuf_fdinfo = android::base::StringPrintf(
272                 "size:\t%u\ncount:\t1\nexp_name:\t%s\n", size, exporter.c_str());
273         std::string fdinfo =
274                 android::base::StringPrintf("pos:\t21\nflags:\t0032\nmnt_id:\t02\nino:\t%u\n%s",
275                                             inode, (is_dmabuf) ? dmabuf_fdinfo.c_str() : "");
276 
277         auto fdinfo_file_path = pid_fdinfo_path / android::base::StringPrintf("%d", fd++);
278         ASSERT_TRUE(android::base::WriteStringToFile(fdinfo, fdinfo_file_path));
279     }
280 
AddSysfsDmaBufStats(unsigned int inode,unsigned int size,unsigned int mmap_count)281     void AddSysfsDmaBufStats(unsigned int inode, unsigned int size, unsigned int mmap_count) {
282         auto buffer_path = dmabuf_sysfs_path / android::base::StringPrintf("%u", inode);
283         ASSERT_TRUE(fs::create_directory(buffer_path));
284 
285         auto size_path = buffer_path / "size";
286         ASSERT_TRUE(android::base::WriteStringToFile(android::base::StringPrintf("%u", size),
287                                                      size_path));
288 
289         auto mmap_count_path = buffer_path / "mmap_count";
290         ASSERT_TRUE(android::base::WriteStringToFile(
291                 android::base::StringPrintf("%u", mmap_count), mmap_count_path));
292 
293         auto exporter_path = buffer_path / "exporter_name";
294         ASSERT_TRUE(android::base::WriteStringToFile(exporter, exporter_path));
295     }
296 
CreateMapEntry(unsigned int inode,unsigned int size,bool is_dmabuf)297     std::string CreateMapEntry(unsigned int inode, unsigned int size, bool is_dmabuf) {
298         return android::base::StringPrintf("0000000000-%010x rw-s 00000000 00:08 %u %s", size,
299                                            inode, (is_dmabuf) ? "/dmabuf:" : "/not/dmabuf/");
300     }
301 
AddMapEntries(std::vector<std::string> entries)302     void AddMapEntries(std::vector<std::string> entries) {
303         std::string maps_content = android::base::Join(entries, '\n');
304 
305         auto maps_file_path = pid_path / "maps";
306         ASSERT_TRUE(android::base::WriteStringToFile(maps_content, maps_file_path));
307     }
308 
309     std::filesystem::path dmabuf_sysfs_path;
310     std::filesystem::path procfs_path;
311     std::filesystem::path pid_path;
312     std::filesystem::path pid_fdinfo_path;
313     std::string exporter = "system_heap";
314     int pid = 10;
315     int fd = 0;
316 };
317 
TEST_F(DmaBufProcessStatsTest,TestReadDmaBufInfo)318 TEST_F(DmaBufProcessStatsTest, TestReadDmaBufInfo) {
319     AddFdInfo(1, 1024, false);
320     AddFdInfo(2, 2048, true);  // Dmabuf 1
321 
322     std::vector<std::string> map_entries;
323     map_entries.emplace_back(CreateMapEntry(3, 1024, false));
324     map_entries.emplace_back(CreateMapEntry(4, 1024, true));  // Dmabuf 2
325     AddMapEntries(map_entries);
326 
327     AddSysfsDmaBufStats(2, 2048, 4);  // Dmabuf 1
328     AddSysfsDmaBufStats(4, 1024, 1);  // Dmabuf 2
329 
330     std::vector<DmaBuffer> dmabufs;
331     ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs, true, procfs_path, dmabuf_sysfs_path));
332 
333     ASSERT_EQ(dmabufs.size(), 2u);
334 
335     auto dmabuf1 = std::find_if(dmabufs.begin(), dmabufs.end(),
336                                 [](const DmaBuffer& dmabuf) { return dmabuf.inode() == 2; });
337     ASSERT_NE(dmabuf1, dmabufs.end());
338     ASSERT_EQ(dmabuf1->size(), 2048u);
339     ASSERT_EQ(dmabuf1->fdrefs().size(), 1u);
340     ASSERT_EQ(dmabuf1->maprefs().size(), 0u);
341     ASSERT_EQ(dmabuf1->total_refs(), 1u);
342     ASSERT_EQ(dmabuf1->exporter(), exporter);
343 
344     auto dmabuf2 = std::find_if(dmabufs.begin(), dmabufs.end(),
345                                 [](const DmaBuffer& dmabuf) { return dmabuf.inode() == 4; });
346     ASSERT_NE(dmabuf2, dmabufs.end());
347     ASSERT_EQ(dmabuf2->size(), 1024u);
348     ASSERT_EQ(dmabuf2->fdrefs().size(), 0u);
349     ASSERT_EQ(dmabuf2->maprefs().size(), 1u);
350     ASSERT_EQ(dmabuf2->total_refs(), 1u);
351     ASSERT_EQ(dmabuf2->exporter(), exporter);
352 }
353 
TEST_F(DmaBufProcessStatsTest,TestReadDmaBufFdRefs)354 TEST_F(DmaBufProcessStatsTest, TestReadDmaBufFdRefs) {
355     AddFdInfo(1, 1024, false);
356     AddFdInfo(2, 2048, true);  // Dmabuf 1
357     AddFdInfo(2, 2048, true);  // Dmabuf 1
358     AddFdInfo(3, 1024, true);  // Dmabuf 2
359 
360     std::vector<DmaBuffer> dmabufs;
361     ASSERT_TRUE(ReadDmaBufFdRefs(pid, &dmabufs, procfs_path));
362     ASSERT_EQ(dmabufs.size(), 2u);
363 
364     const auto& dmabuf1 = std::find_if(dmabufs.begin(), dmabufs.end(),
365                                        [](const DmaBuffer& dmabuf) { return dmabuf.inode() == 2; });
366 
367     ASSERT_EQ(dmabuf1->size(), 2048u);
368     ASSERT_EQ(dmabuf1->fdrefs().size(), 1u);  // Only one process has FDs to this buffer
369     ASSERT_EQ(dmabuf1->maprefs().size(), 0u);
370     ASSERT_EQ(dmabuf1->total_refs(), 2u);
371     ASSERT_EQ(dmabuf1->exporter(), exporter);
372 
373     // Verify process has 2 FDs to this buffer
374     ASSERT_NE(dmabuf1, dmabufs.end());
375     const auto& fdrefs1 = dmabuf1->fdrefs();
376     const auto& pid_fdrefs1 = fdrefs1.find(pid);
377     ASSERT_NE(pid_fdrefs1, fdrefs1.end());
378     ASSERT_EQ(pid_fdrefs1->second, 2);
379 
380     const auto& dmabuf2 = std::find_if(dmabufs.begin(), dmabufs.end(),
381                                        [](const DmaBuffer& dmabuf) { return dmabuf.inode() == 3; });
382     ASSERT_EQ(dmabuf2->size(), 1024u);
383     ASSERT_EQ(dmabuf2->fdrefs().size(), 1u);  // Only one process has FDs to this buffer
384     ASSERT_EQ(dmabuf2->maprefs().size(), 0u);
385     ASSERT_EQ(dmabuf2->total_refs(), 1u);
386     ASSERT_EQ(dmabuf2->exporter(), exporter);
387 
388     // Verify process only has 1 FD to this buffer
389     ASSERT_NE(dmabuf2, dmabufs.end());
390     const auto& fdrefs2 = dmabuf2->fdrefs();
391     const auto& pid_fdrefs2 = fdrefs2.find(pid);
392     ASSERT_NE(pid_fdrefs2, fdrefs2.end());
393     ASSERT_EQ(pid_fdrefs2->second, 1);
394 }
395 
TEST_F(DmaBufProcessStatsTest,TestReadDmaBufMapRefs)396 TEST_F(DmaBufProcessStatsTest, TestReadDmaBufMapRefs) {
397     std::vector<std::string> map_entries;
398     map_entries.emplace_back(CreateMapEntry(1, 1024, false));
399     map_entries.emplace_back(CreateMapEntry(2, 1024, true));  // Dmabuf 1
400     map_entries.emplace_back(CreateMapEntry(2, 1024, true));  // Dmabuf 1
401     map_entries.emplace_back(CreateMapEntry(3, 2048, true));  // Dmabuf 2
402     AddMapEntries(map_entries);
403 
404     AddSysfsDmaBufStats(2, 1024, 2);  // Dmabuf 1
405     AddSysfsDmaBufStats(3, 2048, 1);  // Dmabuf 2
406 
407     std::vector<DmaBuffer> dmabufs;
408     ASSERT_TRUE(ReadDmaBufMapRefs(pid, &dmabufs, procfs_path, dmabuf_sysfs_path));
409     ASSERT_EQ(dmabufs.size(), 2u);
410 
411     const auto& dmabuf1 = std::find_if(dmabufs.begin(), dmabufs.end(),
412                                        [](const DmaBuffer& dmabuf) { return dmabuf.inode() == 2; });
413 
414     ASSERT_EQ(dmabuf1->size(), 1024u);
415     ASSERT_EQ(dmabuf1->fdrefs().size(), 0u);
416     ASSERT_EQ(dmabuf1->maprefs().size(), 1u);  // Only one process mapped this buffer
417     ASSERT_EQ(dmabuf1->total_refs(), 2u);
418     ASSERT_EQ(dmabuf1->exporter(), exporter);
419 
420     // Verify process mapped this buffer twice
421     ASSERT_NE(dmabuf1, dmabufs.end());
422     const auto& maprefs1 = dmabuf1->maprefs();
423     const auto& pid_maprefs1 = maprefs1.find(pid);
424     ASSERT_NE(pid_maprefs1, maprefs1.end());
425     ASSERT_EQ(pid_maprefs1->second, 2);
426 
427     const auto& dmabuf2 = std::find_if(dmabufs.begin(), dmabufs.end(),
428                                        [](const DmaBuffer& dmabuf) { return dmabuf.inode() == 3; });
429     ASSERT_EQ(dmabuf2->size(), 2048u);
430     ASSERT_EQ(dmabuf2->fdrefs().size(), 0u);
431     ASSERT_EQ(dmabuf2->maprefs().size(), 1u);  // Only one process mapped this buffer
432     ASSERT_EQ(dmabuf2->total_refs(), 1u);
433     ASSERT_EQ(dmabuf2->exporter(), exporter);
434 
435     // Verify process mapped this buffer only once
436     ASSERT_NE(dmabuf2, dmabufs.end());
437     const auto& maprefs2 = dmabuf2->maprefs();
438     const auto& pid_maprefs2 = maprefs2.find(pid);
439     ASSERT_NE(pid_maprefs2, maprefs2.end());
440     ASSERT_EQ(pid_maprefs2->second, 1);
441 }
442 
443 class DmaBufTester : public ::testing::Test {
444   public:
DmaBufTester()445     DmaBufTester() : ion_fd(ion_open()), ion_heap_mask(get_ion_heap_mask()) {}
446 
~DmaBufTester()447     ~DmaBufTester() {
448         if (ion_fd >= 0) {
449             ion_close(ion_fd);
450         }
451     }
452 
is_valid()453     bool is_valid() { return (ion_fd >= 0 && ion_heap_mask > 0); }
454 
is_using_dmabuf_heaps()455     bool is_using_dmabuf_heaps() {
456         // We can verify that a device is running on dmabuf-heaps by checking that
457         // the `dev/ion` is missing, while `dev/dma_heap` is present.
458         // https://source.android.com/docs/core/architecture/kernel/dma-buf-heaps
459         return !fs::is_directory("/dev/ion") && fs::is_directory("/dev/dma_heap");
460     }
461 
allocate(uint64_t size,const std::string & name)462     unique_fd allocate(uint64_t size, const std::string& name) {
463         int fd;
464         int err = ion_alloc_fd(ion_fd, size, 0, ion_heap_mask, 0, &fd);
465         if (err < 0) {
466             printf("Failed ion_alloc_fd, return value: %d\n", err);
467             return unique_fd{};
468         }
469 
470         if (!name.empty()) {
471             if (ioctl(fd, DMA_BUF_SET_NAME, name.c_str()) == -1) {
472                 printf("Failed ioctl(DMA_BUF_SET_NAME): %s\n", strerror(errno));
473                 close(fd);
474                 return unique_fd{};
475             }
476         }
477 
478         return unique_fd{fd};
479     }
480 
readAndCheckDmaBuffer(std::vector<DmaBuffer> * dmabufs,pid_t pid,const std::string name,size_t fdrefs_size,size_t maprefs_size,const std::string exporter,size_t refcount,uint64_t buf_size,bool expectFdrefs,bool expectMapRefs)481     void readAndCheckDmaBuffer(std::vector<DmaBuffer>* dmabufs, pid_t pid, const std::string name,
482                                size_t fdrefs_size, size_t maprefs_size, const std::string exporter,
483                                size_t refcount, uint64_t buf_size, bool expectFdrefs,
484                                bool expectMapRefs) {
485         EXPECT_TRUE(ReadDmaBufInfo(pid, dmabufs));
486         EXPECT_EQ(dmabufs->size(), 1UL);
487         EXPECT_ONE_BUF_EQ(dmabufs->begin(), name, fdrefs_size, maprefs_size, exporter, refcount,
488                           buf_size);
489         // Make sure the buffer has the right pid too.
490         EXPECT_PID_IN_FDREFS(dmabufs->begin(), pid, expectFdrefs);
491         EXPECT_PID_IN_MAPREFS(dmabufs->begin(), pid, expectMapRefs);
492     }
493 
checkPidRef(DmaBuffer & dmabuf,pid_t pid,int expectFdrefs)494     bool checkPidRef(DmaBuffer& dmabuf, pid_t pid, int expectFdrefs) {
495         int fdrefs = dmabuf.fdrefs().find(pid)->second;
496         return fdrefs == expectFdrefs;
497     }
498 
499   private:
get_ion_heap_mask()500     int get_ion_heap_mask() {
501         if (ion_fd < 0) {
502             return 0;
503         }
504 
505         if (ion_is_legacy(ion_fd)) {
506             // Since ION is still in staging, we've seen that the heap mask ids are also
507             // changed across kernels for some reason. So, here we basically ask for a buffer
508             // from _any_ heap.
509             return ION_HEAP_ANY_MASK;
510         }
511 
512         int cnt;
513         int err = ion_query_heap_cnt(ion_fd, &cnt);
514         if (err < 0) {
515             return err;
516         }
517 
518         std::vector<ion_heap_data> heaps;
519         heaps.resize(cnt);
520         err = ion_query_get_heaps(ion_fd, cnt, &heaps[0]);
521         if (err < 0) {
522             return err;
523         }
524 
525         unsigned int ret = 0;
526         for (auto& it : heaps) {
527             if (!strcmp(it.name, "ion_system_heap")) {
528                 ret |= (1 << it.heap_id);
529             }
530         }
531 
532         return ret;
533     }
534 
535     int ion_fd;
536     const int ion_heap_mask;
537 };
538 
TEST_F(DmaBufTester,TestFdRef)539 TEST_F(DmaBufTester, TestFdRef) {
540     // Test if a dma buffer is found while the corresponding file descriptor
541     // is open
542 
543     if (is_using_dmabuf_heaps()) {
544         GTEST_SKIP();
545     }
546 
547     ASSERT_TRUE(is_valid());
548     pid_t pid = getpid();
549     std::vector<DmaBuffer> dmabufs;
550     {
551         // Allocate one buffer and make sure the library can see it
552         unique_fd buf = allocate(4096, "dmabuftester-4k");
553         ASSERT_GT(buf, 0) << "Allocated buffer is invalid";
554         ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
555 
556         EXPECT_EQ(dmabufs.size(), 1UL);
557         EXPECT_ONE_BUF_EQ(dmabufs.begin(), "dmabuftester-4k", 1UL, 0UL, "ion", 1UL, 4096ULL);
558 
559         // Make sure the buffer has the right pid too.
560         EXPECT_PID_IN_FDREFS(dmabufs.begin(), pid, true);
561     }
562 
563     // Now make sure the buffer has disappeared
564     ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
565     EXPECT_TRUE(dmabufs.empty());
566 }
567 
TEST_F(DmaBufTester,TestMapRef)568 TEST_F(DmaBufTester, TestMapRef) {
569     // Test to make sure we can find a buffer if the fd is closed but the buffer
570     // is mapped
571 
572     if (is_using_dmabuf_heaps()) {
573         GTEST_SKIP();
574     }
575 
576     ASSERT_TRUE(is_valid());
577     pid_t pid = getpid();
578     std::vector<DmaBuffer> dmabufs;
579     {
580         // Allocate one buffer and make sure the library can see it
581         unique_fd buf = allocate(4096, "dmabuftester-4k");
582         ASSERT_GT(buf, 0) << "Allocated buffer is invalid";
583         auto ptr = mmap(0, 4096, PROT_READ, MAP_SHARED, buf, 0);
584         ASSERT_NE(ptr, MAP_FAILED);
585         ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
586 
587         EXPECT_EQ(dmabufs.size(), 1UL);
588         EXPECT_ONE_BUF_EQ(dmabufs.begin(), "dmabuftester-4k", 1UL, 1UL, "ion", 2UL, 4096ULL);
589 
590         // Make sure the buffer has the right pid too.
591         EXPECT_PID_IN_FDREFS(dmabufs.begin(), pid, true);
592         EXPECT_PID_IN_MAPREFS(dmabufs.begin(), pid, true);
593 
594         // close the file descriptor and re-read the stats
595         buf.reset(-1);
596         ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
597 
598         EXPECT_EQ(dmabufs.size(), 1UL);
599         EXPECT_ONE_BUF_EQ(dmabufs.begin(), "<unknown>", 0UL, 1UL, "<unknown>", 0UL, 4096ULL);
600 
601         EXPECT_PID_IN_FDREFS(dmabufs.begin(), pid, false);
602         EXPECT_PID_IN_MAPREFS(dmabufs.begin(), pid, true);
603 
604         // unmap the bufer and lose all references
605         munmap(ptr, 4096);
606     }
607 
608     // Now make sure the buffer has disappeared
609     ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
610     EXPECT_TRUE(dmabufs.empty());
611 }
612 
TEST_F(DmaBufTester,TestSharedfd)613 TEST_F(DmaBufTester, TestSharedfd) {
614     // Each time a shared buffer is received over a socket, the remote process
615     // will take an extra reference on it.
616 
617     if (is_using_dmabuf_heaps()) {
618         GTEST_SKIP();
619     }
620 
621     ASSERT_TRUE(is_valid());
622 
623     pid_t pid = getpid();
624     std::vector<DmaBuffer> dmabufs;
625     {
626         fd_sharer sharer{};
627         ASSERT_TRUE(sharer.ok());
628         // Allocate one buffer and make sure the library can see it
629         unique_fd buf = allocate(4096, "dmabuftester-4k");
630         ASSERT_GT(buf, 0) << "Allocated buffer is invalid";
631         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 1UL, 4096ULL, true,
632                               false);
633 
634         ASSERT_TRUE(sharer.sendfd(buf));
635         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 2UL, 4096ULL, true,
636                               false);
637         EXPECT_TRUE(checkPidRef(dmabufs[0], pid, 1));
638         readAndCheckDmaBuffer(&dmabufs, sharer.pid(), "dmabuftester-4k", 1UL, 0UL, "ion", 2UL,
639                               4096ULL, true, false);
640         EXPECT_TRUE(checkPidRef(dmabufs[0], sharer.pid(), 1));
641 
642         ASSERT_TRUE(sharer.sendfd(buf));
643         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 3UL, 4096ULL, true,
644                               false);
645         EXPECT_TRUE(checkPidRef(dmabufs[0], pid, 1));
646         readAndCheckDmaBuffer(&dmabufs, sharer.pid(), "dmabuftester-4k", 1UL, 0UL, "ion", 3UL,
647                               4096ULL, true, false);
648         EXPECT_TRUE(checkPidRef(dmabufs[0], sharer.pid(), 2));
649 
650         ASSERT_TRUE(sharer.kill());
651         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 1UL, 4096ULL, true,
652                               false);
653     }
654 
655     // Now make sure the buffer has disappeared
656     ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
657     EXPECT_TRUE(dmabufs.empty());
658 }
659 
TEST_F(DmaBufTester,DupFdTest)660 TEST_F(DmaBufTester, DupFdTest) {
661     // dup()ing an fd will make this process take an extra reference on the
662     // shared buffer.
663 
664     if (is_using_dmabuf_heaps()) {
665         GTEST_SKIP();
666     }
667 
668     ASSERT_TRUE(is_valid());
669 
670     pid_t pid = getpid();
671     std::vector<DmaBuffer> dmabufs;
672     {
673         // Allocate one buffer and make sure the library can see it
674         unique_fd buf = allocate(4096, "dmabuftester-4k");
675         ASSERT_GT(buf, 0) << "Allocated buffer is invalid";
676         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 1UL, 4096ULL, true,
677                               false);
678 
679         unique_fd buf2{dup(buf)};
680         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 2UL, 4096ULL, true,
681                               false);
682         EXPECT_TRUE(checkPidRef(dmabufs[0], pid, 2));
683 
684         close(buf2.release());
685         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 1UL, 4096ULL, true,
686                               false);
687         EXPECT_TRUE(checkPidRef(dmabufs[0], pid, 1));
688     }
689 
690     // Now make sure the buffer has disappeared
691     ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
692     EXPECT_TRUE(dmabufs.empty());
693 }
694 
TEST_F(DmaBufTester,ForkTest)695 TEST_F(DmaBufTester, ForkTest) {
696     // fork()ing a child will cause the child to automatically take a reference
697     // on any existing shared buffers.
698 
699     if (is_using_dmabuf_heaps()) {
700         GTEST_SKIP();
701     }
702 
703     ASSERT_TRUE(is_valid());
704 
705     pid_t pid = getpid();
706     std::vector<DmaBuffer> dmabufs;
707     {
708         // Allocate one buffer and make sure the library can see it
709         unique_fd buf = allocate(4096, "dmabuftester-4k");
710         ASSERT_GT(buf, 0) << "Allocated buffer is invalid";
711         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 1UL, 4096ULL, true,
712                               false);
713         fd_sharer sharer{};
714         ASSERT_TRUE(sharer.ok());
715         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 2UL, 4096ULL, true,
716                               false);
717         readAndCheckDmaBuffer(&dmabufs, sharer.pid(), "dmabuftester-4k", 1UL, 0UL, "ion", 2UL,
718                               4096ULL, true, false);
719         ASSERT_TRUE(sharer.kill());
720         readAndCheckDmaBuffer(&dmabufs, pid, "dmabuftester-4k", 1UL, 0UL, "ion", 1UL, 4096ULL, true,
721                               false);
722     }
723 
724     // Now make sure the buffer has disappeared
725     ASSERT_TRUE(ReadDmaBufInfo(pid, &dmabufs));
726     EXPECT_TRUE(dmabufs.empty());
727 }
728 
main(int argc,char ** argv)729 int main(int argc, char** argv) {
730     ::testing::InitGoogleTest(&argc, argv);
731     ::android::base::InitLogging(argv, android::base::StderrLogger);
732     return RUN_ALL_TESTS();
733 }
734