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 #include "Utils/FenceUtils.h"
29
30 #include <binder/IInterface.h>
31 #include <common/trace.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 for (const auto& handle : handles) {
66 if (!containsOnCommitCallbacks(handle->callbackIds)) {
67 outRemainingHandles.push_back(handle);
68 continue;
69 }
70 status_t err = addCallbackHandle(handle);
71 if (err != NO_ERROR) {
72 return err;
73 }
74 }
75
76 return NO_ERROR;
77 }
78
addCallbackHandles(const std::deque<sp<CallbackHandle>> & handles)79 status_t TransactionCallbackInvoker::addCallbackHandles(
80 const std::deque<sp<CallbackHandle>>& handles) {
81 if (handles.empty()) {
82 return NO_ERROR;
83 }
84 for (const auto& handle : handles) {
85 status_t err = addCallbackHandle(handle);
86 if (err != NO_ERROR) {
87 return err;
88 }
89 }
90
91 return NO_ERROR;
92 }
93
findOrCreateTransactionStats(const sp<IBinder> & listener,const std::vector<CallbackId> & callbackIds,TransactionStats ** outTransactionStats)94 status_t TransactionCallbackInvoker::findOrCreateTransactionStats(
95 const sp<IBinder>& listener, const std::vector<CallbackId>& callbackIds,
96 TransactionStats** outTransactionStats) {
97 auto& transactionStatsDeque = mCompletedTransactions[listener];
98
99 // Search back to front because the most recent transactions are at the back of the deque
100 auto itr = transactionStatsDeque.rbegin();
101 for (; itr != transactionStatsDeque.rend(); itr++) {
102 if (compareCallbackIds(itr->callbackIds, callbackIds) == 0) {
103 *outTransactionStats = &(*itr);
104 return NO_ERROR;
105 }
106 }
107 *outTransactionStats = &transactionStatsDeque.emplace_back(callbackIds);
108 return NO_ERROR;
109 }
110
addCallbackHandle(const sp<CallbackHandle> & handle)111 status_t TransactionCallbackInvoker::addCallbackHandle(const sp<CallbackHandle>& handle) {
112 // If we can't find the transaction stats something has gone wrong. The client should call
113 // startRegistration before trying to add a callback handle.
114 TransactionStats* transactionStats;
115 status_t err =
116 findOrCreateTransactionStats(handle->listener, handle->callbackIds, &transactionStats);
117 if (err != NO_ERROR) {
118 return err;
119 }
120
121 transactionStats->latchTime = handle->latchTime;
122 // If the layer has already been destroyed, don't add the SurfaceControl to the callback.
123 // The client side keeps a sp<> to the SurfaceControl so if the SurfaceControl has been
124 // destroyed the client side is dead and there won't be anyone to send the callback to.
125 sp<IBinder> surfaceControl = handle->surfaceControl.promote();
126 if (surfaceControl) {
127 sp<Fence> prevFence = nullptr;
128
129 for (auto& future : handle->previousReleaseFences) {
130 mergeFence(handle->name.c_str(), future.get().value_or(Fence::NO_FENCE), prevFence);
131 }
132
133 handle->previousReleaseFence = prevFence;
134 handle->previousReleaseFences.clear();
135
136 FrameEventHistoryStats eventStats(handle->frameNumber, handle->previousFrameNumber,
137 handle->gpuCompositionDoneFence->getSnapshot().fence,
138 handle->compositorTiming, handle->refreshStartTime,
139 handle->dequeueReadyTime);
140 transactionStats->surfaceStats.emplace_back(surfaceControl, handle->acquireTimeOrFence,
141 handle->previousReleaseFence,
142 handle->transformHint,
143 handle->currentMaxAcquiredBufferCount,
144 eventStats, handle->previousReleaseCallbackId);
145 if (handle->bufferReleaseChannel &&
146 handle->previousReleaseCallbackId != ReleaseCallbackId::INVALID_ID) {
147 mBufferReleases.emplace_back(handle->name, handle->bufferReleaseChannel,
148 handle->previousReleaseCallbackId,
149 handle->previousReleaseFence,
150 handle->currentMaxAcquiredBufferCount);
151 }
152 }
153 return NO_ERROR;
154 }
155
addPresentFence(sp<Fence> presentFence)156 void TransactionCallbackInvoker::addPresentFence(sp<Fence> presentFence) {
157 mPresentFence = std::move(presentFence);
158 }
159
sendCallbacks(bool onCommitOnly)160 void TransactionCallbackInvoker::sendCallbacks(bool onCommitOnly) {
161 for (const auto& bufferRelease : mBufferReleases) {
162 status_t status = bufferRelease.channel
163 ->writeReleaseFence(bufferRelease.callbackId, bufferRelease.fence,
164 bufferRelease.currentMaxAcquiredBufferCount);
165 if (status != OK) {
166 ALOGE("[%s] writeReleaseFence failed. error %d (%s)", bufferRelease.layerName.c_str(),
167 -status, strerror(-status));
168 }
169 }
170 mBufferReleases.clear();
171
172 // For each listener
173 auto completedTransactionsItr = mCompletedTransactions.begin();
174 ftl::SmallVector<ListenerStats, 10> listenerStatsToSend;
175 while (completedTransactionsItr != mCompletedTransactions.end()) {
176 auto& [listener, transactionStatsDeque] = *completedTransactionsItr;
177 ListenerStats listenerStats;
178 listenerStats.listener = listener;
179
180 // For each transaction
181 auto transactionStatsItr = transactionStatsDeque.begin();
182 while (transactionStatsItr != transactionStatsDeque.end()) {
183 auto& transactionStats = *transactionStatsItr;
184 if (onCommitOnly && !containsOnCommitCallbacks(transactionStats.callbackIds)) {
185 transactionStatsItr++;
186 continue;
187 }
188
189 // If the transaction has been latched
190 if (transactionStats.latchTime >= 0 &&
191 !containsOnCommitCallbacks(transactionStats.callbackIds)) {
192 transactionStats.presentFence = mPresentFence;
193 }
194
195 // Remove the transaction from completed to the callback
196 listenerStats.transactionStats.push_back(std::move(transactionStats));
197 transactionStatsItr = transactionStatsDeque.erase(transactionStatsItr);
198 }
199 // If the listener has completed transactions
200 if (!listenerStats.transactionStats.empty()) {
201 // If the listener is still alive
202 if (listener->isBinderAlive()) {
203 // Send callback. The listener stored in listenerStats
204 // comes from the cross-process setTransactionState call to
205 // SF. This MUST be an ITransactionCompletedListener. We
206 // keep it as an IBinder due to consistency reasons: if we
207 // interface_cast at the IPC boundary when reading a Parcel,
208 // we get pointers that compare unequal in the SF process.
209 listenerStatsToSend.emplace_back(std::move(listenerStats));
210 }
211 }
212 completedTransactionsItr++;
213 }
214
215 if (mPresentFence) {
216 mPresentFence.clear();
217 }
218
219 BackgroundExecutor::getInstance().sendCallbacks(
220 {[listenerStatsToSend = std::move(listenerStatsToSend)]() {
221 SFTRACE_NAME("TransactionCallbackInvoker::sendCallbacks");
222 for (auto& stats : listenerStatsToSend) {
223 interface_cast<ITransactionCompletedListener>(stats.listener)
224 ->onTransactionCompleted(stats);
225 }
226 }});
227 }
228
229 // -----------------------------------------------------------------------
230
CallbackHandle(const sp<IBinder> & transactionListener,const std::vector<CallbackId> & ids,const sp<IBinder> & sc)231 CallbackHandle::CallbackHandle(const sp<IBinder>& transactionListener,
232 const std::vector<CallbackId>& ids, const sp<IBinder>& sc)
233 : listener(transactionListener), callbackIds(ids), surfaceControl(sc) {}
234
235 } // namespace android
236
237 // TODO(b/129481165): remove the #pragma below and fix conversion issues
238 #pragma clang diagnostic pop // ignored "-Wconversion"
239