1 /*
2 * Copyright 2018 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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20
21 //#define LOG_NDEBUG 0
22 #undef LOG_TAG
23 #define LOG_TAG "TransactionCallbackInvoker"
24 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
26 #include "TransactionCallbackInvoker.h"
27
28 #include <cinttypes>
29
30 #include <binder/IInterface.h>
31 #include <utils/RefBase.h>
32
33 namespace android {
34
35 // Returns 0 if they are equal
36 // <0 if the first id that doesn't match is lower in c2 or all ids match but c2 is shorter
37 // >0 if the first id that doesn't match is greater in c2 or all ids match but c2 is longer
38 //
39 // See CallbackIdsHash for a explanation of why this works
compareCallbackIds(const std::vector<CallbackId> & c1,const std::vector<CallbackId> & c2)40 static int compareCallbackIds(const std::vector<CallbackId>& c1,
41 const std::vector<CallbackId>& c2) {
42 if (c1.empty()) {
43 return !c2.empty();
44 }
45 return c1.front().id - c2.front().id;
46 }
47
containsOnCommitCallbacks(const std::vector<CallbackId> & callbacks)48 static bool containsOnCommitCallbacks(const std::vector<CallbackId>& callbacks) {
49 return !callbacks.empty() && callbacks.front().type == CallbackId::Type::ON_COMMIT;
50 }
51
~TransactionCallbackInvoker()52 TransactionCallbackInvoker::~TransactionCallbackInvoker() {
53 {
54 std::lock_guard lock(mMutex);
55 for (const auto& [listener, transactionStats] : mCompletedTransactions) {
56 listener->unlinkToDeath(mDeathRecipient);
57 }
58 }
59 }
60
startRegistration(const ListenerCallbacks & listenerCallbacks)61 status_t TransactionCallbackInvoker::startRegistration(const ListenerCallbacks& listenerCallbacks) {
62 std::lock_guard lock(mMutex);
63
64 auto [itr, inserted] = mRegisteringTransactions.insert(listenerCallbacks);
65 auto& [listener, callbackIds] = listenerCallbacks;
66
67 if (inserted) {
68 if (mCompletedTransactions.count(listener) == 0) {
69 status_t err = listener->linkToDeath(mDeathRecipient);
70 if (err != NO_ERROR) {
71 ALOGE("cannot add callback because linkToDeath failed, err: %d", err);
72 return err;
73 }
74 }
75 auto& transactionStatsDeque = mCompletedTransactions[listener];
76 transactionStatsDeque.emplace_back(callbackIds);
77 }
78
79 return NO_ERROR;
80 }
81
endRegistration(const ListenerCallbacks & listenerCallbacks)82 status_t TransactionCallbackInvoker::endRegistration(const ListenerCallbacks& listenerCallbacks) {
83 std::lock_guard lock(mMutex);
84
85 auto itr = mRegisteringTransactions.find(listenerCallbacks);
86 if (itr == mRegisteringTransactions.end()) {
87 ALOGE("cannot end a registration that does not exist");
88 return BAD_VALUE;
89 }
90
91 mRegisteringTransactions.erase(itr);
92
93 return NO_ERROR;
94 }
95
isRegisteringTransaction(const sp<IBinder> & transactionListener,const std::vector<CallbackId> & callbackIds)96 bool TransactionCallbackInvoker::isRegisteringTransaction(
97 const sp<IBinder>& transactionListener, const std::vector<CallbackId>& callbackIds) {
98 ListenerCallbacks listenerCallbacks(transactionListener, callbackIds);
99
100 auto itr = mRegisteringTransactions.find(listenerCallbacks);
101 return itr != mRegisteringTransactions.end();
102 }
103
registerPendingCallbackHandle(const sp<CallbackHandle> & handle)104 status_t TransactionCallbackInvoker::registerPendingCallbackHandle(
105 const sp<CallbackHandle>& handle) {
106 std::lock_guard lock(mMutex);
107
108 // If we can't find the transaction stats something has gone wrong. The client should call
109 // startRegistration before trying to register a pending callback handle.
110 TransactionStats* transactionStats;
111 status_t err = findTransactionStats(handle->listener, handle->callbackIds, &transactionStats);
112 if (err != NO_ERROR) {
113 ALOGE("cannot find transaction stats");
114 return err;
115 }
116
117 mPendingTransactions[handle->listener][handle->callbackIds]++;
118 return NO_ERROR;
119 }
120
finalizeCallbackHandle(const sp<CallbackHandle> & handle,const std::vector<JankData> & jankData)121 status_t TransactionCallbackInvoker::finalizeCallbackHandle(const sp<CallbackHandle>& handle,
122 const std::vector<JankData>& jankData) {
123 auto listener = mPendingTransactions.find(handle->listener);
124 if (listener != mPendingTransactions.end()) {
125 auto& pendingCallbacks = listener->second;
126 auto pendingCallback = pendingCallbacks.find(handle->callbackIds);
127
128 if (pendingCallback != pendingCallbacks.end()) {
129 auto& pendingCount = pendingCallback->second;
130
131 // Decrease the pending count for this listener
132 if (--pendingCount == 0) {
133 pendingCallbacks.erase(pendingCallback);
134 }
135 } else {
136 ALOGW("there are more latched callbacks than there were registered callbacks");
137 }
138 if (listener->second.size() == 0) {
139 mPendingTransactions.erase(listener);
140 }
141 } else {
142 ALOGW("cannot find listener in mPendingTransactions");
143 }
144
145 status_t err = addCallbackHandle(handle, jankData);
146 if (err != NO_ERROR) {
147 ALOGE("could not add callback handle");
148 return err;
149 }
150 return NO_ERROR;
151 }
152
finalizeOnCommitCallbackHandles(const std::deque<sp<CallbackHandle>> & handles,std::deque<sp<CallbackHandle>> & outRemainingHandles)153 status_t TransactionCallbackInvoker::finalizeOnCommitCallbackHandles(
154 const std::deque<sp<CallbackHandle>>& handles,
155 std::deque<sp<CallbackHandle>>& outRemainingHandles) {
156 if (handles.empty()) {
157 return NO_ERROR;
158 }
159 std::lock_guard lock(mMutex);
160 const std::vector<JankData>& jankData = std::vector<JankData>();
161 for (const auto& handle : handles) {
162 if (!containsOnCommitCallbacks(handle->callbackIds)) {
163 outRemainingHandles.push_back(handle);
164 continue;
165 }
166 status_t err = finalizeCallbackHandle(handle, jankData);
167 if (err != NO_ERROR) {
168 return err;
169 }
170 }
171
172 return NO_ERROR;
173 }
174
finalizePendingCallbackHandles(const std::deque<sp<CallbackHandle>> & handles,const std::vector<JankData> & jankData)175 status_t TransactionCallbackInvoker::finalizePendingCallbackHandles(
176 const std::deque<sp<CallbackHandle>>& handles, const std::vector<JankData>& jankData) {
177 if (handles.empty()) {
178 return NO_ERROR;
179 }
180 std::lock_guard lock(mMutex);
181 for (const auto& handle : handles) {
182 status_t err = finalizeCallbackHandle(handle, jankData);
183 if (err != NO_ERROR) {
184 return err;
185 }
186 }
187
188 return NO_ERROR;
189 }
190
registerUnpresentedCallbackHandle(const sp<CallbackHandle> & handle)191 status_t TransactionCallbackInvoker::registerUnpresentedCallbackHandle(
192 const sp<CallbackHandle>& handle) {
193 std::lock_guard lock(mMutex);
194
195 return addCallbackHandle(handle, std::vector<JankData>());
196 }
197
findTransactionStats(const sp<IBinder> & listener,const std::vector<CallbackId> & callbackIds,TransactionStats ** outTransactionStats)198 status_t TransactionCallbackInvoker::findTransactionStats(
199 const sp<IBinder>& listener, const std::vector<CallbackId>& callbackIds,
200 TransactionStats** outTransactionStats) {
201 auto& transactionStatsDeque = mCompletedTransactions[listener];
202
203 // Search back to front because the most recent transactions are at the back of the deque
204 auto itr = transactionStatsDeque.rbegin();
205 for (; itr != transactionStatsDeque.rend(); itr++) {
206 if (compareCallbackIds(itr->callbackIds, callbackIds) == 0) {
207 *outTransactionStats = &(*itr);
208 return NO_ERROR;
209 }
210 }
211
212 ALOGE("could not find transaction stats");
213 return BAD_VALUE;
214 }
215
addCallbackHandle(const sp<CallbackHandle> & handle,const std::vector<JankData> & jankData)216 status_t TransactionCallbackInvoker::addCallbackHandle(const sp<CallbackHandle>& handle,
217 const std::vector<JankData>& jankData) {
218 // If we can't find the transaction stats something has gone wrong. The client should call
219 // startRegistration before trying to add a callback handle.
220 TransactionStats* transactionStats;
221 status_t err = findTransactionStats(handle->listener, handle->callbackIds, &transactionStats);
222 if (err != NO_ERROR) {
223 return err;
224 }
225
226 transactionStats->latchTime = handle->latchTime;
227 // If the layer has already been destroyed, don't add the SurfaceControl to the callback.
228 // The client side keeps a sp<> to the SurfaceControl so if the SurfaceControl has been
229 // destroyed the client side is dead and there won't be anyone to send the callback to.
230 sp<IBinder> surfaceControl = handle->surfaceControl.promote();
231 if (surfaceControl) {
232 FrameEventHistoryStats eventStats(handle->frameNumber,
233 handle->gpuCompositionDoneFence->getSnapshot().fence,
234 handle->compositorTiming, handle->refreshStartTime,
235 handle->dequeueReadyTime);
236 transactionStats->surfaceStats.emplace_back(surfaceControl, handle->acquireTime,
237 handle->previousReleaseFence,
238 handle->transformHint,
239 handle->currentMaxAcquiredBufferCount,
240 eventStats, jankData,
241 handle->previousReleaseCallbackId);
242 }
243 return NO_ERROR;
244 }
245
addPresentFence(const sp<Fence> & presentFence)246 void TransactionCallbackInvoker::addPresentFence(const sp<Fence>& presentFence) {
247 std::lock_guard<std::mutex> lock(mMutex);
248 mPresentFence = presentFence;
249 }
250
sendCallbacks()251 void TransactionCallbackInvoker::sendCallbacks() {
252 std::lock_guard lock(mMutex);
253
254 // For each listener
255 auto completedTransactionsItr = mCompletedTransactions.begin();
256 while (completedTransactionsItr != mCompletedTransactions.end()) {
257 auto& [listener, transactionStatsDeque] = *completedTransactionsItr;
258 ListenerStats listenerStats;
259 listenerStats.listener = listener;
260
261 // For each transaction
262 auto transactionStatsItr = transactionStatsDeque.begin();
263 while (transactionStatsItr != transactionStatsDeque.end()) {
264 auto& transactionStats = *transactionStatsItr;
265
266 // If this transaction is still registering, it is not safe to send a callback
267 // because there could be surface controls that haven't been added to
268 // transaction stats or mPendingTransactions.
269 if (isRegisteringTransaction(listener, transactionStats.callbackIds)) {
270 break;
271 }
272
273 // If we are still waiting on the callback handles for this transaction, stop
274 // here because all transaction callbacks for the same listener must come in order
275 auto pendingTransactions = mPendingTransactions.find(listener);
276 if (pendingTransactions != mPendingTransactions.end() &&
277 pendingTransactions->second.count(transactionStats.callbackIds) != 0) {
278 break;
279 }
280
281 // If the transaction has been latched
282 if (transactionStats.latchTime >= 0 &&
283 !containsOnCommitCallbacks(transactionStats.callbackIds)) {
284 if (!mPresentFence) {
285 break;
286 }
287 transactionStats.presentFence = mPresentFence;
288 }
289
290 // Remove the transaction from completed to the callback
291 listenerStats.transactionStats.push_back(std::move(transactionStats));
292 transactionStatsItr = transactionStatsDeque.erase(transactionStatsItr);
293 }
294 // If the listener has completed transactions
295 if (!listenerStats.transactionStats.empty()) {
296 // If the listener is still alive
297 if (listener->isBinderAlive()) {
298 // Send callback. The listener stored in listenerStats
299 // comes from the cross-process setTransactionState call to
300 // SF. This MUST be an ITransactionCompletedListener. We
301 // keep it as an IBinder due to consistency reasons: if we
302 // interface_cast at the IPC boundary when reading a Parcel,
303 // we get pointers that compare unequal in the SF process.
304 interface_cast<ITransactionCompletedListener>(listenerStats.listener)
305 ->onTransactionCompleted(listenerStats);
306 if (transactionStatsDeque.empty()) {
307 listener->unlinkToDeath(mDeathRecipient);
308 completedTransactionsItr =
309 mCompletedTransactions.erase(completedTransactionsItr);
310 } else {
311 completedTransactionsItr++;
312 }
313 } else {
314 completedTransactionsItr =
315 mCompletedTransactions.erase(completedTransactionsItr);
316 }
317 } else {
318 completedTransactionsItr++;
319 }
320 }
321
322 if (mPresentFence) {
323 mPresentFence.clear();
324 }
325 }
326
327 // -----------------------------------------------------------------------
328
CallbackHandle(const sp<IBinder> & transactionListener,const std::vector<CallbackId> & ids,const sp<IBinder> & sc)329 CallbackHandle::CallbackHandle(const sp<IBinder>& transactionListener,
330 const std::vector<CallbackId>& ids, const sp<IBinder>& sc)
331 : listener(transactionListener), callbackIds(ids), surfaceControl(sc) {}
332
333 } // namespace android
334
335 // TODO(b/129481165): remove the #pragma below and fix conversion issues
336 #pragma clang diagnostic pop // ignored "-Wconversion"
337