blob: 5d387d68e8b405354484f44c27f2e662354f3d41 [file] [log] [blame]
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001/*
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 */
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080016
Alec Mouri75de8f22021-01-20 14:53:44 -080017#include <unordered_map>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070018#undef LOG_TAG
19#define LOG_TAG "TimeStats"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include "TimeStats.h"
23
24#include <android-base/stringprintf.h>
Alec Mouri37384342020-01-02 17:23:37 -080025#include <android/util/ProtoOutputStream.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070026#include <log/log.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070027#include <utils/String8.h>
Yiwei Zhang3a226d22018-10-16 09:23:03 -070028#include <utils/Timers.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070029#include <utils/Trace.h>
30
31#include <algorithm>
Alec Mouri9519bf12019-11-15 16:54:44 -080032#include <chrono>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070033
Alec Mouri9a29e672020-09-14 12:39:14 -070034#include "timestatsproto/TimeStatsHelper.h"
35
Yiwei Zhang0102ad22018-05-02 17:37:17 -070036namespace android {
37
Alec Mourifb571ea2019-01-24 18:42:10 -080038namespace impl {
39
Tej Singh2a457b62020-01-31 16:16:10 -080040AStatsManager_PullAtomCallbackReturn TimeStats::pullAtomCallback(int32_t atom_tag,
41 AStatsEventList* data,
42 void* cookie) {
Alec Mouri8e2f31b2020-01-16 22:04:35 +000043 impl::TimeStats* timeStats = reinterpret_cast<impl::TimeStats*>(cookie);
Tej Singh2a457b62020-01-31 16:16:10 -080044 AStatsManager_PullAtomCallbackReturn result = AStatsManager_PULL_SKIP;
Alec Mouri37384342020-01-02 17:23:37 -080045 if (atom_tag == android::util::SURFACEFLINGER_STATS_GLOBAL_INFO) {
Alec Mouri3ecd5cd2020-01-29 12:53:07 -080046 result = timeStats->populateGlobalAtom(data);
Alec Mouri37384342020-01-02 17:23:37 -080047 } else if (atom_tag == android::util::SURFACEFLINGER_STATS_LAYER_INFO) {
Alec Mouri3ecd5cd2020-01-29 12:53:07 -080048 result = timeStats->populateLayerAtom(data);
Alec Mouri8e2f31b2020-01-16 22:04:35 +000049 }
50
Alec Mouri3ecd5cd2020-01-29 12:53:07 -080051 // Enable timestats now. The first full pull for a given build is expected to
52 // have empty or very little stats, as stats are first enabled after the
53 // first pull is completed for either the global or layer stats.
54 timeStats->enable();
55 return result;
Alec Mouri37384342020-01-02 17:23:37 -080056}
Alec Mouri8e2f31b2020-01-16 22:04:35 +000057
Alec Mouri37384342020-01-02 17:23:37 -080058namespace {
59// Histograms align with the order of fields in SurfaceflingerStatsLayerInfo.
60const std::array<std::string, 6> kHistogramNames = {
61 "present2present", "post2present", "acquire2present",
62 "latch2present", "desired2present", "post2acquire",
63};
Alec Mouri8e2f31b2020-01-16 22:04:35 +000064
Alec Mouri37384342020-01-02 17:23:37 -080065std::string histogramToProtoByteString(const std::unordered_map<int32_t, int32_t>& histogram,
66 size_t maxPulledHistogramBuckets) {
67 auto buckets = std::vector<std::pair<int32_t, int32_t>>(histogram.begin(), histogram.end());
68 std::sort(buckets.begin(), buckets.end(),
69 [](std::pair<int32_t, int32_t>& left, std::pair<int32_t, int32_t>& right) {
70 return left.second > right.second;
71 });
72
73 util::ProtoOutputStream proto;
74 int histogramSize = 0;
75 for (const auto& bucket : buckets) {
76 if (++histogramSize > maxPulledHistogramBuckets) {
77 break;
78 }
79 proto.write(android::util::FIELD_TYPE_INT32 | android::util::FIELD_COUNT_REPEATED |
80 1 /* field id */,
81 (int32_t)bucket.first);
82 proto.write(android::util::FIELD_TYPE_INT64 | android::util::FIELD_COUNT_REPEATED |
83 2 /* field id */,
84 (int64_t)bucket.second);
85 }
86
87 std::string byteString;
88 proto.serializeToString(&byteString);
89 return byteString;
90}
Alec Mouri75de8f22021-01-20 14:53:44 -080091
92std::string frameRateVoteToProtoByteString(float refreshRate, int frameRateCompatibility,
93 int seamlessness) {
94 util::ProtoOutputStream proto;
95 proto.write(android::util::FIELD_TYPE_FLOAT | 1 /* field id */, refreshRate);
96 proto.write(android::util::FIELD_TYPE_ENUM | 2 /* field id */, frameRateCompatibility);
97 proto.write(android::util::FIELD_TYPE_ENUM | 3 /* field id */, seamlessness);
98
99 std::string byteString;
100 proto.serializeToString(&byteString);
101 return byteString;
102}
Alec Mouri37384342020-01-02 17:23:37 -0800103} // namespace
104
Alec Mouridfad9002020-02-12 17:49:09 -0800105AStatsManager_PullAtomCallbackReturn TimeStats::populateGlobalAtom(AStatsEventList* data) {
106 std::lock_guard<std::mutex> lock(mMutex);
107
108 if (mTimeStats.statsStart == 0) {
109 return AStatsManager_PULL_SKIP;
110 }
111 flushPowerTimeLocked();
112
113 AStatsEvent* event = mStatsDelegate->addStatsEventToPullData(data);
114 mStatsDelegate->statsEventSetAtomId(event, android::util::SURFACEFLINGER_STATS_GLOBAL_INFO);
115 mStatsDelegate->statsEventWriteInt64(event, mTimeStats.totalFrames);
116 mStatsDelegate->statsEventWriteInt64(event, mTimeStats.missedFrames);
117 mStatsDelegate->statsEventWriteInt64(event, mTimeStats.clientCompositionFrames);
118 mStatsDelegate->statsEventWriteInt64(event, mTimeStats.displayOnTime);
119 mStatsDelegate->statsEventWriteInt64(event, mTimeStats.presentToPresent.totalTime());
120 mStatsDelegate->statsEventWriteInt32(event, mTimeStats.displayEventConnectionsCount);
121 std::string frameDurationBytes =
122 histogramToProtoByteString(mTimeStats.frameDuration.hist, mMaxPulledHistogramBuckets);
123 mStatsDelegate->statsEventWriteByteArray(event, (const uint8_t*)frameDurationBytes.c_str(),
124 frameDurationBytes.size());
125 std::string renderEngineTimingBytes =
126 histogramToProtoByteString(mTimeStats.renderEngineTiming.hist,
127 mMaxPulledHistogramBuckets);
128 mStatsDelegate->statsEventWriteByteArray(event, (const uint8_t*)renderEngineTimingBytes.c_str(),
129 renderEngineTimingBytes.size());
Alec Mouri9a29e672020-09-14 12:39:14 -0700130
131 mStatsDelegate->statsEventWriteInt32(event, mTimeStats.jankPayload.totalFrames);
132 mStatsDelegate->statsEventWriteInt32(event, mTimeStats.jankPayload.totalJankyFrames);
133 mStatsDelegate->statsEventWriteInt32(event, mTimeStats.jankPayload.totalSFLongCpu);
134 mStatsDelegate->statsEventWriteInt32(event, mTimeStats.jankPayload.totalSFLongGpu);
135 mStatsDelegate->statsEventWriteInt32(event, mTimeStats.jankPayload.totalSFUnattributed);
136 mStatsDelegate->statsEventWriteInt32(event, mTimeStats.jankPayload.totalAppUnattributed);
Alec Mouri75de8f22021-01-20 14:53:44 -0800137
138 // TODO: populate these with real values
139 mStatsDelegate->statsEventWriteInt32(event, 0); // total_janky_frames_sf_scheduling
140 mStatsDelegate->statsEventWriteInt32(event, 0); // total_jank_frames_sf_prediction_error
141 mStatsDelegate->statsEventWriteInt32(event, 0); // total_jank_frames_app_buffer_stuffing
142 mStatsDelegate->statsEventWriteInt32(event, 0); // display_refresh_rate_bucket
143 std::string sfDeadlineMissedBytes =
144 histogramToProtoByteString(std::unordered_map<int32_t, int32_t>(),
145 mMaxPulledHistogramBuckets);
146 mStatsDelegate->statsEventWriteByteArray(event, (const uint8_t*)sfDeadlineMissedBytes.c_str(),
147 sfDeadlineMissedBytes.size()); // sf_deadline_misses
148 std::string sfPredictionErrorBytes =
149 histogramToProtoByteString(std::unordered_map<int32_t, int32_t>(),
150 mMaxPulledHistogramBuckets);
151 mStatsDelegate->statsEventWriteByteArray(event, (const uint8_t*)sfPredictionErrorBytes.c_str(),
152 sfPredictionErrorBytes.size()); // sf_prediction_errors
153 mStatsDelegate->statsEventWriteInt32(event, 0); // render_rate_bucket
Alec Mouridfad9002020-02-12 17:49:09 -0800154 mStatsDelegate->statsEventBuild(event);
155 clearGlobalLocked();
156
157 return AStatsManager_PULL_SUCCESS;
158}
159
Tej Singh2a457b62020-01-31 16:16:10 -0800160AStatsManager_PullAtomCallbackReturn TimeStats::populateLayerAtom(AStatsEventList* data) {
Alec Mouri37384342020-01-02 17:23:37 -0800161 std::lock_guard<std::mutex> lock(mMutex);
162
163 std::vector<TimeStatsHelper::TimeStatsLayer const*> dumpStats;
164 for (const auto& ele : mTimeStats.stats) {
165 dumpStats.push_back(&ele.second);
166 }
167
168 std::sort(dumpStats.begin(), dumpStats.end(),
169 [](TimeStatsHelper::TimeStatsLayer const* l,
170 TimeStatsHelper::TimeStatsLayer const* r) {
171 return l->totalFrames > r->totalFrames;
172 });
173
174 if (mMaxPulledLayers < dumpStats.size()) {
175 dumpStats.resize(mMaxPulledLayers);
176 }
177
178 for (const auto& layer : dumpStats) {
Tej Singh2a457b62020-01-31 16:16:10 -0800179 AStatsEvent* event = mStatsDelegate->addStatsEventToPullData(data);
Alec Mouri37384342020-01-02 17:23:37 -0800180 mStatsDelegate->statsEventSetAtomId(event, android::util::SURFACEFLINGER_STATS_LAYER_INFO);
181 mStatsDelegate->statsEventWriteString8(event, layer->layerName.c_str());
182 mStatsDelegate->statsEventWriteInt64(event, layer->totalFrames);
183 mStatsDelegate->statsEventWriteInt64(event, layer->droppedFrames);
184
185 for (const auto& name : kHistogramNames) {
186 const auto& histogram = layer->deltas.find(name);
187 if (histogram == layer->deltas.cend()) {
188 mStatsDelegate->statsEventWriteByteArray(event, nullptr, 0);
189 } else {
190 std::string bytes = histogramToProtoByteString(histogram->second.hist,
191 mMaxPulledHistogramBuckets);
192 mStatsDelegate->statsEventWriteByteArray(event, (const uint8_t*)bytes.c_str(),
193 bytes.size());
194 }
195 }
196
Yiwei Zhang7bfc75b2020-02-10 11:20:34 -0800197 mStatsDelegate->statsEventWriteInt64(event, layer->lateAcquireFrames);
198 mStatsDelegate->statsEventWriteInt64(event, layer->badDesiredPresentFrames);
Alec Mouri9a29e672020-09-14 12:39:14 -0700199 mStatsDelegate->statsEventWriteInt32(event, layer->uid);
200 mStatsDelegate->statsEventWriteInt32(event, layer->jankPayload.totalFrames);
201 mStatsDelegate->statsEventWriteInt32(event, layer->jankPayload.totalJankyFrames);
202 mStatsDelegate->statsEventWriteInt32(event, layer->jankPayload.totalSFLongCpu);
203 mStatsDelegate->statsEventWriteInt32(event, layer->jankPayload.totalSFLongGpu);
204 mStatsDelegate->statsEventWriteInt32(event, layer->jankPayload.totalSFUnattributed);
205 mStatsDelegate->statsEventWriteInt32(event, layer->jankPayload.totalAppUnattributed);
Yiwei Zhang7bfc75b2020-02-10 11:20:34 -0800206
Alec Mouri75de8f22021-01-20 14:53:44 -0800207 // TODO: populate these with real values
208 mStatsDelegate->statsEventWriteInt32(event, 0); // total_janky_frames_sf_scheduling
209 mStatsDelegate->statsEventWriteInt32(event, 0); // total_jank_frames_sf_prediction_error
210 mStatsDelegate->statsEventWriteInt32(event, 0); // total_jank_frames_app_buffer_stuffing
211 mStatsDelegate->statsEventWriteInt32(event, 0); // display_refresh_rate_bucket
212 mStatsDelegate->statsEventWriteInt32(event, 0); // render_rate_bucket
213 std::string frameRateVoteBytes = frameRateVoteToProtoByteString(0.0, 0, 0);
214 mStatsDelegate->statsEventWriteByteArray(event, (const uint8_t*)frameRateVoteBytes.c_str(),
215 frameRateVoteBytes.size()); // set_frame_rate_vote
216 std::string appDeadlineMissedBytes =
217 histogramToProtoByteString(std::unordered_map<int32_t, int32_t>(),
218 mMaxPulledHistogramBuckets);
219 mStatsDelegate
220 ->statsEventWriteByteArray(event, (const uint8_t*)appDeadlineMissedBytes.c_str(),
221 appDeadlineMissedBytes.size()); // app_deadline_misses
222
Alec Mouri37384342020-01-02 17:23:37 -0800223 mStatsDelegate->statsEventBuild(event);
224 }
225 clearLayersLocked();
226
Tej Singh2a457b62020-01-31 16:16:10 -0800227 return AStatsManager_PULL_SUCCESS;
Alec Mouri37384342020-01-02 17:23:37 -0800228}
229
230TimeStats::TimeStats() : TimeStats(nullptr, std::nullopt, std::nullopt) {}
231
232TimeStats::TimeStats(std::unique_ptr<StatsEventDelegate> statsDelegate,
233 std::optional<size_t> maxPulledLayers,
234 std::optional<size_t> maxPulledHistogramBuckets) {
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000235 if (statsDelegate != nullptr) {
236 mStatsDelegate = std::move(statsDelegate);
237 }
Alec Mouri37384342020-01-02 17:23:37 -0800238
239 if (maxPulledLayers) {
240 mMaxPulledLayers = *maxPulledLayers;
241 }
242
243 if (maxPulledHistogramBuckets) {
244 mMaxPulledHistogramBuckets = *maxPulledHistogramBuckets;
245 }
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000246}
247
Alec Mouri3ecd5cd2020-01-29 12:53:07 -0800248TimeStats::~TimeStats() {
249 std::lock_guard<std::mutex> lock(mMutex);
Tej Singh38a4b212020-03-13 19:04:51 -0700250 mStatsDelegate->clearStatsPullAtomCallback(android::util::SURFACEFLINGER_STATS_GLOBAL_INFO);
251 mStatsDelegate->clearStatsPullAtomCallback(android::util::SURFACEFLINGER_STATS_LAYER_INFO);
Alec Mouri3ecd5cd2020-01-29 12:53:07 -0800252}
253
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000254void TimeStats::onBootFinished() {
Alec Mouri3ecd5cd2020-01-29 12:53:07 -0800255 std::lock_guard<std::mutex> lock(mMutex);
Tej Singh38a4b212020-03-13 19:04:51 -0700256 mStatsDelegate->setStatsPullAtomCallback(android::util::SURFACEFLINGER_STATS_GLOBAL_INFO,
257 nullptr, TimeStats::pullAtomCallback, this);
258 mStatsDelegate->setStatsPullAtomCallback(android::util::SURFACEFLINGER_STATS_LAYER_INFO,
259 nullptr, TimeStats::pullAtomCallback, this);
Alec Mourib3885ad2019-09-06 17:08:55 -0700260}
261
Dominik Laskowskic2867142019-01-21 11:33:38 -0800262void TimeStats::parseArgs(bool asProto, const Vector<String16>& args, std::string& result) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700263 ATRACE_CALL();
264
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700265 std::unordered_map<std::string, int32_t> argsMap;
Dominik Laskowskic2867142019-01-21 11:33:38 -0800266 for (size_t index = 0; index < args.size(); ++index) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700267 argsMap[std::string(String8(args[index]).c_str())] = index;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700268 }
269
270 if (argsMap.count("-disable")) {
271 disable();
272 }
273
274 if (argsMap.count("-dump")) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700275 std::optional<uint32_t> maxLayers = std::nullopt;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700276 auto iter = argsMap.find("-maxlayers");
277 if (iter != argsMap.end() && iter->second + 1 < static_cast<int32_t>(args.size())) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700278 int64_t value = strtol(String8(args[iter->second + 1]).c_str(), nullptr, 10);
279 value = std::clamp(value, int64_t(0), int64_t(UINT32_MAX));
280 maxLayers = static_cast<uint32_t>(value);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700281 }
282
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700283 dump(asProto, maxLayers, result);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700284 }
285
286 if (argsMap.count("-clear")) {
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000287 clearAll();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700288 }
289
290 if (argsMap.count("-enable")) {
291 enable();
292 }
293}
294
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700295std::string TimeStats::miniDump() {
296 ATRACE_CALL();
297
298 std::string result = "TimeStats miniDump:\n";
299 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange926ab52019-08-14 15:16:00 -0700300 android::base::StringAppendF(&result, "Number of layers currently being tracked is %zu\n",
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700301 mTimeStatsTracker.size());
Yiwei Zhange926ab52019-08-14 15:16:00 -0700302 android::base::StringAppendF(&result, "Number of layers in the stats pool is %zu\n",
303 mTimeStats.stats.size());
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700304 return result;
305}
306
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700307void TimeStats::incrementTotalFrames() {
308 if (!mEnabled.load()) return;
309
310 ATRACE_CALL();
311
312 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhangdc224042018-10-18 15:34:00 -0700313 mTimeStats.totalFrames++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700314}
315
Yiwei Zhang621f9d42018-05-07 10:40:55 -0700316void TimeStats::incrementMissedFrames() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700317 if (!mEnabled.load()) return;
318
319 ATRACE_CALL();
320
321 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhangdc224042018-10-18 15:34:00 -0700322 mTimeStats.missedFrames++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700323}
324
325void TimeStats::incrementClientCompositionFrames() {
326 if (!mEnabled.load()) return;
327
328 ATRACE_CALL();
329
330 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhangdc224042018-10-18 15:34:00 -0700331 mTimeStats.clientCompositionFrames++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700332}
333
Vishnu Nair9b079a22020-01-21 14:36:08 -0800334void TimeStats::incrementClientCompositionReusedFrames() {
335 if (!mEnabled.load()) return;
336
337 ATRACE_CALL();
338
339 std::lock_guard<std::mutex> lock(mMutex);
340 mTimeStats.clientCompositionReusedFrames++;
341}
342
Alec Mouri8de697e2020-03-19 10:52:01 -0700343void TimeStats::incrementRefreshRateSwitches() {
344 if (!mEnabled.load()) return;
345
346 ATRACE_CALL();
347
348 std::lock_guard<std::mutex> lock(mMutex);
349 mTimeStats.refreshRateSwitches++;
350}
351
Alec Mouri8f7a0102020-04-15 12:11:10 -0700352void TimeStats::incrementCompositionStrategyChanges() {
353 if (!mEnabled.load()) return;
354
355 ATRACE_CALL();
356
357 std::lock_guard<std::mutex> lock(mMutex);
358 mTimeStats.compositionStrategyChanges++;
359}
360
Alec Mouri717bcb62020-02-10 17:07:19 -0800361void TimeStats::recordDisplayEventConnectionCount(int32_t count) {
362 if (!mEnabled.load()) return;
363
364 ATRACE_CALL();
365
366 std::lock_guard<std::mutex> lock(mMutex);
367 mTimeStats.displayEventConnectionsCount =
368 std::max(mTimeStats.displayEventConnectionsCount, count);
369}
370
Alec Mouri9519bf12019-11-15 16:54:44 -0800371static int32_t msBetween(nsecs_t start, nsecs_t end) {
372 int64_t delta = std::chrono::duration_cast<std::chrono::milliseconds>(
373 std::chrono::nanoseconds(end - start))
374 .count();
375 delta = std::clamp(delta, int64_t(INT32_MIN), int64_t(INT32_MAX));
376 return static_cast<int32_t>(delta);
377}
378
379void TimeStats::recordFrameDuration(nsecs_t startTime, nsecs_t endTime) {
380 if (!mEnabled.load()) return;
381
382 std::lock_guard<std::mutex> lock(mMutex);
Peiyong Lin65248e02020-04-18 21:15:07 -0700383 if (mPowerTime.powerMode == PowerMode::ON) {
Alec Mouri9519bf12019-11-15 16:54:44 -0800384 mTimeStats.frameDuration.insert(msBetween(startTime, endTime));
385 }
386}
387
Alec Mourie4034bb2019-11-19 12:45:54 -0800388void TimeStats::recordRenderEngineDuration(nsecs_t startTime, nsecs_t endTime) {
389 if (!mEnabled.load()) return;
390
391 std::lock_guard<std::mutex> lock(mMutex);
392 if (mGlobalRecord.renderEngineDurations.size() == MAX_NUM_TIME_RECORDS) {
393 ALOGE("RenderEngineTimes are already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
394 mGlobalRecord.renderEngineDurations.pop_front();
395 }
396 mGlobalRecord.renderEngineDurations.push_back({startTime, endTime});
397}
398
399void TimeStats::recordRenderEngineDuration(nsecs_t startTime,
400 const std::shared_ptr<FenceTime>& endTime) {
401 if (!mEnabled.load()) return;
402
403 std::lock_guard<std::mutex> lock(mMutex);
404 if (mGlobalRecord.renderEngineDurations.size() == MAX_NUM_TIME_RECORDS) {
405 ALOGE("RenderEngineTimes are already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
406 mGlobalRecord.renderEngineDurations.pop_front();
407 }
408 mGlobalRecord.renderEngineDurations.push_back({startTime, endTime});
409}
410
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800411bool TimeStats::recordReadyLocked(int32_t layerId, TimeRecord* timeRecord) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700412 if (!timeRecord->ready) {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800413 ALOGV("[%d]-[%" PRIu64 "]-presentFence is still not received", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700414 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700415 return false;
416 }
417
418 if (timeRecord->acquireFence != nullptr) {
419 if (timeRecord->acquireFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
420 return false;
421 }
422 if (timeRecord->acquireFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700423 timeRecord->frameTime.acquireTime = timeRecord->acquireFence->getSignalTime();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700424 timeRecord->acquireFence = nullptr;
425 } else {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800426 ALOGV("[%d]-[%" PRIu64 "]-acquireFence signal time is invalid", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700427 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700428 }
429 }
430
431 if (timeRecord->presentFence != nullptr) {
432 if (timeRecord->presentFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
433 return false;
434 }
435 if (timeRecord->presentFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700436 timeRecord->frameTime.presentTime = timeRecord->presentFence->getSignalTime();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700437 timeRecord->presentFence = nullptr;
438 } else {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800439 ALOGV("[%d]-[%" PRIu64 "]-presentFence signal time invalid", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700440 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700441 }
442 }
443
444 return true;
445}
446
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800447void TimeStats::flushAvailableRecordsToStatsLocked(int32_t layerId) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700448 ATRACE_CALL();
449
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800450 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700451 TimeRecord& prevTimeRecord = layerRecord.prevTimeRecord;
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700452 std::deque<TimeRecord>& timeRecords = layerRecord.timeRecords;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700453 while (!timeRecords.empty()) {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800454 if (!recordReadyLocked(layerId, &timeRecords[0])) break;
455 ALOGV("[%d]-[%" PRIu64 "]-presentFenceTime[%" PRId64 "]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700456 timeRecords[0].frameTime.frameNumber, timeRecords[0].frameTime.presentTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700457
458 if (prevTimeRecord.ready) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700459 uid_t uid = layerRecord.uid;
Yiwei Zhangeafa5cc2019-07-26 15:06:25 -0700460 const std::string& layerName = layerRecord.layerName;
Alec Mouri9a29e672020-09-14 12:39:14 -0700461 if (!mTimeStats.stats.count({uid, layerName})) {
462 mTimeStats.stats[{uid, layerName}].uid = uid;
463 mTimeStats.stats[{uid, layerName}].layerName = layerName;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700464 }
Alec Mouri9a29e672020-09-14 12:39:14 -0700465 TimeStatsHelper::TimeStatsLayer& timeStatsLayer = mTimeStats.stats[{uid, layerName}];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700466 timeStatsLayer.totalFrames++;
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700467 timeStatsLayer.droppedFrames += layerRecord.droppedFrames;
Alec Mouri91f6df32020-01-30 08:48:58 -0800468 timeStatsLayer.lateAcquireFrames += layerRecord.lateAcquireFrames;
469 timeStatsLayer.badDesiredPresentFrames += layerRecord.badDesiredPresentFrames;
470
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700471 layerRecord.droppedFrames = 0;
Alec Mouri91f6df32020-01-30 08:48:58 -0800472 layerRecord.lateAcquireFrames = 0;
473 layerRecord.badDesiredPresentFrames = 0;
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700474
475 const int32_t postToAcquireMs = msBetween(timeRecords[0].frameTime.postTime,
476 timeRecords[0].frameTime.acquireTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800477 ALOGV("[%d]-[%" PRIu64 "]-post2acquire[%d]", layerId,
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700478 timeRecords[0].frameTime.frameNumber, postToAcquireMs);
479 timeStatsLayer.deltas["post2acquire"].insert(postToAcquireMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700480
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700481 const int32_t postToPresentMs = msBetween(timeRecords[0].frameTime.postTime,
482 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800483 ALOGV("[%d]-[%" PRIu64 "]-post2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700484 timeRecords[0].frameTime.frameNumber, postToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700485 timeStatsLayer.deltas["post2present"].insert(postToPresentMs);
486
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700487 const int32_t acquireToPresentMs = msBetween(timeRecords[0].frameTime.acquireTime,
488 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800489 ALOGV("[%d]-[%" PRIu64 "]-acquire2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700490 timeRecords[0].frameTime.frameNumber, acquireToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700491 timeStatsLayer.deltas["acquire2present"].insert(acquireToPresentMs);
492
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700493 const int32_t latchToPresentMs = msBetween(timeRecords[0].frameTime.latchTime,
494 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800495 ALOGV("[%d]-[%" PRIu64 "]-latch2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700496 timeRecords[0].frameTime.frameNumber, latchToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700497 timeStatsLayer.deltas["latch2present"].insert(latchToPresentMs);
498
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700499 const int32_t desiredToPresentMs = msBetween(timeRecords[0].frameTime.desiredTime,
500 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800501 ALOGV("[%d]-[%" PRIu64 "]-desired2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700502 timeRecords[0].frameTime.frameNumber, desiredToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700503 timeStatsLayer.deltas["desired2present"].insert(desiredToPresentMs);
504
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700505 const int32_t presentToPresentMs = msBetween(prevTimeRecord.frameTime.presentTime,
506 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800507 ALOGV("[%d]-[%" PRIu64 "]-present2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700508 timeRecords[0].frameTime.frameNumber, presentToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700509 timeStatsLayer.deltas["present2present"].insert(presentToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700510 }
511 prevTimeRecord = timeRecords[0];
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700512 timeRecords.pop_front();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700513 layerRecord.waitData--;
514 }
515}
516
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700517static constexpr const char* kPopupWindowPrefix = "PopupWindow";
518static const size_t kMinLenLayerName = std::strlen(kPopupWindowPrefix);
Yiwei Zhangbd408322018-10-15 18:31:53 -0700519
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700520// Avoid tracking the "PopupWindow:<random hash>#<number>" layers
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700521static bool layerNameIsValid(const std::string& layerName) {
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700522 return layerName.length() >= kMinLenLayerName &&
523 layerName.compare(0, kMinLenLayerName, kPopupWindowPrefix) != 0;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700524}
525
Alec Mouri9a29e672020-09-14 12:39:14 -0700526bool TimeStats::canAddNewAggregatedStats(uid_t uid, const std::string& layerName) {
527 return mTimeStats.stats.count({uid, layerName}) > 0 ||
528 mTimeStats.stats.size() < MAX_NUM_LAYER_STATS;
529}
530
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800531void TimeStats::setPostTime(int32_t layerId, uint64_t frameNumber, const std::string& layerName,
Alec Mouri9a29e672020-09-14 12:39:14 -0700532 uid_t uid, nsecs_t postTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700533 if (!mEnabled.load()) return;
534
535 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800536 ALOGV("[%d]-[%" PRIu64 "]-[%s]-PostTime[%" PRId64 "]", layerId, frameNumber, layerName.c_str(),
Yiwei Zhang8e8fe522018-11-02 18:34:07 -0700537 postTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700538
539 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri9a29e672020-09-14 12:39:14 -0700540 if (!canAddNewAggregatedStats(uid, layerName)) {
Yiwei Zhange926ab52019-08-14 15:16:00 -0700541 return;
542 }
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800543 if (!mTimeStatsTracker.count(layerId) && mTimeStatsTracker.size() < MAX_NUM_LAYER_RECORDS &&
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700544 layerNameIsValid(layerName)) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700545 mTimeStatsTracker[layerId].uid = uid;
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800546 mTimeStatsTracker[layerId].layerName = layerName;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700547 }
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800548 if (!mTimeStatsTracker.count(layerId)) return;
549 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700550 if (layerRecord.timeRecords.size() == MAX_NUM_TIME_RECORDS) {
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800551 ALOGE("[%d]-[%s]-timeRecords is at its maximum size[%zu]. Ignore this when unittesting.",
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800552 layerId, layerRecord.layerName.c_str(), MAX_NUM_TIME_RECORDS);
553 mTimeStatsTracker.erase(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700554 return;
555 }
556 // For most media content, the acquireFence is invalid because the buffer is
557 // ready at the queueBuffer stage. In this case, acquireTime should be given
558 // a default value as postTime.
559 TimeRecord timeRecord = {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700560 .frameTime =
561 {
562 .frameNumber = frameNumber,
563 .postTime = postTime,
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800564 .latchTime = postTime,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700565 .acquireTime = postTime,
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800566 .desiredTime = postTime,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700567 },
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700568 };
569 layerRecord.timeRecords.push_back(timeRecord);
570 if (layerRecord.waitData < 0 ||
571 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
572 layerRecord.waitData = layerRecord.timeRecords.size() - 1;
573}
574
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800575void TimeStats::setLatchTime(int32_t layerId, uint64_t frameNumber, nsecs_t latchTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700576 if (!mEnabled.load()) return;
577
578 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800579 ALOGV("[%d]-[%" PRIu64 "]-LatchTime[%" PRId64 "]", layerId, frameNumber, latchTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700580
581 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800582 if (!mTimeStatsTracker.count(layerId)) return;
583 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700584 if (layerRecord.waitData < 0 ||
585 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
586 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700587 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700588 if (timeRecord.frameTime.frameNumber == frameNumber) {
589 timeRecord.frameTime.latchTime = latchTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700590 }
591}
592
Alec Mouri91f6df32020-01-30 08:48:58 -0800593void TimeStats::incrementLatchSkipped(int32_t layerId, LatchSkipReason reason) {
594 if (!mEnabled.load()) return;
595
596 ATRACE_CALL();
597 ALOGV("[%d]-LatchSkipped-Reason[%d]", layerId,
598 static_cast<std::underlying_type<LatchSkipReason>::type>(reason));
599
600 std::lock_guard<std::mutex> lock(mMutex);
601 if (!mTimeStatsTracker.count(layerId)) return;
602 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
603
604 switch (reason) {
605 case LatchSkipReason::LateAcquire:
606 layerRecord.lateAcquireFrames++;
607 break;
608 }
609}
610
611void TimeStats::incrementBadDesiredPresent(int32_t layerId) {
612 if (!mEnabled.load()) return;
613
614 ATRACE_CALL();
615 ALOGV("[%d]-BadDesiredPresent", layerId);
616
617 std::lock_guard<std::mutex> lock(mMutex);
618 if (!mTimeStatsTracker.count(layerId)) return;
619 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
620 layerRecord.badDesiredPresentFrames++;
621}
622
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800623void TimeStats::setDesiredTime(int32_t layerId, uint64_t frameNumber, nsecs_t desiredTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700624 if (!mEnabled.load()) return;
625
626 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800627 ALOGV("[%d]-[%" PRIu64 "]-DesiredTime[%" PRId64 "]", layerId, frameNumber, desiredTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700628
629 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800630 if (!mTimeStatsTracker.count(layerId)) return;
631 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700632 if (layerRecord.waitData < 0 ||
633 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
634 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700635 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700636 if (timeRecord.frameTime.frameNumber == frameNumber) {
637 timeRecord.frameTime.desiredTime = desiredTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700638 }
639}
640
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800641void TimeStats::setAcquireTime(int32_t layerId, uint64_t frameNumber, nsecs_t acquireTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700642 if (!mEnabled.load()) return;
643
644 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800645 ALOGV("[%d]-[%" PRIu64 "]-AcquireTime[%" PRId64 "]", layerId, frameNumber, acquireTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700646
647 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800648 if (!mTimeStatsTracker.count(layerId)) return;
649 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700650 if (layerRecord.waitData < 0 ||
651 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
652 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700653 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700654 if (timeRecord.frameTime.frameNumber == frameNumber) {
655 timeRecord.frameTime.acquireTime = acquireTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700656 }
657}
658
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800659void TimeStats::setAcquireFence(int32_t layerId, uint64_t frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700660 const std::shared_ptr<FenceTime>& acquireFence) {
661 if (!mEnabled.load()) return;
662
663 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800664 ALOGV("[%d]-[%" PRIu64 "]-AcquireFenceTime[%" PRId64 "]", layerId, frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700665 acquireFence->getSignalTime());
666
667 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800668 if (!mTimeStatsTracker.count(layerId)) return;
669 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700670 if (layerRecord.waitData < 0 ||
671 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
672 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700673 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700674 if (timeRecord.frameTime.frameNumber == frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700675 timeRecord.acquireFence = acquireFence;
676 }
677}
678
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800679void TimeStats::setPresentTime(int32_t layerId, uint64_t frameNumber, nsecs_t presentTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700680 if (!mEnabled.load()) return;
681
682 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800683 ALOGV("[%d]-[%" PRIu64 "]-PresentTime[%" PRId64 "]", layerId, frameNumber, presentTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700684
685 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800686 if (!mTimeStatsTracker.count(layerId)) return;
687 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700688 if (layerRecord.waitData < 0 ||
689 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
690 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700691 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700692 if (timeRecord.frameTime.frameNumber == frameNumber) {
693 timeRecord.frameTime.presentTime = presentTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700694 timeRecord.ready = true;
695 layerRecord.waitData++;
696 }
697
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800698 flushAvailableRecordsToStatsLocked(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700699}
700
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800701void TimeStats::setPresentFence(int32_t layerId, uint64_t frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700702 const std::shared_ptr<FenceTime>& presentFence) {
703 if (!mEnabled.load()) return;
704
705 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800706 ALOGV("[%d]-[%" PRIu64 "]-PresentFenceTime[%" PRId64 "]", layerId, frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700707 presentFence->getSignalTime());
708
709 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800710 if (!mTimeStatsTracker.count(layerId)) return;
711 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700712 if (layerRecord.waitData < 0 ||
713 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
714 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700715 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700716 if (timeRecord.frameTime.frameNumber == frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700717 timeRecord.presentFence = presentFence;
718 timeRecord.ready = true;
719 layerRecord.waitData++;
720 }
721
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800722 flushAvailableRecordsToStatsLocked(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700723}
724
Alec Mouri9a29e672020-09-14 12:39:14 -0700725template <class T>
726static void updateJankPayload(T& t, int32_t reasons) {
727 t.jankPayload.totalFrames++;
728
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800729 static const constexpr int32_t kValidJankyReason = JankType::SurfaceFlingerCpuDeadlineMissed |
730 JankType::SurfaceFlingerGpuDeadlineMissed | JankType::AppDeadlineMissed |
731 JankType::DisplayHAL;
Alec Mouri9a29e672020-09-14 12:39:14 -0700732 if (reasons & kValidJankyReason) {
733 t.jankPayload.totalJankyFrames++;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800734 if ((reasons & JankType::SurfaceFlingerCpuDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700735 t.jankPayload.totalSFLongCpu++;
736 }
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100737 if ((reasons & JankType::SurfaceFlingerGpuDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700738 t.jankPayload.totalSFLongGpu++;
739 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800740 if ((reasons & JankType::DisplayHAL) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700741 t.jankPayload.totalSFUnattributed++;
742 }
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100743 if ((reasons & JankType::AppDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700744 t.jankPayload.totalAppUnattributed++;
745 }
746 }
747}
748
749void TimeStats::incrementJankyFrames(int32_t reasons) {
750 if (!mEnabled.load()) return;
751
752 ATRACE_CALL();
753 std::lock_guard<std::mutex> lock(mMutex);
754
755 updateJankPayload<TimeStatsHelper::TimeStatsGlobal>(mTimeStats, reasons);
756}
757
758void TimeStats::incrementJankyFrames(uid_t uid, const std::string& layerName, int32_t reasons) {
759 if (!mEnabled.load()) return;
760
761 ATRACE_CALL();
762 std::lock_guard<std::mutex> lock(mMutex);
763
Alec Mouri542de112020-11-13 12:07:32 -0800764 // Only update layer stats if we're already tracking the layer in TimeStats.
765 // Otherwise, continue tracking the statistic but use a default layer name instead.
Alec Mouri9a29e672020-09-14 12:39:14 -0700766 // As an implementation detail, we do this because this method is expected to be
Alec Mouri542de112020-11-13 12:07:32 -0800767 // called from FrameTimeline, whose jank classification includes transaction jank
768 // that occurs without a buffer. But, in general those layer names are not suitable as
769 // aggregation keys: e.g., it's normal and expected for Window Manager to include the hash code
770 // for an animation leash. So while we can show that jank in dumpsys, aggregating based on the
771 // layer blows up the stats size, so as a workaround drop those stats. This assumes that
772 // TimeStats will flush the first present fence for a layer *before* FrameTimeline does so that
773 // the first jank record is not dropped.
Alec Mouri9a29e672020-09-14 12:39:14 -0700774
Alec Mouri542de112020-11-13 12:07:32 -0800775 bool useDefaultLayerKey = false;
776 static const std::string kDefaultLayerName = "none";
Alec Mouri9a29e672020-09-14 12:39:14 -0700777 if (!mTimeStats.stats.count({uid, layerName})) {
Alec Mouri542de112020-11-13 12:07:32 -0800778 mTimeStats.stats[{uid, kDefaultLayerName}].uid = uid;
779 mTimeStats.stats[{uid, kDefaultLayerName}].layerName = kDefaultLayerName;
780 useDefaultLayerKey = true;
Alec Mouri9a29e672020-09-14 12:39:14 -0700781 }
782
Alec Mouri542de112020-11-13 12:07:32 -0800783 TimeStatsHelper::TimeStatsLayer& timeStatsLayer =
784 mTimeStats.stats[{uid, useDefaultLayerKey ? kDefaultLayerName : layerName}];
Alec Mouri9a29e672020-09-14 12:39:14 -0700785 updateJankPayload<TimeStatsHelper::TimeStatsLayer>(timeStatsLayer, reasons);
786}
787
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800788void TimeStats::onDestroy(int32_t layerId) {
Yiwei Zhangdc224042018-10-18 15:34:00 -0700789 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800790 ALOGV("[%d]-onDestroy", layerId);
Mikael Pessa90092f42019-08-26 17:22:04 -0700791 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800792 mTimeStatsTracker.erase(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700793}
794
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800795void TimeStats::removeTimeRecord(int32_t layerId, uint64_t frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700796 if (!mEnabled.load()) return;
797
798 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800799 ALOGV("[%d]-[%" PRIu64 "]-removeTimeRecord", layerId, frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700800
801 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800802 if (!mTimeStatsTracker.count(layerId)) return;
803 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700804 size_t removeAt = 0;
805 for (const TimeRecord& record : layerRecord.timeRecords) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700806 if (record.frameTime.frameNumber == frameNumber) break;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700807 removeAt++;
808 }
809 if (removeAt == layerRecord.timeRecords.size()) return;
810 layerRecord.timeRecords.erase(layerRecord.timeRecords.begin() + removeAt);
811 if (layerRecord.waitData > static_cast<int32_t>(removeAt)) {
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700812 layerRecord.waitData--;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700813 }
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700814 layerRecord.droppedFrames++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700815}
816
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700817void TimeStats::flushPowerTimeLocked() {
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700818 if (!mEnabled.load()) return;
819
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700820 nsecs_t curTime = systemTime();
821 // elapsedTime is in milliseconds.
822 int64_t elapsedTime = (curTime - mPowerTime.prevTime) / 1000000;
823
824 switch (mPowerTime.powerMode) {
Peiyong Lin65248e02020-04-18 21:15:07 -0700825 case PowerMode::ON:
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700826 mTimeStats.displayOnTime += elapsedTime;
827 break;
Peiyong Lin65248e02020-04-18 21:15:07 -0700828 case PowerMode::OFF:
829 case PowerMode::DOZE:
830 case PowerMode::DOZE_SUSPEND:
831 case PowerMode::ON_SUSPEND:
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700832 default:
833 break;
834 }
835
836 mPowerTime.prevTime = curTime;
837}
838
Peiyong Lin65248e02020-04-18 21:15:07 -0700839void TimeStats::setPowerMode(PowerMode powerMode) {
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700840 if (!mEnabled.load()) {
841 std::lock_guard<std::mutex> lock(mMutex);
842 mPowerTime.powerMode = powerMode;
843 return;
844 }
845
846 std::lock_guard<std::mutex> lock(mMutex);
847 if (powerMode == mPowerTime.powerMode) return;
848
849 flushPowerTimeLocked();
850 mPowerTime.powerMode = powerMode;
851}
852
Alec Mourifb571ea2019-01-24 18:42:10 -0800853void TimeStats::recordRefreshRate(uint32_t fps, nsecs_t duration) {
854 std::lock_guard<std::mutex> lock(mMutex);
855 if (mTimeStats.refreshRateStats.count(fps)) {
856 mTimeStats.refreshRateStats[fps] += duration;
857 } else {
858 mTimeStats.refreshRateStats.insert({fps, duration});
859 }
860}
861
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700862void TimeStats::flushAvailableGlobalRecordsToStatsLocked() {
863 ATRACE_CALL();
864
865 while (!mGlobalRecord.presentFences.empty()) {
866 const nsecs_t curPresentTime = mGlobalRecord.presentFences.front()->getSignalTime();
867 if (curPresentTime == Fence::SIGNAL_TIME_PENDING) break;
868
869 if (curPresentTime == Fence::SIGNAL_TIME_INVALID) {
870 ALOGE("GlobalPresentFence is invalid!");
871 mGlobalRecord.prevPresentTime = 0;
872 mGlobalRecord.presentFences.pop_front();
873 continue;
874 }
875
876 ALOGV("GlobalPresentFenceTime[%" PRId64 "]",
877 mGlobalRecord.presentFences.front()->getSignalTime());
878
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700879 if (mGlobalRecord.prevPresentTime != 0) {
880 const int32_t presentToPresentMs =
881 msBetween(mGlobalRecord.prevPresentTime, curPresentTime);
882 ALOGV("Global present2present[%d] prev[%" PRId64 "] curr[%" PRId64 "]",
883 presentToPresentMs, mGlobalRecord.prevPresentTime, curPresentTime);
884 mTimeStats.presentToPresent.insert(presentToPresentMs);
885 }
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700886
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700887 mGlobalRecord.prevPresentTime = curPresentTime;
888 mGlobalRecord.presentFences.pop_front();
889 }
Alec Mourie4034bb2019-11-19 12:45:54 -0800890 while (!mGlobalRecord.renderEngineDurations.empty()) {
891 const auto duration = mGlobalRecord.renderEngineDurations.front();
892 const auto& endTime = duration.endTime;
893
894 nsecs_t endNs = -1;
895
896 if (auto val = std::get_if<nsecs_t>(&endTime)) {
897 endNs = *val;
898 } else {
899 endNs = std::get<std::shared_ptr<FenceTime>>(endTime)->getSignalTime();
900 }
901
902 if (endNs == Fence::SIGNAL_TIME_PENDING) break;
903
904 if (endNs < 0) {
905 ALOGE("RenderEngineTiming is invalid!");
906 mGlobalRecord.renderEngineDurations.pop_front();
907 continue;
908 }
909
910 const int32_t renderEngineMs = msBetween(duration.startTime, endNs);
911 mTimeStats.renderEngineTiming.insert(renderEngineMs);
912
913 mGlobalRecord.renderEngineDurations.pop_front();
914 }
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700915}
916
917void TimeStats::setPresentFenceGlobal(const std::shared_ptr<FenceTime>& presentFence) {
918 if (!mEnabled.load()) return;
919
920 ATRACE_CALL();
921 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700922 if (presentFence == nullptr || !presentFence->isValid()) {
923 mGlobalRecord.prevPresentTime = 0;
924 return;
925 }
926
Peiyong Lin65248e02020-04-18 21:15:07 -0700927 if (mPowerTime.powerMode != PowerMode::ON) {
928 // Try flushing the last present fence on PowerMode::ON.
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700929 flushAvailableGlobalRecordsToStatsLocked();
930 mGlobalRecord.presentFences.clear();
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700931 mGlobalRecord.prevPresentTime = 0;
932 return;
933 }
934
935 if (mGlobalRecord.presentFences.size() == MAX_NUM_TIME_RECORDS) {
936 // The front presentFence must be trapped in pending status in this
937 // case. Try dequeuing the front one to recover.
938 ALOGE("GlobalPresentFences is already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
939 mGlobalRecord.prevPresentTime = 0;
940 mGlobalRecord.presentFences.pop_front();
941 }
942
943 mGlobalRecord.presentFences.emplace_back(presentFence);
944 flushAvailableGlobalRecordsToStatsLocked();
945}
946
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700947void TimeStats::enable() {
948 if (mEnabled.load()) return;
949
950 ATRACE_CALL();
951
952 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700953 mEnabled.store(true);
Yiwei Zhangdc224042018-10-18 15:34:00 -0700954 mTimeStats.statsStart = static_cast<int64_t>(std::time(0));
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700955 mPowerTime.prevTime = systemTime();
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700956 ALOGD("Enabled");
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700957}
958
959void TimeStats::disable() {
960 if (!mEnabled.load()) return;
961
962 ATRACE_CALL();
963
964 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700965 flushPowerTimeLocked();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700966 mEnabled.store(false);
Yiwei Zhangdc224042018-10-18 15:34:00 -0700967 mTimeStats.statsEnd = static_cast<int64_t>(std::time(0));
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700968 ALOGD("Disabled");
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700969}
970
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000971void TimeStats::clearAll() {
972 std::lock_guard<std::mutex> lock(mMutex);
973 clearGlobalLocked();
974 clearLayersLocked();
975}
976
977void TimeStats::clearGlobalLocked() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700978 ATRACE_CALL();
979
Yiwei Zhangdc224042018-10-18 15:34:00 -0700980 mTimeStats.statsStart = (mEnabled.load() ? static_cast<int64_t>(std::time(0)) : 0);
981 mTimeStats.statsEnd = 0;
982 mTimeStats.totalFrames = 0;
983 mTimeStats.missedFrames = 0;
984 mTimeStats.clientCompositionFrames = 0;
Vishnu Nair9b079a22020-01-21 14:36:08 -0800985 mTimeStats.clientCompositionReusedFrames = 0;
Alec Mouri8de697e2020-03-19 10:52:01 -0700986 mTimeStats.refreshRateSwitches = 0;
Alec Mouri8f7a0102020-04-15 12:11:10 -0700987 mTimeStats.compositionStrategyChanges = 0;
Alec Mouri717bcb62020-02-10 17:07:19 -0800988 mTimeStats.displayEventConnectionsCount = 0;
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700989 mTimeStats.displayOnTime = 0;
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700990 mTimeStats.presentToPresent.hist.clear();
Alec Mouri31ac64a2020-01-09 09:26:22 -0800991 mTimeStats.frameDuration.hist.clear();
992 mTimeStats.renderEngineTiming.hist.clear();
Alec Mouri9a29e672020-09-14 12:39:14 -0700993 mTimeStats.jankPayload = TimeStatsHelper::JankPayload();
Alec Mourifb571ea2019-01-24 18:42:10 -0800994 mTimeStats.refreshRateStats.clear();
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700995 mPowerTime.prevTime = systemTime();
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700996 mGlobalRecord.prevPresentTime = 0;
997 mGlobalRecord.presentFences.clear();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000998 ALOGD("Cleared global stats");
999}
1000
1001void TimeStats::clearLayersLocked() {
1002 ATRACE_CALL();
1003
1004 mTimeStatsTracker.clear();
1005 mTimeStats.stats.clear();
1006 ALOGD("Cleared layer stats");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001007}
1008
1009bool TimeStats::isEnabled() {
1010 return mEnabled.load();
1011}
1012
Yiwei Zhang5434a782018-12-05 18:06:32 -08001013void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, std::string& result) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001014 ATRACE_CALL();
1015
1016 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhangdc224042018-10-18 15:34:00 -07001017 if (mTimeStats.statsStart == 0) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001018 return;
1019 }
1020
Yiwei Zhangdc224042018-10-18 15:34:00 -07001021 mTimeStats.statsEnd = static_cast<int64_t>(std::time(0));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001022
Yiwei Zhang3a226d22018-10-16 09:23:03 -07001023 flushPowerTimeLocked();
1024
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001025 if (asProto) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001026 ALOGD("Dumping TimeStats as proto");
Yiwei Zhangdc224042018-10-18 15:34:00 -07001027 SFTimeStatsGlobalProto timeStatsProto = mTimeStats.toProto(maxLayers);
Dominik Laskowski46470112019-08-02 13:13:11 -07001028 result.append(timeStatsProto.SerializeAsString());
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001029 } else {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001030 ALOGD("Dumping TimeStats as text");
Yiwei Zhang5434a782018-12-05 18:06:32 -08001031 result.append(mTimeStats.toString(maxLayers));
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001032 result.append("\n");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001033 }
1034}
1035
Alec Mourifb571ea2019-01-24 18:42:10 -08001036} // namespace impl
1037
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001038} // namespace android