blob: 2246cf9c1948bd0057370d81d0bc8aeb3e889284 [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 Recke70c5752015-03-06 14:40:50 -080018#include <algorithm>
John Reckedc524c2015-03-18 15:24:33 -070019#include <cutils/ashmem.h>
20#include <cutils/log.h>
John Reckba6adf62015-02-19 14:36:50 -080021#include <cstdio>
John Reckedc524c2015-03-18 15:24:33 -070022#include <errno.h>
John Reckba6adf62015-02-19 14:36:50 -080023#include <inttypes.h>
John Reck5ed587f2016-03-24 15:57:01 -070024#include <limits>
25#include <cmath>
John Reckedc524c2015-03-18 15:24:33 -070026#include <sys/mman.h>
John Reckba6adf62015-02-19 14:36:50 -080027
28namespace android {
29namespace uirenderer {
30
31static const char* JANK_TYPE_NAMES[] = {
32 "Missed Vsync",
33 "High input latency",
34 "Slow UI thread",
35 "Slow bitmap uploads",
John Reckbe3fba02015-07-06 13:49:58 -070036 "Slow issue draw commands",
John Reckba6adf62015-02-19 14:36:50 -080037};
38
39struct Comparison {
John Reckc87be992015-02-20 10:57:22 -080040 FrameInfoIndex start;
41 FrameInfoIndex end;
John Reckba6adf62015-02-19 14:36:50 -080042};
43
44static const Comparison COMPARISONS[] = {
Chris Craik1b54fb22015-06-02 17:40:58 -070045 {FrameInfoIndex::IntendedVsync, FrameInfoIndex::Vsync},
46 {FrameInfoIndex::OldestInputEvent, FrameInfoIndex::Vsync},
47 {FrameInfoIndex::Vsync, FrameInfoIndex::SyncStart},
48 {FrameInfoIndex::SyncStart, FrameInfoIndex::IssueDrawCommandsStart},
49 {FrameInfoIndex::IssueDrawCommandsStart, FrameInfoIndex::FrameCompleted},
John Reckba6adf62015-02-19 14:36:50 -080050};
51
52// If the event exceeds 10 seconds throw it away, this isn't a jank event
53// it's an ANR and will be handled as such
54static const int64_t IGNORE_EXCEEDING = seconds_to_nanoseconds(10);
55
56/*
57 * Frames that are exempt from jank metrics.
58 * First-draw frames, for example, are expected to
59 * be slow, this is hidden from the user with window animations and
60 * other tricks
61 *
62 * Similarly, we don't track direct-drawing via Surface:lockHardwareCanvas()
63 * for now
64 *
65 * TODO: kSurfaceCanvas can negatively impact other drawing by using up
66 * time on the RenderThread, figure out how to attribute that as a jank-causer
67 */
68static const int64_t EXEMPT_FRAMES_FLAGS
Chris Craik1b54fb22015-06-02 17:40:58 -070069 = FrameInfoFlags::WindowLayoutChanged
70 | FrameInfoFlags::SurfaceCanvas;
John Reckba6adf62015-02-19 14:36:50 -080071
John Reckedc524c2015-03-18 15:24:33 -070072// The bucketing algorithm controls so to speak
73// If a frame is <= to this it goes in bucket 0
74static const uint32_t kBucketMinThreshold = 7;
75// If a frame is > this, start counting in increments of 2ms
76static const uint32_t kBucket2msIntervals = 32;
77// If a frame is > this, start counting in increments of 4ms
78static const uint32_t kBucket4msIntervals = 48;
79
80// This will be called every frame, performance sensitive
81// Uses bit twiddling to avoid branching while achieving the packing desired
82static uint32_t frameCountIndexForFrameTime(nsecs_t frameTime, uint32_t max) {
83 uint32_t index = static_cast<uint32_t>(ns2ms(frameTime));
84 // If index > kBucketMinThreshold mask will be 0xFFFFFFFF as a result
85 // of negating 1 (twos compliment, yaay) else mask will be 0
86 uint32_t mask = -(index > kBucketMinThreshold);
87 // If index > threshold, this will essentially perform:
88 // amountAboveThreshold = index - threshold;
89 // index = threshold + (amountAboveThreshold / 2)
90 // However if index is <= this will do nothing. It will underflow, do
91 // a right shift by 0 (no-op), then overflow back to the original value
92 index = ((index - kBucket4msIntervals) >> (index > kBucket4msIntervals))
93 + kBucket4msIntervals;
94 index = ((index - kBucket2msIntervals) >> (index > kBucket2msIntervals))
95 + kBucket2msIntervals;
96 // If index was < minThreshold at the start of all this it's going to
97 // be a pretty garbage value right now. However, mask is 0 so we'll end
98 // up with the desired result of 0.
99 index = (index - kBucketMinThreshold) & mask;
100 return index < max ? index : max;
101}
102
103// Only called when dumping stats, less performance sensitive
104static uint32_t frameTimeForFrameCountIndex(uint32_t index) {
105 index = index + kBucketMinThreshold;
106 if (index > kBucket2msIntervals) {
107 index += (index - kBucket2msIntervals);
108 }
109 if (index > kBucket4msIntervals) {
110 // This works because it was already doubled by the above if
111 // 1 is added to shift slightly more towards the middle of the bucket
112 index += (index - kBucket4msIntervals) + 1;
113 }
114 return index;
115}
116
John Reckba6adf62015-02-19 14:36:50 -0800117JankTracker::JankTracker(nsecs_t frameIntervalNanos) {
John Reckedc524c2015-03-18 15:24:33 -0700118 // By default this will use malloc memory. It may be moved later to ashmem
119 // if there is shared space for it and a request comes in to do that.
120 mData = new ProfileData;
John Reckba6adf62015-02-19 14:36:50 -0800121 reset();
122 setFrameInterval(frameIntervalNanos);
123}
124
John Reckedc524c2015-03-18 15:24:33 -0700125JankTracker::~JankTracker() {
126 freeData();
127}
128
129void JankTracker::freeData() {
130 if (mIsMapped) {
131 munmap(mData, sizeof(ProfileData));
132 } else {
133 delete mData;
134 }
135 mIsMapped = false;
136 mData = nullptr;
137}
138
139void JankTracker::switchStorageToAshmem(int ashmemfd) {
140 int regionSize = ashmem_get_size_region(ashmemfd);
141 if (regionSize < static_cast<int>(sizeof(ProfileData))) {
142 ALOGW("Ashmem region is too small! Received %d, required %u",
John Reck98fa0a32015-03-31 12:03:51 -0700143 regionSize, static_cast<unsigned int>(sizeof(ProfileData)));
John Reckedc524c2015-03-18 15:24:33 -0700144 return;
145 }
146 ProfileData* newData = reinterpret_cast<ProfileData*>(
147 mmap(NULL, sizeof(ProfileData), PROT_READ | PROT_WRITE,
148 MAP_SHARED, ashmemfd, 0));
149 if (newData == MAP_FAILED) {
150 int err = errno;
151 ALOGW("Failed to move profile data to ashmem fd %d, error = %d",
152 ashmemfd, err);
153 return;
154 }
155
156 // The new buffer may have historical data that we want to build on top of
157 // But let's make sure we don't overflow Just In Case
158 uint32_t divider = 0;
159 if (newData->totalFrameCount > (1 << 24)) {
160 divider = 4;
161 }
162 for (size_t i = 0; i < mData->jankTypeCounts.size(); i++) {
163 newData->jankTypeCounts[i] >>= divider;
164 newData->jankTypeCounts[i] += mData->jankTypeCounts[i];
165 }
166 for (size_t i = 0; i < mData->frameCounts.size(); i++) {
167 newData->frameCounts[i] >>= divider;
168 newData->frameCounts[i] += mData->frameCounts[i];
169 }
170 newData->jankFrameCount >>= divider;
171 newData->jankFrameCount += mData->jankFrameCount;
172 newData->totalFrameCount >>= divider;
173 newData->totalFrameCount += mData->totalFrameCount;
John Reck379f2642015-04-06 13:29:25 -0700174 if (newData->statStartTime > mData->statStartTime
175 || newData->statStartTime == 0) {
176 newData->statStartTime = mData->statStartTime;
177 }
John Reckedc524c2015-03-18 15:24:33 -0700178
179 freeData();
180 mData = newData;
181 mIsMapped = true;
182}
183
John Reckba6adf62015-02-19 14:36:50 -0800184void JankTracker::setFrameInterval(nsecs_t frameInterval) {
185 mFrameInterval = frameInterval;
186 mThresholds[kMissedVsync] = 1;
187 /*
188 * Due to interpolation and sample rate differences between the touch
189 * panel and the display (example, 85hz touch panel driving a 60hz display)
190 * we call high latency 1.5 * frameinterval
191 *
192 * NOTE: Be careful when tuning this! A theoretical 1,000hz touch panel
193 * on a 60hz display will show kOldestInputEvent - kIntendedVsync of being 15ms
194 * Thus this must always be larger than frameInterval, or it will fail
195 */
196 mThresholds[kHighInputLatency] = static_cast<int64_t>(1.5 * frameInterval);
197
198 // Note that these do not add up to 1. This is intentional. It's to deal
199 // with variance in values, and should be sort of an upper-bound on what
200 // is reasonable to expect.
201 mThresholds[kSlowUI] = static_cast<int64_t>(.5 * frameInterval);
202 mThresholds[kSlowSync] = static_cast<int64_t>(.2 * frameInterval);
203 mThresholds[kSlowRT] = static_cast<int64_t>(.75 * frameInterval);
204
205}
206
John Reck5ed587f2016-03-24 15:57:01 -0700207static bool shouldReplace(SlowFrame& existing, SlowFrame& candidate) {
208 if (candidate.whenHours - existing.whenHours >= 24) {
209 // If the old slowframe is over 24 hours older than the candidate,
210 // replace it. It's too stale
211 return true;
212 }
213 if (candidate.frametimeMs > existing.frametimeMs) {
214 return true;
215 }
216 return false;
217}
218
219void JankTracker::updateSlowest(const FrameInfo& frame) {
220 uint16_t durationMs = static_cast<uint16_t>(std::min(
221 ns2ms(frame[FrameInfoIndex::FrameCompleted] - frame[FrameInfoIndex::IntendedVsync]),
222 static_cast<nsecs_t>(std::numeric_limits<uint16_t>::max())));
223 uint16_t startHours = static_cast<uint16_t>(std::lround(
224 ns2s(frame[FrameInfoIndex::IntendedVsync]) / 3600.0f));
225 SlowFrame* toReplace = nullptr;
226 SlowFrame thisFrame{startHours, durationMs};
227 // First find the best candidate for replacement
228 for (SlowFrame& existing : mData->slowestFrames) {
229 // If we should replace the current data with the replacement candidate,
230 // it means the current data is worse than the replacement candidate
231 if (!toReplace || shouldReplace(existing, *toReplace)) {
232 toReplace = &existing;
233 }
234 }
235 // Now see if we should replace it
236 if (shouldReplace(*toReplace, thisFrame)) {
237 *toReplace = thisFrame;
238 }
239}
240
John Reckba6adf62015-02-19 14:36:50 -0800241void JankTracker::addFrame(const FrameInfo& frame) {
John Reckedc524c2015-03-18 15:24:33 -0700242 mData->totalFrameCount++;
John Reckba6adf62015-02-19 14:36:50 -0800243 // Fast-path for jank-free frames
John Reckc87be992015-02-20 10:57:22 -0800244 int64_t totalDuration =
Chris Craik1b54fb22015-06-02 17:40:58 -0700245 frame[FrameInfoIndex::FrameCompleted] - frame[FrameInfoIndex::IntendedVsync];
John Reckedc524c2015-03-18 15:24:33 -0700246 uint32_t framebucket = frameCountIndexForFrameTime(
247 totalDuration, mData->frameCounts.size());
John Recke70c5752015-03-06 14:40:50 -0800248 // Keep the fast path as fast as possible.
John Reckba6adf62015-02-19 14:36:50 -0800249 if (CC_LIKELY(totalDuration < mFrameInterval)) {
John Reckedc524c2015-03-18 15:24:33 -0700250 mData->frameCounts[framebucket]++;
John Reckba6adf62015-02-19 14:36:50 -0800251 return;
252 }
253
John Reck5ed587f2016-03-24 15:57:01 -0700254 // For slowest frames we are still interested in frames that are otherwise
255 // exempt (such as first-draw). Although those frames don't directly impact
256 // smoothness, they do impact responsiveness.
257 updateSlowest(frame);
258
Chris Craik1b54fb22015-06-02 17:40:58 -0700259 if (frame[FrameInfoIndex::Flags] & EXEMPT_FRAMES_FLAGS) {
John Reckba6adf62015-02-19 14:36:50 -0800260 return;
261 }
262
John Reckedc524c2015-03-18 15:24:33 -0700263 mData->frameCounts[framebucket]++;
264 mData->jankFrameCount++;
John Reckba6adf62015-02-19 14:36:50 -0800265
266 for (int i = 0; i < NUM_BUCKETS; i++) {
John Reckbe3fba02015-07-06 13:49:58 -0700267 int64_t delta = frame.duration(COMPARISONS[i].start, COMPARISONS[i].end);
John Reckba6adf62015-02-19 14:36:50 -0800268 if (delta >= mThresholds[i] && delta < IGNORE_EXCEEDING) {
John Reckedc524c2015-03-18 15:24:33 -0700269 mData->jankTypeCounts[i]++;
John Reckba6adf62015-02-19 14:36:50 -0800270 }
271 }
272}
273
John Reckedc524c2015-03-18 15:24:33 -0700274void JankTracker::dumpBuffer(const void* buffer, size_t bufsize, int fd) {
275 if (bufsize < sizeof(ProfileData)) {
276 return;
John Reckba6adf62015-02-19 14:36:50 -0800277 }
John Reckedc524c2015-03-18 15:24:33 -0700278 const ProfileData* data = reinterpret_cast<const ProfileData*>(buffer);
279 dumpData(data, fd);
280}
281
282void JankTracker::dumpData(const ProfileData* data, int fd) {
Ying Wang05f56742015-04-07 18:03:31 -0700283 dprintf(fd, "\nStats since: %" PRIu64 "ns", data->statStartTime);
John Reckedc524c2015-03-18 15:24:33 -0700284 dprintf(fd, "\nTotal frames rendered: %u", data->totalFrameCount);
285 dprintf(fd, "\nJanky frames: %u (%.2f%%)", data->jankFrameCount,
286 (float) data->jankFrameCount / (float) data->totalFrameCount * 100.0f);
John Reck682573c2015-10-30 10:37:35 -0700287 dprintf(fd, "\n50th percentile: %ums", findPercentile(data, 50));
John Reckedc524c2015-03-18 15:24:33 -0700288 dprintf(fd, "\n90th percentile: %ums", findPercentile(data, 90));
289 dprintf(fd, "\n95th percentile: %ums", findPercentile(data, 95));
290 dprintf(fd, "\n99th percentile: %ums", findPercentile(data, 99));
John Reck5ed587f2016-03-24 15:57:01 -0700291 dprintf(fd, "\nSlowest frames over last 24h: ");
292 for (auto& slowFrame : data->slowestFrames) {
293 if (!slowFrame.frametimeMs) continue;
294 dprintf(fd, "%ums ", slowFrame.frametimeMs);
295 }
John Reckedc524c2015-03-18 15:24:33 -0700296 for (int i = 0; i < NUM_BUCKETS; i++) {
297 dprintf(fd, "\nNumber %s: %u", JANK_TYPE_NAMES[i], data->jankTypeCounts[i]);
298 }
299 dprintf(fd, "\n");
John Reckba6adf62015-02-19 14:36:50 -0800300}
301
302void JankTracker::reset() {
John Reckedc524c2015-03-18 15:24:33 -0700303 mData->jankTypeCounts.fill(0);
304 mData->frameCounts.fill(0);
305 mData->totalFrameCount = 0;
306 mData->jankFrameCount = 0;
John Reck379f2642015-04-06 13:29:25 -0700307 mData->statStartTime = systemTime(CLOCK_MONOTONIC);
John Reckba6adf62015-02-19 14:36:50 -0800308}
309
John Reckedc524c2015-03-18 15:24:33 -0700310uint32_t JankTracker::findPercentile(const ProfileData* data, int percentile) {
311 int pos = percentile * data->totalFrameCount / 100;
312 int remaining = data->totalFrameCount - pos;
313 for (int i = data->frameCounts.size() - 1; i >= 0; i--) {
314 remaining -= data->frameCounts[i];
John Recke70c5752015-03-06 14:40:50 -0800315 if (remaining <= 0) {
John Reckedc524c2015-03-18 15:24:33 -0700316 return frameTimeForFrameCountIndex(i);
John Recke70c5752015-03-06 14:40:50 -0800317 }
318 }
319 return 0;
320}
321
John Reckba6adf62015-02-19 14:36:50 -0800322} /* namespace uirenderer */
323} /* namespace android */