blob: 81afe9ef0e01bd30be33d01eb16a276ee70fa6b9 [file] [log] [blame]
Brian Anderson221de2a2016-09-21 16:53:28 -07001/*
2* Copyright 2016 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#include <ui/FenceTime.h>
18
Brian Anderson8cc8b102016-10-21 12:43:09 -070019#define LOG_TAG "FenceTime"
20
Brian Anderson221de2a2016-09-21 16:53:28 -070021#include <cutils/compiler.h> // For CC_[UN]LIKELY
Brian Anderson175a7202016-10-10 16:52:56 -070022#include <utils/Log.h>
Brian Anderson221de2a2016-09-21 16:53:28 -070023#include <inttypes.h>
24#include <stdlib.h>
25
26#include <memory>
27
28namespace android {
29
30// ============================================================================
31// FenceTime
32// ============================================================================
33
34const auto FenceTime::NO_FENCE = std::make_shared<FenceTime>(Fence::NO_FENCE);
35
Brian Anderson221de2a2016-09-21 16:53:28 -070036FenceTime::FenceTime(const sp<Fence>& fence)
37 : mState(((fence.get() != nullptr) && fence->isValid()) ?
38 State::VALID : State::INVALID),
39 mFence(fence),
40 mSignalTime(mState == State::INVALID ?
41 Fence::SIGNAL_TIME_INVALID : Fence::SIGNAL_TIME_PENDING) {
42}
43
44FenceTime::FenceTime(sp<Fence>&& fence)
45 : mState(((fence.get() != nullptr) && fence->isValid()) ?
46 State::VALID : State::INVALID),
47 mFence(std::move(fence)),
48 mSignalTime(mState == State::INVALID ?
49 Fence::SIGNAL_TIME_INVALID : Fence::SIGNAL_TIME_PENDING) {
50}
51
52FenceTime::FenceTime(nsecs_t signalTime)
53 : mState(Fence::isValidTimestamp(signalTime) ? State::VALID : State::INVALID),
54 mFence(nullptr),
Brian Anderson8cc8b102016-10-21 12:43:09 -070055 mSignalTime(signalTime) {
56 if (CC_UNLIKELY(mSignalTime == Fence::SIGNAL_TIME_PENDING)) {
57 ALOGE("Pending signal time not allowed after signal.");
58 mSignalTime = Fence::SIGNAL_TIME_INVALID;
59 }
Brian Anderson221de2a2016-09-21 16:53:28 -070060}
61
Alec Mouridf868ba2025-02-25 16:08:19 -080062FenceTimePtr FenceTime::makeValid(const sp<Fence>& fence) {
63 if (fence && fence->isValid()) {
64 return std::make_shared<FenceTime>(fence);
65 } else {
66 return std::make_shared<FenceTime>(systemTime());
67 }
68}
69
Brian Anderson221de2a2016-09-21 16:53:28 -070070void FenceTime::applyTrustedSnapshot(const Snapshot& src) {
71 if (CC_UNLIKELY(src.state != Snapshot::State::SIGNAL_TIME)) {
72 // Applying Snapshot::State::FENCE, could change the valid state of the
73 // FenceTime, which is not allowed. Callers should create a new
74 // FenceTime from the snapshot instead.
Brian Anderson8cc8b102016-10-21 12:43:09 -070075 ALOGE("applyTrustedSnapshot: Unexpected fence.");
Brian Anderson221de2a2016-09-21 16:53:28 -070076 return;
77 }
78
79 if (src.state == Snapshot::State::EMPTY) {
80 return;
81 }
82
83 nsecs_t signalTime = mSignalTime.load(std::memory_order_relaxed);
84 if (signalTime != Fence::SIGNAL_TIME_PENDING) {
85 // We should always get the same signalTime here that we did in
86 // getSignalTime(). This check races with getSignalTime(), but it is
87 // only a sanity check so that's okay.
88 if (CC_UNLIKELY(signalTime != src.signalTime)) {
89 ALOGE("FenceTime::applyTrustedSnapshot: signalTime mismatch. "
90 "(%" PRId64 " (old) != %" PRId64 " (new))",
91 signalTime, src.signalTime);
92 }
93 return;
94 }
95
96 std::lock_guard<std::mutex> lock(mMutex);
97 mFence.clear();
98 mSignalTime.store(src.signalTime, std::memory_order_relaxed);
99}
100
101bool FenceTime::isValid() const {
102 // We store the valid state in the constructors and return it here.
103 // This lets release code remember the valid state even after the
104 // underlying fence is destroyed.
105 return mState != State::INVALID;
106}
107
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700108status_t FenceTime::wait(int timeout) {
109 // See if we already have a cached value we can return.
110 nsecs_t signalTime = mSignalTime.load(std::memory_order_relaxed);
111 if (signalTime != Fence::SIGNAL_TIME_PENDING) {
112 return NO_ERROR;
113 }
114
115 // Hold a reference to the fence on the stack in case the class'
116 // reference is removed by another thread. This prevents the
117 // fence from being destroyed until the end of this method, where
118 // we conveniently do not have the lock held.
119 sp<Fence> fence;
120 {
121 // With the lock acquired this time, see if we have the cached
122 // value or if we need to poll the fence.
123 std::lock_guard<std::mutex> lock(mMutex);
124 if (!mFence.get()) {
125 // Another thread set the signal time just before we added the
126 // reference to mFence.
127 return NO_ERROR;
128 }
129 fence = mFence;
130 }
131
132 // Make the system call without the lock held.
133 return fence->wait(timeout);
134}
135
Brian Anderson221de2a2016-09-21 16:53:28 -0700136nsecs_t FenceTime::getSignalTime() {
137 // See if we already have a cached value we can return.
138 nsecs_t signalTime = mSignalTime.load(std::memory_order_relaxed);
139 if (signalTime != Fence::SIGNAL_TIME_PENDING) {
140 return signalTime;
141 }
142
143 // Hold a reference to the fence on the stack in case the class'
144 // reference is removed by another thread. This prevents the
145 // fence from being destroyed until the end of this method, where
146 // we conveniently do not have the lock held.
147 sp<Fence> fence;
148 {
149 // With the lock acquired this time, see if we have the cached
150 // value or if we need to poll the fence.
151 std::lock_guard<std::mutex> lock(mMutex);
152 if (!mFence.get()) {
153 // Another thread set the signal time just before we added the
154 // reference to mFence.
155 return mSignalTime.load(std::memory_order_relaxed);
156 }
157 fence = mFence;
158 }
159
160 // Make the system call without the lock held.
161 signalTime = fence->getSignalTime();
162
Brian Anderson3da8d272016-07-28 16:20:47 -0700163 // Allow tests to override SIGNAL_TIME_INVALID behavior, since tests
164 // use invalid underlying Fences without real file descriptors.
165 if (CC_UNLIKELY(mState == State::FORCED_VALID_FOR_TEST)) {
166 if (signalTime == Fence::SIGNAL_TIME_INVALID) {
167 signalTime = Fence::SIGNAL_TIME_PENDING;
168 }
169 }
170
Brian Anderson221de2a2016-09-21 16:53:28 -0700171 // Make the signal time visible to everyone if it is no longer pending
172 // and remove the class' reference to the fence.
173 if (signalTime != Fence::SIGNAL_TIME_PENDING) {
174 std::lock_guard<std::mutex> lock(mMutex);
175 mFence.clear();
176 mSignalTime.store(signalTime, std::memory_order_relaxed);
177 }
178
179 return signalTime;
180}
181
182nsecs_t FenceTime::getCachedSignalTime() const {
183 // memory_order_acquire since we don't have a lock fallback path
184 // that will do an acquire.
185 return mSignalTime.load(std::memory_order_acquire);
186}
187
188FenceTime::Snapshot FenceTime::getSnapshot() const {
189 // Quick check without the lock.
190 nsecs_t signalTime = mSignalTime.load(std::memory_order_relaxed);
191 if (signalTime != Fence::SIGNAL_TIME_PENDING) {
192 return Snapshot(signalTime);
193 }
194
195 // Do the full check with the lock.
196 std::lock_guard<std::mutex> lock(mMutex);
197 signalTime = mSignalTime.load(std::memory_order_relaxed);
198 if (signalTime != Fence::SIGNAL_TIME_PENDING) {
199 return Snapshot(signalTime);
200 }
201 return Snapshot(mFence);
202}
203
Brian Anderson3da8d272016-07-28 16:20:47 -0700204// For tests only. If forceValidForTest is true, then getSignalTime will
205// never return SIGNAL_TIME_INVALID and isValid will always return true.
206FenceTime::FenceTime(const sp<Fence>& fence, bool forceValidForTest)
207 : mState(forceValidForTest ?
208 State::FORCED_VALID_FOR_TEST : State::INVALID),
209 mFence(fence),
210 mSignalTime(mState == State::INVALID ?
211 Fence::SIGNAL_TIME_INVALID : Fence::SIGNAL_TIME_PENDING) {
212}
213
214void FenceTime::signalForTest(nsecs_t signalTime) {
215 // To be realistic, this should really set a hidden value that
216 // gets picked up in the next call to getSignalTime, but this should
217 // be good enough.
218 std::lock_guard<std::mutex> lock(mMutex);
219 mFence.clear();
220 mSignalTime.store(signalTime, std::memory_order_relaxed);
221}
222
Brian Anderson221de2a2016-09-21 16:53:28 -0700223// ============================================================================
224// FenceTime::Snapshot
225// ============================================================================
Brian Anderson221de2a2016-09-21 16:53:28 -0700226FenceTime::Snapshot::Snapshot(const sp<Fence>& srcFence)
227 : state(State::FENCE), fence(srcFence) {
228}
229
230FenceTime::Snapshot::Snapshot(nsecs_t srcSignalTime)
231 : state(State::SIGNAL_TIME), signalTime(srcSignalTime) {
232}
233
234size_t FenceTime::Snapshot::getFlattenedSize() const {
235 constexpr size_t min = sizeof(state);
236 switch (state) {
237 case State::EMPTY:
238 return min;
239 case State::FENCE:
240 return min + fence->getFlattenedSize();
241 case State::SIGNAL_TIME:
242 return min + sizeof(signalTime);
243 }
244 return 0;
245}
246
247size_t FenceTime::Snapshot::getFdCount() const {
248 return state == State::FENCE ? fence->getFdCount() : 0u;
249}
250
251status_t FenceTime::Snapshot::flatten(
252 void*& buffer, size_t& size, int*& fds, size_t& count) const {
253 if (size < getFlattenedSize()) {
254 return NO_MEMORY;
255 }
256
257 FlattenableUtils::write(buffer, size, state);
258 switch (state) {
259 case State::EMPTY:
260 return NO_ERROR;
261 case State::FENCE:
262 return fence->flatten(buffer, size, fds, count);
263 case State::SIGNAL_TIME:
264 FlattenableUtils::write(buffer, size, signalTime);
265 return NO_ERROR;
266 }
267
268 return NO_ERROR;
269}
270
271status_t FenceTime::Snapshot::unflatten(
272 void const*& buffer, size_t& size, int const*& fds, size_t& count) {
273 if (size < sizeof(state)) {
274 return NO_MEMORY;
275 }
276
277 FlattenableUtils::read(buffer, size, state);
278 switch (state) {
279 case State::EMPTY:
280 return NO_ERROR;
281 case State::FENCE:
282 fence = new Fence;
283 return fence->unflatten(buffer, size, fds, count);
284 case State::SIGNAL_TIME:
285 if (size < sizeof(signalTime)) {
286 return NO_MEMORY;
287 }
288 FlattenableUtils::read(buffer, size, signalTime);
289 return NO_ERROR;
290 }
291
292 return NO_ERROR;
293}
294
295// ============================================================================
296// FenceTimeline
297// ============================================================================
298void FenceTimeline::push(const std::shared_ptr<FenceTime>& fence) {
299 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouridf868ba2025-02-25 16:08:19 -0800300 static constexpr size_t MAX_QUEUE_SIZE = 64;
301 while (mQueue.size() >= MAX_QUEUE_SIZE) {
Brian Anderson221de2a2016-09-21 16:53:28 -0700302 // This is a sanity check to make sure the queue doesn't grow unbounded.
Alec Mouridf868ba2025-02-25 16:08:19 -0800303 // MAX_QUEUE_SIZE should be big enough not to trigger this path.
Brian Anderson221de2a2016-09-21 16:53:28 -0700304 // In case this path is taken though, users of FenceTime must make sure
305 // not to rely solely on FenceTimeline to get the final timestamp and
306 // should eventually call Fence::getSignalTime on their own.
307 std::shared_ptr<FenceTime> front = mQueue.front().lock();
308 if (front) {
309 // Make a last ditch effort to get the signalTime here since
310 // we are removing it from the timeline.
311 front->getSignalTime();
312 }
313 mQueue.pop();
314 }
315 mQueue.push(fence);
316}
317
318void FenceTimeline::updateSignalTimes() {
Ady Abraham90055aa2019-05-15 13:47:16 -0700319 std::lock_guard<std::mutex> lock(mMutex);
Brian Anderson221de2a2016-09-21 16:53:28 -0700320 while (!mQueue.empty()) {
Brian Anderson221de2a2016-09-21 16:53:28 -0700321 std::shared_ptr<FenceTime> fence = mQueue.front().lock();
322 if (!fence) {
323 // The shared_ptr no longer exists and no one cares about the
324 // timestamp anymore.
325 mQueue.pop();
326 continue;
327 } else if (fence->getSignalTime() != Fence::SIGNAL_TIME_PENDING) {
328 // The fence has signaled and we've removed the sp<Fence> ref.
329 mQueue.pop();
330 continue;
331 } else {
332 // The fence didn't signal yet. Break since the later ones
333 // shouldn't have signaled either.
334 break;
335 }
336 }
337}
338
Brian Anderson3da8d272016-07-28 16:20:47 -0700339// ============================================================================
340// FenceToFenceTimeMap
341// ============================================================================
342std::shared_ptr<FenceTime> FenceToFenceTimeMap::createFenceTimeForTest(
343 const sp<Fence>& fence) {
344 std::lock_guard<std::mutex> lock(mMutex);
345 // Always garbage collecting isn't efficient, but this is only for testing.
346 garbageCollectLocked();
347 std::shared_ptr<FenceTime> fenceTime(new FenceTime(fence, true));
348 mMap[fence.get()].push_back(fenceTime);
349 return fenceTime;
350}
351
352void FenceToFenceTimeMap::signalAllForTest(
353 const sp<Fence>& fence, nsecs_t signalTime) {
354 bool signaled = false;
355
356 std::lock_guard<std::mutex> lock(mMutex);
357 auto it = mMap.find(fence.get());
358 if (it != mMap.end()) {
359 for (auto& weakFenceTime : it->second) {
360 std::shared_ptr<FenceTime> fenceTime = weakFenceTime.lock();
361 if (!fenceTime) {
362 continue;
363 }
364 ALOGE_IF(!fenceTime->isValid(),
Brian Anderson8cc8b102016-10-21 12:43:09 -0700365 "signalAllForTest: Signaling invalid fence.");
Brian Anderson3da8d272016-07-28 16:20:47 -0700366 fenceTime->signalForTest(signalTime);
367 signaled = true;
368 }
369 }
370
Brian Anderson8cc8b102016-10-21 12:43:09 -0700371 ALOGE_IF(!signaled, "signalAllForTest: Nothing to signal.");
Brian Anderson3da8d272016-07-28 16:20:47 -0700372}
373
374void FenceToFenceTimeMap::garbageCollectLocked() {
Daniele Di Proietto42e79132023-11-10 12:42:31 +0000375 for (auto it = mMap.begin(); it != mMap.end();) {
Brian Anderson3da8d272016-07-28 16:20:47 -0700376 // Erase all expired weak pointers from the vector.
Daniele Di Proietto42e79132023-11-10 12:42:31 +0000377 auto& vect = it->second;
Brian Anderson3da8d272016-07-28 16:20:47 -0700378 vect.erase(
379 std::remove_if(vect.begin(), vect.end(),
380 [](const std::weak_ptr<FenceTime>& ft) {
381 return ft.expired();
382 }),
383 vect.end());
384
385 // Also erase the map entry if the vector is now empty.
386 if (vect.empty()) {
Daniele Di Proietto42e79132023-11-10 12:42:31 +0000387 it = mMap.erase(it);
388 } else {
389 it++;
Brian Anderson3da8d272016-07-28 16:20:47 -0700390 }
391 }
392}
393
Brian Anderson221de2a2016-09-21 16:53:28 -0700394} // namespace android