1 /*
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
19 #define LOG_TAG "FenceTime"
20
21 #include <cutils/compiler.h> // For CC_[UN]LIKELY
22 #include <utils/Log.h>
23 #include <inttypes.h>
24 #include <stdlib.h>
25
26 #include <memory>
27
28 namespace android {
29
30 // ============================================================================
31 // FenceTime
32 // ============================================================================
33
34 const auto FenceTime::NO_FENCE = std::make_shared<FenceTime>(Fence::NO_FENCE);
35
FenceTime(const sp<Fence> & fence)36 FenceTime::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
FenceTime(sp<Fence> && fence)44 FenceTime::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
FenceTime(nsecs_t signalTime)52 FenceTime::FenceTime(nsecs_t signalTime)
53 : mState(Fence::isValidTimestamp(signalTime) ? State::VALID : State::INVALID),
54 mFence(nullptr),
55 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 }
60 }
61
makeValid(const sp<Fence> & fence)62 FenceTimePtr 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
applyTrustedSnapshot(const Snapshot & src)70 void 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.
75 ALOGE("applyTrustedSnapshot: Unexpected fence.");
76 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
isValid() const101 bool 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
wait(int timeout)108 status_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
getSignalTime()136 nsecs_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
163 // 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
171 // 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
getCachedSignalTime() const182 nsecs_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
getSnapshot() const188 FenceTime::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
204 // For tests only. If forceValidForTest is true, then getSignalTime will
205 // never return SIGNAL_TIME_INVALID and isValid will always return true.
FenceTime(const sp<Fence> & fence,bool forceValidForTest)206 FenceTime::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
signalForTest(nsecs_t signalTime)214 void 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
223 // ============================================================================
224 // FenceTime::Snapshot
225 // ============================================================================
Snapshot(const sp<Fence> & srcFence)226 FenceTime::Snapshot::Snapshot(const sp<Fence>& srcFence)
227 : state(State::FENCE), fence(srcFence) {
228 }
229
Snapshot(nsecs_t srcSignalTime)230 FenceTime::Snapshot::Snapshot(nsecs_t srcSignalTime)
231 : state(State::SIGNAL_TIME), signalTime(srcSignalTime) {
232 }
233
getFlattenedSize() const234 size_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
getFdCount() const247 size_t FenceTime::Snapshot::getFdCount() const {
248 return state == State::FENCE ? fence->getFdCount() : 0u;
249 }
250
flatten(void * & buffer,size_t & size,int * & fds,size_t & count) const251 status_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
unflatten(void const * & buffer,size_t & size,int const * & fds,size_t & count)271 status_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 // ============================================================================
push(const std::shared_ptr<FenceTime> & fence)298 void FenceTimeline::push(const std::shared_ptr<FenceTime>& fence) {
299 std::lock_guard<std::mutex> lock(mMutex);
300 static constexpr size_t MAX_QUEUE_SIZE = 64;
301 while (mQueue.size() >= MAX_QUEUE_SIZE) {
302 // This is a sanity check to make sure the queue doesn't grow unbounded.
303 // MAX_QUEUE_SIZE should be big enough not to trigger this path.
304 // 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
updateSignalTimes()318 void FenceTimeline::updateSignalTimes() {
319 std::lock_guard<std::mutex> lock(mMutex);
320 while (!mQueue.empty()) {
321 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
339 // ============================================================================
340 // FenceToFenceTimeMap
341 // ============================================================================
createFenceTimeForTest(const sp<Fence> & fence)342 std::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
signalAllForTest(const sp<Fence> & fence,nsecs_t signalTime)352 void 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(),
365 "signalAllForTest: Signaling invalid fence.");
366 fenceTime->signalForTest(signalTime);
367 signaled = true;
368 }
369 }
370
371 ALOGE_IF(!signaled, "signalAllForTest: Nothing to signal.");
372 }
373
garbageCollectLocked()374 void FenceToFenceTimeMap::garbageCollectLocked() {
375 for (auto it = mMap.begin(); it != mMap.end();) {
376 // Erase all expired weak pointers from the vector.
377 auto& vect = it->second;
378 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()) {
387 it = mMap.erase(it);
388 } else {
389 it++;
390 }
391 }
392 }
393
394 } // namespace android
395