blob: e0303a8a62d5815d58e631435d73bb6f667c125f [file] [log] [blame]
John Reckdf1742e2017-01-19 15:56:21 -08001/*
2 * Copyright (C) 2017 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 "GraphicsStatsService.h"
18
19#include "JankTracker.h"
20
21#include <frameworks/base/core/proto/android/service/graphicsstats.pb.h>
John Reck915883b2017-05-03 10:27:20 -070022#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
John Reckdf1742e2017-01-19 15:56:21 -080023#include <log/log.h>
24
Dan Albert110e0072017-10-11 12:41:26 -070025#include <errno.h>
John Reckdf1742e2017-01-19 15:56:21 -080026#include <fcntl.h>
Dan Albert110e0072017-10-11 12:41:26 -070027#include <inttypes.h>
John Reck1bcacfd2017-11-03 10:12:19 -070028#include <sys/mman.h>
Dan Albert110e0072017-10-11 12:41:26 -070029#include <sys/stat.h>
30#include <sys/types.h>
John Reckdf1742e2017-01-19 15:56:21 -080031#include <unistd.h>
32
33namespace android {
34namespace uirenderer {
35
36using namespace google::protobuf;
37
38constexpr int32_t sCurrentFileVersion = 1;
39constexpr int32_t sHeaderSize = 4;
40static_assert(sizeof(sCurrentFileVersion) == sHeaderSize, "Header size is wrong");
41
John Reck7075c792017-07-05 14:03:43 -070042constexpr int sHistogramSize = ProfileData::HistogramSize();
John Reckdf1742e2017-01-19 15:56:21 -080043
John Reck5206a872017-09-18 11:08:31 -070044static bool mergeProfileDataIntoProto(service::GraphicsStatsProto* proto,
Dianne Hackborn73453e42017-12-11 16:30:36 -080045 const std::string& package, int64_t versionCode,
John Reck1bcacfd2017-11-03 10:12:19 -070046 int64_t startTime, int64_t endTime, const ProfileData* data);
John Reckdf1742e2017-01-19 15:56:21 -080047static void dumpAsTextToFd(service::GraphicsStatsProto* proto, int outFd);
48
John Reck915883b2017-05-03 10:27:20 -070049class FileDescriptor {
50public:
51 FileDescriptor(int fd) : mFd(fd) {}
52 ~FileDescriptor() {
53 if (mFd != -1) {
54 close(mFd);
55 mFd = -1;
56 }
57 }
58 bool valid() { return mFd != -1; }
59 operator int() { return mFd; }
John Reck1bcacfd2017-11-03 10:12:19 -070060
John Reck915883b2017-05-03 10:27:20 -070061private:
62 int mFd;
63};
64
65class FileOutputStreamLite : public io::ZeroCopyOutputStream {
66public:
67 FileOutputStreamLite(int fd) : mCopyAdapter(fd), mImpl(&mCopyAdapter) {}
68 virtual ~FileOutputStreamLite() {}
69
70 int GetErrno() { return mCopyAdapter.mErrno; }
71
John Reck1bcacfd2017-11-03 10:12:19 -070072 virtual bool Next(void** data, int* size) override { return mImpl.Next(data, size); }
John Reck915883b2017-05-03 10:27:20 -070073
John Reck1bcacfd2017-11-03 10:12:19 -070074 virtual void BackUp(int count) override { mImpl.BackUp(count); }
John Reck915883b2017-05-03 10:27:20 -070075
John Reck1bcacfd2017-11-03 10:12:19 -070076 virtual int64 ByteCount() const override { return mImpl.ByteCount(); }
John Reck915883b2017-05-03 10:27:20 -070077
John Reck1bcacfd2017-11-03 10:12:19 -070078 bool Flush() { return mImpl.Flush(); }
John Reck915883b2017-05-03 10:27:20 -070079
80private:
81 struct FDAdapter : public io::CopyingOutputStream {
82 int mFd;
83 int mErrno = 0;
84
85 FDAdapter(int fd) : mFd(fd) {}
86 virtual ~FDAdapter() {}
87
88 virtual bool Write(const void* buffer, int size) override {
89 int ret;
90 while (size) {
John Reck1bcacfd2017-11-03 10:12:19 -070091 ret = TEMP_FAILURE_RETRY(write(mFd, buffer, size));
John Reck915883b2017-05-03 10:27:20 -070092 if (ret <= 0) {
93 mErrno = errno;
94 return false;
95 }
96 size -= ret;
97 }
98 return true;
99 }
100 };
101
102 FileOutputStreamLite::FDAdapter mCopyAdapter;
103 io::CopyingOutputStreamAdaptor mImpl;
104};
105
John Reck1bcacfd2017-11-03 10:12:19 -0700106bool GraphicsStatsService::parseFromFile(const std::string& path,
107 service::GraphicsStatsProto* output) {
John Reck915883b2017-05-03 10:27:20 -0700108 FileDescriptor fd{open(path.c_str(), O_RDONLY)};
109 if (!fd.valid()) {
John Reckdf1742e2017-01-19 15:56:21 -0800110 int err = errno;
111 // The file not existing is normal for addToDump(), so only log if
112 // we get an unexpected error
113 if (err != ENOENT) {
114 ALOGW("Failed to open '%s', errno=%d (%s)", path.c_str(), err, strerror(err));
115 }
116 return false;
117 }
John Reck915883b2017-05-03 10:27:20 -0700118 struct stat sb;
119 if (fstat(fd, &sb) || sb.st_size < sHeaderSize) {
120 int err = errno;
121 // The file not existing is normal for addToDump(), so only log if
122 // we get an unexpected error
123 if (err != ENOENT) {
124 ALOGW("Failed to fstat '%s', errno=%d (%s) (st_size %d)", path.c_str(), err,
John Reck1bcacfd2017-11-03 10:12:19 -0700125 strerror(err), (int)sb.st_size);
John Reck915883b2017-05-03 10:27:20 -0700126 }
127 return false;
128 }
129 void* addr = mmap(nullptr, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
130 if (!addr) {
131 int err = errno;
132 // The file not existing is normal for addToDump(), so only log if
133 // we get an unexpected error
134 if (err != ENOENT) {
135 ALOGW("Failed to mmap '%s', errno=%d (%s)", path.c_str(), err, strerror(err));
136 }
137 return false;
138 }
139 uint32_t file_version = *reinterpret_cast<uint32_t*>(addr);
140 if (file_version != sCurrentFileVersion) {
141 ALOGW("file_version mismatch! expected %d got %d", sCurrentFileVersion, file_version);
John Reckdf1742e2017-01-19 15:56:21 -0800142 return false;
143 }
144
John Reck915883b2017-05-03 10:27:20 -0700145 void* data = reinterpret_cast<uint8_t*>(addr) + sHeaderSize;
146 int dataSize = sb.st_size - sHeaderSize;
147 io::ArrayInputStream input{data, dataSize};
John Reckdf1742e2017-01-19 15:56:21 -0800148 bool success = output->ParseFromZeroCopyStream(&input);
John Reck915883b2017-05-03 10:27:20 -0700149 if (!success) {
John Reck1bcacfd2017-11-03 10:12:19 -0700150 ALOGW("Parse failed on '%s' error='%s'", path.c_str(),
151 output->InitializationErrorString().c_str());
John Reckdf1742e2017-01-19 15:56:21 -0800152 }
John Reckdf1742e2017-01-19 15:56:21 -0800153 return success;
154}
155
John Reck5206a872017-09-18 11:08:31 -0700156bool mergeProfileDataIntoProto(service::GraphicsStatsProto* proto, const std::string& package,
Dianne Hackborn73453e42017-12-11 16:30:36 -0800157 int64_t versionCode, int64_t startTime, int64_t endTime,
John Reck1bcacfd2017-11-03 10:12:19 -0700158 const ProfileData* data) {
John Reckdf1742e2017-01-19 15:56:21 -0800159 if (proto->stats_start() == 0 || proto->stats_start() > startTime) {
160 proto->set_stats_start(startTime);
161 }
162 if (proto->stats_end() == 0 || proto->stats_end() < endTime) {
163 proto->set_stats_end(endTime);
164 }
165 proto->set_package_name(package);
166 proto->set_version_code(versionCode);
167 auto summary = proto->mutable_summary();
John Reck7075c792017-07-05 14:03:43 -0700168 summary->set_total_frames(summary->total_frames() + data->totalFrameCount());
169 summary->set_janky_frames(summary->janky_frames() + data->jankFrameCount());
John Reck1bcacfd2017-11-03 10:12:19 -0700170 summary->set_missed_vsync_count(summary->missed_vsync_count() +
171 data->jankTypeCount(kMissedVsync));
172 summary->set_high_input_latency_count(summary->high_input_latency_count() +
173 data->jankTypeCount(kHighInputLatency));
174 summary->set_slow_ui_thread_count(summary->slow_ui_thread_count() +
175 data->jankTypeCount(kSlowUI));
176 summary->set_slow_bitmap_upload_count(summary->slow_bitmap_upload_count() +
177 data->jankTypeCount(kSlowSync));
178 summary->set_slow_draw_count(summary->slow_draw_count() + data->jankTypeCount(kSlowRT));
John Reckdf1742e2017-01-19 15:56:21 -0800179
180 bool creatingHistogram = false;
181 if (proto->histogram_size() == 0) {
182 proto->mutable_histogram()->Reserve(sHistogramSize);
183 creatingHistogram = true;
184 } else if (proto->histogram_size() != sHistogramSize) {
John Reck1bcacfd2017-11-03 10:12:19 -0700185 ALOGE("Histogram size mismatch, proto is %d expected %d", proto->histogram_size(),
186 sHistogramSize);
John Reck5206a872017-09-18 11:08:31 -0700187 return false;
John Reckdf1742e2017-01-19 15:56:21 -0800188 }
John Reck7075c792017-07-05 14:03:43 -0700189 int index = 0;
John Reck5206a872017-09-18 11:08:31 -0700190 bool hitMergeError = false;
John Reck7075c792017-07-05 14:03:43 -0700191 data->histogramForEach([&](ProfileData::HistogramEntry entry) {
John Reck5206a872017-09-18 11:08:31 -0700192 if (hitMergeError) return;
193
John Reckdf1742e2017-01-19 15:56:21 -0800194 service::GraphicsStatsHistogramBucketProto* bucket;
John Reckdf1742e2017-01-19 15:56:21 -0800195 if (creatingHistogram) {
196 bucket = proto->add_histogram();
John Reck7075c792017-07-05 14:03:43 -0700197 bucket->set_render_millis(entry.renderTimeMs);
John Reckdf1742e2017-01-19 15:56:21 -0800198 } else {
John Reck7075c792017-07-05 14:03:43 -0700199 bucket = proto->mutable_histogram(index);
John Reck5206a872017-09-18 11:08:31 -0700200 if (bucket->render_millis() != static_cast<int32_t>(entry.renderTimeMs)) {
John Reck1bcacfd2017-11-03 10:12:19 -0700201 ALOGW("Frame time mistmatch %d vs. %u", bucket->render_millis(),
202 entry.renderTimeMs);
John Reck5206a872017-09-18 11:08:31 -0700203 hitMergeError = true;
204 return;
205 }
John Reckdf1742e2017-01-19 15:56:21 -0800206 }
John Reck7075c792017-07-05 14:03:43 -0700207 bucket->set_frame_count(bucket->frame_count() + entry.frameCount);
208 index++;
209 });
John Reck5206a872017-09-18 11:08:31 -0700210 return !hitMergeError;
John Reckdf1742e2017-01-19 15:56:21 -0800211}
212
213static int32_t findPercentile(service::GraphicsStatsProto* proto, int percentile) {
214 int32_t pos = percentile * proto->summary().total_frames() / 100;
215 int32_t remaining = proto->summary().total_frames() - pos;
216 for (auto it = proto->histogram().rbegin(); it != proto->histogram().rend(); ++it) {
217 remaining -= it->frame_count();
218 if (remaining <= 0) {
219 return it->render_millis();
220 }
221 }
222 return 0;
223}
224
225void dumpAsTextToFd(service::GraphicsStatsProto* proto, int fd) {
226 // This isn't a full validation, just enough that we can deref at will
John Reck5206a872017-09-18 11:08:31 -0700227 if (proto->package_name().empty() || !proto->has_summary()) {
228 ALOGW("Skipping dump, invalid package_name() '%s' or summary %d",
John Reck1bcacfd2017-11-03 10:12:19 -0700229 proto->package_name().c_str(), proto->has_summary());
John Reck5206a872017-09-18 11:08:31 -0700230 return;
231 }
John Reckdf1742e2017-01-19 15:56:21 -0800232 dprintf(fd, "\nPackage: %s", proto->package_name().c_str());
Dianne Hackborn73453e42017-12-11 16:30:36 -0800233 dprintf(fd, "\nVersion: %lld", proto->version_code());
John Reckdf1742e2017-01-19 15:56:21 -0800234 dprintf(fd, "\nStats since: %lldns", proto->stats_start());
235 dprintf(fd, "\nStats end: %lldns", proto->stats_end());
236 auto summary = proto->summary();
237 dprintf(fd, "\nTotal frames rendered: %d", summary.total_frames());
238 dprintf(fd, "\nJanky frames: %d (%.2f%%)", summary.janky_frames(),
John Reck1bcacfd2017-11-03 10:12:19 -0700239 (float)summary.janky_frames() / (float)summary.total_frames() * 100.0f);
John Reckdf1742e2017-01-19 15:56:21 -0800240 dprintf(fd, "\n50th percentile: %dms", findPercentile(proto, 50));
241 dprintf(fd, "\n90th percentile: %dms", findPercentile(proto, 90));
242 dprintf(fd, "\n95th percentile: %dms", findPercentile(proto, 95));
243 dprintf(fd, "\n99th percentile: %dms", findPercentile(proto, 99));
244 dprintf(fd, "\nNumber Missed Vsync: %d", summary.missed_vsync_count());
245 dprintf(fd, "\nNumber High input latency: %d", summary.high_input_latency_count());
246 dprintf(fd, "\nNumber Slow UI thread: %d", summary.slow_ui_thread_count());
247 dprintf(fd, "\nNumber Slow bitmap uploads: %d", summary.slow_bitmap_upload_count());
248 dprintf(fd, "\nNumber Slow issue draw commands: %d", summary.slow_draw_count());
249 dprintf(fd, "\nHISTOGRAM:");
250 for (const auto& it : proto->histogram()) {
251 dprintf(fd, " %dms=%d", it.render_millis(), it.frame_count());
252 }
253 dprintf(fd, "\n");
254}
255
256void GraphicsStatsService::saveBuffer(const std::string& path, const std::string& package,
Dianne Hackborn73453e42017-12-11 16:30:36 -0800257 int64_t versionCode, int64_t startTime, int64_t endTime,
John Reck1bcacfd2017-11-03 10:12:19 -0700258 const ProfileData* data) {
John Reckdf1742e2017-01-19 15:56:21 -0800259 service::GraphicsStatsProto statsProto;
260 if (!parseFromFile(path, &statsProto)) {
261 statsProto.Clear();
262 }
John Reck5206a872017-09-18 11:08:31 -0700263 if (!mergeProfileDataIntoProto(&statsProto, package, versionCode, startTime, endTime, data)) {
264 return;
265 }
John Reckdf1742e2017-01-19 15:56:21 -0800266 // Although we might not have read any data from the file, merging the existing data
267 // should always fully-initialize the proto
John Reck5206a872017-09-18 11:08:31 -0700268 if (!statsProto.IsInitialized()) {
269 ALOGE("proto initialization error %s", statsProto.InitializationErrorString().c_str());
270 return;
271 }
272 if (statsProto.package_name().empty() || !statsProto.has_summary()) {
John Reck1bcacfd2017-11-03 10:12:19 -0700273 ALOGE("missing package_name() '%s' summary %d", statsProto.package_name().c_str(),
274 statsProto.has_summary());
John Reck5206a872017-09-18 11:08:31 -0700275 return;
276 }
John Reckdf1742e2017-01-19 15:56:21 -0800277 int outFd = open(path.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0660);
278 if (outFd <= 0) {
279 int err = errno;
280 ALOGW("Failed to open '%s', error=%d (%s)", path.c_str(), err, strerror(err));
281 return;
282 }
283 int wrote = write(outFd, &sCurrentFileVersion, sHeaderSize);
284 if (wrote != sHeaderSize) {
285 int err = errno;
John Reck1bcacfd2017-11-03 10:12:19 -0700286 ALOGW("Failed to write header to '%s', returned=%d errno=%d (%s)", path.c_str(), wrote, err,
287 strerror(err));
John Reckdf1742e2017-01-19 15:56:21 -0800288 close(outFd);
289 return;
290 }
291 {
John Reck915883b2017-05-03 10:27:20 -0700292 FileOutputStreamLite output(outFd);
John Reckdf1742e2017-01-19 15:56:21 -0800293 bool success = statsProto.SerializeToZeroCopyStream(&output) && output.Flush();
294 if (output.GetErrno() != 0) {
John Reck1bcacfd2017-11-03 10:12:19 -0700295 ALOGW("Error writing to fd=%d, path='%s' err=%d (%s)", outFd, path.c_str(),
296 output.GetErrno(), strerror(output.GetErrno()));
John Reckdf1742e2017-01-19 15:56:21 -0800297 success = false;
298 } else if (!success) {
299 ALOGW("Serialize failed on '%s' unknown error", path.c_str());
300 }
301 }
302 close(outFd);
303}
304
305class GraphicsStatsService::Dump {
306public:
307 Dump(int outFd, DumpType type) : mFd(outFd), mType(type) {}
308 int fd() { return mFd; }
309 DumpType type() { return mType; }
310 service::GraphicsStatsServiceDumpProto& proto() { return mProto; }
John Reck1bcacfd2017-11-03 10:12:19 -0700311
John Reckdf1742e2017-01-19 15:56:21 -0800312private:
313 int mFd;
314 DumpType mType;
315 service::GraphicsStatsServiceDumpProto mProto;
316};
317
318GraphicsStatsService::Dump* GraphicsStatsService::createDump(int outFd, DumpType type) {
319 return new Dump(outFd, type);
320}
321
John Reck1bcacfd2017-11-03 10:12:19 -0700322void GraphicsStatsService::addToDump(Dump* dump, const std::string& path,
Dianne Hackborn73453e42017-12-11 16:30:36 -0800323 const std::string& package, int64_t versionCode,
324 int64_t startTime, int64_t endTime, const ProfileData* data) {
John Reckdf1742e2017-01-19 15:56:21 -0800325 service::GraphicsStatsProto statsProto;
326 if (!path.empty() && !parseFromFile(path, &statsProto)) {
327 statsProto.Clear();
328 }
John Reck1bcacfd2017-11-03 10:12:19 -0700329 if (data &&
330 !mergeProfileDataIntoProto(&statsProto, package, versionCode, startTime, endTime, data)) {
John Reck5206a872017-09-18 11:08:31 -0700331 return;
John Reckdf1742e2017-01-19 15:56:21 -0800332 }
333 if (!statsProto.IsInitialized()) {
334 ALOGW("Failed to load profile data from path '%s' and data %p",
John Reck1bcacfd2017-11-03 10:12:19 -0700335 path.empty() ? "<empty>" : path.c_str(), data);
John Reckdf1742e2017-01-19 15:56:21 -0800336 return;
337 }
338
339 if (dump->type() == DumpType::Protobuf) {
340 dump->proto().add_stats()->CopyFrom(statsProto);
341 } else {
342 dumpAsTextToFd(&statsProto, dump->fd());
343 }
344}
345
346void GraphicsStatsService::addToDump(Dump* dump, const std::string& path) {
347 service::GraphicsStatsProto statsProto;
348 if (!parseFromFile(path, &statsProto)) {
349 return;
350 }
351 if (dump->type() == DumpType::Protobuf) {
352 dump->proto().add_stats()->CopyFrom(statsProto);
353 } else {
354 dumpAsTextToFd(&statsProto, dump->fd());
355 }
356}
357
358void GraphicsStatsService::finishDump(Dump* dump) {
359 if (dump->type() == DumpType::Protobuf) {
John Reck915883b2017-05-03 10:27:20 -0700360 FileOutputStreamLite stream(dump->fd());
John Reckdf1742e2017-01-19 15:56:21 -0800361 dump->proto().SerializeToZeroCopyStream(&stream);
362 }
363 delete dump;
364}
365
366} /* namespace uirenderer */
Dan Albert110e0072017-10-11 12:41:26 -0700367} /* namespace android */