1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <bpf/BpfMap.h>
20 #include <utils/String16.h>
21 #include <utils/Vector.h>
22 
23 #include <functional>
24 
25 namespace android {
26 
27 class GpuMem {
28 public:
29     GpuMem() = default;
30     ~GpuMem();
31 
32     // initialize eBPF program and map
33     void initialize();
34     // dumpsys interface
35     void dump(const Vector<String16>& args, std::string* result);
isInitialized()36     bool isInitialized() { return mInitialized.load(); }
37 
38     // Traverse the gpu memory total map to feed the callback function.
39     void traverseGpuMemTotals(const std::function<void(int64_t ts, uint32_t gpuId, uint32_t pid,
40                                                        uint64_t size)>& callback);
41 
42 private:
43     // Friend class for testing.
44     friend class TestableGpuMem;
45 
46     // set gpu memory total map
47     void setGpuMemTotalMap(bpf::BpfMap<uint64_t, uint64_t>& map);
48 
49     // indicate whether ebpf has been initialized
50     std::atomic<bool> mInitialized = false;
51     // bpf map for GPU memory total data
52     android::bpf::BpfMap<uint64_t, uint64_t> mGpuMemTotalMap;
53 
54     // gpu memory tracepoint event category
55     static constexpr char kGpuMemTraceGroup[] = "gpu_mem";
56     // gpu memory total tracepoint
57     static constexpr char kGpuMemTotalTracepoint[] = "gpu_mem_total";
58     // pinned gpu memory total bpf c program path in bpf sysfs
59     static constexpr char kGpuMemTotalProgPath[] =
60             "/sys/fs/bpf/prog_gpu_mem_tracepoint_gpu_mem_gpu_mem_total";
61     // pinned gpu memory total bpf map path in bpf sysfs
62     static constexpr char kGpuMemTotalMapPath[] = "/sys/fs/bpf/map_gpu_mem_gpu_mem_total_map";
63     // 30 seconds timeout for trying to attach bpf program to tracepoint
64     static constexpr int kGpuWaitTimeout = 30;
65 };
66 
67 } // namespace android
68