1 /* 2 * Copyright (c) 2021-2022 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 UTILS_INCLUDE_SYNC_FENCE_H 17 #define UTILS_INCLUDE_SYNC_FENCE_H 18 19 #include <cstddef> 20 #include <cstdint> 21 #include <string> 22 #include <mutex> 23 #include <vector> 24 25 #include <refbase.h> 26 #include <message_parcel.h> 27 #include <unique_fd.h> 28 29 namespace OHOS { 30 31 using ns_sec_t = int64_t; 32 33 // same to linux/sync_file define 34 enum FenceStatus { 35 ERROR = -1, 36 ACTIVE = 0, 37 SIGNALED = 1 38 }; 39 40 struct SyncPointInfo { 41 uint64_t timestampNs; 42 FenceStatus status; 43 }; 44 45 class SyncTimeline : public RefBase { 46 public: 47 SyncTimeline() noexcept; 48 ~SyncTimeline() noexcept; 49 50 SyncTimeline(const SyncTimeline& rhs) = delete; 51 SyncTimeline& operator=(const SyncTimeline& rhs) = delete; 52 SyncTimeline(SyncTimeline&& rhs) = delete; 53 SyncTimeline& operator=(SyncTimeline&& rhs) = delete; 54 55 bool IsValid(); 56 int32_t IncreaseSyncPoint(uint32_t step = 1); 57 int32_t GenerateFence(std::string name, uint32_t point); 58 59 private: 60 int32_t timeLineFd_ = -1; 61 bool isValid_ = false; 62 }; 63 64 class SyncFence : public RefBase { 65 public: 66 explicit SyncFence(int32_t fenceFd); 67 /* When the SyncFence is destroyed, the fd will be closed in UniqueFd */ 68 virtual ~SyncFence(); 69 70 SyncFence(const SyncFence& rhs) = delete; 71 SyncFence& operator=(const SyncFence& rhs) = delete; 72 SyncFence(SyncFence&& rhs) = delete; 73 SyncFence& operator=(SyncFence&& rhs) = delete; 74 75 static const sptr<SyncFence> INVALID_FENCE; 76 static const ns_sec_t INVALID_TIMESTAMP; 77 static const ns_sec_t FENCE_PENDING_TIMESTAMP; 78 int32_t Wait(uint32_t timeout); 79 static sptr<SyncFence> MergeFence(const std::string &name, 80 const sptr<SyncFence>& fence1, const sptr<SyncFence>& fence2); 81 ns_sec_t SyncFileReadTimestamp(); 82 int32_t Dup() const; 83 bool IsValid() const; 84 85 /* this is dangerous, when you use it, do not operator the fd */ 86 int32_t Get() const; 87 88 void WriteToMessageParcel(MessageParcel &parcel); 89 static sptr<SyncFence> ReadFromMessageParcel(MessageParcel &parcel); 90 FenceStatus GetStatus(); 91 92 private: 93 std::vector<SyncPointInfo> GetFenceInfo(); 94 95 UniqueFd fenceFd_; 96 static int SyncMerge(const char *name, int fd1, int fd2); 97 }; 98 99 } 100 101 #endif // UTILS_INCLUDE_SYNC_FENCE_H