1 /* 2 * Copyright (C) 2025 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 16 #ifndef TRACE_BUFFER_MANAGER_H 17 #define TRACE_BUFFER_MANAGER_H 18 19 #include <list> 20 #include <memory> 21 #include <mutex> 22 #include <map> 23 #include <vector> 24 25 #include "nocopyable.h" 26 27 namespace OHOS { 28 namespace HiviewDFX { 29 namespace Hitrace { 30 /** 31 * @brief BufferBlock is a block of memory that can be used to store trace data. 32 * @note The current trace collection service already ensures that memory reading and writing are serial, 33 * so there is no need to add lock protection. 34 */ 35 struct BufferBlock { 36 int cpu; 37 std::vector<uint8_t> data; 38 size_t usedBytes = 0; BufferBlockBufferBlock39 BufferBlock(int cpuIdx, size_t size) : cpu(cpuIdx), data(size) {} 40 size_t FreeBytes() const; 41 bool Append(const uint8_t* src, size_t size); 42 }; 43 44 using BufferBlockPtr = std::shared_ptr<BufferBlock>; 45 using BufferList = std::list<BufferBlockPtr>; 46 47 constexpr size_t DEFAULT_MAX_TOTAL_SZ = 300 * 1024 * 1024; // 300 MB 48 constexpr size_t DEFAULT_BLOCK_SZ = 10 * 1024 * 1024; // 10 MB 49 50 class TraceBufferManager final { 51 public: GetInstance()52 static TraceBufferManager& GetInstance() 53 { 54 static TraceBufferManager instance(DEFAULT_MAX_TOTAL_SZ); 55 return instance; 56 } 57 58 BufferBlockPtr AllocateBlock(const uint64_t taskId, const int cpu); 59 void ReleaseTaskBlocks(const uint64_t taskId); 60 BufferList GetTaskBuffers(const uint64_t taskId); 61 size_t GetTaskTotalUsedBytes(const uint64_t taskId); 62 size_t GetCurrentTotalSize(); 63 size_t GetBlockSize() const; 64 65 private: 66 TraceBufferManager(); 67 explicit TraceBufferManager(size_t maxTotalSz, size_t blockSz = DEFAULT_BLOCK_SZ) maxTotalSz_(maxTotalSz)68 : maxTotalSz_(maxTotalSz), blockSz_(blockSz), curTotalSz_(0) {} 69 DISALLOW_COPY_AND_MOVE(TraceBufferManager); 70 71 private: 72 size_t maxTotalSz_; 73 size_t blockSz_; 74 size_t curTotalSz_; 75 76 mutable std::mutex mutex_; 77 std::map<uint64_t, BufferList> taskBuffers_; 78 }; 79 } // namespace Hitrace 80 } // namespace HiviewDFX 81 } // namespace OHOS 82 #endif // TRACE_BUFFER_MANAGER_H