blob: c4186174b637b0d40ebc536c13da72e402f68d2a [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
Dan Albert110e0072017-10-11 12:41:26 -070019#include <errno.h>
John Reckdf1742e2017-01-19 15:56:21 -080020#include <fcntl.h>
Stan Iliev637ba5e2019-08-16 13:43:08 -040021#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
Dan Albert110e0072017-10-11 12:41:26 -070022#include <inttypes.h>
Stan Iliev637ba5e2019-08-16 13:43:08 -040023#include <log/log.h>
John Reck1bcacfd2017-11-03 10:12:19 -070024#include <sys/mman.h>
Dan Albert110e0072017-10-11 12:41:26 -070025#include <sys/stat.h>
26#include <sys/types.h>
John Reckdf1742e2017-01-19 15:56:21 -080027#include <unistd.h>
28
Stan Iliev637ba5e2019-08-16 13:43:08 -040029#include <algorithm>
30#include <map>
31#include <vector>
32
33#include "JankTracker.h"
34#include "protos/graphicsstats.pb.h"
35
John Reckdf1742e2017-01-19 15:56:21 -080036namespace android {
37namespace uirenderer {
38
39using namespace google::protobuf;
Stan Iliev637ba5e2019-08-16 13:43:08 -040040using namespace uirenderer::protos;
John Reckdf1742e2017-01-19 15:56:21 -080041
42constexpr int32_t sCurrentFileVersion = 1;
43constexpr int32_t sHeaderSize = 4;
44static_assert(sizeof(sCurrentFileVersion) == sHeaderSize, "Header size is wrong");
45
John Reck7075c792017-07-05 14:03:43 -070046constexpr int sHistogramSize = ProfileData::HistogramSize();
Stan Iliev7203e1f2019-07-25 13:12:02 -040047constexpr int sGPUHistogramSize = ProfileData::GPUHistogramSize();
John Reckdf1742e2017-01-19 15:56:21 -080048
Stan Iliev637ba5e2019-08-16 13:43:08 -040049static bool mergeProfileDataIntoProto(protos::GraphicsStatsProto* proto, const std::string& package,
50 int64_t versionCode, int64_t startTime, int64_t endTime,
51 const ProfileData* data);
Kweku Adams1856a4c2018-04-03 16:31:10 -070052static void dumpAsTextToFd(protos::GraphicsStatsProto* proto, int outFd);
John Reckdf1742e2017-01-19 15:56:21 -080053
John Reck915883b2017-05-03 10:27:20 -070054class FileDescriptor {
55public:
Chih-Hung Hsiehf21b0b62018-12-20 13:48:02 -080056 explicit FileDescriptor(int fd) : mFd(fd) {}
John Reck915883b2017-05-03 10:27:20 -070057 ~FileDescriptor() {
58 if (mFd != -1) {
59 close(mFd);
60 mFd = -1;
61 }
62 }
63 bool valid() { return mFd != -1; }
Stan Iliev637ba5e2019-08-16 13:43:08 -040064 operator int() { return mFd; } // NOLINT(google-explicit-constructor)
John Reck1bcacfd2017-11-03 10:12:19 -070065
John Reck915883b2017-05-03 10:27:20 -070066private:
67 int mFd;
68};
69
70class FileOutputStreamLite : public io::ZeroCopyOutputStream {
71public:
Chih-Hung Hsiehf21b0b62018-12-20 13:48:02 -080072 explicit FileOutputStreamLite(int fd) : mCopyAdapter(fd), mImpl(&mCopyAdapter) {}
John Reck915883b2017-05-03 10:27:20 -070073 virtual ~FileOutputStreamLite() {}
74
75 int GetErrno() { return mCopyAdapter.mErrno; }
76
John Reck1bcacfd2017-11-03 10:12:19 -070077 virtual bool Next(void** data, int* size) override { return mImpl.Next(data, size); }
John Reck915883b2017-05-03 10:27:20 -070078
John Reck1bcacfd2017-11-03 10:12:19 -070079 virtual void BackUp(int count) override { mImpl.BackUp(count); }
John Reck915883b2017-05-03 10:27:20 -070080
John Reck1bcacfd2017-11-03 10:12:19 -070081 virtual int64 ByteCount() const override { return mImpl.ByteCount(); }
John Reck915883b2017-05-03 10:27:20 -070082
John Reck1bcacfd2017-11-03 10:12:19 -070083 bool Flush() { return mImpl.Flush(); }
John Reck915883b2017-05-03 10:27:20 -070084
85private:
86 struct FDAdapter : public io::CopyingOutputStream {
87 int mFd;
88 int mErrno = 0;
89
Chih-Hung Hsiehf21b0b62018-12-20 13:48:02 -080090 explicit FDAdapter(int fd) : mFd(fd) {}
John Reck915883b2017-05-03 10:27:20 -070091 virtual ~FDAdapter() {}
92
93 virtual bool Write(const void* buffer, int size) override {
94 int ret;
95 while (size) {
John Reck1bcacfd2017-11-03 10:12:19 -070096 ret = TEMP_FAILURE_RETRY(write(mFd, buffer, size));
John Reck915883b2017-05-03 10:27:20 -070097 if (ret <= 0) {
98 mErrno = errno;
99 return false;
100 }
101 size -= ret;
102 }
103 return true;
104 }
105 };
106
107 FileOutputStreamLite::FDAdapter mCopyAdapter;
108 io::CopyingOutputStreamAdaptor mImpl;
109};
110
John Reck1bcacfd2017-11-03 10:12:19 -0700111bool GraphicsStatsService::parseFromFile(const std::string& path,
Kweku Adams1856a4c2018-04-03 16:31:10 -0700112 protos::GraphicsStatsProto* output) {
John Reck915883b2017-05-03 10:27:20 -0700113 FileDescriptor fd{open(path.c_str(), O_RDONLY)};
114 if (!fd.valid()) {
John Reckdf1742e2017-01-19 15:56:21 -0800115 int err = errno;
116 // The file not existing is normal for addToDump(), so only log if
117 // we get an unexpected error
118 if (err != ENOENT) {
119 ALOGW("Failed to open '%s', errno=%d (%s)", path.c_str(), err, strerror(err));
120 }
121 return false;
122 }
John Reck915883b2017-05-03 10:27:20 -0700123 struct stat sb;
124 if (fstat(fd, &sb) || sb.st_size < sHeaderSize) {
125 int err = errno;
126 // The file not existing is normal for addToDump(), so only log if
127 // we get an unexpected error
128 if (err != ENOENT) {
129 ALOGW("Failed to fstat '%s', errno=%d (%s) (st_size %d)", path.c_str(), err,
John Reck1bcacfd2017-11-03 10:12:19 -0700130 strerror(err), (int)sb.st_size);
John Reck915883b2017-05-03 10:27:20 -0700131 }
132 return false;
133 }
134 void* addr = mmap(nullptr, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
zhangkuili24a1bc32018-05-29 10:23:29 +0800135 if (addr == MAP_FAILED) {
John Reck915883b2017-05-03 10:27:20 -0700136 int err = errno;
137 // The file not existing is normal for addToDump(), so only log if
138 // we get an unexpected error
139 if (err != ENOENT) {
140 ALOGW("Failed to mmap '%s', errno=%d (%s)", path.c_str(), err, strerror(err));
141 }
142 return false;
143 }
144 uint32_t file_version = *reinterpret_cast<uint32_t*>(addr);
145 if (file_version != sCurrentFileVersion) {
146 ALOGW("file_version mismatch! expected %d got %d", sCurrentFileVersion, file_version);
liulvping4832438c2018-12-20 20:34:56 +0800147 munmap(addr, sb.st_size);
John Reckdf1742e2017-01-19 15:56:21 -0800148 return false;
149 }
150
John Reck915883b2017-05-03 10:27:20 -0700151 void* data = reinterpret_cast<uint8_t*>(addr) + sHeaderSize;
152 int dataSize = sb.st_size - sHeaderSize;
153 io::ArrayInputStream input{data, dataSize};
John Reckdf1742e2017-01-19 15:56:21 -0800154 bool success = output->ParseFromZeroCopyStream(&input);
John Reck915883b2017-05-03 10:27:20 -0700155 if (!success) {
John Reck1bcacfd2017-11-03 10:12:19 -0700156 ALOGW("Parse failed on '%s' error='%s'", path.c_str(),
157 output->InitializationErrorString().c_str());
John Reckdf1742e2017-01-19 15:56:21 -0800158 }
liulvping4832438c2018-12-20 20:34:56 +0800159 munmap(addr, sb.st_size);
John Reckdf1742e2017-01-19 15:56:21 -0800160 return success;
161}
162
Kweku Adams1856a4c2018-04-03 16:31:10 -0700163bool mergeProfileDataIntoProto(protos::GraphicsStatsProto* proto, const std::string& package,
Dianne Hackborn73453e42017-12-11 16:30:36 -0800164 int64_t versionCode, int64_t startTime, int64_t endTime,
John Reck1bcacfd2017-11-03 10:12:19 -0700165 const ProfileData* data) {
John Reckdf1742e2017-01-19 15:56:21 -0800166 if (proto->stats_start() == 0 || proto->stats_start() > startTime) {
167 proto->set_stats_start(startTime);
168 }
169 if (proto->stats_end() == 0 || proto->stats_end() < endTime) {
170 proto->set_stats_end(endTime);
171 }
172 proto->set_package_name(package);
173 proto->set_version_code(versionCode);
Stan Iliev637ba5e2019-08-16 13:43:08 -0400174 proto->set_pipeline(data->pipelineType() == RenderPipelineType::SkiaGL ?
175 GraphicsStatsProto_PipelineType_GL : GraphicsStatsProto_PipelineType_VULKAN);
John Reckdf1742e2017-01-19 15:56:21 -0800176 auto summary = proto->mutable_summary();
John Reck7075c792017-07-05 14:03:43 -0700177 summary->set_total_frames(summary->total_frames() + data->totalFrameCount());
178 summary->set_janky_frames(summary->janky_frames() + data->jankFrameCount());
John Reck1bcacfd2017-11-03 10:12:19 -0700179 summary->set_missed_vsync_count(summary->missed_vsync_count() +
180 data->jankTypeCount(kMissedVsync));
181 summary->set_high_input_latency_count(summary->high_input_latency_count() +
182 data->jankTypeCount(kHighInputLatency));
183 summary->set_slow_ui_thread_count(summary->slow_ui_thread_count() +
184 data->jankTypeCount(kSlowUI));
185 summary->set_slow_bitmap_upload_count(summary->slow_bitmap_upload_count() +
186 data->jankTypeCount(kSlowSync));
187 summary->set_slow_draw_count(summary->slow_draw_count() + data->jankTypeCount(kSlowRT));
Stan Iliev637ba5e2019-08-16 13:43:08 -0400188 summary->set_missed_deadline_count(summary->missed_deadline_count() +
189 data->jankTypeCount(kMissedDeadline));
John Reckdf1742e2017-01-19 15:56:21 -0800190
191 bool creatingHistogram = false;
192 if (proto->histogram_size() == 0) {
193 proto->mutable_histogram()->Reserve(sHistogramSize);
194 creatingHistogram = true;
195 } else if (proto->histogram_size() != sHistogramSize) {
John Reck1bcacfd2017-11-03 10:12:19 -0700196 ALOGE("Histogram size mismatch, proto is %d expected %d", proto->histogram_size(),
197 sHistogramSize);
John Reck5206a872017-09-18 11:08:31 -0700198 return false;
John Reckdf1742e2017-01-19 15:56:21 -0800199 }
John Reck7075c792017-07-05 14:03:43 -0700200 int index = 0;
John Reck5206a872017-09-18 11:08:31 -0700201 bool hitMergeError = false;
John Reck7075c792017-07-05 14:03:43 -0700202 data->histogramForEach([&](ProfileData::HistogramEntry entry) {
John Reck5206a872017-09-18 11:08:31 -0700203 if (hitMergeError) return;
204
Kweku Adams1856a4c2018-04-03 16:31:10 -0700205 protos::GraphicsStatsHistogramBucketProto* bucket;
John Reckdf1742e2017-01-19 15:56:21 -0800206 if (creatingHistogram) {
207 bucket = proto->add_histogram();
John Reck7075c792017-07-05 14:03:43 -0700208 bucket->set_render_millis(entry.renderTimeMs);
John Reckdf1742e2017-01-19 15:56:21 -0800209 } else {
John Reck7075c792017-07-05 14:03:43 -0700210 bucket = proto->mutable_histogram(index);
John Reck5206a872017-09-18 11:08:31 -0700211 if (bucket->render_millis() != static_cast<int32_t>(entry.renderTimeMs)) {
John Reck1bcacfd2017-11-03 10:12:19 -0700212 ALOGW("Frame time mistmatch %d vs. %u", bucket->render_millis(),
213 entry.renderTimeMs);
John Reck5206a872017-09-18 11:08:31 -0700214 hitMergeError = true;
215 return;
216 }
John Reckdf1742e2017-01-19 15:56:21 -0800217 }
John Reck7075c792017-07-05 14:03:43 -0700218 bucket->set_frame_count(bucket->frame_count() + entry.frameCount);
219 index++;
220 });
Stan Iliev7203e1f2019-07-25 13:12:02 -0400221 if (hitMergeError) return false;
222 // fill in GPU frame time histogram
223 creatingHistogram = false;
224 if (proto->gpu_histogram_size() == 0) {
225 proto->mutable_gpu_histogram()->Reserve(sGPUHistogramSize);
226 creatingHistogram = true;
227 } else if (proto->gpu_histogram_size() != sGPUHistogramSize) {
228 ALOGE("GPU histogram size mismatch, proto is %d expected %d", proto->gpu_histogram_size(),
229 sGPUHistogramSize);
230 return false;
231 }
232 index = 0;
233 data->histogramGPUForEach([&](ProfileData::HistogramEntry entry) {
234 if (hitMergeError) return;
235
236 protos::GraphicsStatsHistogramBucketProto* bucket;
237 if (creatingHistogram) {
238 bucket = proto->add_gpu_histogram();
239 bucket->set_render_millis(entry.renderTimeMs);
240 } else {
241 bucket = proto->mutable_gpu_histogram(index);
242 if (bucket->render_millis() != static_cast<int32_t>(entry.renderTimeMs)) {
243 ALOGW("GPU frame time mistmatch %d vs. %u", bucket->render_millis(),
244 entry.renderTimeMs);
245 hitMergeError = true;
246 return;
247 }
248 }
249 bucket->set_frame_count(bucket->frame_count() + entry.frameCount);
250 index++;
251 });
John Reck5206a872017-09-18 11:08:31 -0700252 return !hitMergeError;
John Reckdf1742e2017-01-19 15:56:21 -0800253}
254
Kweku Adams1856a4c2018-04-03 16:31:10 -0700255static int32_t findPercentile(protos::GraphicsStatsProto* proto, int percentile) {
John Reckdf1742e2017-01-19 15:56:21 -0800256 int32_t pos = percentile * proto->summary().total_frames() / 100;
257 int32_t remaining = proto->summary().total_frames() - pos;
258 for (auto it = proto->histogram().rbegin(); it != proto->histogram().rend(); ++it) {
259 remaining -= it->frame_count();
260 if (remaining <= 0) {
261 return it->render_millis();
262 }
263 }
264 return 0;
265}
266
Stan Iliev7203e1f2019-07-25 13:12:02 -0400267static int32_t findGPUPercentile(protos::GraphicsStatsProto* proto, int percentile) {
268 uint32_t totalGPUFrameCount = 0; // this is usually proto->summary().total_frames() - 3.
269 for (auto it = proto->gpu_histogram().rbegin(); it != proto->gpu_histogram().rend(); ++it) {
270 totalGPUFrameCount += it->frame_count();
271 }
272 int32_t pos = percentile * totalGPUFrameCount / 100;
273 int32_t remaining = totalGPUFrameCount - pos;
274 for (auto it = proto->gpu_histogram().rbegin(); it != proto->gpu_histogram().rend(); ++it) {
275 remaining -= it->frame_count();
276 if (remaining <= 0) {
277 return it->render_millis();
278 }
279 }
280 return 0;
281}
282
Kweku Adams1856a4c2018-04-03 16:31:10 -0700283void dumpAsTextToFd(protos::GraphicsStatsProto* proto, int fd) {
John Reckdf1742e2017-01-19 15:56:21 -0800284 // This isn't a full validation, just enough that we can deref at will
John Reck5206a872017-09-18 11:08:31 -0700285 if (proto->package_name().empty() || !proto->has_summary()) {
286 ALOGW("Skipping dump, invalid package_name() '%s' or summary %d",
John Reck1bcacfd2017-11-03 10:12:19 -0700287 proto->package_name().c_str(), proto->has_summary());
John Reck5206a872017-09-18 11:08:31 -0700288 return;
289 }
John Reckdf1742e2017-01-19 15:56:21 -0800290 dprintf(fd, "\nPackage: %s", proto->package_name().c_str());
Colin Crossd013a882018-10-26 13:04:41 -0700291 dprintf(fd, "\nVersion: %" PRId64, proto->version_code());
292 dprintf(fd, "\nStats since: %" PRId64 "ns", proto->stats_start());
293 dprintf(fd, "\nStats end: %" PRId64 "ns", proto->stats_end());
John Reckdf1742e2017-01-19 15:56:21 -0800294 auto summary = proto->summary();
295 dprintf(fd, "\nTotal frames rendered: %d", summary.total_frames());
296 dprintf(fd, "\nJanky frames: %d (%.2f%%)", summary.janky_frames(),
John Reck1bcacfd2017-11-03 10:12:19 -0700297 (float)summary.janky_frames() / (float)summary.total_frames() * 100.0f);
John Reckdf1742e2017-01-19 15:56:21 -0800298 dprintf(fd, "\n50th percentile: %dms", findPercentile(proto, 50));
299 dprintf(fd, "\n90th percentile: %dms", findPercentile(proto, 90));
300 dprintf(fd, "\n95th percentile: %dms", findPercentile(proto, 95));
301 dprintf(fd, "\n99th percentile: %dms", findPercentile(proto, 99));
302 dprintf(fd, "\nNumber Missed Vsync: %d", summary.missed_vsync_count());
303 dprintf(fd, "\nNumber High input latency: %d", summary.high_input_latency_count());
304 dprintf(fd, "\nNumber Slow UI thread: %d", summary.slow_ui_thread_count());
305 dprintf(fd, "\nNumber Slow bitmap uploads: %d", summary.slow_bitmap_upload_count());
306 dprintf(fd, "\nNumber Slow issue draw commands: %d", summary.slow_draw_count());
John Reck0e486472018-03-19 14:06:16 -0700307 dprintf(fd, "\nNumber Frame deadline missed: %d", summary.missed_deadline_count());
John Reckdf1742e2017-01-19 15:56:21 -0800308 dprintf(fd, "\nHISTOGRAM:");
309 for (const auto& it : proto->histogram()) {
310 dprintf(fd, " %dms=%d", it.render_millis(), it.frame_count());
311 }
Stan Iliev7203e1f2019-07-25 13:12:02 -0400312 dprintf(fd, "\n50th gpu percentile: %dms", findGPUPercentile(proto, 50));
313 dprintf(fd, "\n90th gpu percentile: %dms", findGPUPercentile(proto, 90));
314 dprintf(fd, "\n95th gpu percentile: %dms", findGPUPercentile(proto, 95));
315 dprintf(fd, "\n99th gpu percentile: %dms", findGPUPercentile(proto, 99));
316 dprintf(fd, "\nGPU HISTOGRAM:");
317 for (const auto& it : proto->gpu_histogram()) {
318 dprintf(fd, " %dms=%d", it.render_millis(), it.frame_count());
319 }
John Reckdf1742e2017-01-19 15:56:21 -0800320 dprintf(fd, "\n");
321}
322
323void GraphicsStatsService::saveBuffer(const std::string& path, const std::string& package,
Dianne Hackborn73453e42017-12-11 16:30:36 -0800324 int64_t versionCode, int64_t startTime, int64_t endTime,
John Reck1bcacfd2017-11-03 10:12:19 -0700325 const ProfileData* data) {
Kweku Adams1856a4c2018-04-03 16:31:10 -0700326 protos::GraphicsStatsProto statsProto;
John Reckdf1742e2017-01-19 15:56:21 -0800327 if (!parseFromFile(path, &statsProto)) {
328 statsProto.Clear();
329 }
John Reck5206a872017-09-18 11:08:31 -0700330 if (!mergeProfileDataIntoProto(&statsProto, package, versionCode, startTime, endTime, data)) {
331 return;
332 }
John Reckdf1742e2017-01-19 15:56:21 -0800333 // Although we might not have read any data from the file, merging the existing data
334 // should always fully-initialize the proto
John Reck5206a872017-09-18 11:08:31 -0700335 if (!statsProto.IsInitialized()) {
336 ALOGE("proto initialization error %s", statsProto.InitializationErrorString().c_str());
337 return;
338 }
339 if (statsProto.package_name().empty() || !statsProto.has_summary()) {
John Reck1bcacfd2017-11-03 10:12:19 -0700340 ALOGE("missing package_name() '%s' summary %d", statsProto.package_name().c_str(),
341 statsProto.has_summary());
John Reck5206a872017-09-18 11:08:31 -0700342 return;
343 }
John Reckdf1742e2017-01-19 15:56:21 -0800344 int outFd = open(path.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0660);
345 if (outFd <= 0) {
346 int err = errno;
347 ALOGW("Failed to open '%s', error=%d (%s)", path.c_str(), err, strerror(err));
348 return;
349 }
350 int wrote = write(outFd, &sCurrentFileVersion, sHeaderSize);
351 if (wrote != sHeaderSize) {
352 int err = errno;
John Reck1bcacfd2017-11-03 10:12:19 -0700353 ALOGW("Failed to write header to '%s', returned=%d errno=%d (%s)", path.c_str(), wrote, err,
354 strerror(err));
John Reckdf1742e2017-01-19 15:56:21 -0800355 close(outFd);
356 return;
357 }
358 {
John Reck915883b2017-05-03 10:27:20 -0700359 FileOutputStreamLite output(outFd);
John Reckdf1742e2017-01-19 15:56:21 -0800360 bool success = statsProto.SerializeToZeroCopyStream(&output) && output.Flush();
361 if (output.GetErrno() != 0) {
John Reck1bcacfd2017-11-03 10:12:19 -0700362 ALOGW("Error writing to fd=%d, path='%s' err=%d (%s)", outFd, path.c_str(),
363 output.GetErrno(), strerror(output.GetErrno()));
John Reckdf1742e2017-01-19 15:56:21 -0800364 success = false;
365 } else if (!success) {
366 ALOGW("Serialize failed on '%s' unknown error", path.c_str());
367 }
368 }
369 close(outFd);
370}
371
372class GraphicsStatsService::Dump {
373public:
Stan Iliev637ba5e2019-08-16 13:43:08 -0400374 Dump(int outFd, DumpType type) : mFd(outFd), mType(type) {
375 if (mFd == -1 && mType == DumpType::Protobuf) {
376 mType = DumpType::ProtobufStatsd;
377 }
378 }
John Reckdf1742e2017-01-19 15:56:21 -0800379 int fd() { return mFd; }
380 DumpType type() { return mType; }
Kweku Adams1856a4c2018-04-03 16:31:10 -0700381 protos::GraphicsStatsServiceDumpProto& proto() { return mProto; }
Stan Iliev637ba5e2019-08-16 13:43:08 -0400382 void mergeStat(const protos::GraphicsStatsProto& stat);
383 void updateProto();
John Reck1bcacfd2017-11-03 10:12:19 -0700384
John Reckdf1742e2017-01-19 15:56:21 -0800385private:
Stan Iliev637ba5e2019-08-16 13:43:08 -0400386 // use package name and app version for a key
387 typedef std::pair<std::string, int64_t> DumpKey;
388
389 std::map<DumpKey, protos::GraphicsStatsProto> mStats;
John Reckdf1742e2017-01-19 15:56:21 -0800390 int mFd;
391 DumpType mType;
Kweku Adams1856a4c2018-04-03 16:31:10 -0700392 protos::GraphicsStatsServiceDumpProto mProto;
John Reckdf1742e2017-01-19 15:56:21 -0800393};
394
Stan Iliev637ba5e2019-08-16 13:43:08 -0400395void GraphicsStatsService::Dump::mergeStat(const protos::GraphicsStatsProto& stat) {
396 auto dumpKey = std::make_pair(stat.package_name(), stat.version_code());
397 auto findIt = mStats.find(dumpKey);
398 if (findIt == mStats.end()) {
399 mStats[dumpKey] = stat;
400 } else {
401 auto summary = findIt->second.mutable_summary();
402 summary->set_total_frames(summary->total_frames() + stat.summary().total_frames());
403 summary->set_janky_frames(summary->janky_frames() + stat.summary().janky_frames());
404 summary->set_missed_vsync_count(summary->missed_vsync_count() +
405 stat.summary().missed_vsync_count());
406 summary->set_high_input_latency_count(summary->high_input_latency_count() +
407 stat.summary().high_input_latency_count());
408 summary->set_slow_ui_thread_count(summary->slow_ui_thread_count() +
409 stat.summary().slow_ui_thread_count());
410 summary->set_slow_bitmap_upload_count(summary->slow_bitmap_upload_count() +
411 stat.summary().slow_bitmap_upload_count());
412 summary->set_slow_draw_count(summary->slow_draw_count() + stat.summary().slow_draw_count());
413 summary->set_missed_deadline_count(summary->missed_deadline_count() +
414 stat.summary().missed_deadline_count());
415 for (int bucketIndex = 0; bucketIndex < findIt->second.histogram_size(); bucketIndex++) {
416 auto bucket = findIt->second.mutable_histogram(bucketIndex);
417 bucket->set_frame_count(bucket->frame_count() +
418 stat.histogram(bucketIndex).frame_count());
419 }
420 for (int bucketIndex = 0; bucketIndex < findIt->second.gpu_histogram_size();
421 bucketIndex++) {
422 auto bucket = findIt->second.mutable_gpu_histogram(bucketIndex);
423 bucket->set_frame_count(bucket->frame_count() +
424 stat.gpu_histogram(bucketIndex).frame_count());
425 }
426 findIt->second.set_stats_start(std::min(findIt->second.stats_start(), stat.stats_start()));
427 findIt->second.set_stats_end(std::max(findIt->second.stats_end(), stat.stats_end()));
428 }
429}
430
431void GraphicsStatsService::Dump::updateProto() {
432 for (auto& stat : mStats) {
433 mProto.add_stats()->CopyFrom(stat.second);
434 }
435}
436
John Reckdf1742e2017-01-19 15:56:21 -0800437GraphicsStatsService::Dump* GraphicsStatsService::createDump(int outFd, DumpType type) {
438 return new Dump(outFd, type);
439}
440
John Reck1bcacfd2017-11-03 10:12:19 -0700441void GraphicsStatsService::addToDump(Dump* dump, const std::string& path,
Dianne Hackborn73453e42017-12-11 16:30:36 -0800442 const std::string& package, int64_t versionCode,
443 int64_t startTime, int64_t endTime, const ProfileData* data) {
Kweku Adams1856a4c2018-04-03 16:31:10 -0700444 protos::GraphicsStatsProto statsProto;
John Reckdf1742e2017-01-19 15:56:21 -0800445 if (!path.empty() && !parseFromFile(path, &statsProto)) {
446 statsProto.Clear();
447 }
John Reck1bcacfd2017-11-03 10:12:19 -0700448 if (data &&
449 !mergeProfileDataIntoProto(&statsProto, package, versionCode, startTime, endTime, data)) {
John Reck5206a872017-09-18 11:08:31 -0700450 return;
John Reckdf1742e2017-01-19 15:56:21 -0800451 }
452 if (!statsProto.IsInitialized()) {
453 ALOGW("Failed to load profile data from path '%s' and data %p",
John Reck1bcacfd2017-11-03 10:12:19 -0700454 path.empty() ? "<empty>" : path.c_str(), data);
John Reckdf1742e2017-01-19 15:56:21 -0800455 return;
456 }
Stan Iliev637ba5e2019-08-16 13:43:08 -0400457 if (dump->type() == DumpType::ProtobufStatsd) {
458 dump->mergeStat(statsProto);
459 } else if (dump->type() == DumpType::Protobuf) {
John Reckdf1742e2017-01-19 15:56:21 -0800460 dump->proto().add_stats()->CopyFrom(statsProto);
461 } else {
462 dumpAsTextToFd(&statsProto, dump->fd());
463 }
464}
465
466void GraphicsStatsService::addToDump(Dump* dump, const std::string& path) {
Kweku Adams1856a4c2018-04-03 16:31:10 -0700467 protos::GraphicsStatsProto statsProto;
John Reckdf1742e2017-01-19 15:56:21 -0800468 if (!parseFromFile(path, &statsProto)) {
469 return;
470 }
Stan Iliev637ba5e2019-08-16 13:43:08 -0400471 if (dump->type() == DumpType::ProtobufStatsd) {
472 dump->mergeStat(statsProto);
473 } else if (dump->type() == DumpType::Protobuf) {
John Reckdf1742e2017-01-19 15:56:21 -0800474 dump->proto().add_stats()->CopyFrom(statsProto);
475 } else {
476 dumpAsTextToFd(&statsProto, dump->fd());
477 }
478}
479
480void GraphicsStatsService::finishDump(Dump* dump) {
481 if (dump->type() == DumpType::Protobuf) {
John Reck915883b2017-05-03 10:27:20 -0700482 FileOutputStreamLite stream(dump->fd());
John Reckdf1742e2017-01-19 15:56:21 -0800483 dump->proto().SerializeToZeroCopyStream(&stream);
484 }
485 delete dump;
486}
487
Stan Iliev637ba5e2019-08-16 13:43:08 -0400488class MemOutputStreamLite : public io::ZeroCopyOutputStream {
489public:
490 explicit MemOutputStreamLite() : mCopyAdapter(), mImpl(&mCopyAdapter) {}
491 virtual ~MemOutputStreamLite() {}
492
493 virtual bool Next(void** data, int* size) override { return mImpl.Next(data, size); }
494
495 virtual void BackUp(int count) override { mImpl.BackUp(count); }
496
497 virtual int64 ByteCount() const override { return mImpl.ByteCount(); }
498
499 bool Flush() { return mImpl.Flush(); }
500
501 void copyData(const DumpMemoryFn& reader, void* param1, void* param2) {
502 int bufferOffset = 0;
503 int totalSize = mCopyAdapter.mBuffersSize - mCopyAdapter.mCurrentBufferUnusedSize;
504 int totalDataLeft = totalSize;
505 for (auto& it : mCopyAdapter.mBuffers) {
506 int bufferSize = std::min(totalDataLeft, (int)it.size()); // last buffer is not full
507 reader(it.data(), bufferOffset, bufferSize, totalSize, param1, param2);
508 bufferOffset += bufferSize;
509 totalDataLeft -= bufferSize;
510 }
511 }
512
513private:
514 struct MemAdapter : public io::CopyingOutputStream {
515 // Data is stored in an array of buffers.
516 // JNI SetByteArrayRegion assembles data in one continuous Java byte[] buffer.
517 std::vector<std::vector<unsigned char>> mBuffers;
518 int mBuffersSize = 0; // total bytes allocated in mBuffers
519 int mCurrentBufferUnusedSize = 0; // unused bytes in the last buffer mBuffers.back()
520 unsigned char* mCurrentBuffer = nullptr; // pointer to next free byte in mBuffers.back()
521
522 explicit MemAdapter() {}
523 virtual ~MemAdapter() {}
524
525 virtual bool Write(const void* buffer, int size) override {
526 while (size > 0) {
527 if (0 == mCurrentBufferUnusedSize) {
528 mCurrentBufferUnusedSize =
529 std::max(size, mBuffersSize ? 2 * mBuffersSize : 10000);
530 mBuffers.emplace_back();
531 mBuffers.back().resize(mCurrentBufferUnusedSize);
532 mCurrentBuffer = mBuffers.back().data();
533 mBuffersSize += mCurrentBufferUnusedSize;
534 }
535 int dataMoved = std::min(mCurrentBufferUnusedSize, size);
536 memcpy(mCurrentBuffer, buffer, dataMoved);
537 mCurrentBufferUnusedSize -= dataMoved;
538 mCurrentBuffer += dataMoved;
539 buffer = reinterpret_cast<const unsigned char*>(buffer) + dataMoved;
540 size -= dataMoved;
541 }
542 return true;
543 }
544 };
545
546 MemOutputStreamLite::MemAdapter mCopyAdapter;
547 io::CopyingOutputStreamAdaptor mImpl;
548};
549
550void GraphicsStatsService::finishDumpInMemory(Dump* dump, const DumpMemoryFn& reader, void* param1,
551 void* param2) {
552 MemOutputStreamLite stream;
553 dump->updateProto();
554 bool success = dump->proto().SerializeToZeroCopyStream(&stream) && stream.Flush();
555 delete dump;
556 if (!success) {
557 return;
558 }
559 stream.copyData(reader, param1, param2);
560}
561
John Reckdf1742e2017-01-19 15:56:21 -0800562} /* namespace uirenderer */
Dan Albert110e0072017-10-11 12:41:26 -0700563} /* namespace android */