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