1 #include <Memtrack.h>
2 #include <stdlib.h>
3 
4 #include <sstream>
5 #include <string>
6 #include <vector>
7 
8 #include "GpuSysfsReader.h"
9 #include "filesystem.h"
10 
11 #undef LOG_TAG
12 #define LOG_TAG "memtrack-core"
13 
14 namespace aidl {
15 namespace android {
16 namespace hardware {
17 namespace memtrack {
18 
getMemory(int pid,MemtrackType type,std::vector<MemtrackRecord> * _aidl_return)19 ndk::ScopedAStatus Memtrack::getMemory(int pid, MemtrackType type,
20                                        std::vector<MemtrackRecord>* _aidl_return) {
21     if (pid < 0)
22         return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_ILLEGAL_ARGUMENT));
23 
24     if (type != MemtrackType::OTHER && type != MemtrackType::GL && type != MemtrackType::GRAPHICS &&
25         type != MemtrackType::MULTIMEDIA && type != MemtrackType::CAMERA)
26         return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_UNSUPPORTED_OPERATION));
27 
28     _aidl_return->clear();
29 
30     // Other types are retained only for backward compatibility
31     if (type != MemtrackType::GL && type != MemtrackType::GRAPHICS)
32         return ndk::ScopedAStatus::ok();
33 
34     // pid 0 is only supported for GL type to report total private memory
35     if (pid == 0 && type != MemtrackType::GL)
36         return ndk::ScopedAStatus::ok();
37 
38     uint64_t size = 0;
39     switch (type) {
40         case MemtrackType::GL:
41             size = GpuSysfsReader::getPrivateGpuMem(pid);
42             break;
43         case MemtrackType::GRAPHICS:
44             // TODO(b/194483693): This is not PSS as required by memtrack HAL
45             // but complete dmabuf allocations. Reporting PSS requires reading
46             // procfs. This HAL does not have that permission yet.
47             size = GpuSysfsReader::getDmaBufGpuMem(pid);
48             break;
49         default:
50             break;
51     }
52 
53     MemtrackRecord record = {
54             .flags = MemtrackRecord::FLAG_SMAPS_UNACCOUNTED,
55             .sizeInBytes = static_cast<long>(size),
56     };
57     _aidl_return->emplace_back(record);
58 
59     return ndk::ScopedAStatus::ok();
60 }
61 
getGpuDeviceInfo(std::vector<DeviceInfo> * _aidl_return)62 ndk::ScopedAStatus Memtrack::getGpuDeviceInfo(std::vector<DeviceInfo>* _aidl_return) {
63     auto devPath = filesystem::path(GpuSysfsReader::kSysfsDevicePath);
64     std::string devName = "default-gpu";
65     if (filesystem::exists(devPath) && filesystem::is_symlink(devPath)) {
66         devName = filesystem::read_symlink(devPath).filename().string();
67     }
68 
69     DeviceInfo dev_info = {.id = 0, .name = devName};
70 
71     _aidl_return->clear();
72     _aidl_return->emplace_back(dev_info);
73     return ndk::ScopedAStatus::ok();
74 }
75 
76 } // namespace memtrack
77 } // namespace hardware
78 } // namespace android
79 } // namespace aidl
80