blob: 47d01088f6f74894281b94fc4e2b8305081f9067 [file] [log] [blame]
John Reckba6adf62015-02-19 14:36:50 -08001/*
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#include "JankTracker.h"
17
John Reckc7cd9cf2016-03-28 10:38:19 -070018#include "Properties.h"
19
John Recke70c5752015-03-06 14:40:50 -080020#include <algorithm>
John Reckedc524c2015-03-18 15:24:33 -070021#include <cutils/ashmem.h>
22#include <cutils/log.h>
John Reckba6adf62015-02-19 14:36:50 -080023#include <cstdio>
John Reckedc524c2015-03-18 15:24:33 -070024#include <errno.h>
John Reckba6adf62015-02-19 14:36:50 -080025#include <inttypes.h>
John Reck5ed587f2016-03-24 15:57:01 -070026#include <limits>
27#include <cmath>
John Reckedc524c2015-03-18 15:24:33 -070028#include <sys/mman.h>
John Reckba6adf62015-02-19 14:36:50 -080029
30namespace android {
31namespace uirenderer {
32
33static const char* JANK_TYPE_NAMES[] = {
34 "Missed Vsync",
35 "High input latency",
36 "Slow UI thread",
37 "Slow bitmap uploads",
John Reckbe3fba02015-07-06 13:49:58 -070038 "Slow issue draw commands",
John Reckba6adf62015-02-19 14:36:50 -080039};
40
41struct Comparison {
John Reckc87be992015-02-20 10:57:22 -080042 FrameInfoIndex start;
43 FrameInfoIndex end;
John Reckba6adf62015-02-19 14:36:50 -080044};
45
46static const Comparison COMPARISONS[] = {
Chris Craik1b54fb22015-06-02 17:40:58 -070047 {FrameInfoIndex::IntendedVsync, FrameInfoIndex::Vsync},
48 {FrameInfoIndex::OldestInputEvent, FrameInfoIndex::Vsync},
49 {FrameInfoIndex::Vsync, FrameInfoIndex::SyncStart},
50 {FrameInfoIndex::SyncStart, FrameInfoIndex::IssueDrawCommandsStart},
51 {FrameInfoIndex::IssueDrawCommandsStart, FrameInfoIndex::FrameCompleted},
John Reckba6adf62015-02-19 14:36:50 -080052};
53
54// If the event exceeds 10 seconds throw it away, this isn't a jank event
55// it's an ANR and will be handled as such
56static const int64_t IGNORE_EXCEEDING = seconds_to_nanoseconds(10);
57
58/*
59 * Frames that are exempt from jank metrics.
60 * First-draw frames, for example, are expected to
61 * be slow, this is hidden from the user with window animations and
62 * other tricks
63 *
64 * Similarly, we don't track direct-drawing via Surface:lockHardwareCanvas()
65 * for now
66 *
67 * TODO: kSurfaceCanvas can negatively impact other drawing by using up
68 * time on the RenderThread, figure out how to attribute that as a jank-causer
69 */
70static const int64_t EXEMPT_FRAMES_FLAGS
Chris Craik1b54fb22015-06-02 17:40:58 -070071 = FrameInfoFlags::WindowLayoutChanged
72 | FrameInfoFlags::SurfaceCanvas;
John Reckba6adf62015-02-19 14:36:50 -080073
John Reckedc524c2015-03-18 15:24:33 -070074// The bucketing algorithm controls so to speak
75// If a frame is <= to this it goes in bucket 0
76static const uint32_t kBucketMinThreshold = 7;
77// If a frame is > this, start counting in increments of 2ms
78static const uint32_t kBucket2msIntervals = 32;
79// If a frame is > this, start counting in increments of 4ms
80static const uint32_t kBucket4msIntervals = 48;
81
John Reckc7cd9cf2016-03-28 10:38:19 -070082// For testing purposes to try and eliminate test infra overhead we will
83// consider any unknown delay of frame start as part of the test infrastructure
84// and filter it out of the frame profile data
85static FrameInfoIndex sFrameStart = FrameInfoIndex::IntendedVsync;
86
John Reckedc524c2015-03-18 15:24:33 -070087// This will be called every frame, performance sensitive
88// Uses bit twiddling to avoid branching while achieving the packing desired
89static uint32_t frameCountIndexForFrameTime(nsecs_t frameTime, uint32_t max) {
90 uint32_t index = static_cast<uint32_t>(ns2ms(frameTime));
91 // If index > kBucketMinThreshold mask will be 0xFFFFFFFF as a result
92 // of negating 1 (twos compliment, yaay) else mask will be 0
93 uint32_t mask = -(index > kBucketMinThreshold);
94 // If index > threshold, this will essentially perform:
95 // amountAboveThreshold = index - threshold;
96 // index = threshold + (amountAboveThreshold / 2)
97 // However if index is <= this will do nothing. It will underflow, do
98 // a right shift by 0 (no-op), then overflow back to the original value
99 index = ((index - kBucket4msIntervals) >> (index > kBucket4msIntervals))
100 + kBucket4msIntervals;
101 index = ((index - kBucket2msIntervals) >> (index > kBucket2msIntervals))
102 + kBucket2msIntervals;
103 // If index was < minThreshold at the start of all this it's going to
104 // be a pretty garbage value right now. However, mask is 0 so we'll end
105 // up with the desired result of 0.
106 index = (index - kBucketMinThreshold) & mask;
107 return index < max ? index : max;
108}
109
110// Only called when dumping stats, less performance sensitive
111static uint32_t frameTimeForFrameCountIndex(uint32_t index) {
112 index = index + kBucketMinThreshold;
113 if (index > kBucket2msIntervals) {
114 index += (index - kBucket2msIntervals);
115 }
116 if (index > kBucket4msIntervals) {
117 // This works because it was already doubled by the above if
118 // 1 is added to shift slightly more towards the middle of the bucket
119 index += (index - kBucket4msIntervals) + 1;
120 }
121 return index;
122}
123
John Reckba6adf62015-02-19 14:36:50 -0800124JankTracker::JankTracker(nsecs_t frameIntervalNanos) {
John Reckedc524c2015-03-18 15:24:33 -0700125 // By default this will use malloc memory. It may be moved later to ashmem
126 // if there is shared space for it and a request comes in to do that.
127 mData = new ProfileData;
John Reckba6adf62015-02-19 14:36:50 -0800128 reset();
129 setFrameInterval(frameIntervalNanos);
130}
131
John Reckedc524c2015-03-18 15:24:33 -0700132JankTracker::~JankTracker() {
133 freeData();
134}
135
136void JankTracker::freeData() {
137 if (mIsMapped) {
138 munmap(mData, sizeof(ProfileData));
139 } else {
140 delete mData;
141 }
142 mIsMapped = false;
143 mData = nullptr;
144}
145
146void JankTracker::switchStorageToAshmem(int ashmemfd) {
147 int regionSize = ashmem_get_size_region(ashmemfd);
148 if (regionSize < static_cast<int>(sizeof(ProfileData))) {
149 ALOGW("Ashmem region is too small! Received %d, required %u",
John Reck98fa0a32015-03-31 12:03:51 -0700150 regionSize, static_cast<unsigned int>(sizeof(ProfileData)));
John Reckedc524c2015-03-18 15:24:33 -0700151 return;
152 }
153 ProfileData* newData = reinterpret_cast<ProfileData*>(
154 mmap(NULL, sizeof(ProfileData), PROT_READ | PROT_WRITE,
155 MAP_SHARED, ashmemfd, 0));
156 if (newData == MAP_FAILED) {
157 int err = errno;
158 ALOGW("Failed to move profile data to ashmem fd %d, error = %d",
159 ashmemfd, err);
160 return;
161 }
162
163 // The new buffer may have historical data that we want to build on top of
164 // But let's make sure we don't overflow Just In Case
165 uint32_t divider = 0;
166 if (newData->totalFrameCount > (1 << 24)) {
167 divider = 4;
168 }
169 for (size_t i = 0; i < mData->jankTypeCounts.size(); i++) {
170 newData->jankTypeCounts[i] >>= divider;
171 newData->jankTypeCounts[i] += mData->jankTypeCounts[i];
172 }
173 for (size_t i = 0; i < mData->frameCounts.size(); i++) {
174 newData->frameCounts[i] >>= divider;
175 newData->frameCounts[i] += mData->frameCounts[i];
176 }
177 newData->jankFrameCount >>= divider;
178 newData->jankFrameCount += mData->jankFrameCount;
179 newData->totalFrameCount >>= divider;
180 newData->totalFrameCount += mData->totalFrameCount;
John Reck379f2642015-04-06 13:29:25 -0700181 if (newData->statStartTime > mData->statStartTime
182 || newData->statStartTime == 0) {
183 newData->statStartTime = mData->statStartTime;
184 }
John Reckedc524c2015-03-18 15:24:33 -0700185
186 freeData();
187 mData = newData;
188 mIsMapped = true;
189}
190
John Reckba6adf62015-02-19 14:36:50 -0800191void JankTracker::setFrameInterval(nsecs_t frameInterval) {
192 mFrameInterval = frameInterval;
193 mThresholds[kMissedVsync] = 1;
194 /*
195 * Due to interpolation and sample rate differences between the touch
196 * panel and the display (example, 85hz touch panel driving a 60hz display)
197 * we call high latency 1.5 * frameinterval
198 *
199 * NOTE: Be careful when tuning this! A theoretical 1,000hz touch panel
200 * on a 60hz display will show kOldestInputEvent - kIntendedVsync of being 15ms
201 * Thus this must always be larger than frameInterval, or it will fail
202 */
203 mThresholds[kHighInputLatency] = static_cast<int64_t>(1.5 * frameInterval);
204
205 // Note that these do not add up to 1. This is intentional. It's to deal
206 // with variance in values, and should be sort of an upper-bound on what
207 // is reasonable to expect.
208 mThresholds[kSlowUI] = static_cast<int64_t>(.5 * frameInterval);
209 mThresholds[kSlowSync] = static_cast<int64_t>(.2 * frameInterval);
210 mThresholds[kSlowRT] = static_cast<int64_t>(.75 * frameInterval);
211
212}
213
John Reck5ed587f2016-03-24 15:57:01 -0700214static bool shouldReplace(SlowFrame& existing, SlowFrame& candidate) {
215 if (candidate.whenHours - existing.whenHours >= 24) {
216 // If the old slowframe is over 24 hours older than the candidate,
217 // replace it. It's too stale
218 return true;
219 }
220 if (candidate.frametimeMs > existing.frametimeMs) {
221 return true;
222 }
223 return false;
224}
225
226void JankTracker::updateSlowest(const FrameInfo& frame) {
227 uint16_t durationMs = static_cast<uint16_t>(std::min(
228 ns2ms(frame[FrameInfoIndex::FrameCompleted] - frame[FrameInfoIndex::IntendedVsync]),
229 static_cast<nsecs_t>(std::numeric_limits<uint16_t>::max())));
230 uint16_t startHours = static_cast<uint16_t>(std::lround(
231 ns2s(frame[FrameInfoIndex::IntendedVsync]) / 3600.0f));
232 SlowFrame* toReplace = nullptr;
233 SlowFrame thisFrame{startHours, durationMs};
234 // First find the best candidate for replacement
235 for (SlowFrame& existing : mData->slowestFrames) {
236 // If we should replace the current data with the replacement candidate,
237 // it means the current data is worse than the replacement candidate
238 if (!toReplace || shouldReplace(existing, *toReplace)) {
239 toReplace = &existing;
240 }
241 }
242 // Now see if we should replace it
243 if (shouldReplace(*toReplace, thisFrame)) {
244 *toReplace = thisFrame;
245 }
246}
247
John Reckba6adf62015-02-19 14:36:50 -0800248void JankTracker::addFrame(const FrameInfo& frame) {
John Reckedc524c2015-03-18 15:24:33 -0700249 mData->totalFrameCount++;
John Reckba6adf62015-02-19 14:36:50 -0800250 // Fast-path for jank-free frames
John Reckc87be992015-02-20 10:57:22 -0800251 int64_t totalDuration =
John Reckc7cd9cf2016-03-28 10:38:19 -0700252 frame[FrameInfoIndex::FrameCompleted] - frame[sFrameStart];
John Reckedc524c2015-03-18 15:24:33 -0700253 uint32_t framebucket = frameCountIndexForFrameTime(
John Reckd6e3cf42016-03-28 09:35:00 -0700254 totalDuration, mData->frameCounts.size() - 1);
John Recke70c5752015-03-06 14:40:50 -0800255 // Keep the fast path as fast as possible.
John Reckba6adf62015-02-19 14:36:50 -0800256 if (CC_LIKELY(totalDuration < mFrameInterval)) {
John Reckedc524c2015-03-18 15:24:33 -0700257 mData->frameCounts[framebucket]++;
John Reckba6adf62015-02-19 14:36:50 -0800258 return;
259 }
260
John Reck5ed587f2016-03-24 15:57:01 -0700261 // For slowest frames we are still interested in frames that are otherwise
262 // exempt (such as first-draw). Although those frames don't directly impact
263 // smoothness, they do impact responsiveness.
264 updateSlowest(frame);
265
Chris Craik1b54fb22015-06-02 17:40:58 -0700266 if (frame[FrameInfoIndex::Flags] & EXEMPT_FRAMES_FLAGS) {
John Reckba6adf62015-02-19 14:36:50 -0800267 return;
268 }
269
John Reckedc524c2015-03-18 15:24:33 -0700270 mData->frameCounts[framebucket]++;
271 mData->jankFrameCount++;
John Reckba6adf62015-02-19 14:36:50 -0800272
273 for (int i = 0; i < NUM_BUCKETS; i++) {
John Reckbe3fba02015-07-06 13:49:58 -0700274 int64_t delta = frame.duration(COMPARISONS[i].start, COMPARISONS[i].end);
John Reckba6adf62015-02-19 14:36:50 -0800275 if (delta >= mThresholds[i] && delta < IGNORE_EXCEEDING) {
John Reckedc524c2015-03-18 15:24:33 -0700276 mData->jankTypeCounts[i]++;
John Reckba6adf62015-02-19 14:36:50 -0800277 }
278 }
279}
280
John Reckedc524c2015-03-18 15:24:33 -0700281void JankTracker::dumpBuffer(const void* buffer, size_t bufsize, int fd) {
282 if (bufsize < sizeof(ProfileData)) {
283 return;
John Reckba6adf62015-02-19 14:36:50 -0800284 }
John Reckedc524c2015-03-18 15:24:33 -0700285 const ProfileData* data = reinterpret_cast<const ProfileData*>(buffer);
286 dumpData(data, fd);
287}
288
289void JankTracker::dumpData(const ProfileData* data, int fd) {
John Reckc7cd9cf2016-03-28 10:38:19 -0700290 if (sFrameStart != FrameInfoIndex::IntendedVsync) {
291 dprintf(fd, "\nNote: Data has been filtered!");
292 }
Ying Wang05f56742015-04-07 18:03:31 -0700293 dprintf(fd, "\nStats since: %" PRIu64 "ns", data->statStartTime);
John Reckedc524c2015-03-18 15:24:33 -0700294 dprintf(fd, "\nTotal frames rendered: %u", data->totalFrameCount);
295 dprintf(fd, "\nJanky frames: %u (%.2f%%)", data->jankFrameCount,
296 (float) data->jankFrameCount / (float) data->totalFrameCount * 100.0f);
John Reck682573c2015-10-30 10:37:35 -0700297 dprintf(fd, "\n50th percentile: %ums", findPercentile(data, 50));
John Reckedc524c2015-03-18 15:24:33 -0700298 dprintf(fd, "\n90th percentile: %ums", findPercentile(data, 90));
299 dprintf(fd, "\n95th percentile: %ums", findPercentile(data, 95));
300 dprintf(fd, "\n99th percentile: %ums", findPercentile(data, 99));
John Reck5ed587f2016-03-24 15:57:01 -0700301 dprintf(fd, "\nSlowest frames over last 24h: ");
302 for (auto& slowFrame : data->slowestFrames) {
303 if (!slowFrame.frametimeMs) continue;
304 dprintf(fd, "%ums ", slowFrame.frametimeMs);
305 }
John Reckedc524c2015-03-18 15:24:33 -0700306 for (int i = 0; i < NUM_BUCKETS; i++) {
307 dprintf(fd, "\nNumber %s: %u", JANK_TYPE_NAMES[i], data->jankTypeCounts[i]);
308 }
309 dprintf(fd, "\n");
John Reckba6adf62015-02-19 14:36:50 -0800310}
311
312void JankTracker::reset() {
John Reckedc524c2015-03-18 15:24:33 -0700313 mData->jankTypeCounts.fill(0);
314 mData->frameCounts.fill(0);
315 mData->totalFrameCount = 0;
316 mData->jankFrameCount = 0;
John Reck379f2642015-04-06 13:29:25 -0700317 mData->statStartTime = systemTime(CLOCK_MONOTONIC);
John Reckc7cd9cf2016-03-28 10:38:19 -0700318 sFrameStart = Properties::filterOutTestOverhead
319 ? FrameInfoIndex::HandleInputStart
320 : FrameInfoIndex::IntendedVsync;
John Reckba6adf62015-02-19 14:36:50 -0800321}
322
John Reckedc524c2015-03-18 15:24:33 -0700323uint32_t JankTracker::findPercentile(const ProfileData* data, int percentile) {
324 int pos = percentile * data->totalFrameCount / 100;
325 int remaining = data->totalFrameCount - pos;
326 for (int i = data->frameCounts.size() - 1; i >= 0; i--) {
327 remaining -= data->frameCounts[i];
John Recke70c5752015-03-06 14:40:50 -0800328 if (remaining <= 0) {
John Reckedc524c2015-03-18 15:24:33 -0700329 return frameTimeForFrameCountIndex(i);
John Recke70c5752015-03-06 14:40:50 -0800330 }
331 }
332 return 0;
333}
334
John Reckba6adf62015-02-19 14:36:50 -0800335} /* namespace uirenderer */
336} /* namespace android */