blob: 1c7688464c276ad4319a82a9ad7e4d0bc1d121bc [file] [log] [blame]
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -04001/*
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 "CacheManager.h"
18
John Reck5f66fb82022-09-23 17:49:23 -040019#include <GrContextOptions.h>
20#include <SkExecutor.h>
21#include <SkGraphics.h>
22#include <SkMathPriv.h>
23#include <math.h>
24#include <utils/Trace.h>
25
26#include <set>
27
28#include "CanvasContext.h"
Alec Mouri22d753f2019-09-05 17:11:45 -070029#include "DeviceInfo.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040030#include "Layer.h"
Stan Ilieve75ef1f2017-11-27 17:22:42 -050031#include "Properties.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040032#include "RenderThread.h"
Stan Ilieve0fae232020-01-07 17:21:49 -050033#include "pipeline/skia/ATraceMemoryDump.h"
Stan Ilieve75ef1f2017-11-27 17:22:42 -050034#include "pipeline/skia/ShaderCache.h"
Derek Sollenberger0057db22018-03-29 14:18:44 -040035#include "pipeline/skia/SkiaMemoryTracer.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040036#include "renderstate/RenderState.h"
John Reck322b8ab2019-03-14 13:15:28 -070037#include "thread/CommonPool.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040038
39namespace android {
40namespace uirenderer {
41namespace renderthread {
42
John Reck5f66fb82022-09-23 17:49:23 -040043CacheManager::CacheManager(RenderThread& thread)
44 : mRenderThread(thread), mMemoryPolicy(loadMemoryPolicy()) {
45 mMaxSurfaceArea = static_cast<size_t>((DeviceInfo::getWidth() * DeviceInfo::getHeight()) *
46 mMemoryPolicy.initialMaxSurfaceAreaScale);
47 setupCacheLimits();
48}
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040049
John Reck5f66fb82022-09-23 17:49:23 -040050void CacheManager::setupCacheLimits() {
51 mMaxResourceBytes = mMaxSurfaceArea * mMemoryPolicy.surfaceSizeMultiplier;
52 mBackgroundResourceBytes = mMaxResourceBytes * mMemoryPolicy.backgroundRetentionPercent;
53 // This sets the maximum size for a single texture atlas in the GPU font cache. If
54 // necessary, the cache can allocate additional textures that are counted against the
55 // total cache limits provided to Skia.
56 mMaxGpuFontAtlasBytes = GrNextSizePow2(mMaxSurfaceArea);
57 // This sets the maximum size of the CPU font cache to be at least the same size as the
58 // total number of GPU font caches (i.e. 4 separate GPU atlases).
59 mMaxCpuFontCacheBytes = std::max(mMaxGpuFontAtlasBytes * 4, SkGraphics::GetFontCacheLimit());
60 mBackgroundCpuFontCacheBytes = mMaxCpuFontCacheBytes * mMemoryPolicy.backgroundRetentionPercent;
61
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -040062 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -040063 if (mGrContext) {
64 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
65 }
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040066}
67
Adlai Hollerd2345212020-10-07 14:16:40 -040068void CacheManager::reset(sk_sp<GrDirectContext> context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050069 if (context != mGrContext) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040070 destroy();
71 }
72
73 if (context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050074 mGrContext = std::move(context);
Robert Phillips57bb0bf2019-09-06 13:18:17 -040075 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
John Reck5f66fb82022-09-23 17:49:23 -040076 mLastDeferredCleanup = systemTime(CLOCK_MONOTONIC);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040077 }
78}
79
80void CacheManager::destroy() {
81 // cleanup any caches here as the GrContext is about to go away...
82 mGrContext.reset(nullptr);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040083}
84
John Reck322b8ab2019-03-14 13:15:28 -070085class CommonPoolExecutor : public SkExecutor {
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040086public:
John Reck0fa0cbc2019-04-05 16:57:46 -070087 virtual void add(std::function<void(void)> func) override { CommonPool::post(std::move(func)); }
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040088};
89
John Reck322b8ab2019-03-14 13:15:28 -070090static CommonPoolExecutor sDefaultExecutor;
91
John Reck0fa0cbc2019-04-05 16:57:46 -070092void CacheManager::configureContext(GrContextOptions* contextOptions, const void* identity,
93 ssize_t size) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040094 contextOptions->fAllowPathMaskCaching = true;
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -040095 contextOptions->fGlyphCacheTextureMaximumBytes = mMaxGpuFontAtlasBytes;
John Reck322b8ab2019-03-14 13:15:28 -070096 contextOptions->fExecutor = &sDefaultExecutor;
Stan Ilieve75ef1f2017-11-27 17:22:42 -050097
Yichi Chen9f959552018-03-29 21:21:54 +080098 auto& cache = skiapipeline::ShaderCache::get();
99 cache.initShaderDiskCache(identity, size);
100 contextOptions->fPersistentCache = &cache;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400101}
102
John Reck5f66fb82022-09-23 17:49:23 -0400103void CacheManager::trimMemory(TrimLevel mode) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400104 if (!mGrContext) {
105 return;
106 }
107
Greg Daniel41ef5662021-02-01 14:25:48 -0500108 // flush and submit all work to the gpu and wait for it to finish
109 mGrContext->flushAndSubmit(/*syncCpu=*/true);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400110
John Reck5f66fb82022-09-23 17:49:23 -0400111 if (!Properties::isHighEndGfx && mode >= TrimLevel::MODERATE) {
112 mode = TrimLevel::COMPLETE;
113 }
114
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400115 switch (mode) {
John Reck5f66fb82022-09-23 17:49:23 -0400116 case TrimLevel::COMPLETE:
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400117 mGrContext->freeGpuResources();
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400118 SkGraphics::PurgeAllCaches();
John Reck5f66fb82022-09-23 17:49:23 -0400119 mRenderThread.destroyRenderingContext();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400120 break;
John Reck5f66fb82022-09-23 17:49:23 -0400121 case TrimLevel::UI_HIDDEN:
Derek Sollenbergerb1f27aa2018-04-02 13:36:45 -0400122 // Here we purge all the unlocked scratch resources and then toggle the resources cache
123 // limits between the background and max amounts. This causes the unlocked resources
124 // that have persistent data to be purged in LRU order.
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400125 mGrContext->setResourceCacheLimit(mBackgroundResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400126 SkGraphics::SetFontCacheLimit(mBackgroundCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -0400127 mGrContext->purgeUnlockedResources(mMemoryPolicy.purgeScratchOnly);
128 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400129 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400130 break;
John Reck5f66fb82022-09-23 17:49:23 -0400131 default:
132 break;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400133 }
134}
135
136void CacheManager::trimStaleResources() {
137 if (!mGrContext) {
138 return;
139 }
Greg Danielc7ad4082020-05-14 15:38:26 -0400140 mGrContext->flushAndSubmit();
John Reckf846aee2019-10-08 23:28:41 +0000141 mGrContext->purgeResourcesNotUsedInMs(std::chrono::seconds(30));
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400142}
143
John Reck39207682021-05-12 19:10:47 -0400144void CacheManager::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
145 *cpuUsage = 0;
146 *gpuUsage = 0;
147 if (!mGrContext) {
148 return;
149 }
150
151 skiapipeline::SkiaMemoryTracer cpuTracer("category", true);
152 SkGraphics::DumpMemoryStatistics(&cpuTracer);
153 *cpuUsage += cpuTracer.total();
154
155 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
156 mGrContext->dumpMemoryStatistics(&gpuTracer);
157 *gpuUsage += gpuTracer.total();
158}
159
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400160void CacheManager::dumpMemoryUsage(String8& log, const RenderState* renderState) {
John Reck5f66fb82022-09-23 17:49:23 -0400161 log.appendFormat(R"(Memory policy:
162 Max surface area: %zu
163 Max resource usage: %.2fMB (x%.0f)
164 Background retention: %.0f%% (altUiHidden = %s)
165)",
166 mMaxSurfaceArea, mMaxResourceBytes / 1000000.f,
167 mMemoryPolicy.surfaceSizeMultiplier,
168 mMemoryPolicy.backgroundRetentionPercent * 100.0f,
169 mMemoryPolicy.useAlternativeUiHidden ? "true" : "false");
170 if (Properties::isSystemOrPersistent) {
171 log.appendFormat(" IsSystemOrPersistent\n");
172 }
173 log.appendFormat(" GPU Context timeout: %" PRIu64 "\n", ns2s(mMemoryPolicy.contextTimeout));
174 size_t stoppedContexts = 0;
175 for (auto context : mCanvasContexts) {
176 if (context->isStopped()) stoppedContexts++;
177 }
178 log.appendFormat("Contexts: %zu (stopped = %zu)\n", mCanvasContexts.size(), stoppedContexts);
179
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400180 if (!mGrContext) {
John Reck5f66fb82022-09-23 17:49:23 -0400181 log.appendFormat("No GPU context.\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400182 return;
183 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400184 std::vector<skiapipeline::ResourcePair> cpuResourceMap = {
185 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
186 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
187 {"skia/sk_resource_cache/rects-blur_", "Masks"},
188 {"skia/sk_resource_cache/tessellated", "Shadows"},
John Reck39207682021-05-12 19:10:47 -0400189 {"skia/sk_glyph_cache", "Glyph Cache"},
Derek Sollenberger0057db22018-03-29 14:18:44 -0400190 };
191 skiapipeline::SkiaMemoryTracer cpuTracer(cpuResourceMap, false);
192 SkGraphics::DumpMemoryStatistics(&cpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400193 if (cpuTracer.hasOutput()) {
194 log.appendFormat("CPU Caches:\n");
195 cpuTracer.logOutput(log);
John Reck39207682021-05-12 19:10:47 -0400196 log.appendFormat(" Glyph Count: %d \n", SkGraphics::GetFontCacheCountUsed());
197 log.appendFormat("Total CPU memory usage:\n");
198 cpuTracer.logTotals(log);
John Reck66e06d42021-05-11 17:04:54 -0400199 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400200
Derek Sollenberger0057db22018-03-29 14:18:44 -0400201 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
202 mGrContext->dumpMemoryStatistics(&gpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400203 if (gpuTracer.hasOutput()) {
204 log.appendFormat("GPU Caches:\n");
205 gpuTracer.logOutput(log);
206 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400207
John Reck66e06d42021-05-11 17:04:54 -0400208 if (renderState && renderState->mActiveLayers.size() > 0) {
209 log.appendFormat("Layer Info:\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400210
Stan Iliev564ca3e2018-09-04 22:00:00 +0000211 const char* layerType = Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL
John Reck0fa0cbc2019-04-05 16:57:46 -0700212 ? "GlLayer"
213 : "VkLayer";
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400214 size_t layerMemoryTotal = 0;
215 for (std::set<Layer*>::iterator it = renderState->mActiveLayers.begin();
John Reck1bcacfd2017-11-03 10:12:19 -0700216 it != renderState->mActiveLayers.end(); it++) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400217 const Layer* layer = *it;
John Reck1bcacfd2017-11-03 10:12:19 -0700218 log.appendFormat(" %s size %dx%d\n", layerType, layer->getWidth(),
219 layer->getHeight());
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400220 layerMemoryTotal += layer->getWidth() * layer->getHeight() * 4;
221 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400222 log.appendFormat(" Layers Total %6.2f KB (numLayers = %zu)\n",
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400223 layerMemoryTotal / 1024.0f, renderState->mActiveLayers.size());
224 }
225
Derek Sollenberger0057db22018-03-29 14:18:44 -0400226 log.appendFormat("Total GPU memory usage:\n");
227 gpuTracer.logTotals(log);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400228}
229
Stan Ilieve0fae232020-01-07 17:21:49 -0500230void CacheManager::onFrameCompleted() {
John Reck5f66fb82022-09-23 17:49:23 -0400231 cancelDestroyContext();
232 mFrameCompletions.next() = systemTime(CLOCK_MONOTONIC);
Stan Ilieve0fae232020-01-07 17:21:49 -0500233 if (ATRACE_ENABLED()) {
234 static skiapipeline::ATraceMemoryDump tracer;
235 tracer.startFrame();
236 SkGraphics::DumpMemoryStatistics(&tracer);
237 if (mGrContext) {
238 mGrContext->dumpMemoryStatistics(&tracer);
239 }
240 tracer.logTraces();
241 }
242}
243
John Reck5f66fb82022-09-23 17:49:23 -0400244void CacheManager::onThreadIdle() {
245 if (!mGrContext || mFrameCompletions.size() == 0) return;
246
247 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
248 // Rate limiting
249 if ((now - mLastDeferredCleanup) < 25_ms) {
250 mLastDeferredCleanup = now;
251 const nsecs_t frameCompleteNanos = mFrameCompletions[0];
252 const nsecs_t frameDiffNanos = now - frameCompleteNanos;
253 const nsecs_t cleanupMillis =
254 ns2ms(std::max(frameDiffNanos, mMemoryPolicy.minimumResourceRetention));
255 mGrContext->performDeferredCleanup(std::chrono::milliseconds(cleanupMillis),
256 mMemoryPolicy.purgeScratchOnly);
257 }
258}
259
260void CacheManager::scheduleDestroyContext() {
261 if (mMemoryPolicy.contextTimeout > 0) {
262 mRenderThread.queue().postDelayed(mMemoryPolicy.contextTimeout,
263 [this, genId = mGenerationId] {
264 if (mGenerationId != genId) return;
265 // GenID should have already stopped this, but just in
266 // case
267 if (!areAllContextsStopped()) return;
268 mRenderThread.destroyRenderingContext();
269 });
270 }
271}
272
273void CacheManager::cancelDestroyContext() {
274 if (mIsDestructionPending) {
275 mIsDestructionPending = false;
276 mGenerationId++;
277 }
278}
279
280bool CacheManager::areAllContextsStopped() {
281 for (auto context : mCanvasContexts) {
282 if (!context->isStopped()) return false;
283 }
284 return true;
285}
286
287void CacheManager::checkUiHidden() {
288 if (!mGrContext) return;
289
290 if (mMemoryPolicy.useAlternativeUiHidden && areAllContextsStopped()) {
291 trimMemory(TrimLevel::UI_HIDDEN);
292 }
293}
294
295void CacheManager::registerCanvasContext(CanvasContext* context) {
296 mCanvasContexts.push_back(context);
297 cancelDestroyContext();
298}
299
300void CacheManager::unregisterCanvasContext(CanvasContext* context) {
301 std::erase(mCanvasContexts, context);
302 checkUiHidden();
303 if (mCanvasContexts.empty()) {
304 scheduleDestroyContext();
305 }
306}
307
308void CacheManager::onContextStopped(CanvasContext* context) {
309 checkUiHidden();
310 if (mMemoryPolicy.releaseContextOnStoppedOnly && areAllContextsStopped()) {
311 scheduleDestroyContext();
312 }
313}
314
315void CacheManager::notifyNextFrameSize(int width, int height) {
316 int frameArea = width * height;
317 if (frameArea > mMaxSurfaceArea) {
318 mMaxSurfaceArea = frameArea;
319 setupCacheLimits();
Nader Jawaddd1fcab2021-06-10 18:54:23 -0700320 }
321}
322
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400323} /* namespace renderthread */
324} /* namespace uirenderer */
325} /* namespace android */