1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
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 #ifndef RS_MEMORY_SNAPSHOT
16 #define RS_MEMORY_SNAPSHOT
17 
18 #include <mutex>
19 #include <set>
20 
21 #include "common/rs_common_def.h"
22 
23 namespace OHOS {
24 namespace Rosen {
25 struct MemorySnapshotInfo {
26     size_t cpuMemory = 0;
27     size_t gpuMemory = 0;
28 
TotalMemoryMemorySnapshotInfo29     size_t TotalMemory() const
30     {
31         return cpuMemory + gpuMemory;
32     }
33 };
34 
35 using MemoryOverflowCalllback = std::function<void(pid_t, uint64_t, bool)>;
36 class RSB_EXPORT MemorySnapshot {
37 public:
38     static MemorySnapshot& Instance();
39     void AddCpuMemory(const pid_t pid, const size_t size);
40     void RemoveCpuMemory(const pid_t pid, const size_t size);
41     bool GetMemorySnapshotInfoByPid(const pid_t pid, MemorySnapshotInfo& info);
42     void EraseSnapshotInfoByPid(const std::set<pid_t>& exitedPidSet);
43     void UpdateGpuMemoryInfo(const std::unordered_map<pid_t, size_t>& gpuInfo,
44         std::unordered_map<pid_t, MemorySnapshotInfo>& pidForReport, bool& isTotalOver);
45     void InitMemoryLimit(MemoryOverflowCalllback callback, uint64_t warning, uint64_t overflow, uint64_t totalSize);
46     void GetMemorySnapshot(std::unordered_map<pid_t, MemorySnapshotInfo>& map);
47 private:
48     MemorySnapshot() = default;
49     ~MemorySnapshot() = default;
50     MemorySnapshot(const MemorySnapshot&) = delete;
51     MemorySnapshot(const MemorySnapshot&&) = delete;
52     MemorySnapshot& operator=(const MemorySnapshot&) = delete;
53     MemorySnapshot& operator=(const MemorySnapshot&&) = delete;
54     std::mutex mutex_;
55     std::unordered_map<pid_t, MemorySnapshotInfo> appMemorySnapshots_;
56 
57     uint64_t singleMemoryWarning_ = UINT64_MAX; // warning threshold for total memory of a single process
58     uint64_t singleCpuMemoryLimit_ = UINT64_MAX; // error threshold for cpu memory of a single process
59     uint64_t totalMemoryLimit_ = UINT64_MAX; // error threshold for total memory of all process
60     size_t totalMemory_ = 0; // record the total memory of all processes
61     MemoryOverflowCalllback callback_ = nullptr;
62 };
63 } // namespace OHOS
64 } // namespace Rosen
65 #endif