blob: 9368edd6ac9a052e78b1fd1f32b3d49ee20a876a [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
Yiwei Zhang0102ad22018-05-02 17:37:17 -070017#undef LOG_TAG
18#define LOG_TAG "TimeStats"
19#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
Yiwei Zhang0102ad22018-05-02 17:37:17 -070021#include <android-base/stringprintf.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070022#include <log/log.h>
Tej Singhe2751772021-04-06 22:05:29 -070023#include <timestatsatomsproto/TimeStatsAtomsProtoHeader.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070024#include <utils/String8.h>
Yiwei Zhang3a226d22018-10-16 09:23:03 -070025#include <utils/Timers.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070026#include <utils/Trace.h>
27
28#include <algorithm>
Alec Mouri9519bf12019-11-15 16:54:44 -080029#include <chrono>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070030#include <unordered_map>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070031
Tej Singhe2751772021-04-06 22:05:29 -070032#include "TimeStats.h"
Alec Mouri9a29e672020-09-14 12:39:14 -070033#include "timestatsproto/TimeStatsHelper.h"
34
Yiwei Zhang0102ad22018-05-02 17:37:17 -070035namespace android {
36
Alec Mourifb571ea2019-01-24 18:42:10 -080037namespace impl {
38
Alec Mouri37384342020-01-02 17:23:37 -080039namespace {
Alec Mouri8e2f31b2020-01-16 22:04:35 +000040
Tej Singhe2751772021-04-06 22:05:29 -070041FrameTimingHistogram histogramToProto(const std::unordered_map<int32_t, int32_t>& histogram,
42 size_t maxPulledHistogramBuckets) {
Alec Mouri37384342020-01-02 17:23:37 -080043 auto buckets = std::vector<std::pair<int32_t, int32_t>>(histogram.begin(), histogram.end());
44 std::sort(buckets.begin(), buckets.end(),
45 [](std::pair<int32_t, int32_t>& left, std::pair<int32_t, int32_t>& right) {
46 return left.second > right.second;
47 });
48
Tej Singhe2751772021-04-06 22:05:29 -070049 FrameTimingHistogram histogramProto;
Alec Mouri37384342020-01-02 17:23:37 -080050 int histogramSize = 0;
51 for (const auto& bucket : buckets) {
52 if (++histogramSize > maxPulledHistogramBuckets) {
53 break;
54 }
Tej Singhe2751772021-04-06 22:05:29 -070055 histogramProto.add_time_millis_buckets((int32_t)bucket.first);
56 histogramProto.add_frame_counts((int64_t)bucket.second);
Alec Mouri37384342020-01-02 17:23:37 -080057 }
Tej Singhe2751772021-04-06 22:05:29 -070058 return histogramProto;
Alec Mouri37384342020-01-02 17:23:37 -080059}
Alec Mouri75de8f22021-01-20 14:53:44 -080060
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070061SurfaceflingerStatsLayerInfo_GameMode gameModeToProto(GameMode gameMode) {
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000062 switch (gameMode) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070063 case GameMode::Unsupported:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000064 return SurfaceflingerStatsLayerInfo::GAME_MODE_UNSUPPORTED;
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070065 case GameMode::Standard:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000066 return SurfaceflingerStatsLayerInfo::GAME_MODE_STANDARD;
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070067 case GameMode::Performance:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000068 return SurfaceflingerStatsLayerInfo::GAME_MODE_PERFORMANCE;
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070069 case GameMode::Battery:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000070 return SurfaceflingerStatsLayerInfo::GAME_MODE_BATTERY;
Xiang Wangf0c5cca2022-11-09 18:03:09 -080071 case GameMode::Custom:
72 return SurfaceflingerStatsLayerInfo::GAME_MODE_CUSTOM;
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000073 default:
74 return SurfaceflingerStatsLayerInfo::GAME_MODE_UNSPECIFIED;
75 }
76}
77
Tej Singhe2751772021-04-06 22:05:29 -070078SurfaceflingerStatsLayerInfo_SetFrameRateVote frameRateVoteToProto(
79 const TimeStats::SetFrameRateVote& setFrameRateVote) {
80 using FrameRateCompatibilityEnum =
81 SurfaceflingerStatsLayerInfo::SetFrameRateVote::FrameRateCompatibility;
82 using SeamlessnessEnum = SurfaceflingerStatsLayerInfo::SetFrameRateVote::Seamlessness;
Alec Mouri75de8f22021-01-20 14:53:44 -080083
Tej Singhe2751772021-04-06 22:05:29 -070084 SurfaceflingerStatsLayerInfo_SetFrameRateVote proto;
85 proto.set_frame_rate(setFrameRateVote.frameRate);
86 proto.set_frame_rate_compatibility(
87 static_cast<FrameRateCompatibilityEnum>(setFrameRateVote.frameRateCompatibility));
88 proto.set_seamlessness(static_cast<SeamlessnessEnum>(setFrameRateVote.seamlessness));
89 return proto;
Alec Mouri75de8f22021-01-20 14:53:44 -080090}
Alec Mouri37384342020-01-02 17:23:37 -080091} // namespace
92
Huihong Luo30aa4372022-10-03 14:54:12 -070093bool TimeStats::populateGlobalAtom(std::vector<uint8_t>* pulledData) {
Alec Mouridfad9002020-02-12 17:49:09 -080094 std::lock_guard<std::mutex> lock(mMutex);
95
Alec Mouri7d436ec2021-01-27 20:40:50 -080096 if (mTimeStats.statsStartLegacy == 0) {
Tej Singhe2751772021-04-06 22:05:29 -070097 return false;
Alec Mouridfad9002020-02-12 17:49:09 -080098 }
99 flushPowerTimeLocked();
Tej Singhe2751772021-04-06 22:05:29 -0700100 SurfaceflingerStatsGlobalInfoWrapper atomList;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800101 for (const auto& globalSlice : mTimeStats.stats) {
Tej Singhe2751772021-04-06 22:05:29 -0700102 SurfaceflingerStatsGlobalInfo* atom = atomList.add_atom();
103 atom->set_total_frames(mTimeStats.totalFramesLegacy);
104 atom->set_missed_frames(mTimeStats.missedFramesLegacy);
105 atom->set_client_composition_frames(mTimeStats.clientCompositionFramesLegacy);
106 atom->set_display_on_millis(mTimeStats.displayOnTimeLegacy);
107 atom->set_animation_millis(mTimeStats.presentToPresentLegacy.totalTime());
108 atom->set_event_connection_count(mTimeStats.displayEventConnectionsCountLegacy);
109 *atom->mutable_frame_duration() =
110 histogramToProto(mTimeStats.frameDurationLegacy.hist, mMaxPulledHistogramBuckets);
111 *atom->mutable_render_engine_timing() =
112 histogramToProto(mTimeStats.renderEngineTimingLegacy.hist,
113 mMaxPulledHistogramBuckets);
114 atom->set_total_timeline_frames(globalSlice.second.jankPayload.totalFrames);
115 atom->set_total_janky_frames(globalSlice.second.jankPayload.totalJankyFrames);
116 atom->set_total_janky_frames_with_long_cpu(globalSlice.second.jankPayload.totalSFLongCpu);
117 atom->set_total_janky_frames_with_long_gpu(globalSlice.second.jankPayload.totalSFLongGpu);
118 atom->set_total_janky_frames_sf_unattributed(
119 globalSlice.second.jankPayload.totalSFUnattributed);
120 atom->set_total_janky_frames_app_unattributed(
121 globalSlice.second.jankPayload.totalAppUnattributed);
122 atom->set_total_janky_frames_sf_scheduling(
123 globalSlice.second.jankPayload.totalSFScheduling);
124 atom->set_total_jank_frames_sf_prediction_error(
125 globalSlice.second.jankPayload.totalSFPredictionError);
126 atom->set_total_jank_frames_app_buffer_stuffing(
127 globalSlice.second.jankPayload.totalAppBufferStuffing);
128 atom->set_display_refresh_rate_bucket(globalSlice.first.displayRefreshRateBucket);
129 *atom->mutable_sf_deadline_misses() =
130 histogramToProto(globalSlice.second.displayDeadlineDeltas.hist,
131 mMaxPulledHistogramBuckets);
132 *atom->mutable_sf_prediction_errors() =
133 histogramToProto(globalSlice.second.displayPresentDeltas.hist,
134 mMaxPulledHistogramBuckets);
135 atom->set_render_rate_bucket(globalSlice.first.renderRateBucket);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800136 }
137
Tej Singhe2751772021-04-06 22:05:29 -0700138 // Always clear data.
Alec Mouridfad9002020-02-12 17:49:09 -0800139 clearGlobalLocked();
140
Huihong Luo30aa4372022-10-03 14:54:12 -0700141 pulledData->resize(atomList.ByteSizeLong());
142 return atomList.SerializeToArray(pulledData->data(), atomList.ByteSizeLong());
Alec Mouridfad9002020-02-12 17:49:09 -0800143}
144
Huihong Luo30aa4372022-10-03 14:54:12 -0700145bool TimeStats::populateLayerAtom(std::vector<uint8_t>* pulledData) {
Alec Mouri37384342020-01-02 17:23:37 -0800146 std::lock_guard<std::mutex> lock(mMutex);
147
Alec Mouri363faf02021-01-29 16:34:55 -0800148 std::vector<TimeStatsHelper::TimeStatsLayer*> dumpStats;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800149 uint32_t numLayers = 0;
150 for (const auto& globalSlice : mTimeStats.stats) {
151 numLayers += globalSlice.second.stats.size();
152 }
153
154 dumpStats.reserve(numLayers);
155
Alec Mouri363faf02021-01-29 16:34:55 -0800156 for (auto& globalSlice : mTimeStats.stats) {
157 for (auto& layerSlice : globalSlice.second.stats) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800158 dumpStats.push_back(&layerSlice.second);
159 }
Alec Mouri37384342020-01-02 17:23:37 -0800160 }
161
162 std::sort(dumpStats.begin(), dumpStats.end(),
163 [](TimeStatsHelper::TimeStatsLayer const* l,
164 TimeStatsHelper::TimeStatsLayer const* r) {
165 return l->totalFrames > r->totalFrames;
166 });
167
168 if (mMaxPulledLayers < dumpStats.size()) {
169 dumpStats.resize(mMaxPulledLayers);
170 }
171
Tej Singhe2751772021-04-06 22:05:29 -0700172 SurfaceflingerStatsLayerInfoWrapper atomList;
Alec Mouri363faf02021-01-29 16:34:55 -0800173 for (auto& layer : dumpStats) {
Tej Singhe2751772021-04-06 22:05:29 -0700174 SurfaceflingerStatsLayerInfo* atom = atomList.add_atom();
175 atom->set_layer_name(layer->layerName);
176 atom->set_total_frames(layer->totalFrames);
177 atom->set_dropped_frames(layer->droppedFrames);
178 const auto& present2PresentHist = layer->deltas.find("present2present");
179 if (present2PresentHist != layer->deltas.cend()) {
180 *atom->mutable_present_to_present() =
181 histogramToProto(present2PresentHist->second.hist, mMaxPulledHistogramBuckets);
182 }
183 const auto& post2presentHist = layer->deltas.find("post2present");
184 if (post2presentHist != layer->deltas.cend()) {
185 *atom->mutable_post_to_present() =
186 histogramToProto(post2presentHist->second.hist, mMaxPulledHistogramBuckets);
187 }
188 const auto& acquire2presentHist = layer->deltas.find("acquire2present");
189 if (acquire2presentHist != layer->deltas.cend()) {
190 *atom->mutable_acquire_to_present() =
191 histogramToProto(acquire2presentHist->second.hist, mMaxPulledHistogramBuckets);
192 }
193 const auto& latch2presentHist = layer->deltas.find("latch2present");
194 if (latch2presentHist != layer->deltas.cend()) {
195 *atom->mutable_latch_to_present() =
196 histogramToProto(latch2presentHist->second.hist, mMaxPulledHistogramBuckets);
197 }
198 const auto& desired2presentHist = layer->deltas.find("desired2present");
199 if (desired2presentHist != layer->deltas.cend()) {
200 *atom->mutable_desired_to_present() =
201 histogramToProto(desired2presentHist->second.hist, mMaxPulledHistogramBuckets);
202 }
203 const auto& post2acquireHist = layer->deltas.find("post2acquire");
204 if (post2acquireHist != layer->deltas.cend()) {
205 *atom->mutable_post_to_acquire() =
206 histogramToProto(post2acquireHist->second.hist, mMaxPulledHistogramBuckets);
Alec Mouri37384342020-01-02 17:23:37 -0800207 }
208
Tej Singhe2751772021-04-06 22:05:29 -0700209 atom->set_late_acquire_frames(layer->lateAcquireFrames);
210 atom->set_bad_desired_present_frames(layer->badDesiredPresentFrames);
211 atom->set_uid(layer->uid);
212 atom->set_total_timeline_frames(layer->jankPayload.totalFrames);
213 atom->set_total_janky_frames(layer->jankPayload.totalJankyFrames);
214 atom->set_total_janky_frames_with_long_cpu(layer->jankPayload.totalSFLongCpu);
215 atom->set_total_janky_frames_with_long_gpu(layer->jankPayload.totalSFLongGpu);
216 atom->set_total_janky_frames_sf_unattributed(layer->jankPayload.totalSFUnattributed);
217 atom->set_total_janky_frames_app_unattributed(layer->jankPayload.totalAppUnattributed);
218 atom->set_total_janky_frames_sf_scheduling(layer->jankPayload.totalSFScheduling);
219 atom->set_total_jank_frames_sf_prediction_error(layer->jankPayload.totalSFPredictionError);
220 atom->set_total_jank_frames_app_buffer_stuffing(layer->jankPayload.totalAppBufferStuffing);
221 atom->set_display_refresh_rate_bucket(layer->displayRefreshRateBucket);
222 atom->set_render_rate_bucket(layer->renderRateBucket);
223 *atom->mutable_set_frame_rate_vote() = frameRateVoteToProto(layer->setFrameRateVote);
224 *atom->mutable_app_deadline_misses() =
225 histogramToProto(layer->deltas["appDeadlineDeltas"].hist,
226 mMaxPulledHistogramBuckets);
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000227 atom->set_game_mode(gameModeToProto(layer->gameMode));
Alec Mouri37384342020-01-02 17:23:37 -0800228 }
Tej Singhe2751772021-04-06 22:05:29 -0700229
230 // Always clear data.
Alec Mouri37384342020-01-02 17:23:37 -0800231 clearLayersLocked();
232
Huihong Luo30aa4372022-10-03 14:54:12 -0700233 pulledData->resize(atomList.ByteSizeLong());
234 return atomList.SerializeToArray(pulledData->data(), atomList.ByteSizeLong());
Alec Mouri37384342020-01-02 17:23:37 -0800235}
236
Tej Singhe2751772021-04-06 22:05:29 -0700237TimeStats::TimeStats() : TimeStats(std::nullopt, std::nullopt) {}
Alec Mouri37384342020-01-02 17:23:37 -0800238
Tej Singhe2751772021-04-06 22:05:29 -0700239TimeStats::TimeStats(std::optional<size_t> maxPulledLayers,
Alec Mouri37384342020-01-02 17:23:37 -0800240 std::optional<size_t> maxPulledHistogramBuckets) {
Alec Mouri37384342020-01-02 17:23:37 -0800241 if (maxPulledLayers) {
242 mMaxPulledLayers = *maxPulledLayers;
243 }
244
245 if (maxPulledHistogramBuckets) {
246 mMaxPulledHistogramBuckets = *maxPulledHistogramBuckets;
247 }
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000248}
249
Huihong Luo30aa4372022-10-03 14:54:12 -0700250bool TimeStats::onPullAtom(const int atomId, std::vector<uint8_t>* pulledData) {
Tej Singhe2751772021-04-06 22:05:29 -0700251 bool success = false;
252 if (atomId == 10062) { // SURFACEFLINGER_STATS_GLOBAL_INFO
253 success = populateGlobalAtom(pulledData);
254 } else if (atomId == 10063) { // SURFACEFLINGER_STATS_LAYER_INFO
255 success = populateLayerAtom(pulledData);
256 }
Alec Mouri3ecd5cd2020-01-29 12:53:07 -0800257
Tej Singhe2751772021-04-06 22:05:29 -0700258 // Enable timestats now. The first full pull for a given build is expected to
259 // have empty or very little stats, as stats are first enabled after the
260 // first pull is completed for either the global or layer stats.
261 enable();
262 return success;
Alec Mourib3885ad2019-09-06 17:08:55 -0700263}
264
Dominik Laskowskic2867142019-01-21 11:33:38 -0800265void TimeStats::parseArgs(bool asProto, const Vector<String16>& args, std::string& result) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700266 ATRACE_CALL();
267
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700268 std::unordered_map<std::string, int32_t> argsMap;
Dominik Laskowskic2867142019-01-21 11:33:38 -0800269 for (size_t index = 0; index < args.size(); ++index) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700270 argsMap[std::string(String8(args[index]).c_str())] = index;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700271 }
272
273 if (argsMap.count("-disable")) {
274 disable();
275 }
276
277 if (argsMap.count("-dump")) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700278 std::optional<uint32_t> maxLayers = std::nullopt;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700279 auto iter = argsMap.find("-maxlayers");
280 if (iter != argsMap.end() && iter->second + 1 < static_cast<int32_t>(args.size())) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700281 int64_t value = strtol(String8(args[iter->second + 1]).c_str(), nullptr, 10);
282 value = std::clamp(value, int64_t(0), int64_t(UINT32_MAX));
283 maxLayers = static_cast<uint32_t>(value);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700284 }
285
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700286 dump(asProto, maxLayers, result);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700287 }
288
289 if (argsMap.count("-clear")) {
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000290 clearAll();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700291 }
292
293 if (argsMap.count("-enable")) {
294 enable();
295 }
296}
297
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700298std::string TimeStats::miniDump() {
299 ATRACE_CALL();
300
301 std::string result = "TimeStats miniDump:\n";
302 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange926ab52019-08-14 15:16:00 -0700303 android::base::StringAppendF(&result, "Number of layers currently being tracked is %zu\n",
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700304 mTimeStatsTracker.size());
Yiwei Zhange926ab52019-08-14 15:16:00 -0700305 android::base::StringAppendF(&result, "Number of layers in the stats pool is %zu\n",
306 mTimeStats.stats.size());
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700307 return result;
308}
309
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700310void TimeStats::incrementTotalFrames() {
311 if (!mEnabled.load()) return;
312
313 ATRACE_CALL();
314
315 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800316 mTimeStats.totalFramesLegacy++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700317}
318
Yiwei Zhang621f9d42018-05-07 10:40:55 -0700319void TimeStats::incrementMissedFrames() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700320 if (!mEnabled.load()) return;
321
322 ATRACE_CALL();
323
324 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800325 mTimeStats.missedFramesLegacy++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700326}
327
Vishnu Nair9cf89262022-02-26 09:17:49 -0800328void TimeStats::pushCompositionStrategyState(const TimeStats::ClientCompositionRecord& record) {
329 if (!mEnabled.load() || !record.hasInterestingData()) {
330 return;
331 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700332
333 ATRACE_CALL();
334
335 std::lock_guard<std::mutex> lock(mMutex);
Vishnu Nair9cf89262022-02-26 09:17:49 -0800336 if (record.changed) mTimeStats.compositionStrategyChangesLegacy++;
337 if (record.hadClientComposition) mTimeStats.clientCompositionFramesLegacy++;
338 if (record.reused) mTimeStats.clientCompositionReusedFramesLegacy++;
339 if (record.predicted) mTimeStats.compositionStrategyPredictedLegacy++;
340 if (record.predictionSucceeded) mTimeStats.compositionStrategyPredictionSucceededLegacy++;
Vishnu Nair9b079a22020-01-21 14:36:08 -0800341}
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);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800349 mTimeStats.refreshRateSwitchesLegacy++;
Alec Mouri8de697e2020-03-19 10:52:01 -0700350}
351
Alec Mouri717bcb62020-02-10 17:07:19 -0800352void TimeStats::recordDisplayEventConnectionCount(int32_t count) {
353 if (!mEnabled.load()) return;
354
355 ATRACE_CALL();
356
357 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800358 mTimeStats.displayEventConnectionsCountLegacy =
359 std::max(mTimeStats.displayEventConnectionsCountLegacy, count);
Alec Mouri717bcb62020-02-10 17:07:19 -0800360}
361
Ady Abraham3e8cc072021-05-11 16:29:54 -0700362static int32_t toMs(nsecs_t nanos) {
363 int64_t millis =
364 std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds(nanos))
365 .count();
366 millis = std::clamp(millis, int64_t(INT32_MIN), int64_t(INT32_MAX));
367 return static_cast<int32_t>(millis);
368}
369
Alec Mouri9519bf12019-11-15 16:54:44 -0800370static int32_t msBetween(nsecs_t start, nsecs_t end) {
Ady Abraham3e8cc072021-05-11 16:29:54 -0700371 return toMs(end - start);
Alec Mouri9519bf12019-11-15 16:54:44 -0800372}
373
374void TimeStats::recordFrameDuration(nsecs_t startTime, nsecs_t endTime) {
375 if (!mEnabled.load()) return;
376
377 std::lock_guard<std::mutex> lock(mMutex);
Peiyong Lin65248e02020-04-18 21:15:07 -0700378 if (mPowerTime.powerMode == PowerMode::ON) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800379 mTimeStats.frameDurationLegacy.insert(msBetween(startTime, endTime));
Alec Mouri9519bf12019-11-15 16:54:44 -0800380 }
381}
382
Alec Mourie4034bb2019-11-19 12:45:54 -0800383void TimeStats::recordRenderEngineDuration(nsecs_t startTime, nsecs_t endTime) {
384 if (!mEnabled.load()) return;
385
386 std::lock_guard<std::mutex> lock(mMutex);
387 if (mGlobalRecord.renderEngineDurations.size() == MAX_NUM_TIME_RECORDS) {
388 ALOGE("RenderEngineTimes are already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
389 mGlobalRecord.renderEngineDurations.pop_front();
390 }
391 mGlobalRecord.renderEngineDurations.push_back({startTime, endTime});
392}
393
394void TimeStats::recordRenderEngineDuration(nsecs_t startTime,
395 const std::shared_ptr<FenceTime>& endTime) {
396 if (!mEnabled.load()) return;
397
398 std::lock_guard<std::mutex> lock(mMutex);
399 if (mGlobalRecord.renderEngineDurations.size() == MAX_NUM_TIME_RECORDS) {
400 ALOGE("RenderEngineTimes are already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
401 mGlobalRecord.renderEngineDurations.pop_front();
402 }
403 mGlobalRecord.renderEngineDurations.push_back({startTime, endTime});
404}
405
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800406bool TimeStats::recordReadyLocked(int32_t layerId, TimeRecord* timeRecord) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700407 if (!timeRecord->ready) {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800408 ALOGV("[%d]-[%" PRIu64 "]-presentFence is still not received", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700409 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700410 return false;
411 }
412
413 if (timeRecord->acquireFence != nullptr) {
414 if (timeRecord->acquireFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
415 return false;
416 }
417 if (timeRecord->acquireFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700418 timeRecord->frameTime.acquireTime = timeRecord->acquireFence->getSignalTime();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700419 timeRecord->acquireFence = nullptr;
420 } else {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800421 ALOGV("[%d]-[%" PRIu64 "]-acquireFence signal time is invalid", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700422 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700423 }
424 }
425
426 if (timeRecord->presentFence != nullptr) {
427 if (timeRecord->presentFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
428 return false;
429 }
430 if (timeRecord->presentFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700431 timeRecord->frameTime.presentTime = timeRecord->presentFence->getSignalTime();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700432 timeRecord->presentFence = nullptr;
433 } else {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800434 ALOGV("[%d]-[%" PRIu64 "]-presentFence signal time invalid", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700435 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700436 }
437 }
438
439 return true;
440}
441
Ady Abraham3403a3f2021-04-27 16:58:40 -0700442static int32_t clampToNearestBucket(Fps fps, size_t bucketWidth) {
443 return std::round(fps.getValue() / bucketWidth) * bucketWidth;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800444}
445
446void TimeStats::flushAvailableRecordsToStatsLocked(int32_t layerId, Fps displayRefreshRate,
Ady Abraham8b9e6122021-01-26 19:11:45 -0800447 std::optional<Fps> renderRate,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000448 SetFrameRateVote frameRateVote,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700449 GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700450 ATRACE_CALL();
Ady Abraham8b9e6122021-01-26 19:11:45 -0800451 ALOGV("[%d]-flushAvailableRecordsToStatsLocked", layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700452
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800453 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700454 TimeRecord& prevTimeRecord = layerRecord.prevTimeRecord;
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700455 std::deque<TimeRecord>& timeRecords = layerRecord.timeRecords;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800456 const int32_t refreshRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700457 clampToNearestBucket(displayRefreshRate, REFRESH_RATE_BUCKET_WIDTH);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800458 const int32_t renderRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700459 clampToNearestBucket(renderRate ? *renderRate : displayRefreshRate,
460 RENDER_RATE_BUCKET_WIDTH);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700461 while (!timeRecords.empty()) {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800462 if (!recordReadyLocked(layerId, &timeRecords[0])) break;
463 ALOGV("[%d]-[%" PRIu64 "]-presentFenceTime[%" PRId64 "]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700464 timeRecords[0].frameTime.frameNumber, timeRecords[0].frameTime.presentTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700465
466 if (prevTimeRecord.ready) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700467 uid_t uid = layerRecord.uid;
Yiwei Zhangeafa5cc2019-07-26 15:06:25 -0700468 const std::string& layerName = layerRecord.layerName;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800469 TimeStatsHelper::TimelineStatsKey timelineKey = {refreshRateBucket, renderRateBucket};
470 if (!mTimeStats.stats.count(timelineKey)) {
471 mTimeStats.stats[timelineKey].key = timelineKey;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700472 }
Alec Mouri7d436ec2021-01-27 20:40:50 -0800473
474 TimeStatsHelper::TimelineStats& displayStats = mTimeStats.stats[timelineKey];
475
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000476 TimeStatsHelper::LayerStatsKey layerKey = {uid, layerName, gameMode};
Alec Mouri7d436ec2021-01-27 20:40:50 -0800477 if (!displayStats.stats.count(layerKey)) {
478 displayStats.stats[layerKey].displayRefreshRateBucket = refreshRateBucket;
479 displayStats.stats[layerKey].renderRateBucket = renderRateBucket;
480 displayStats.stats[layerKey].uid = uid;
481 displayStats.stats[layerKey].layerName = layerName;
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000482 displayStats.stats[layerKey].gameMode = gameMode;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800483 }
Ady Abraham8b9e6122021-01-26 19:11:45 -0800484 if (frameRateVote.frameRate > 0.0f) {
485 displayStats.stats[layerKey].setFrameRateVote = frameRateVote;
486 }
Alec Mouri7d436ec2021-01-27 20:40:50 -0800487 TimeStatsHelper::TimeStatsLayer& timeStatsLayer = displayStats.stats[layerKey];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700488 timeStatsLayer.totalFrames++;
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700489 timeStatsLayer.droppedFrames += layerRecord.droppedFrames;
Alec Mouri91f6df32020-01-30 08:48:58 -0800490 timeStatsLayer.lateAcquireFrames += layerRecord.lateAcquireFrames;
491 timeStatsLayer.badDesiredPresentFrames += layerRecord.badDesiredPresentFrames;
492
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700493 layerRecord.droppedFrames = 0;
Alec Mouri91f6df32020-01-30 08:48:58 -0800494 layerRecord.lateAcquireFrames = 0;
495 layerRecord.badDesiredPresentFrames = 0;
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700496
497 const int32_t postToAcquireMs = msBetween(timeRecords[0].frameTime.postTime,
498 timeRecords[0].frameTime.acquireTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800499 ALOGV("[%d]-[%" PRIu64 "]-post2acquire[%d]", layerId,
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700500 timeRecords[0].frameTime.frameNumber, postToAcquireMs);
501 timeStatsLayer.deltas["post2acquire"].insert(postToAcquireMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700502
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700503 const int32_t postToPresentMs = msBetween(timeRecords[0].frameTime.postTime,
504 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800505 ALOGV("[%d]-[%" PRIu64 "]-post2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700506 timeRecords[0].frameTime.frameNumber, postToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700507 timeStatsLayer.deltas["post2present"].insert(postToPresentMs);
508
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700509 const int32_t acquireToPresentMs = msBetween(timeRecords[0].frameTime.acquireTime,
510 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800511 ALOGV("[%d]-[%" PRIu64 "]-acquire2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700512 timeRecords[0].frameTime.frameNumber, acquireToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700513 timeStatsLayer.deltas["acquire2present"].insert(acquireToPresentMs);
514
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700515 const int32_t latchToPresentMs = msBetween(timeRecords[0].frameTime.latchTime,
516 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800517 ALOGV("[%d]-[%" PRIu64 "]-latch2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700518 timeRecords[0].frameTime.frameNumber, latchToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700519 timeStatsLayer.deltas["latch2present"].insert(latchToPresentMs);
520
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700521 const int32_t desiredToPresentMs = msBetween(timeRecords[0].frameTime.desiredTime,
522 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800523 ALOGV("[%d]-[%" PRIu64 "]-desired2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700524 timeRecords[0].frameTime.frameNumber, desiredToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700525 timeStatsLayer.deltas["desired2present"].insert(desiredToPresentMs);
526
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700527 const int32_t presentToPresentMs = msBetween(prevTimeRecord.frameTime.presentTime,
528 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800529 ALOGV("[%d]-[%" PRIu64 "]-present2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700530 timeRecords[0].frameTime.frameNumber, presentToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700531 timeStatsLayer.deltas["present2present"].insert(presentToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700532 }
533 prevTimeRecord = timeRecords[0];
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700534 timeRecords.pop_front();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700535 layerRecord.waitData--;
536 }
537}
538
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700539static constexpr const char* kPopupWindowPrefix = "PopupWindow";
540static const size_t kMinLenLayerName = std::strlen(kPopupWindowPrefix);
Yiwei Zhangbd408322018-10-15 18:31:53 -0700541
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700542// Avoid tracking the "PopupWindow:<random hash>#<number>" layers
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700543static bool layerNameIsValid(const std::string& layerName) {
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700544 return layerName.length() >= kMinLenLayerName &&
545 layerName.compare(0, kMinLenLayerName, kPopupWindowPrefix) != 0;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700546}
547
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000548bool TimeStats::canAddNewAggregatedStats(uid_t uid, const std::string& layerName,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700549 GameMode gameMode) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800550 uint32_t layerRecords = 0;
551 for (const auto& record : mTimeStats.stats) {
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000552 if (record.second.stats.count({uid, layerName, gameMode}) > 0) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800553 return true;
554 }
555
556 layerRecords += record.second.stats.size();
557 }
558
Dominik Laskowskib4ba8f52021-09-27 18:20:58 -0700559 return layerRecords < MAX_NUM_LAYER_STATS;
Alec Mouri9a29e672020-09-14 12:39:14 -0700560}
561
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800562void TimeStats::setPostTime(int32_t layerId, uint64_t frameNumber, const std::string& layerName,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700563 uid_t uid, nsecs_t postTime, GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700564 if (!mEnabled.load()) return;
565
566 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800567 ALOGV("[%d]-[%" PRIu64 "]-[%s]-PostTime[%" PRId64 "]", layerId, frameNumber, layerName.c_str(),
Yiwei Zhang8e8fe522018-11-02 18:34:07 -0700568 postTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700569
570 std::lock_guard<std::mutex> lock(mMutex);
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000571 if (!canAddNewAggregatedStats(uid, layerName, gameMode)) {
Yiwei Zhange926ab52019-08-14 15:16:00 -0700572 return;
573 }
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800574 if (!mTimeStatsTracker.count(layerId) && mTimeStatsTracker.size() < MAX_NUM_LAYER_RECORDS &&
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700575 layerNameIsValid(layerName)) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700576 mTimeStatsTracker[layerId].uid = uid;
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800577 mTimeStatsTracker[layerId].layerName = layerName;
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000578 mTimeStatsTracker[layerId].gameMode = gameMode;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700579 }
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800580 if (!mTimeStatsTracker.count(layerId)) return;
581 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700582 if (layerRecord.timeRecords.size() == MAX_NUM_TIME_RECORDS) {
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800583 ALOGE("[%d]-[%s]-timeRecords is at its maximum size[%zu]. Ignore this when unittesting.",
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800584 layerId, layerRecord.layerName.c_str(), MAX_NUM_TIME_RECORDS);
585 mTimeStatsTracker.erase(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700586 return;
587 }
588 // For most media content, the acquireFence is invalid because the buffer is
589 // ready at the queueBuffer stage. In this case, acquireTime should be given
590 // a default value as postTime.
591 TimeRecord timeRecord = {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700592 .frameTime =
593 {
594 .frameNumber = frameNumber,
595 .postTime = postTime,
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800596 .latchTime = postTime,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700597 .acquireTime = postTime,
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800598 .desiredTime = postTime,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700599 },
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700600 };
601 layerRecord.timeRecords.push_back(timeRecord);
602 if (layerRecord.waitData < 0 ||
603 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
604 layerRecord.waitData = layerRecord.timeRecords.size() - 1;
605}
606
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800607void TimeStats::setLatchTime(int32_t layerId, uint64_t frameNumber, nsecs_t latchTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700608 if (!mEnabled.load()) return;
609
610 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800611 ALOGV("[%d]-[%" PRIu64 "]-LatchTime[%" PRId64 "]", layerId, frameNumber, latchTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700612
613 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800614 if (!mTimeStatsTracker.count(layerId)) return;
615 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700616 if (layerRecord.waitData < 0 ||
617 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
618 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700619 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700620 if (timeRecord.frameTime.frameNumber == frameNumber) {
621 timeRecord.frameTime.latchTime = latchTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700622 }
623}
624
Alec Mouri91f6df32020-01-30 08:48:58 -0800625void TimeStats::incrementLatchSkipped(int32_t layerId, LatchSkipReason reason) {
626 if (!mEnabled.load()) return;
627
628 ATRACE_CALL();
629 ALOGV("[%d]-LatchSkipped-Reason[%d]", layerId,
630 static_cast<std::underlying_type<LatchSkipReason>::type>(reason));
631
632 std::lock_guard<std::mutex> lock(mMutex);
633 if (!mTimeStatsTracker.count(layerId)) return;
634 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
635
636 switch (reason) {
637 case LatchSkipReason::LateAcquire:
638 layerRecord.lateAcquireFrames++;
639 break;
640 }
641}
642
643void TimeStats::incrementBadDesiredPresent(int32_t layerId) {
644 if (!mEnabled.load()) return;
645
646 ATRACE_CALL();
647 ALOGV("[%d]-BadDesiredPresent", layerId);
648
649 std::lock_guard<std::mutex> lock(mMutex);
650 if (!mTimeStatsTracker.count(layerId)) return;
651 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
652 layerRecord.badDesiredPresentFrames++;
653}
654
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800655void TimeStats::setDesiredTime(int32_t layerId, uint64_t frameNumber, nsecs_t desiredTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700656 if (!mEnabled.load()) return;
657
658 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800659 ALOGV("[%d]-[%" PRIu64 "]-DesiredTime[%" PRId64 "]", layerId, frameNumber, desiredTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700660
661 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800662 if (!mTimeStatsTracker.count(layerId)) return;
663 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700664 if (layerRecord.waitData < 0 ||
665 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
666 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700667 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700668 if (timeRecord.frameTime.frameNumber == frameNumber) {
669 timeRecord.frameTime.desiredTime = desiredTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700670 }
671}
672
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800673void TimeStats::setAcquireTime(int32_t layerId, uint64_t frameNumber, nsecs_t acquireTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700674 if (!mEnabled.load()) return;
675
676 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800677 ALOGV("[%d]-[%" PRIu64 "]-AcquireTime[%" PRId64 "]", layerId, frameNumber, acquireTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700678
679 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800680 if (!mTimeStatsTracker.count(layerId)) return;
681 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700682 if (layerRecord.waitData < 0 ||
683 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
684 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700685 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700686 if (timeRecord.frameTime.frameNumber == frameNumber) {
687 timeRecord.frameTime.acquireTime = acquireTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700688 }
689}
690
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800691void TimeStats::setAcquireFence(int32_t layerId, uint64_t frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700692 const std::shared_ptr<FenceTime>& acquireFence) {
693 if (!mEnabled.load()) return;
694
695 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800696 ALOGV("[%d]-[%" PRIu64 "]-AcquireFenceTime[%" PRId64 "]", layerId, frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700697 acquireFence->getSignalTime());
698
699 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800700 if (!mTimeStatsTracker.count(layerId)) return;
701 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700702 if (layerRecord.waitData < 0 ||
703 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
704 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700705 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700706 if (timeRecord.frameTime.frameNumber == frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700707 timeRecord.acquireFence = acquireFence;
708 }
709}
710
Alec Mouri7d436ec2021-01-27 20:40:50 -0800711void TimeStats::setPresentTime(int32_t layerId, uint64_t frameNumber, nsecs_t presentTime,
Ady Abraham8b9e6122021-01-26 19:11:45 -0800712 Fps displayRefreshRate, std::optional<Fps> renderRate,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700713 SetFrameRateVote frameRateVote, GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700714 if (!mEnabled.load()) return;
715
716 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800717 ALOGV("[%d]-[%" PRIu64 "]-PresentTime[%" PRId64 "]", layerId, frameNumber, presentTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700718
719 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800720 if (!mTimeStatsTracker.count(layerId)) return;
721 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700722 if (layerRecord.waitData < 0 ||
723 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
724 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700725 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700726 if (timeRecord.frameTime.frameNumber == frameNumber) {
727 timeRecord.frameTime.presentTime = presentTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700728 timeRecord.ready = true;
729 layerRecord.waitData++;
730 }
731
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000732 flushAvailableRecordsToStatsLocked(layerId, displayRefreshRate, renderRate, frameRateVote,
733 gameMode);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700734}
735
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800736void TimeStats::setPresentFence(int32_t layerId, uint64_t frameNumber,
Alec Mouri7d436ec2021-01-27 20:40:50 -0800737 const std::shared_ptr<FenceTime>& presentFence,
Ady Abraham8b9e6122021-01-26 19:11:45 -0800738 Fps displayRefreshRate, std::optional<Fps> renderRate,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700739 SetFrameRateVote frameRateVote, GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700740 if (!mEnabled.load()) return;
741
742 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800743 ALOGV("[%d]-[%" PRIu64 "]-PresentFenceTime[%" PRId64 "]", layerId, frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700744 presentFence->getSignalTime());
745
746 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800747 if (!mTimeStatsTracker.count(layerId)) return;
748 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700749 if (layerRecord.waitData < 0 ||
750 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
751 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700752 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700753 if (timeRecord.frameTime.frameNumber == frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700754 timeRecord.presentFence = presentFence;
755 timeRecord.ready = true;
756 layerRecord.waitData++;
757 }
758
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000759 flushAvailableRecordsToStatsLocked(layerId, displayRefreshRate, renderRate, frameRateVote,
760 gameMode);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700761}
762
Adithya Srinivasanead17162021-02-18 02:17:37 +0000763static const constexpr int32_t kValidJankyReason = JankType::DisplayHAL |
764 JankType::SurfaceFlingerCpuDeadlineMissed | JankType::SurfaceFlingerGpuDeadlineMissed |
765 JankType::AppDeadlineMissed | JankType::PredictionError |
Adithya Srinivasan53e5c402021-04-16 17:34:30 +0000766 JankType::SurfaceFlingerScheduling;
Alec Mouri363faf02021-01-29 16:34:55 -0800767
Alec Mouri9a29e672020-09-14 12:39:14 -0700768template <class T>
769static void updateJankPayload(T& t, int32_t reasons) {
770 t.jankPayload.totalFrames++;
771
Alec Mouri9a29e672020-09-14 12:39:14 -0700772 if (reasons & kValidJankyReason) {
773 t.jankPayload.totalJankyFrames++;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800774 if ((reasons & JankType::SurfaceFlingerCpuDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700775 t.jankPayload.totalSFLongCpu++;
776 }
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100777 if ((reasons & JankType::SurfaceFlingerGpuDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700778 t.jankPayload.totalSFLongGpu++;
779 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800780 if ((reasons & JankType::DisplayHAL) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700781 t.jankPayload.totalSFUnattributed++;
782 }
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100783 if ((reasons & JankType::AppDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700784 t.jankPayload.totalAppUnattributed++;
785 }
Adithya Srinivasanead17162021-02-18 02:17:37 +0000786 if ((reasons & JankType::PredictionError) != 0) {
787 t.jankPayload.totalSFPredictionError++;
788 }
789 if ((reasons & JankType::SurfaceFlingerScheduling) != 0) {
790 t.jankPayload.totalSFScheduling++;
791 }
Adithya Srinivasan53e5c402021-04-16 17:34:30 +0000792 }
793
794 // We want to track BufferStuffing separately as it can provide info on latency issues
795 if (reasons & JankType::BufferStuffing) {
796 t.jankPayload.totalAppBufferStuffing++;
Alec Mouri9a29e672020-09-14 12:39:14 -0700797 }
798}
799
Alec Mouri363faf02021-01-29 16:34:55 -0800800void TimeStats::incrementJankyFrames(const JankyFramesInfo& info) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700801 if (!mEnabled.load()) return;
802
803 ATRACE_CALL();
804 std::lock_guard<std::mutex> lock(mMutex);
805
Alec Mouri542de112020-11-13 12:07:32 -0800806 // Only update layer stats if we're already tracking the layer in TimeStats.
807 // Otherwise, continue tracking the statistic but use a default layer name instead.
Alec Mouri9a29e672020-09-14 12:39:14 -0700808 // As an implementation detail, we do this because this method is expected to be
Alec Mouri542de112020-11-13 12:07:32 -0800809 // called from FrameTimeline, whose jank classification includes transaction jank
810 // that occurs without a buffer. But, in general those layer names are not suitable as
811 // aggregation keys: e.g., it's normal and expected for Window Manager to include the hash code
812 // for an animation leash. So while we can show that jank in dumpsys, aggregating based on the
813 // layer blows up the stats size, so as a workaround drop those stats. This assumes that
814 // TimeStats will flush the first present fence for a layer *before* FrameTimeline does so that
815 // the first jank record is not dropped.
Alec Mouri9a29e672020-09-14 12:39:14 -0700816
Alec Mouri542de112020-11-13 12:07:32 -0800817 static const std::string kDefaultLayerName = "none";
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700818 constexpr GameMode kDefaultGameMode = GameMode::Unsupported;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800819
Alec Mouri363faf02021-01-29 16:34:55 -0800820 const int32_t refreshRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700821 clampToNearestBucket(info.refreshRate, REFRESH_RATE_BUCKET_WIDTH);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800822 const int32_t renderRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700823 clampToNearestBucket(info.renderRate ? *info.renderRate : info.refreshRate,
824 RENDER_RATE_BUCKET_WIDTH);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800825 const TimeStatsHelper::TimelineStatsKey timelineKey = {refreshRateBucket, renderRateBucket};
826
827 if (!mTimeStats.stats.count(timelineKey)) {
828 mTimeStats.stats[timelineKey].key = timelineKey;
Alec Mouri9a29e672020-09-14 12:39:14 -0700829 }
830
Alec Mouri7d436ec2021-01-27 20:40:50 -0800831 TimeStatsHelper::TimelineStats& timelineStats = mTimeStats.stats[timelineKey];
832
Alec Mouri363faf02021-01-29 16:34:55 -0800833 updateJankPayload<TimeStatsHelper::TimelineStats>(timelineStats, info.reasons);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800834
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000835 TimeStatsHelper::LayerStatsKey layerKey = {info.uid, info.layerName, info.gameMode};
Alec Mouri7d436ec2021-01-27 20:40:50 -0800836 if (!timelineStats.stats.count(layerKey)) {
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000837 layerKey = {info.uid, kDefaultLayerName, kDefaultGameMode};
Alec Mouri7d436ec2021-01-27 20:40:50 -0800838 timelineStats.stats[layerKey].displayRefreshRateBucket = refreshRateBucket;
839 timelineStats.stats[layerKey].renderRateBucket = renderRateBucket;
Alec Mouri363faf02021-01-29 16:34:55 -0800840 timelineStats.stats[layerKey].uid = info.uid;
Adithya Srinivasanf427f762021-06-15 19:46:26 +0000841 timelineStats.stats[layerKey].layerName = kDefaultLayerName;
842 timelineStats.stats[layerKey].gameMode = kDefaultGameMode;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800843 }
844
845 TimeStatsHelper::TimeStatsLayer& timeStatsLayer = timelineStats.stats[layerKey];
Alec Mouri363faf02021-01-29 16:34:55 -0800846 updateJankPayload<TimeStatsHelper::TimeStatsLayer>(timeStatsLayer, info.reasons);
847
848 if (info.reasons & kValidJankyReason) {
849 // TimeStats Histograms only retain positive values, so we don't need to check if these
850 // deadlines were really missed if we know that the frame had jank, since deadlines
851 // that were met will be dropped.
Ady Abraham3e8cc072021-05-11 16:29:54 -0700852 timelineStats.displayDeadlineDeltas.insert(toMs(info.displayDeadlineDelta));
853 timelineStats.displayPresentDeltas.insert(toMs(info.displayPresentJitter));
854 timeStatsLayer.deltas["appDeadlineDeltas"].insert(toMs(info.appDeadlineDelta));
Alec Mouri363faf02021-01-29 16:34:55 -0800855 }
Alec Mouri9a29e672020-09-14 12:39:14 -0700856}
857
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800858void TimeStats::onDestroy(int32_t layerId) {
Yiwei Zhangdc224042018-10-18 15:34:00 -0700859 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800860 ALOGV("[%d]-onDestroy", layerId);
Mikael Pessa90092f42019-08-26 17:22:04 -0700861 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800862 mTimeStatsTracker.erase(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700863}
864
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800865void TimeStats::removeTimeRecord(int32_t layerId, uint64_t frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700866 if (!mEnabled.load()) return;
867
868 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800869 ALOGV("[%d]-[%" PRIu64 "]-removeTimeRecord", layerId, frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700870
871 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800872 if (!mTimeStatsTracker.count(layerId)) return;
873 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700874 size_t removeAt = 0;
875 for (const TimeRecord& record : layerRecord.timeRecords) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700876 if (record.frameTime.frameNumber == frameNumber) break;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700877 removeAt++;
878 }
879 if (removeAt == layerRecord.timeRecords.size()) return;
880 layerRecord.timeRecords.erase(layerRecord.timeRecords.begin() + removeAt);
881 if (layerRecord.waitData > static_cast<int32_t>(removeAt)) {
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700882 layerRecord.waitData--;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700883 }
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700884 layerRecord.droppedFrames++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700885}
886
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700887void TimeStats::flushPowerTimeLocked() {
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700888 if (!mEnabled.load()) return;
889
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700890 nsecs_t curTime = systemTime();
891 // elapsedTime is in milliseconds.
892 int64_t elapsedTime = (curTime - mPowerTime.prevTime) / 1000000;
893
894 switch (mPowerTime.powerMode) {
Peiyong Lin65248e02020-04-18 21:15:07 -0700895 case PowerMode::ON:
Alec Mouri7d436ec2021-01-27 20:40:50 -0800896 mTimeStats.displayOnTimeLegacy += elapsedTime;
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700897 break;
Peiyong Lin65248e02020-04-18 21:15:07 -0700898 case PowerMode::OFF:
899 case PowerMode::DOZE:
900 case PowerMode::DOZE_SUSPEND:
901 case PowerMode::ON_SUSPEND:
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700902 default:
903 break;
904 }
905
906 mPowerTime.prevTime = curTime;
907}
908
Peiyong Lin65248e02020-04-18 21:15:07 -0700909void TimeStats::setPowerMode(PowerMode powerMode) {
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700910 if (!mEnabled.load()) {
911 std::lock_guard<std::mutex> lock(mMutex);
912 mPowerTime.powerMode = powerMode;
913 return;
914 }
915
916 std::lock_guard<std::mutex> lock(mMutex);
917 if (powerMode == mPowerTime.powerMode) return;
918
919 flushPowerTimeLocked();
920 mPowerTime.powerMode = powerMode;
921}
922
Alec Mourifb571ea2019-01-24 18:42:10 -0800923void TimeStats::recordRefreshRate(uint32_t fps, nsecs_t duration) {
924 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800925 if (mTimeStats.refreshRateStatsLegacy.count(fps)) {
926 mTimeStats.refreshRateStatsLegacy[fps] += duration;
Alec Mourifb571ea2019-01-24 18:42:10 -0800927 } else {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800928 mTimeStats.refreshRateStatsLegacy.insert({fps, duration});
Alec Mourifb571ea2019-01-24 18:42:10 -0800929 }
930}
931
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700932void TimeStats::flushAvailableGlobalRecordsToStatsLocked() {
933 ATRACE_CALL();
934
935 while (!mGlobalRecord.presentFences.empty()) {
936 const nsecs_t curPresentTime = mGlobalRecord.presentFences.front()->getSignalTime();
937 if (curPresentTime == Fence::SIGNAL_TIME_PENDING) break;
938
939 if (curPresentTime == Fence::SIGNAL_TIME_INVALID) {
940 ALOGE("GlobalPresentFence is invalid!");
941 mGlobalRecord.prevPresentTime = 0;
942 mGlobalRecord.presentFences.pop_front();
943 continue;
944 }
945
946 ALOGV("GlobalPresentFenceTime[%" PRId64 "]",
947 mGlobalRecord.presentFences.front()->getSignalTime());
948
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700949 if (mGlobalRecord.prevPresentTime != 0) {
950 const int32_t presentToPresentMs =
951 msBetween(mGlobalRecord.prevPresentTime, curPresentTime);
952 ALOGV("Global present2present[%d] prev[%" PRId64 "] curr[%" PRId64 "]",
953 presentToPresentMs, mGlobalRecord.prevPresentTime, curPresentTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800954 mTimeStats.presentToPresentLegacy.insert(presentToPresentMs);
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700955 }
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700956
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700957 mGlobalRecord.prevPresentTime = curPresentTime;
958 mGlobalRecord.presentFences.pop_front();
959 }
Alec Mourie4034bb2019-11-19 12:45:54 -0800960 while (!mGlobalRecord.renderEngineDurations.empty()) {
961 const auto duration = mGlobalRecord.renderEngineDurations.front();
962 const auto& endTime = duration.endTime;
963
964 nsecs_t endNs = -1;
965
966 if (auto val = std::get_if<nsecs_t>(&endTime)) {
967 endNs = *val;
968 } else {
969 endNs = std::get<std::shared_ptr<FenceTime>>(endTime)->getSignalTime();
970 }
971
972 if (endNs == Fence::SIGNAL_TIME_PENDING) break;
973
974 if (endNs < 0) {
975 ALOGE("RenderEngineTiming is invalid!");
976 mGlobalRecord.renderEngineDurations.pop_front();
977 continue;
978 }
979
980 const int32_t renderEngineMs = msBetween(duration.startTime, endNs);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800981 mTimeStats.renderEngineTimingLegacy.insert(renderEngineMs);
Alec Mourie4034bb2019-11-19 12:45:54 -0800982
983 mGlobalRecord.renderEngineDurations.pop_front();
984 }
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700985}
986
987void TimeStats::setPresentFenceGlobal(const std::shared_ptr<FenceTime>& presentFence) {
988 if (!mEnabled.load()) return;
989
990 ATRACE_CALL();
991 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700992 if (presentFence == nullptr || !presentFence->isValid()) {
993 mGlobalRecord.prevPresentTime = 0;
994 return;
995 }
996
Peiyong Lin65248e02020-04-18 21:15:07 -0700997 if (mPowerTime.powerMode != PowerMode::ON) {
998 // Try flushing the last present fence on PowerMode::ON.
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700999 flushAvailableGlobalRecordsToStatsLocked();
1000 mGlobalRecord.presentFences.clear();
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001001 mGlobalRecord.prevPresentTime = 0;
1002 return;
1003 }
1004
1005 if (mGlobalRecord.presentFences.size() == MAX_NUM_TIME_RECORDS) {
1006 // The front presentFence must be trapped in pending status in this
1007 // case. Try dequeuing the front one to recover.
1008 ALOGE("GlobalPresentFences is already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
1009 mGlobalRecord.prevPresentTime = 0;
1010 mGlobalRecord.presentFences.pop_front();
1011 }
1012
1013 mGlobalRecord.presentFences.emplace_back(presentFence);
1014 flushAvailableGlobalRecordsToStatsLocked();
1015}
1016
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001017void TimeStats::enable() {
1018 if (mEnabled.load()) return;
1019
1020 ATRACE_CALL();
1021
1022 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001023 mEnabled.store(true);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001024 mTimeStats.statsStartLegacy = static_cast<int64_t>(std::time(0));
Yiwei Zhang3a226d22018-10-16 09:23:03 -07001025 mPowerTime.prevTime = systemTime();
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001026 ALOGD("Enabled");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001027}
1028
1029void TimeStats::disable() {
1030 if (!mEnabled.load()) return;
1031
1032 ATRACE_CALL();
1033
1034 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001035 flushPowerTimeLocked();
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001036 mEnabled.store(false);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001037 mTimeStats.statsEndLegacy = static_cast<int64_t>(std::time(0));
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001038 ALOGD("Disabled");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001039}
1040
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001041void TimeStats::clearAll() {
1042 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham3403a3f2021-04-27 16:58:40 -07001043 mTimeStats.stats.clear();
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001044 clearGlobalLocked();
1045 clearLayersLocked();
1046}
1047
1048void TimeStats::clearGlobalLocked() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001049 ATRACE_CALL();
1050
Alec Mouri7d436ec2021-01-27 20:40:50 -08001051 mTimeStats.statsStartLegacy = (mEnabled.load() ? static_cast<int64_t>(std::time(0)) : 0);
1052 mTimeStats.statsEndLegacy = 0;
1053 mTimeStats.totalFramesLegacy = 0;
1054 mTimeStats.missedFramesLegacy = 0;
1055 mTimeStats.clientCompositionFramesLegacy = 0;
1056 mTimeStats.clientCompositionReusedFramesLegacy = 0;
Robert Carra00eb142022-03-09 13:49:30 -08001057 mTimeStats.compositionStrategyChangesLegacy = 0;
Vishnu Nair9cf89262022-02-26 09:17:49 -08001058 mTimeStats.compositionStrategyPredictedLegacy = 0;
1059 mTimeStats.compositionStrategyPredictionSucceededLegacy = 0;
1060 mTimeStats.refreshRateSwitchesLegacy = 0;
Alec Mouri7d436ec2021-01-27 20:40:50 -08001061 mTimeStats.displayEventConnectionsCountLegacy = 0;
1062 mTimeStats.displayOnTimeLegacy = 0;
1063 mTimeStats.presentToPresentLegacy.hist.clear();
1064 mTimeStats.frameDurationLegacy.hist.clear();
1065 mTimeStats.renderEngineTimingLegacy.hist.clear();
1066 mTimeStats.refreshRateStatsLegacy.clear();
Yiwei Zhang3a226d22018-10-16 09:23:03 -07001067 mPowerTime.prevTime = systemTime();
Alec Mouri56e63852021-03-09 18:17:25 -08001068 for (auto& globalRecord : mTimeStats.stats) {
1069 globalRecord.second.clearGlobals();
1070 }
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001071 mGlobalRecord.prevPresentTime = 0;
1072 mGlobalRecord.presentFences.clear();
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001073 ALOGD("Cleared global stats");
1074}
1075
1076void TimeStats::clearLayersLocked() {
1077 ATRACE_CALL();
1078
1079 mTimeStatsTracker.clear();
Alec Mouri56e63852021-03-09 18:17:25 -08001080
1081 for (auto& globalRecord : mTimeStats.stats) {
1082 globalRecord.second.stats.clear();
1083 }
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001084 ALOGD("Cleared layer stats");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001085}
1086
1087bool TimeStats::isEnabled() {
1088 return mEnabled.load();
1089}
1090
Yiwei Zhang5434a782018-12-05 18:06:32 -08001091void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, std::string& result) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001092 ATRACE_CALL();
1093
1094 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001095 if (mTimeStats.statsStartLegacy == 0) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001096 return;
1097 }
1098
Alec Mouri7d436ec2021-01-27 20:40:50 -08001099 mTimeStats.statsEndLegacy = static_cast<int64_t>(std::time(0));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001100
Yiwei Zhang3a226d22018-10-16 09:23:03 -07001101 flushPowerTimeLocked();
1102
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001103 if (asProto) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001104 ALOGD("Dumping TimeStats as proto");
Yiwei Zhangdc224042018-10-18 15:34:00 -07001105 SFTimeStatsGlobalProto timeStatsProto = mTimeStats.toProto(maxLayers);
Dominik Laskowski46470112019-08-02 13:13:11 -07001106 result.append(timeStatsProto.SerializeAsString());
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001107 } else {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001108 ALOGD("Dumping TimeStats as text");
Yiwei Zhang5434a782018-12-05 18:06:32 -08001109 result.append(mTimeStats.toString(maxLayers));
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001110 result.append("\n");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001111 }
1112}
1113
Alec Mourifb571ea2019-01-24 18:42:10 -08001114} // namespace impl
1115
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001116} // namespace android