• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/FlagManager.h>
32 #include <common/trace.h>
33 #include <utils/RefBase.h>
34 
35 namespace android {
36 
37 // Returns 0 if they are equal
38 //         <0 if the first id that doesn't match is lower in c2 or all ids match but c2 is shorter
39 //         >0 if the first id that doesn't match is greater in c2 or all ids match but c2 is longer
40 //
41 // See CallbackIdsHash for a explanation of why this works
compareCallbackIds(const std::vector<CallbackId> & c1,const std::vector<CallbackId> & c2)42 static int compareCallbackIds(const std::vector<CallbackId>& c1,
43                               const std::vector<CallbackId>& c2) {
44     if (c1.empty()) {
45         return !c2.empty();
46     }
47     return c1.front().id - c2.front().id;
48 }
49 
containsOnCommitCallbacks(const std::vector<CallbackId> & callbacks)50 static bool containsOnCommitCallbacks(const std::vector<CallbackId>& callbacks) {
51     return !callbacks.empty() && callbacks.front().type == CallbackId::Type::ON_COMMIT;
52 }
53 
addEmptyTransaction(const ListenerCallbacks & listenerCallbacks)54 void TransactionCallbackInvoker::addEmptyTransaction(const ListenerCallbacks& listenerCallbacks) {
55     auto& [listener, callbackIds] = listenerCallbacks;
56     auto& transactionStatsDeque = mCompletedTransactions[listener];
57     transactionStatsDeque.emplace_back(callbackIds);
58 }
59 
addOnCommitCallbackHandles(const std::deque<sp<CallbackHandle>> & handles,std::deque<sp<CallbackHandle>> & outRemainingHandles)60 status_t TransactionCallbackInvoker::addOnCommitCallbackHandles(
61         const std::deque<sp<CallbackHandle>>& handles,
62         std::deque<sp<CallbackHandle>>& outRemainingHandles) {
63     if (handles.empty()) {
64         return NO_ERROR;
65     }
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);
72         if (err != NO_ERROR) {
73             return err;
74         }
75     }
76 
77     return NO_ERROR;
78 }
79 
addCallbackHandles(const std::deque<sp<CallbackHandle>> & handles)80 status_t TransactionCallbackInvoker::addCallbackHandles(
81         const std::deque<sp<CallbackHandle>>& handles) {
82     if (handles.empty()) {
83         return NO_ERROR;
84     }
85     for (const auto& handle : handles) {
86         status_t err = addCallbackHandle(handle);
87         if (err != NO_ERROR) {
88             return err;
89         }
90     }
91 
92     return NO_ERROR;
93 }
94 
findOrCreateTransactionStats(const sp<IBinder> & listener,const std::vector<CallbackId> & callbackIds,TransactionStats ** outTransactionStats)95 status_t TransactionCallbackInvoker::findOrCreateTransactionStats(
96         const sp<IBinder>& listener, const std::vector<CallbackId>& callbackIds,
97         TransactionStats** outTransactionStats) {
98     auto& transactionStatsDeque = mCompletedTransactions[listener];
99 
100     // Search back to front because the most recent transactions are at the back of the deque
101     auto itr = transactionStatsDeque.rbegin();
102     for (; itr != transactionStatsDeque.rend(); itr++) {
103         if (compareCallbackIds(itr->callbackIds, callbackIds) == 0) {
104             *outTransactionStats = &(*itr);
105             return NO_ERROR;
106         }
107     }
108     *outTransactionStats = &transactionStatsDeque.emplace_back(callbackIds);
109     return NO_ERROR;
110 }
111 
addCallbackHandle(const sp<CallbackHandle> & handle)112 status_t TransactionCallbackInvoker::addCallbackHandle(const sp<CallbackHandle>& handle) {
113     // If we can't find the transaction stats something has gone wrong. The client should call
114     // startRegistration before trying to add a callback handle.
115     TransactionStats* transactionStats;
116     status_t err =
117             findOrCreateTransactionStats(handle->listener, handle->callbackIds, &transactionStats);
118     if (err != NO_ERROR) {
119         return err;
120     }
121 
122     transactionStats->latchTime = handle->latchTime;
123     // If the layer has already been destroyed, don't add the SurfaceControl to the callback.
124     // The client side keeps a sp<> to the SurfaceControl so if the SurfaceControl has been
125     // destroyed the client side is dead and there won't be anyone to send the callback to.
126     sp<IBinder> surfaceControl = handle->surfaceControl.promote();
127     if (surfaceControl) {
128         sp<Fence> prevFence = nullptr;
129 
130         for (auto& future : handle->previousReleaseFences) {
131             mergeFence(handle->name.c_str(), future.get().value_or(Fence::NO_FENCE), prevFence);
132         }
133 
134         handle->previousReleaseFence = prevFence;
135         handle->previousReleaseFences.clear();
136 
137         FrameEventHistoryStats eventStats(handle->frameNumber, handle->previousFrameNumber,
138                                           handle->gpuCompositionDoneFence->getSnapshot().fence,
139                                           handle->compositorTiming, handle->refreshStartTime,
140                                           handle->dequeueReadyTime);
141         transactionStats->surfaceStats.emplace_back(surfaceControl, handle->acquireTimeOrFence,
142                                                     handle->previousReleaseFence,
143                                                     handle->transformHint,
144                                                     handle->currentMaxAcquiredBufferCount,
145                                                     eventStats, handle->previousReleaseCallbackId);
146 
147         if (handle->bufferReleaseChannel &&
148             handle->previousReleaseCallbackId != ReleaseCallbackId::INVALID_ID) {
149             if (FlagManager::getInstance().monitor_buffer_fences()) {
150                 if (auto previousBuffer = handle->previousBuffer.lock()) {
151                     previousBuffer->getBuffer()
152                             ->getDependencyMonitor()
153                             .addEgress(FenceTime::makeValid(handle->previousReleaseFence),
154                                        "Txn release");
155                 }
156             }
157             mBufferReleases.emplace_back(handle->name, handle->bufferReleaseChannel,
158                                          handle->previousReleaseCallbackId,
159                                          handle->previousReleaseFence,
160                                          handle->currentMaxAcquiredBufferCount);
161         }
162     }
163     return NO_ERROR;
164 }
165 
addPresentFence(sp<Fence> presentFence)166 void TransactionCallbackInvoker::addPresentFence(sp<Fence> presentFence) {
167     mPresentFence = std::move(presentFence);
168 }
169 
sendCallbacks(bool onCommitOnly)170 void TransactionCallbackInvoker::sendCallbacks(bool onCommitOnly) {
171     for (const auto& bufferRelease : mBufferReleases) {
172         status_t status = bufferRelease.channel
173                                   ->writeReleaseFence(bufferRelease.callbackId, bufferRelease.fence,
174                                                       bufferRelease.currentMaxAcquiredBufferCount);
175         if (status != OK) {
176             ALOGE("[%s] writeReleaseFence failed. error %d (%s)", bufferRelease.layerName.c_str(),
177                   -status, strerror(-status));
178         }
179     }
180     mBufferReleases.clear();
181 
182     // For each listener
183     auto completedTransactionsItr = mCompletedTransactions.begin();
184     ftl::SmallVector<ListenerStats, 10> listenerStatsToSend;
185     while (completedTransactionsItr != mCompletedTransactions.end()) {
186         auto& [listener, transactionStatsDeque] = *completedTransactionsItr;
187         ListenerStats listenerStats;
188         listenerStats.listener = listener;
189 
190         // For each transaction
191         auto transactionStatsItr = transactionStatsDeque.begin();
192         while (transactionStatsItr != transactionStatsDeque.end()) {
193             auto& transactionStats = *transactionStatsItr;
194             if (onCommitOnly && !containsOnCommitCallbacks(transactionStats.callbackIds)) {
195                 transactionStatsItr++;
196                 continue;
197             }
198 
199             // If the transaction has been latched
200             if (transactionStats.latchTime >= 0 &&
201                 !containsOnCommitCallbacks(transactionStats.callbackIds)) {
202                 transactionStats.presentFence = mPresentFence;
203             }
204 
205             // Remove the transaction from completed to the callback
206             listenerStats.transactionStats.push_back(std::move(transactionStats));
207             transactionStatsItr = transactionStatsDeque.erase(transactionStatsItr);
208         }
209         // If the listener has completed transactions
210         if (!listenerStats.transactionStats.empty()) {
211             // If the listener is still alive
212             if (listener->isBinderAlive()) {
213                 // Send callback.  The listener stored in listenerStats
214                 // comes from the cross-process setTransactionState call to
215                 // SF.  This MUST be an ITransactionCompletedListener.  We
216                 // keep it as an IBinder due to consistency reasons: if we
217                 // interface_cast at the IPC boundary when reading a Parcel,
218                 // we get pointers that compare unequal in the SF process.
219                 listenerStatsToSend.emplace_back(std::move(listenerStats));
220             }
221         }
222         completedTransactionsItr++;
223     }
224 
225     if (mPresentFence) {
226         mPresentFence.clear();
227     }
228 
229     BackgroundExecutor::getInstance().sendCallbacks(
230             {[listenerStatsToSend = std::move(listenerStatsToSend)]() {
231                 SFTRACE_NAME("TransactionCallbackInvoker::sendCallbacks");
232                 for (auto& stats : listenerStatsToSend) {
233                     interface_cast<ITransactionCompletedListener>(stats.listener)
234                             ->onTransactionCompleted(stats);
235                 }
236             }});
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