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 #include "BackgroundExecutor.h"
28
29 #include <cinttypes>
30
31 #include <binder/IInterface.h>
32 #include <utils/RefBase.h>
33
34 namespace android {
35
36 // Returns 0 if they are equal
37 // <0 if the first id that doesn't match is lower in c2 or all ids match but c2 is shorter
38 // >0 if the first id that doesn't match is greater in c2 or all ids match but c2 is longer
39 //
40 // See CallbackIdsHash for a explanation of why this works
compareCallbackIds(const std::vector<CallbackId> & c1,const std::vector<CallbackId> & c2)41 static int compareCallbackIds(const std::vector<CallbackId>& c1,
42 const std::vector<CallbackId>& c2) {
43 if (c1.empty()) {
44 return !c2.empty();
45 }
46 return c1.front().id - c2.front().id;
47 }
48
containsOnCommitCallbacks(const std::vector<CallbackId> & callbacks)49 static bool containsOnCommitCallbacks(const std::vector<CallbackId>& callbacks) {
50 return !callbacks.empty() && callbacks.front().type == CallbackId::Type::ON_COMMIT;
51 }
52
addEmptyTransaction(const ListenerCallbacks & listenerCallbacks)53 void TransactionCallbackInvoker::addEmptyTransaction(const ListenerCallbacks& listenerCallbacks) {
54 auto& [listener, callbackIds] = listenerCallbacks;
55 auto& transactionStatsDeque = mCompletedTransactions[listener];
56 transactionStatsDeque.emplace_back(callbackIds);
57 }
58
addOnCommitCallbackHandles(const std::deque<sp<CallbackHandle>> & handles,std::deque<sp<CallbackHandle>> & outRemainingHandles)59 status_t TransactionCallbackInvoker::addOnCommitCallbackHandles(
60 const std::deque<sp<CallbackHandle>>& handles,
61 std::deque<sp<CallbackHandle>>& outRemainingHandles) {
62 if (handles.empty()) {
63 return NO_ERROR;
64 }
65 const std::vector<JankData>& jankData = std::vector<JankData>();
66 for (const auto& handle : handles) {
67 if (!containsOnCommitCallbacks(handle->callbackIds)) {
68 outRemainingHandles.push_back(handle);
69 continue;
70 }
71 status_t err = addCallbackHandle(handle, jankData);
72 if (err != NO_ERROR) {
73 return err;
74 }
75 }
76
77 return NO_ERROR;
78 }
79
addCallbackHandles(const std::deque<sp<CallbackHandle>> & handles,const std::vector<JankData> & jankData)80 status_t TransactionCallbackInvoker::addCallbackHandles(
81 const std::deque<sp<CallbackHandle>>& handles, const std::vector<JankData>& jankData) {
82 if (handles.empty()) {
83 return NO_ERROR;
84 }
85 for (const auto& handle : handles) {
86 status_t err = addCallbackHandle(handle, jankData);
87 if (err != NO_ERROR) {
88 return err;
89 }
90 }
91
92 return NO_ERROR;
93 }
94
registerUnpresentedCallbackHandle(const sp<CallbackHandle> & handle)95 status_t TransactionCallbackInvoker::registerUnpresentedCallbackHandle(
96 const sp<CallbackHandle>& handle) {
97 return addCallbackHandle(handle, std::vector<JankData>());
98 }
99
findOrCreateTransactionStats(const sp<IBinder> & listener,const std::vector<CallbackId> & callbackIds,TransactionStats ** outTransactionStats)100 status_t TransactionCallbackInvoker::findOrCreateTransactionStats(
101 const sp<IBinder>& listener, const std::vector<CallbackId>& callbackIds,
102 TransactionStats** outTransactionStats) {
103 auto& transactionStatsDeque = mCompletedTransactions[listener];
104
105 // Search back to front because the most recent transactions are at the back of the deque
106 auto itr = transactionStatsDeque.rbegin();
107 for (; itr != transactionStatsDeque.rend(); itr++) {
108 if (compareCallbackIds(itr->callbackIds, callbackIds) == 0) {
109 *outTransactionStats = &(*itr);
110 return NO_ERROR;
111 }
112 }
113 *outTransactionStats = &transactionStatsDeque.emplace_back(callbackIds);
114 return NO_ERROR;
115 }
116
addCallbackHandle(const sp<CallbackHandle> & handle,const std::vector<JankData> & jankData)117 status_t TransactionCallbackInvoker::addCallbackHandle(const sp<CallbackHandle>& handle,
118 const std::vector<JankData>& jankData) {
119 // If we can't find the transaction stats something has gone wrong. The client should call
120 // startRegistration before trying to add a callback handle.
121 TransactionStats* transactionStats;
122 status_t err =
123 findOrCreateTransactionStats(handle->listener, handle->callbackIds, &transactionStats);
124 if (err != NO_ERROR) {
125 return err;
126 }
127
128 transactionStats->latchTime = handle->latchTime;
129 // If the layer has already been destroyed, don't add the SurfaceControl to the callback.
130 // The client side keeps a sp<> to the SurfaceControl so if the SurfaceControl has been
131 // destroyed the client side is dead and there won't be anyone to send the callback to.
132 sp<IBinder> surfaceControl = handle->surfaceControl.promote();
133 if (surfaceControl) {
134 sp<Fence> prevFence = nullptr;
135
136 for (const auto& future : handle->previousReleaseFences) {
137 sp<Fence> currentFence = future.get().value_or(Fence::NO_FENCE);
138 if (prevFence == nullptr && currentFence->getStatus() != Fence::Status::Invalid) {
139 prevFence = std::move(currentFence);
140 handle->previousReleaseFence = prevFence;
141 } else if (prevFence != nullptr) {
142 // If both fences are signaled or both are unsignaled, we need to merge
143 // them to get an accurate timestamp.
144 if (prevFence->getStatus() != Fence::Status::Invalid &&
145 prevFence->getStatus() == currentFence->getStatus()) {
146 char fenceName[32] = {};
147 snprintf(fenceName, 32, "%.28s", handle->name.c_str());
148 sp<Fence> mergedFence = Fence::merge(fenceName, prevFence, currentFence);
149 if (mergedFence->isValid()) {
150 handle->previousReleaseFence = std::move(mergedFence);
151 prevFence = handle->previousReleaseFence;
152 }
153 } else if (currentFence->getStatus() == Fence::Status::Unsignaled) {
154 // If one fence has signaled and the other hasn't, the unsignaled
155 // fence will approximately correspond with the correct timestamp.
156 // There's a small race if both fences signal at about the same time
157 // and their statuses are retrieved with unfortunate timing. However,
158 // by this point, they will have both signaled and only the timestamp
159 // will be slightly off; any dependencies after this point will
160 // already have been met.
161 handle->previousReleaseFence = std::move(currentFence);
162 }
163 }
164 }
165 handle->previousReleaseFences.clear();
166
167 FrameEventHistoryStats eventStats(handle->frameNumber,
168 handle->gpuCompositionDoneFence->getSnapshot().fence,
169 handle->compositorTiming, handle->refreshStartTime,
170 handle->dequeueReadyTime);
171 transactionStats->surfaceStats.emplace_back(surfaceControl, handle->acquireTimeOrFence,
172 handle->previousReleaseFence,
173 handle->transformHint,
174 handle->currentMaxAcquiredBufferCount,
175 eventStats, jankData,
176 handle->previousReleaseCallbackId);
177 }
178 return NO_ERROR;
179 }
180
addPresentFence(const sp<Fence> & presentFence)181 void TransactionCallbackInvoker::addPresentFence(const sp<Fence>& presentFence) {
182 mPresentFence = presentFence;
183 }
184
sendCallbacks(bool onCommitOnly)185 void TransactionCallbackInvoker::sendCallbacks(bool onCommitOnly) {
186 // For each listener
187 auto completedTransactionsItr = mCompletedTransactions.begin();
188 BackgroundExecutor::Callbacks callbacks;
189 while (completedTransactionsItr != mCompletedTransactions.end()) {
190 auto& [listener, transactionStatsDeque] = *completedTransactionsItr;
191 ListenerStats listenerStats;
192 listenerStats.listener = listener;
193
194 // For each transaction
195 auto transactionStatsItr = transactionStatsDeque.begin();
196 while (transactionStatsItr != transactionStatsDeque.end()) {
197 auto& transactionStats = *transactionStatsItr;
198 if (onCommitOnly && !containsOnCommitCallbacks(transactionStats.callbackIds)) {
199 transactionStatsItr++;
200 continue;
201 }
202
203 // If the transaction has been latched
204 if (transactionStats.latchTime >= 0 &&
205 !containsOnCommitCallbacks(transactionStats.callbackIds)) {
206 transactionStats.presentFence = mPresentFence;
207 }
208
209 // Remove the transaction from completed to the callback
210 listenerStats.transactionStats.push_back(std::move(transactionStats));
211 transactionStatsItr = transactionStatsDeque.erase(transactionStatsItr);
212 }
213 // If the listener has completed transactions
214 if (!listenerStats.transactionStats.empty()) {
215 // If the listener is still alive
216 if (listener->isBinderAlive()) {
217 // Send callback. The listener stored in listenerStats
218 // comes from the cross-process setTransactionState call to
219 // SF. This MUST be an ITransactionCompletedListener. We
220 // keep it as an IBinder due to consistency reasons: if we
221 // interface_cast at the IPC boundary when reading a Parcel,
222 // we get pointers that compare unequal in the SF process.
223 callbacks.emplace_back([stats = std::move(listenerStats)]() {
224 interface_cast<ITransactionCompletedListener>(stats.listener)
225 ->onTransactionCompleted(stats);
226 });
227 }
228 }
229 completedTransactionsItr++;
230 }
231
232 if (mPresentFence) {
233 mPresentFence.clear();
234 }
235
236 BackgroundExecutor::getInstance().sendCallbacks(std::move(callbacks));
237 }
238
239 // -----------------------------------------------------------------------
240
CallbackHandle(const sp<IBinder> & transactionListener,const std::vector<CallbackId> & ids,const sp<IBinder> & sc)241 CallbackHandle::CallbackHandle(const sp<IBinder>& transactionListener,
242 const std::vector<CallbackId>& ids, const sp<IBinder>& sc)
243 : listener(transactionListener), callbackIds(ids), surfaceControl(sc) {}
244
245 } // namespace android
246
247 // TODO(b/129481165): remove the #pragma below and fix conversion issues
248 #pragma clang diagnostic pop // ignored "-Wconversion"
249