1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "JankTracker.h"
18
19 #include <cutils/ashmem.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <log/log.h>
23 #include <sys/mman.h>
24
25 #include <algorithm>
26 #include <cmath>
27 #include <cstdio>
28 #include <limits>
29 #include <sstream>
30
31 #include "DeviceInfo.h"
32 #include "Properties.h"
33 #include "utils/TimeUtils.h"
34 #include "utils/Trace.h"
35
36 namespace android {
37 namespace uirenderer {
38
39 struct Comparison {
40 JankType type;
41 std::function<int64_t(nsecs_t)> computeThreadshold;
42 FrameInfoIndex start;
43 FrameInfoIndex end;
44 };
45
46 static const std::array<Comparison, 4> COMPARISONS{
__anon082b4a060102() 47 Comparison{JankType::kMissedVsync, [](nsecs_t) { return 1; }, FrameInfoIndex::IntendedVsync,
48 FrameInfoIndex::Vsync},
49
50 Comparison{JankType::kSlowUI,
__anon082b4a060202() 51 [](nsecs_t frameInterval) { return static_cast<int64_t>(.5 * frameInterval); },
52 FrameInfoIndex::Vsync, FrameInfoIndex::SyncStart},
53
54 Comparison{JankType::kSlowSync,
__anon082b4a060302() 55 [](nsecs_t frameInterval) { return static_cast<int64_t>(.2 * frameInterval); },
56 FrameInfoIndex::SyncStart, FrameInfoIndex::IssueDrawCommandsStart},
57
58 Comparison{JankType::kSlowRT,
__anon082b4a060402() 59 [](nsecs_t frameInterval) { return static_cast<int64_t>(.75 * frameInterval); },
60 FrameInfoIndex::IssueDrawCommandsStart, FrameInfoIndex::FrameCompleted},
61 };
62
63 // If the event exceeds 10 seconds throw it away, this isn't a jank event
64 // it's an ANR and will be handled as such
65 static const int64_t IGNORE_EXCEEDING = seconds_to_nanoseconds(10);
66
67 /*
68 * We don't track direct-drawing via Surface:lockHardwareCanvas()
69 * for now
70 *
71 * TODO: kSurfaceCanvas can negatively impact other drawing by using up
72 * time on the RenderThread, figure out how to attribute that as a jank-causer
73 */
74 static const int64_t EXEMPT_FRAMES_FLAGS = FrameInfoFlags::SurfaceCanvas;
75
76 // For testing purposes to try and eliminate test infra overhead we will
77 // consider any unknown delay of frame start as part of the test infrastructure
78 // and filter it out of the frame profile data
79 static FrameInfoIndex sFrameStart = FrameInfoIndex::IntendedVsync;
80
JankTracker(ProfileDataContainer * globalData)81 JankTracker::JankTracker(ProfileDataContainer* globalData)
82 : mData(globalData->getDataMutex())
83 , mDataMutex(globalData->getDataMutex()) {
84 mGlobalData = globalData;
85 nsecs_t frameIntervalNanos = DeviceInfo::getVsyncPeriod();
86 nsecs_t sfOffset = DeviceInfo::getCompositorOffset();
87 nsecs_t offsetDelta = sfOffset - DeviceInfo::getAppOffset();
88 // There are two different offset cases. If the offsetDelta is positive
89 // and small, then the intention is to give apps extra time by leveraging
90 // pipelining between the UI & RT threads. If the offsetDelta is large or
91 // negative, the intention is to subtract time from the total duration
92 // in which case we can't afford to wait for dequeueBuffer blockage.
93 if (offsetDelta <= 4_ms && offsetDelta >= 0) {
94 // SF will begin composition at VSYNC-app + offsetDelta. If we are triple
95 // buffered, this is the expected time at which dequeueBuffer will
96 // return due to the staggering of VSYNC-app & VSYNC-sf.
97 mDequeueTimeForgivenessLegacy = offsetDelta + 4_ms;
98 }
99 mFrameIntervalLegacy = frameIntervalNanos;
100 }
101
calculateLegacyJank(FrameInfo & frame)102 void JankTracker::calculateLegacyJank(FrameInfo& frame) REQUIRES(mDataMutex) {
103 // Fast-path for jank-free frames
104 int64_t totalDuration = frame.duration(sFrameStart, FrameInfoIndex::SwapBuffersCompleted);
105 if (mDequeueTimeForgivenessLegacy && frame[FrameInfoIndex::DequeueBufferDuration] > 500_us) {
106 nsecs_t expectedDequeueDuration = mDequeueTimeForgivenessLegacy
107 + frame[FrameInfoIndex::Vsync]
108 - frame[FrameInfoIndex::IssueDrawCommandsStart];
109 if (expectedDequeueDuration > 0) {
110 // Forgive only up to the expected amount, but not more than
111 // the actual time spent blocked.
112 nsecs_t forgiveAmount =
113 std::min(expectedDequeueDuration, frame[FrameInfoIndex::DequeueBufferDuration]);
114 LOG_ALWAYS_FATAL_IF(forgiveAmount >= totalDuration,
115 "Impossible dequeue duration! dequeue duration reported %" PRId64
116 ", total duration %" PRId64,
117 forgiveAmount, totalDuration);
118 totalDuration -= forgiveAmount;
119 }
120 }
121
122 LOG_ALWAYS_FATAL_IF(totalDuration <= 0, "Impossible totalDuration %" PRId64 " start=%" PRIi64
123 " gpuComplete=%" PRIi64, totalDuration,
124 frame[FrameInfoIndex::IntendedVsync],
125 frame[FrameInfoIndex::GpuCompleted]);
126
127
128 // Only things like Surface.lockHardwareCanvas() are exempt from tracking
129 if (CC_UNLIKELY(frame[FrameInfoIndex::Flags] & EXEMPT_FRAMES_FLAGS)) {
130 return;
131 }
132
133 if (totalDuration > mFrameIntervalLegacy) {
134 mData->reportJankLegacy();
135 (*mGlobalData)->reportJankLegacy();
136 }
137
138 if (mSwapDeadlineLegacy < 0) {
139 mSwapDeadlineLegacy = frame[FrameInfoIndex::IntendedVsync] + mFrameIntervalLegacy;
140 }
141 bool isTripleBuffered = (mSwapDeadlineLegacy - frame[FrameInfoIndex::IntendedVsync])
142 > (mFrameIntervalLegacy * 0.1);
143
144 mSwapDeadlineLegacy = std::max(mSwapDeadlineLegacy + mFrameIntervalLegacy,
145 frame[FrameInfoIndex::IntendedVsync] + mFrameIntervalLegacy);
146
147 // If we hit the deadline, cool!
148 if (frame[FrameInfoIndex::FrameCompleted] < mSwapDeadlineLegacy
149 || totalDuration < mFrameIntervalLegacy) {
150 if (isTripleBuffered) {
151 mData->reportJankType(JankType::kHighInputLatency);
152 (*mGlobalData)->reportJankType(JankType::kHighInputLatency);
153 }
154 return;
155 }
156
157 mData->reportJankType(JankType::kMissedDeadlineLegacy);
158 (*mGlobalData)->reportJankType(JankType::kMissedDeadlineLegacy);
159
160 // Janked, reset the swap deadline
161 nsecs_t jitterNanos = frame[FrameInfoIndex::FrameCompleted] - frame[FrameInfoIndex::Vsync];
162 nsecs_t lastFrameOffset = jitterNanos % mFrameIntervalLegacy;
163 mSwapDeadlineLegacy = frame[FrameInfoIndex::FrameCompleted]
164 - lastFrameOffset + mFrameIntervalLegacy;
165 }
166
finishFrame(FrameInfo & frame,std::unique_ptr<FrameMetricsReporter> & reporter)167 void JankTracker::finishFrame(FrameInfo& frame, std::unique_ptr<FrameMetricsReporter>& reporter) {
168 std::lock_guard lock(mDataMutex);
169
170 calculateLegacyJank(frame);
171
172 // Fast-path for jank-free frames
173 int64_t totalDuration = frame.duration(FrameInfoIndex::IntendedVsync,
174 FrameInfoIndex::FrameCompleted);
175
176 LOG_ALWAYS_FATAL_IF(totalDuration <= 0, "Impossible totalDuration %" PRId64, totalDuration);
177 mData->reportFrame(totalDuration);
178 (*mGlobalData)->reportFrame(totalDuration);
179
180 // Only things like Surface.lockHardwareCanvas() are exempt from tracking
181 if (CC_UNLIKELY(frame[FrameInfoIndex::Flags] & EXEMPT_FRAMES_FLAGS)) {
182 return;
183 }
184
185 int64_t frameInterval = frame[FrameInfoIndex::FrameInterval];
186
187 // If we starter earlier than the intended frame start assuming an unstuffed scenario, it means
188 // that we are in a triple buffering situation.
189 bool isTripleBuffered = (mNextFrameStartUnstuffed - frame[FrameInfoIndex::IntendedVsync])
190 > (frameInterval * 0.1);
191
192 int64_t deadline = frame[FrameInfoIndex::FrameDeadline];
193
194 // If we are in triple buffering, we have enough buffers in queue to sustain a single frame
195 // drop without jank, so adjust the frame interval to the deadline.
196 if (isTripleBuffered) {
197 deadline += frameInterval;
198 frame.set(FrameInfoIndex::FrameDeadline) += frameInterval;
199 }
200
201 // If we hit the deadline, cool!
202 if (frame[FrameInfoIndex::GpuCompleted] < deadline) {
203 if (isTripleBuffered) {
204 mData->reportJankType(JankType::kHighInputLatency);
205 (*mGlobalData)->reportJankType(JankType::kHighInputLatency);
206
207 // Buffer stuffing state gets carried over to next frame, unless there is a "pause"
208 mNextFrameStartUnstuffed += frameInterval;
209 }
210 } else {
211 mData->reportJankType(JankType::kMissedDeadline);
212 (*mGlobalData)->reportJankType(JankType::kMissedDeadline);
213 mData->reportJank();
214 (*mGlobalData)->reportJank();
215
216 // Janked, store the adjust deadline to detect triple buffering in next frame correctly.
217 nsecs_t jitterNanos = frame[FrameInfoIndex::GpuCompleted]
218 - frame[FrameInfoIndex::Vsync];
219 nsecs_t lastFrameOffset = jitterNanos % frameInterval;
220
221 // Note the time when the next frame would start in an unstuffed situation. If it starts
222 // earlier, we are in a stuffed situation.
223 mNextFrameStartUnstuffed = frame[FrameInfoIndex::GpuCompleted]
224 - lastFrameOffset + frameInterval;
225
226 recomputeThresholds(frameInterval);
227 for (auto& comparison : COMPARISONS) {
228 int64_t delta = frame.duration(comparison.start, comparison.end);
229 if (delta >= mThresholds[comparison.type] && delta < IGNORE_EXCEEDING) {
230 mData->reportJankType(comparison.type);
231 (*mGlobalData)->reportJankType(comparison.type);
232 }
233 }
234
235 // Log daveys since they are weird and we don't know what they are (b/70339576)
236 if (totalDuration >= 700_ms) {
237 static int sDaveyCount = 0;
238 std::stringstream ss;
239 ss << "Davey! duration=" << ns2ms(totalDuration) << "ms; ";
240 for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
241 ss << FrameInfoNames[i] << "=" << frame[i] << ", ";
242 }
243 ALOGI("%s", ss.str().c_str());
244 // Just so we have something that counts up, the value is largely irrelevant
245 ATRACE_INT(ss.str().c_str(), ++sDaveyCount);
246 }
247 }
248
249 int64_t totalGPUDrawTime = frame.gpuDrawTime();
250 if (totalGPUDrawTime >= 0) {
251 mData->reportGPUFrame(totalGPUDrawTime);
252 (*mGlobalData)->reportGPUFrame(totalGPUDrawTime);
253 }
254
255 if (CC_UNLIKELY(reporter.get() != nullptr)) {
256 reporter->reportFrameMetrics(frame.data(), false /* hasPresentTime */);
257 }
258 }
259
recomputeThresholds(int64_t frameBudget)260 void JankTracker::recomputeThresholds(int64_t frameBudget) REQUIRES(mDataMutex) {
261 if (mThresholdsFrameBudget == frameBudget) {
262 return;
263 }
264 mThresholdsFrameBudget = frameBudget;
265 for (auto& comparison : COMPARISONS) {
266 mThresholds[comparison.type] = comparison.computeThreadshold(frameBudget);
267 }
268 }
269
dumpData(int fd,const ProfileDataDescription * description,const ProfileData * data)270 void JankTracker::dumpData(int fd, const ProfileDataDescription* description,
271 const ProfileData* data) {
272
273 if (description) {
274 switch (description->type) {
275 case JankTrackerType::Generic:
276 break;
277 case JankTrackerType::Package:
278 dprintf(fd, "\nPackage: %s", description->name.c_str());
279 break;
280 case JankTrackerType::Window:
281 dprintf(fd, "\nWindow: %s", description->name.c_str());
282 break;
283 }
284 }
285 if (sFrameStart != FrameInfoIndex::IntendedVsync) {
286 dprintf(fd, "\nNote: Data has been filtered!");
287 }
288 data->dump(fd);
289 dprintf(fd, "\n");
290 }
291
dumpFrames(int fd)292 void JankTracker::dumpFrames(int fd) {
293 dprintf(fd, "\n\n---PROFILEDATA---\n");
294 for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
295 dprintf(fd, "%s", FrameInfoNames[i]);
296 dprintf(fd, ",");
297 }
298 for (size_t i = 0; i < mFrames.size(); i++) {
299 FrameInfo& frame = mFrames[i];
300 if (frame[FrameInfoIndex::SyncStart] == 0) {
301 continue;
302 }
303 dprintf(fd, "\n");
304 for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) {
305 dprintf(fd, "%" PRId64 ",", frame[i]);
306 }
307 }
308 dprintf(fd, "\n---PROFILEDATA---\n\n");
309 }
310
reset()311 void JankTracker::reset() REQUIRES(mDataMutex) {
312 mFrames.clear();
313 mData->reset();
314 (*mGlobalData)->reset();
315 sFrameStart = Properties::filterOutTestOverhead ? FrameInfoIndex::HandleInputStart
316 : FrameInfoIndex::IntendedVsync;
317 }
318
319 } /* namespace uirenderer */
320 } /* namespace android */
321