xref: /aosp_15_r20/frameworks/native/services/surfaceflinger/Tracing/TransactionTracing.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1*38e8c45fSAndroid Build Coastguard Worker /*
2*38e8c45fSAndroid Build Coastguard Worker  * Copyright 2021 The Android Open Source Project
3*38e8c45fSAndroid Build Coastguard Worker  *
4*38e8c45fSAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*38e8c45fSAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*38e8c45fSAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*38e8c45fSAndroid Build Coastguard Worker  *
8*38e8c45fSAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*38e8c45fSAndroid Build Coastguard Worker  *
10*38e8c45fSAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*38e8c45fSAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*38e8c45fSAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*38e8c45fSAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*38e8c45fSAndroid Build Coastguard Worker  * limitations under the License.
15*38e8c45fSAndroid Build Coastguard Worker  */
16*38e8c45fSAndroid Build Coastguard Worker 
17*38e8c45fSAndroid Build Coastguard Worker #undef LOG_TAG
18*38e8c45fSAndroid Build Coastguard Worker #define LOG_TAG "TransactionTracing"
19*38e8c45fSAndroid Build Coastguard Worker 
20*38e8c45fSAndroid Build Coastguard Worker #include <android-base/stringprintf.h>
21*38e8c45fSAndroid Build Coastguard Worker #include <log/log.h>
22*38e8c45fSAndroid Build Coastguard Worker #include <utils/SystemClock.h>
23*38e8c45fSAndroid Build Coastguard Worker 
24*38e8c45fSAndroid Build Coastguard Worker #include "Client.h"
25*38e8c45fSAndroid Build Coastguard Worker #include "FrontEnd/LayerCreationArgs.h"
26*38e8c45fSAndroid Build Coastguard Worker #include "TransactionDataSource.h"
27*38e8c45fSAndroid Build Coastguard Worker #include "TransactionTracing.h"
28*38e8c45fSAndroid Build Coastguard Worker 
29*38e8c45fSAndroid Build Coastguard Worker namespace android {
ANDROID_SINGLETON_STATIC_INSTANCE(android::TransactionTraceWriter)30*38e8c45fSAndroid Build Coastguard Worker ANDROID_SINGLETON_STATIC_INSTANCE(android::TransactionTraceWriter)
31*38e8c45fSAndroid Build Coastguard Worker 
32*38e8c45fSAndroid Build Coastguard Worker TransactionTracing::TransactionTracing()
33*38e8c45fSAndroid Build Coastguard Worker       : mProtoParser(std::make_unique<TransactionProtoParser::FlingerDataMapper>()) {
34*38e8c45fSAndroid Build Coastguard Worker     std::scoped_lock lock(mTraceLock);
35*38e8c45fSAndroid Build Coastguard Worker 
36*38e8c45fSAndroid Build Coastguard Worker     mBuffer.setSize(CONTINUOUS_TRACING_BUFFER_SIZE);
37*38e8c45fSAndroid Build Coastguard Worker 
38*38e8c45fSAndroid Build Coastguard Worker     mStartingTimestamp = systemTime();
39*38e8c45fSAndroid Build Coastguard Worker 
40*38e8c45fSAndroid Build Coastguard Worker     {
41*38e8c45fSAndroid Build Coastguard Worker         std::scoped_lock lock(mMainThreadLock);
42*38e8c45fSAndroid Build Coastguard Worker         mThread = std::thread(&TransactionTracing::loop, this);
43*38e8c45fSAndroid Build Coastguard Worker     }
44*38e8c45fSAndroid Build Coastguard Worker 
45*38e8c45fSAndroid Build Coastguard Worker     TransactionDataSource::Initialize(*this);
46*38e8c45fSAndroid Build Coastguard Worker }
47*38e8c45fSAndroid Build Coastguard Worker 
~TransactionTracing()48*38e8c45fSAndroid Build Coastguard Worker TransactionTracing::~TransactionTracing() {
49*38e8c45fSAndroid Build Coastguard Worker     TransactionDataSource::UnregisterTransactionTracing();
50*38e8c45fSAndroid Build Coastguard Worker     std::thread thread;
51*38e8c45fSAndroid Build Coastguard Worker     {
52*38e8c45fSAndroid Build Coastguard Worker         std::scoped_lock lock(mMainThreadLock);
53*38e8c45fSAndroid Build Coastguard Worker         mDone = true;
54*38e8c45fSAndroid Build Coastguard Worker         mTransactionsAvailableCv.notify_all();
55*38e8c45fSAndroid Build Coastguard Worker         thread = std::move(mThread);
56*38e8c45fSAndroid Build Coastguard Worker     }
57*38e8c45fSAndroid Build Coastguard Worker     if (thread.joinable()) {
58*38e8c45fSAndroid Build Coastguard Worker         thread.join();
59*38e8c45fSAndroid Build Coastguard Worker     }
60*38e8c45fSAndroid Build Coastguard Worker }
61*38e8c45fSAndroid Build Coastguard Worker 
onStart(TransactionTracing::Mode mode)62*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::onStart(TransactionTracing::Mode mode) {
63*38e8c45fSAndroid Build Coastguard Worker     // In "active" mode write the ring buffer (starting state + following sequence of transactions)
64*38e8c45fSAndroid Build Coastguard Worker     // to perfetto when tracing starts (only once).
65*38e8c45fSAndroid Build Coastguard Worker     if (mode != Mode::MODE_ACTIVE) {
66*38e8c45fSAndroid Build Coastguard Worker         return;
67*38e8c45fSAndroid Build Coastguard Worker     }
68*38e8c45fSAndroid Build Coastguard Worker 
69*38e8c45fSAndroid Build Coastguard Worker     writeRingBufferToPerfetto(TransactionTracing::Mode::MODE_ACTIVE);
70*38e8c45fSAndroid Build Coastguard Worker 
71*38e8c45fSAndroid Build Coastguard Worker     ALOGD("Started active mode tracing (wrote initial transactions ring buffer to perfetto)");
72*38e8c45fSAndroid Build Coastguard Worker }
73*38e8c45fSAndroid Build Coastguard Worker 
onFlush(TransactionTracing::Mode mode)74*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::onFlush(TransactionTracing::Mode mode) {
75*38e8c45fSAndroid Build Coastguard Worker     // In "continuous" mode write the ring buffer (starting state + following sequence of
76*38e8c45fSAndroid Build Coastguard Worker     // transactions) to perfetto when a "flush" event is received (bugreport is taken or tracing is
77*38e8c45fSAndroid Build Coastguard Worker     // stopped).
78*38e8c45fSAndroid Build Coastguard Worker     if (mode != Mode::MODE_CONTINUOUS) {
79*38e8c45fSAndroid Build Coastguard Worker         return;
80*38e8c45fSAndroid Build Coastguard Worker     }
81*38e8c45fSAndroid Build Coastguard Worker 
82*38e8c45fSAndroid Build Coastguard Worker     writeRingBufferToPerfetto(TransactionTracing::Mode::MODE_CONTINUOUS);
83*38e8c45fSAndroid Build Coastguard Worker 
84*38e8c45fSAndroid Build Coastguard Worker     ALOGD("Flushed continuous mode tracing (wrote transactions ring buffer to perfetto");
85*38e8c45fSAndroid Build Coastguard Worker }
86*38e8c45fSAndroid Build Coastguard Worker 
writeRingBufferToPerfetto(TransactionTracing::Mode mode)87*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::writeRingBufferToPerfetto(TransactionTracing::Mode mode) {
88*38e8c45fSAndroid Build Coastguard Worker     // Write the ring buffer (starting state + following sequence of transactions) to perfetto
89*38e8c45fSAndroid Build Coastguard Worker     // tracing sessions with the specified mode.
90*38e8c45fSAndroid Build Coastguard Worker     const auto fileProto = writeToProto();
91*38e8c45fSAndroid Build Coastguard Worker 
92*38e8c45fSAndroid Build Coastguard Worker     TransactionDataSource::Trace([&](TransactionDataSource::TraceContext context) {
93*38e8c45fSAndroid Build Coastguard Worker         // Write packets only to tracing sessions with specified mode
94*38e8c45fSAndroid Build Coastguard Worker         if (context.GetCustomTlsState()->mMode != mode) {
95*38e8c45fSAndroid Build Coastguard Worker             return;
96*38e8c45fSAndroid Build Coastguard Worker         }
97*38e8c45fSAndroid Build Coastguard Worker         for (const auto& entryProto : fileProto.entry()) {
98*38e8c45fSAndroid Build Coastguard Worker             const auto entryBytes = entryProto.SerializeAsString();
99*38e8c45fSAndroid Build Coastguard Worker 
100*38e8c45fSAndroid Build Coastguard Worker             auto packet = context.NewTracePacket();
101*38e8c45fSAndroid Build Coastguard Worker             packet->set_timestamp(static_cast<uint64_t>(entryProto.elapsed_realtime_nanos()));
102*38e8c45fSAndroid Build Coastguard Worker             packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
103*38e8c45fSAndroid Build Coastguard Worker 
104*38e8c45fSAndroid Build Coastguard Worker             auto* transactionsProto = packet->set_surfaceflinger_transactions();
105*38e8c45fSAndroid Build Coastguard Worker             transactionsProto->AppendRawProtoBytes(entryBytes.data(), entryBytes.size());
106*38e8c45fSAndroid Build Coastguard Worker         }
107*38e8c45fSAndroid Build Coastguard Worker         {
108*38e8c45fSAndroid Build Coastguard Worker             // TODO (b/162206162): remove empty packet when perfetto bug is fixed.
109*38e8c45fSAndroid Build Coastguard Worker             //  It is currently needed in order not to lose the last trace entry.
110*38e8c45fSAndroid Build Coastguard Worker             context.NewTracePacket();
111*38e8c45fSAndroid Build Coastguard Worker         }
112*38e8c45fSAndroid Build Coastguard Worker     });
113*38e8c45fSAndroid Build Coastguard Worker }
114*38e8c45fSAndroid Build Coastguard Worker 
writeToFile(const std::string & filename)115*38e8c45fSAndroid Build Coastguard Worker status_t TransactionTracing::writeToFile(const std::string& filename) {
116*38e8c45fSAndroid Build Coastguard Worker     auto fileProto = writeToProto();
117*38e8c45fSAndroid Build Coastguard Worker 
118*38e8c45fSAndroid Build Coastguard Worker     std::string output;
119*38e8c45fSAndroid Build Coastguard Worker     if (!fileProto.SerializeToString(&output)) {
120*38e8c45fSAndroid Build Coastguard Worker         ALOGE("Could not serialize proto.");
121*38e8c45fSAndroid Build Coastguard Worker         return UNKNOWN_ERROR;
122*38e8c45fSAndroid Build Coastguard Worker     }
123*38e8c45fSAndroid Build Coastguard Worker 
124*38e8c45fSAndroid Build Coastguard Worker     // -rw-r--r--
125*38e8c45fSAndroid Build Coastguard Worker     const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
126*38e8c45fSAndroid Build Coastguard Worker     if (!android::base::WriteStringToFile(output, filename, mode, getuid(), getgid(), true)) {
127*38e8c45fSAndroid Build Coastguard Worker         ALOGE("Could not save the proto file %s", filename.c_str());
128*38e8c45fSAndroid Build Coastguard Worker         return PERMISSION_DENIED;
129*38e8c45fSAndroid Build Coastguard Worker     }
130*38e8c45fSAndroid Build Coastguard Worker 
131*38e8c45fSAndroid Build Coastguard Worker     return NO_ERROR;
132*38e8c45fSAndroid Build Coastguard Worker }
133*38e8c45fSAndroid Build Coastguard Worker 
writeToProto()134*38e8c45fSAndroid Build Coastguard Worker perfetto::protos::TransactionTraceFile TransactionTracing::writeToProto() {
135*38e8c45fSAndroid Build Coastguard Worker     std::scoped_lock<std::mutex> lock(mTraceLock);
136*38e8c45fSAndroid Build Coastguard Worker     perfetto::protos::TransactionTraceFile fileProto = createTraceFileProto();
137*38e8c45fSAndroid Build Coastguard Worker     const auto startingStateProto = createStartingStateProtoLocked();
138*38e8c45fSAndroid Build Coastguard Worker     if (startingStateProto) {
139*38e8c45fSAndroid Build Coastguard Worker         *fileProto.add_entry() = std::move(*startingStateProto);
140*38e8c45fSAndroid Build Coastguard Worker     }
141*38e8c45fSAndroid Build Coastguard Worker     mBuffer.writeToProto(fileProto);
142*38e8c45fSAndroid Build Coastguard Worker     return fileProto;
143*38e8c45fSAndroid Build Coastguard Worker }
144*38e8c45fSAndroid Build Coastguard Worker 
setBufferSize(size_t bufferSizeInBytes)145*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::setBufferSize(size_t bufferSizeInBytes) {
146*38e8c45fSAndroid Build Coastguard Worker     std::scoped_lock lock(mTraceLock);
147*38e8c45fSAndroid Build Coastguard Worker     mBuffer.setSize(bufferSizeInBytes);
148*38e8c45fSAndroid Build Coastguard Worker }
149*38e8c45fSAndroid Build Coastguard Worker 
createTraceFileProto() const150*38e8c45fSAndroid Build Coastguard Worker perfetto::protos::TransactionTraceFile TransactionTracing::createTraceFileProto() const {
151*38e8c45fSAndroid Build Coastguard Worker     perfetto::protos::TransactionTraceFile proto;
152*38e8c45fSAndroid Build Coastguard Worker     proto.set_magic_number(
153*38e8c45fSAndroid Build Coastguard Worker             uint64_t(perfetto::protos::TransactionTraceFile_MagicNumber_MAGIC_NUMBER_H) << 32 |
154*38e8c45fSAndroid Build Coastguard Worker             perfetto::protos::TransactionTraceFile_MagicNumber_MAGIC_NUMBER_L);
155*38e8c45fSAndroid Build Coastguard Worker     auto timeOffsetNs = static_cast<uint64_t>(systemTime(SYSTEM_TIME_REALTIME) -
156*38e8c45fSAndroid Build Coastguard Worker                                               systemTime(SYSTEM_TIME_MONOTONIC));
157*38e8c45fSAndroid Build Coastguard Worker     proto.set_real_to_elapsed_time_offset_nanos(timeOffsetNs);
158*38e8c45fSAndroid Build Coastguard Worker     proto.set_version(TRACING_VERSION);
159*38e8c45fSAndroid Build Coastguard Worker     return proto;
160*38e8c45fSAndroid Build Coastguard Worker }
161*38e8c45fSAndroid Build Coastguard Worker 
dump(std::string & result) const162*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::dump(std::string& result) const {
163*38e8c45fSAndroid Build Coastguard Worker     std::scoped_lock lock(mTraceLock);
164*38e8c45fSAndroid Build Coastguard Worker     base::StringAppendF(&result, "  queued transactions=%zu created layers=%zu states=%zu\n",
165*38e8c45fSAndroid Build Coastguard Worker                         mQueuedTransactions.size(), mCreatedLayers.size(), mStartingStates.size());
166*38e8c45fSAndroid Build Coastguard Worker     mBuffer.dump(result);
167*38e8c45fSAndroid Build Coastguard Worker }
168*38e8c45fSAndroid Build Coastguard Worker 
addQueuedTransaction(const TransactionState & transaction)169*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::addQueuedTransaction(const TransactionState& transaction) {
170*38e8c45fSAndroid Build Coastguard Worker     perfetto::protos::TransactionState* state =
171*38e8c45fSAndroid Build Coastguard Worker             new perfetto::protos::TransactionState(mProtoParser.toProto(transaction));
172*38e8c45fSAndroid Build Coastguard Worker     mTransactionQueue.push(state);
173*38e8c45fSAndroid Build Coastguard Worker }
174*38e8c45fSAndroid Build Coastguard Worker 
addCommittedTransactions(int64_t vsyncId,nsecs_t commitTime,frontend::Update & newUpdate,const frontend::DisplayInfos & displayInfos,bool displayInfoChanged)175*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::addCommittedTransactions(int64_t vsyncId, nsecs_t commitTime,
176*38e8c45fSAndroid Build Coastguard Worker                                                   frontend::Update& newUpdate,
177*38e8c45fSAndroid Build Coastguard Worker                                                   const frontend::DisplayInfos& displayInfos,
178*38e8c45fSAndroid Build Coastguard Worker                                                   bool displayInfoChanged) {
179*38e8c45fSAndroid Build Coastguard Worker     CommittedUpdates update;
180*38e8c45fSAndroid Build Coastguard Worker     update.vsyncId = vsyncId;
181*38e8c45fSAndroid Build Coastguard Worker     update.timestamp = commitTime;
182*38e8c45fSAndroid Build Coastguard Worker     update.transactionIds.reserve(newUpdate.transactions.size());
183*38e8c45fSAndroid Build Coastguard Worker     for (const auto& transaction : newUpdate.transactions) {
184*38e8c45fSAndroid Build Coastguard Worker         update.transactionIds.emplace_back(transaction.id);
185*38e8c45fSAndroid Build Coastguard Worker     }
186*38e8c45fSAndroid Build Coastguard Worker     update.displayInfoChanged = displayInfoChanged;
187*38e8c45fSAndroid Build Coastguard Worker     if (displayInfoChanged) {
188*38e8c45fSAndroid Build Coastguard Worker         update.displayInfos = displayInfos;
189*38e8c45fSAndroid Build Coastguard Worker     }
190*38e8c45fSAndroid Build Coastguard Worker     update.createdLayers = std::move(newUpdate.layerCreationArgs);
191*38e8c45fSAndroid Build Coastguard Worker     newUpdate.layerCreationArgs.clear();
192*38e8c45fSAndroid Build Coastguard Worker     update.destroyedLayerHandles.reserve(newUpdate.destroyedHandles.size());
193*38e8c45fSAndroid Build Coastguard Worker     for (auto& [handle, _] : newUpdate.destroyedHandles) {
194*38e8c45fSAndroid Build Coastguard Worker         update.destroyedLayerHandles.push_back(handle);
195*38e8c45fSAndroid Build Coastguard Worker     }
196*38e8c45fSAndroid Build Coastguard Worker     mPendingUpdates.emplace_back(update);
197*38e8c45fSAndroid Build Coastguard Worker     tryPushToTracingThread();
198*38e8c45fSAndroid Build Coastguard Worker     mLastUpdatedVsyncId = vsyncId;
199*38e8c45fSAndroid Build Coastguard Worker }
200*38e8c45fSAndroid Build Coastguard Worker 
loop()201*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::loop() {
202*38e8c45fSAndroid Build Coastguard Worker     while (true) {
203*38e8c45fSAndroid Build Coastguard Worker         std::vector<CommittedUpdates> committedUpdates;
204*38e8c45fSAndroid Build Coastguard Worker         std::vector<uint32_t> destroyedLayers;
205*38e8c45fSAndroid Build Coastguard Worker         {
206*38e8c45fSAndroid Build Coastguard Worker             std::unique_lock<std::mutex> lock(mMainThreadLock);
207*38e8c45fSAndroid Build Coastguard Worker             base::ScopedLockAssertion assumeLocked(mMainThreadLock);
208*38e8c45fSAndroid Build Coastguard Worker             mTransactionsAvailableCv.wait(lock, [&]() REQUIRES(mMainThreadLock) {
209*38e8c45fSAndroid Build Coastguard Worker                 return mDone || !mUpdates.empty();
210*38e8c45fSAndroid Build Coastguard Worker             });
211*38e8c45fSAndroid Build Coastguard Worker             if (mDone) {
212*38e8c45fSAndroid Build Coastguard Worker                 mUpdates.clear();
213*38e8c45fSAndroid Build Coastguard Worker                 mDestroyedLayers.clear();
214*38e8c45fSAndroid Build Coastguard Worker                 break;
215*38e8c45fSAndroid Build Coastguard Worker             }
216*38e8c45fSAndroid Build Coastguard Worker 
217*38e8c45fSAndroid Build Coastguard Worker             destroyedLayers = std::move(mDestroyedLayers);
218*38e8c45fSAndroid Build Coastguard Worker             mDestroyedLayers.clear();
219*38e8c45fSAndroid Build Coastguard Worker             committedUpdates = std::move(mUpdates);
220*38e8c45fSAndroid Build Coastguard Worker             mUpdates.clear();
221*38e8c45fSAndroid Build Coastguard Worker         } // unlock mMainThreadLock
222*38e8c45fSAndroid Build Coastguard Worker 
223*38e8c45fSAndroid Build Coastguard Worker         if (!committedUpdates.empty() || !destroyedLayers.empty()) {
224*38e8c45fSAndroid Build Coastguard Worker             addEntry(committedUpdates, destroyedLayers);
225*38e8c45fSAndroid Build Coastguard Worker         }
226*38e8c45fSAndroid Build Coastguard Worker     }
227*38e8c45fSAndroid Build Coastguard Worker }
228*38e8c45fSAndroid Build Coastguard Worker 
addEntry(const std::vector<CommittedUpdates> & committedUpdates,const std::vector<uint32_t> & destroyedLayers)229*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::addEntry(const std::vector<CommittedUpdates>& committedUpdates,
230*38e8c45fSAndroid Build Coastguard Worker                                   const std::vector<uint32_t>& destroyedLayers) {
231*38e8c45fSAndroid Build Coastguard Worker     std::scoped_lock lock(mTraceLock);
232*38e8c45fSAndroid Build Coastguard Worker     std::vector<std::string> removedEntries;
233*38e8c45fSAndroid Build Coastguard Worker     perfetto::protos::TransactionTraceEntry entryProto;
234*38e8c45fSAndroid Build Coastguard Worker 
235*38e8c45fSAndroid Build Coastguard Worker     while (auto incomingTransaction = mTransactionQueue.pop()) {
236*38e8c45fSAndroid Build Coastguard Worker         auto transaction = *incomingTransaction;
237*38e8c45fSAndroid Build Coastguard Worker         mQueuedTransactions[incomingTransaction->transaction_id()] = transaction;
238*38e8c45fSAndroid Build Coastguard Worker         delete incomingTransaction;
239*38e8c45fSAndroid Build Coastguard Worker     }
240*38e8c45fSAndroid Build Coastguard Worker     for (const CommittedUpdates& update : committedUpdates) {
241*38e8c45fSAndroid Build Coastguard Worker         entryProto.set_elapsed_realtime_nanos(update.timestamp);
242*38e8c45fSAndroid Build Coastguard Worker         entryProto.set_vsync_id(update.vsyncId);
243*38e8c45fSAndroid Build Coastguard Worker         entryProto.mutable_added_layers()->Reserve(
244*38e8c45fSAndroid Build Coastguard Worker                 static_cast<int32_t>(update.createdLayers.size()));
245*38e8c45fSAndroid Build Coastguard Worker 
246*38e8c45fSAndroid Build Coastguard Worker         for (const auto& args : update.createdLayers) {
247*38e8c45fSAndroid Build Coastguard Worker             entryProto.mutable_added_layers()->Add(mProtoParser.toProto(args));
248*38e8c45fSAndroid Build Coastguard Worker         }
249*38e8c45fSAndroid Build Coastguard Worker 
250*38e8c45fSAndroid Build Coastguard Worker         entryProto.mutable_destroyed_layers()->Reserve(
251*38e8c45fSAndroid Build Coastguard Worker                 static_cast<int32_t>(destroyedLayers.size()));
252*38e8c45fSAndroid Build Coastguard Worker         for (auto& destroyedLayer : destroyedLayers) {
253*38e8c45fSAndroid Build Coastguard Worker             entryProto.mutable_destroyed_layers()->Add(destroyedLayer);
254*38e8c45fSAndroid Build Coastguard Worker         }
255*38e8c45fSAndroid Build Coastguard Worker         entryProto.mutable_transactions()->Reserve(
256*38e8c45fSAndroid Build Coastguard Worker                 static_cast<int32_t>(update.transactionIds.size()));
257*38e8c45fSAndroid Build Coastguard Worker         for (const uint64_t& id : update.transactionIds) {
258*38e8c45fSAndroid Build Coastguard Worker             auto it = mQueuedTransactions.find(id);
259*38e8c45fSAndroid Build Coastguard Worker             if (it != mQueuedTransactions.end()) {
260*38e8c45fSAndroid Build Coastguard Worker                 entryProto.mutable_transactions()->Add(std::move(it->second));
261*38e8c45fSAndroid Build Coastguard Worker                 mQueuedTransactions.erase(it);
262*38e8c45fSAndroid Build Coastguard Worker             } else {
263*38e8c45fSAndroid Build Coastguard Worker                 ALOGW("Could not find transaction id %" PRIu64, id);
264*38e8c45fSAndroid Build Coastguard Worker             }
265*38e8c45fSAndroid Build Coastguard Worker         }
266*38e8c45fSAndroid Build Coastguard Worker 
267*38e8c45fSAndroid Build Coastguard Worker         entryProto.mutable_destroyed_layer_handles()->Reserve(
268*38e8c45fSAndroid Build Coastguard Worker                 static_cast<int32_t>(update.destroyedLayerHandles.size()));
269*38e8c45fSAndroid Build Coastguard Worker         for (auto layerId : update.destroyedLayerHandles) {
270*38e8c45fSAndroid Build Coastguard Worker             entryProto.mutable_destroyed_layer_handles()->Add(layerId);
271*38e8c45fSAndroid Build Coastguard Worker         }
272*38e8c45fSAndroid Build Coastguard Worker 
273*38e8c45fSAndroid Build Coastguard Worker         entryProto.set_displays_changed(update.displayInfoChanged);
274*38e8c45fSAndroid Build Coastguard Worker         if (update.displayInfoChanged) {
275*38e8c45fSAndroid Build Coastguard Worker             entryProto.mutable_displays()->Reserve(
276*38e8c45fSAndroid Build Coastguard Worker                     static_cast<int32_t>(update.displayInfos.size()));
277*38e8c45fSAndroid Build Coastguard Worker             for (auto& [layerStack, displayInfo] : update.displayInfos) {
278*38e8c45fSAndroid Build Coastguard Worker                 entryProto.mutable_displays()->Add(
279*38e8c45fSAndroid Build Coastguard Worker                         mProtoParser.toProto(displayInfo, layerStack.id));
280*38e8c45fSAndroid Build Coastguard Worker             }
281*38e8c45fSAndroid Build Coastguard Worker         }
282*38e8c45fSAndroid Build Coastguard Worker 
283*38e8c45fSAndroid Build Coastguard Worker         std::string serializedProto;
284*38e8c45fSAndroid Build Coastguard Worker         entryProto.SerializeToString(&serializedProto);
285*38e8c45fSAndroid Build Coastguard Worker 
286*38e8c45fSAndroid Build Coastguard Worker         TransactionDataSource::Trace([&](TransactionDataSource::TraceContext context) {
287*38e8c45fSAndroid Build Coastguard Worker             // In "active" mode write each committed transaction to perfetto.
288*38e8c45fSAndroid Build Coastguard Worker             // Note: the starting state is written (once) when the perfetto "start" event is
289*38e8c45fSAndroid Build Coastguard Worker             // received.
290*38e8c45fSAndroid Build Coastguard Worker             if (context.GetCustomTlsState()->mMode != Mode::MODE_ACTIVE) {
291*38e8c45fSAndroid Build Coastguard Worker                 return;
292*38e8c45fSAndroid Build Coastguard Worker             }
293*38e8c45fSAndroid Build Coastguard Worker             {
294*38e8c45fSAndroid Build Coastguard Worker                 auto packet = context.NewTracePacket();
295*38e8c45fSAndroid Build Coastguard Worker                 packet->set_timestamp(static_cast<uint64_t>(entryProto.elapsed_realtime_nanos()));
296*38e8c45fSAndroid Build Coastguard Worker                 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
297*38e8c45fSAndroid Build Coastguard Worker                 auto* transactions = packet->set_surfaceflinger_transactions();
298*38e8c45fSAndroid Build Coastguard Worker                 transactions->AppendRawProtoBytes(serializedProto.data(), serializedProto.size());
299*38e8c45fSAndroid Build Coastguard Worker             }
300*38e8c45fSAndroid Build Coastguard Worker             {
301*38e8c45fSAndroid Build Coastguard Worker                 // TODO (b/162206162): remove empty packet when perfetto bug is fixed.
302*38e8c45fSAndroid Build Coastguard Worker                 //  It is currently needed in order not to lose the last trace entry.
303*38e8c45fSAndroid Build Coastguard Worker                 context.NewTracePacket();
304*38e8c45fSAndroid Build Coastguard Worker             }
305*38e8c45fSAndroid Build Coastguard Worker         });
306*38e8c45fSAndroid Build Coastguard Worker 
307*38e8c45fSAndroid Build Coastguard Worker         std::vector<std::string> entries = mBuffer.emplace(std::move(serializedProto));
308*38e8c45fSAndroid Build Coastguard Worker         removedEntries.reserve(removedEntries.size() + entries.size());
309*38e8c45fSAndroid Build Coastguard Worker         removedEntries.insert(removedEntries.end(), std::make_move_iterator(entries.begin()),
310*38e8c45fSAndroid Build Coastguard Worker                               std::make_move_iterator(entries.end()));
311*38e8c45fSAndroid Build Coastguard Worker 
312*38e8c45fSAndroid Build Coastguard Worker         entryProto.Clear();
313*38e8c45fSAndroid Build Coastguard Worker     }
314*38e8c45fSAndroid Build Coastguard Worker 
315*38e8c45fSAndroid Build Coastguard Worker     perfetto::protos::TransactionTraceEntry removedEntryProto;
316*38e8c45fSAndroid Build Coastguard Worker     for (const std::string& removedEntry : removedEntries) {
317*38e8c45fSAndroid Build Coastguard Worker         removedEntryProto.ParseFromString(removedEntry);
318*38e8c45fSAndroid Build Coastguard Worker         updateStartingStateLocked(removedEntryProto);
319*38e8c45fSAndroid Build Coastguard Worker         removedEntryProto.Clear();
320*38e8c45fSAndroid Build Coastguard Worker     }
321*38e8c45fSAndroid Build Coastguard Worker     mTransactionsAddedToBufferCv.notify_one();
322*38e8c45fSAndroid Build Coastguard Worker }
323*38e8c45fSAndroid Build Coastguard Worker 
flush()324*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::flush() {
325*38e8c45fSAndroid Build Coastguard Worker     {
326*38e8c45fSAndroid Build Coastguard Worker         std::scoped_lock lock(mMainThreadLock);
327*38e8c45fSAndroid Build Coastguard Worker         // Collect any pending transactions and wait for transactions to be added to
328*38e8c45fSAndroid Build Coastguard Worker         mUpdates.insert(mUpdates.end(), std::make_move_iterator(mPendingUpdates.begin()),
329*38e8c45fSAndroid Build Coastguard Worker                         std::make_move_iterator(mPendingUpdates.end()));
330*38e8c45fSAndroid Build Coastguard Worker         mPendingUpdates.clear();
331*38e8c45fSAndroid Build Coastguard Worker         mDestroyedLayers.insert(mDestroyedLayers.end(), mPendingDestroyedLayers.begin(),
332*38e8c45fSAndroid Build Coastguard Worker                                 mPendingDestroyedLayers.end());
333*38e8c45fSAndroid Build Coastguard Worker         mPendingDestroyedLayers.clear();
334*38e8c45fSAndroid Build Coastguard Worker         mTransactionsAvailableCv.notify_one();
335*38e8c45fSAndroid Build Coastguard Worker     }
336*38e8c45fSAndroid Build Coastguard Worker     std::unique_lock<std::mutex> lock(mTraceLock);
337*38e8c45fSAndroid Build Coastguard Worker     base::ScopedLockAssertion assumeLocked(mTraceLock);
338*38e8c45fSAndroid Build Coastguard Worker     mTransactionsAddedToBufferCv.wait_for(lock, std::chrono::milliseconds(100),
339*38e8c45fSAndroid Build Coastguard Worker                                           [&]() REQUIRES(mTraceLock) {
340*38e8c45fSAndroid Build Coastguard Worker                                               perfetto::protos::TransactionTraceEntry entry;
341*38e8c45fSAndroid Build Coastguard Worker                                               if (mBuffer.used() > 0) {
342*38e8c45fSAndroid Build Coastguard Worker                                                   entry.ParseFromString(mBuffer.back());
343*38e8c45fSAndroid Build Coastguard Worker                                               }
344*38e8c45fSAndroid Build Coastguard Worker                                               return mBuffer.used() > 0 &&
345*38e8c45fSAndroid Build Coastguard Worker                                                       entry.vsync_id() >= mLastUpdatedVsyncId;
346*38e8c45fSAndroid Build Coastguard Worker                                           });
347*38e8c45fSAndroid Build Coastguard Worker }
348*38e8c45fSAndroid Build Coastguard Worker 
onLayerRemoved(int32_t layerId)349*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::onLayerRemoved(int32_t layerId) {
350*38e8c45fSAndroid Build Coastguard Worker     mPendingDestroyedLayers.emplace_back(layerId);
351*38e8c45fSAndroid Build Coastguard Worker     tryPushToTracingThread();
352*38e8c45fSAndroid Build Coastguard Worker }
353*38e8c45fSAndroid Build Coastguard Worker 
tryPushToTracingThread()354*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::tryPushToTracingThread() {
355*38e8c45fSAndroid Build Coastguard Worker     // Try to acquire the lock from main thread.
356*38e8c45fSAndroid Build Coastguard Worker     if (mMainThreadLock.try_lock()) {
357*38e8c45fSAndroid Build Coastguard Worker         // We got the lock! Collect any pending transactions and continue.
358*38e8c45fSAndroid Build Coastguard Worker         mUpdates.insert(mUpdates.end(), std::make_move_iterator(mPendingUpdates.begin()),
359*38e8c45fSAndroid Build Coastguard Worker                         std::make_move_iterator(mPendingUpdates.end()));
360*38e8c45fSAndroid Build Coastguard Worker         mPendingUpdates.clear();
361*38e8c45fSAndroid Build Coastguard Worker         mDestroyedLayers.insert(mDestroyedLayers.end(), mPendingDestroyedLayers.begin(),
362*38e8c45fSAndroid Build Coastguard Worker                                 mPendingDestroyedLayers.end());
363*38e8c45fSAndroid Build Coastguard Worker         mPendingDestroyedLayers.clear();
364*38e8c45fSAndroid Build Coastguard Worker         mTransactionsAvailableCv.notify_one();
365*38e8c45fSAndroid Build Coastguard Worker         mMainThreadLock.unlock();
366*38e8c45fSAndroid Build Coastguard Worker     } else {
367*38e8c45fSAndroid Build Coastguard Worker         ALOGV("Couldn't get lock");
368*38e8c45fSAndroid Build Coastguard Worker     }
369*38e8c45fSAndroid Build Coastguard Worker }
370*38e8c45fSAndroid Build Coastguard Worker 
updateStartingStateLocked(const perfetto::protos::TransactionTraceEntry & removedEntry)371*38e8c45fSAndroid Build Coastguard Worker void TransactionTracing::updateStartingStateLocked(
372*38e8c45fSAndroid Build Coastguard Worker         const perfetto::protos::TransactionTraceEntry& removedEntry) {
373*38e8c45fSAndroid Build Coastguard Worker     mStartingTimestamp = removedEntry.elapsed_realtime_nanos();
374*38e8c45fSAndroid Build Coastguard Worker     // Keep track of layer starting state so we can reconstruct the layer state as we purge
375*38e8c45fSAndroid Build Coastguard Worker     // transactions from the buffer.
376*38e8c45fSAndroid Build Coastguard Worker     for (const perfetto::protos::LayerCreationArgs& addedLayer : removedEntry.added_layers()) {
377*38e8c45fSAndroid Build Coastguard Worker         TracingLayerState& startingState = mStartingStates[addedLayer.layer_id()];
378*38e8c45fSAndroid Build Coastguard Worker         startingState.layerId = addedLayer.layer_id();
379*38e8c45fSAndroid Build Coastguard Worker         mProtoParser.fromProto(addedLayer, startingState.args);
380*38e8c45fSAndroid Build Coastguard Worker     }
381*38e8c45fSAndroid Build Coastguard Worker 
382*38e8c45fSAndroid Build Coastguard Worker     // Merge layer states to starting transaction state.
383*38e8c45fSAndroid Build Coastguard Worker     for (const perfetto::protos::TransactionState& transaction : removedEntry.transactions()) {
384*38e8c45fSAndroid Build Coastguard Worker         for (const perfetto::protos::LayerState& layerState : transaction.layer_changes()) {
385*38e8c45fSAndroid Build Coastguard Worker             auto it = mStartingStates.find(layerState.layer_id());
386*38e8c45fSAndroid Build Coastguard Worker             if (it == mStartingStates.end()) {
387*38e8c45fSAndroid Build Coastguard Worker                 // TODO(b/238781169) make this log fatal when we switch over to using new fe
388*38e8c45fSAndroid Build Coastguard Worker                 ALOGW("Could not find layer id %d", layerState.layer_id());
389*38e8c45fSAndroid Build Coastguard Worker                 continue;
390*38e8c45fSAndroid Build Coastguard Worker             }
391*38e8c45fSAndroid Build Coastguard Worker             mProtoParser.mergeFromProto(layerState, it->second);
392*38e8c45fSAndroid Build Coastguard Worker         }
393*38e8c45fSAndroid Build Coastguard Worker     }
394*38e8c45fSAndroid Build Coastguard Worker 
395*38e8c45fSAndroid Build Coastguard Worker     for (const uint32_t destroyedLayerHandleId : removedEntry.destroyed_layer_handles()) {
396*38e8c45fSAndroid Build Coastguard Worker         mRemovedLayerHandlesAtStart.insert(destroyedLayerHandleId);
397*38e8c45fSAndroid Build Coastguard Worker     }
398*38e8c45fSAndroid Build Coastguard Worker 
399*38e8c45fSAndroid Build Coastguard Worker     // Clean up stale starting states since the layer has been removed and the buffer does not
400*38e8c45fSAndroid Build Coastguard Worker     // contain any references to the layer.
401*38e8c45fSAndroid Build Coastguard Worker     for (const uint32_t destroyedLayerId : removedEntry.destroyed_layers()) {
402*38e8c45fSAndroid Build Coastguard Worker         mStartingStates.erase(destroyedLayerId);
403*38e8c45fSAndroid Build Coastguard Worker         mRemovedLayerHandlesAtStart.erase(destroyedLayerId);
404*38e8c45fSAndroid Build Coastguard Worker     }
405*38e8c45fSAndroid Build Coastguard Worker 
406*38e8c45fSAndroid Build Coastguard Worker     if (removedEntry.displays_changed()) {
407*38e8c45fSAndroid Build Coastguard Worker         mProtoParser.fromProto(removedEntry.displays(), mStartingDisplayInfos);
408*38e8c45fSAndroid Build Coastguard Worker     }
409*38e8c45fSAndroid Build Coastguard Worker }
410*38e8c45fSAndroid Build Coastguard Worker 
411*38e8c45fSAndroid Build Coastguard Worker std::optional<perfetto::protos::TransactionTraceEntry>
createStartingStateProtoLocked()412*38e8c45fSAndroid Build Coastguard Worker TransactionTracing::createStartingStateProtoLocked() {
413*38e8c45fSAndroid Build Coastguard Worker     if (mStartingStates.empty()) {
414*38e8c45fSAndroid Build Coastguard Worker         return std::nullopt;
415*38e8c45fSAndroid Build Coastguard Worker     }
416*38e8c45fSAndroid Build Coastguard Worker 
417*38e8c45fSAndroid Build Coastguard Worker     perfetto::protos::TransactionTraceEntry entryProto;
418*38e8c45fSAndroid Build Coastguard Worker     entryProto.set_elapsed_realtime_nanos(mStartingTimestamp);
419*38e8c45fSAndroid Build Coastguard Worker     entryProto.set_vsync_id(0);
420*38e8c45fSAndroid Build Coastguard Worker 
421*38e8c45fSAndroid Build Coastguard Worker     entryProto.mutable_added_layers()->Reserve(static_cast<int32_t>(mStartingStates.size()));
422*38e8c45fSAndroid Build Coastguard Worker     for (auto& [layerId, state] : mStartingStates) {
423*38e8c45fSAndroid Build Coastguard Worker         entryProto.mutable_added_layers()->Add(mProtoParser.toProto(state.args));
424*38e8c45fSAndroid Build Coastguard Worker     }
425*38e8c45fSAndroid Build Coastguard Worker 
426*38e8c45fSAndroid Build Coastguard Worker     perfetto::protos::TransactionState transactionProto = mProtoParser.toProto(mStartingStates);
427*38e8c45fSAndroid Build Coastguard Worker     transactionProto.set_vsync_id(0);
428*38e8c45fSAndroid Build Coastguard Worker     transactionProto.set_post_time(mStartingTimestamp);
429*38e8c45fSAndroid Build Coastguard Worker     entryProto.mutable_transactions()->Add(std::move(transactionProto));
430*38e8c45fSAndroid Build Coastguard Worker 
431*38e8c45fSAndroid Build Coastguard Worker     entryProto.mutable_destroyed_layer_handles()->Reserve(
432*38e8c45fSAndroid Build Coastguard Worker             static_cast<int32_t>(mRemovedLayerHandlesAtStart.size()));
433*38e8c45fSAndroid Build Coastguard Worker     for (const uint32_t destroyedLayerHandleId : mRemovedLayerHandlesAtStart) {
434*38e8c45fSAndroid Build Coastguard Worker         entryProto.mutable_destroyed_layer_handles()->Add(destroyedLayerHandleId);
435*38e8c45fSAndroid Build Coastguard Worker     }
436*38e8c45fSAndroid Build Coastguard Worker 
437*38e8c45fSAndroid Build Coastguard Worker     entryProto.mutable_displays()->Reserve(static_cast<int32_t>(mStartingDisplayInfos.size()));
438*38e8c45fSAndroid Build Coastguard Worker     for (auto& [layerStack, displayInfo] : mStartingDisplayInfos) {
439*38e8c45fSAndroid Build Coastguard Worker         entryProto.mutable_displays()->Add(mProtoParser.toProto(displayInfo, layerStack.id));
440*38e8c45fSAndroid Build Coastguard Worker     }
441*38e8c45fSAndroid Build Coastguard Worker     entryProto.set_displays_changed(true);
442*38e8c45fSAndroid Build Coastguard Worker 
443*38e8c45fSAndroid Build Coastguard Worker     return entryProto;
444*38e8c45fSAndroid Build Coastguard Worker }
445*38e8c45fSAndroid Build Coastguard Worker 
446*38e8c45fSAndroid Build Coastguard Worker } // namespace android
447