blob: 1d24e718db1a7aa72ca9af22b590ff7addec13a9 [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;
Christopher Dalton3fcb6972019-02-21 20:09:22 +0000101 contextOptions->fGpuPathRenderers &= ~GpuPathRenderers::kCoverageCounting;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400102}
103
John Reck5f66fb82022-09-23 17:49:23 -0400104void CacheManager::trimMemory(TrimLevel mode) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400105 if (!mGrContext) {
106 return;
107 }
108
Greg Daniel41ef5662021-02-01 14:25:48 -0500109 // flush and submit all work to the gpu and wait for it to finish
110 mGrContext->flushAndSubmit(/*syncCpu=*/true);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400111
John Reck5f66fb82022-09-23 17:49:23 -0400112 if (!Properties::isHighEndGfx && mode >= TrimLevel::MODERATE) {
113 mode = TrimLevel::COMPLETE;
114 }
115
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400116 switch (mode) {
John Reck5f66fb82022-09-23 17:49:23 -0400117 case TrimLevel::COMPLETE:
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400118 mGrContext->freeGpuResources();
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400119 SkGraphics::PurgeAllCaches();
John Reck5f66fb82022-09-23 17:49:23 -0400120 mRenderThread.destroyRenderingContext();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400121 break;
John Reck5f66fb82022-09-23 17:49:23 -0400122 case TrimLevel::UI_HIDDEN:
Derek Sollenbergerb1f27aa2018-04-02 13:36:45 -0400123 // Here we purge all the unlocked scratch resources and then toggle the resources cache
124 // limits between the background and max amounts. This causes the unlocked resources
125 // that have persistent data to be purged in LRU order.
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400126 mGrContext->setResourceCacheLimit(mBackgroundResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400127 SkGraphics::SetFontCacheLimit(mBackgroundCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -0400128 mGrContext->purgeUnlockedResources(mMemoryPolicy.purgeScratchOnly);
129 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400130 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400131 break;
John Reck5f66fb82022-09-23 17:49:23 -0400132 default:
133 break;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400134 }
135}
136
137void CacheManager::trimStaleResources() {
138 if (!mGrContext) {
139 return;
140 }
Greg Danielc7ad4082020-05-14 15:38:26 -0400141 mGrContext->flushAndSubmit();
John Reckf846aee2019-10-08 23:28:41 +0000142 mGrContext->purgeResourcesNotUsedInMs(std::chrono::seconds(30));
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400143}
144
John Reck39207682021-05-12 19:10:47 -0400145void CacheManager::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
146 *cpuUsage = 0;
147 *gpuUsage = 0;
148 if (!mGrContext) {
149 return;
150 }
151
152 skiapipeline::SkiaMemoryTracer cpuTracer("category", true);
153 SkGraphics::DumpMemoryStatistics(&cpuTracer);
154 *cpuUsage += cpuTracer.total();
155
156 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
157 mGrContext->dumpMemoryStatistics(&gpuTracer);
158 *gpuUsage += gpuTracer.total();
159}
160
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400161void CacheManager::dumpMemoryUsage(String8& log, const RenderState* renderState) {
John Reck5f66fb82022-09-23 17:49:23 -0400162 log.appendFormat(R"(Memory policy:
163 Max surface area: %zu
164 Max resource usage: %.2fMB (x%.0f)
165 Background retention: %.0f%% (altUiHidden = %s)
166)",
167 mMaxSurfaceArea, mMaxResourceBytes / 1000000.f,
168 mMemoryPolicy.surfaceSizeMultiplier,
169 mMemoryPolicy.backgroundRetentionPercent * 100.0f,
170 mMemoryPolicy.useAlternativeUiHidden ? "true" : "false");
171 if (Properties::isSystemOrPersistent) {
172 log.appendFormat(" IsSystemOrPersistent\n");
173 }
174 log.appendFormat(" GPU Context timeout: %" PRIu64 "\n", ns2s(mMemoryPolicy.contextTimeout));
175 size_t stoppedContexts = 0;
176 for (auto context : mCanvasContexts) {
177 if (context->isStopped()) stoppedContexts++;
178 }
179 log.appendFormat("Contexts: %zu (stopped = %zu)\n", mCanvasContexts.size(), stoppedContexts);
180
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400181 if (!mGrContext) {
John Reck5f66fb82022-09-23 17:49:23 -0400182 log.appendFormat("No GPU context.\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400183 return;
184 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400185 std::vector<skiapipeline::ResourcePair> cpuResourceMap = {
186 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
187 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
188 {"skia/sk_resource_cache/rects-blur_", "Masks"},
189 {"skia/sk_resource_cache/tessellated", "Shadows"},
John Reck39207682021-05-12 19:10:47 -0400190 {"skia/sk_glyph_cache", "Glyph Cache"},
Derek Sollenberger0057db22018-03-29 14:18:44 -0400191 };
192 skiapipeline::SkiaMemoryTracer cpuTracer(cpuResourceMap, false);
193 SkGraphics::DumpMemoryStatistics(&cpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400194 if (cpuTracer.hasOutput()) {
195 log.appendFormat("CPU Caches:\n");
196 cpuTracer.logOutput(log);
John Reck39207682021-05-12 19:10:47 -0400197 log.appendFormat(" Glyph Count: %d \n", SkGraphics::GetFontCacheCountUsed());
198 log.appendFormat("Total CPU memory usage:\n");
199 cpuTracer.logTotals(log);
John Reck66e06d42021-05-11 17:04:54 -0400200 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400201
Derek Sollenberger0057db22018-03-29 14:18:44 -0400202 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
203 mGrContext->dumpMemoryStatistics(&gpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400204 if (gpuTracer.hasOutput()) {
205 log.appendFormat("GPU Caches:\n");
206 gpuTracer.logOutput(log);
207 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400208
John Reck66e06d42021-05-11 17:04:54 -0400209 if (renderState && renderState->mActiveLayers.size() > 0) {
210 log.appendFormat("Layer Info:\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400211
Stan Iliev564ca3e2018-09-04 22:00:00 +0000212 const char* layerType = Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL
John Reck0fa0cbc2019-04-05 16:57:46 -0700213 ? "GlLayer"
214 : "VkLayer";
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400215 size_t layerMemoryTotal = 0;
216 for (std::set<Layer*>::iterator it = renderState->mActiveLayers.begin();
John Reck1bcacfd2017-11-03 10:12:19 -0700217 it != renderState->mActiveLayers.end(); it++) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400218 const Layer* layer = *it;
John Reck1bcacfd2017-11-03 10:12:19 -0700219 log.appendFormat(" %s size %dx%d\n", layerType, layer->getWidth(),
220 layer->getHeight());
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400221 layerMemoryTotal += layer->getWidth() * layer->getHeight() * 4;
222 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400223 log.appendFormat(" Layers Total %6.2f KB (numLayers = %zu)\n",
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400224 layerMemoryTotal / 1024.0f, renderState->mActiveLayers.size());
225 }
226
Derek Sollenberger0057db22018-03-29 14:18:44 -0400227 log.appendFormat("Total GPU memory usage:\n");
228 gpuTracer.logTotals(log);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400229}
230
Stan Ilieve0fae232020-01-07 17:21:49 -0500231void CacheManager::onFrameCompleted() {
John Reck5f66fb82022-09-23 17:49:23 -0400232 cancelDestroyContext();
233 mFrameCompletions.next() = systemTime(CLOCK_MONOTONIC);
Stan Ilieve0fae232020-01-07 17:21:49 -0500234 if (ATRACE_ENABLED()) {
235 static skiapipeline::ATraceMemoryDump tracer;
236 tracer.startFrame();
237 SkGraphics::DumpMemoryStatistics(&tracer);
238 if (mGrContext) {
239 mGrContext->dumpMemoryStatistics(&tracer);
240 }
241 tracer.logTraces();
242 }
243}
244
John Reck5f66fb82022-09-23 17:49:23 -0400245void CacheManager::onThreadIdle() {
246 if (!mGrContext || mFrameCompletions.size() == 0) return;
247
248 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
249 // Rate limiting
250 if ((now - mLastDeferredCleanup) < 25_ms) {
251 mLastDeferredCleanup = now;
252 const nsecs_t frameCompleteNanos = mFrameCompletions[0];
253 const nsecs_t frameDiffNanos = now - frameCompleteNanos;
254 const nsecs_t cleanupMillis =
255 ns2ms(std::max(frameDiffNanos, mMemoryPolicy.minimumResourceRetention));
256 mGrContext->performDeferredCleanup(std::chrono::milliseconds(cleanupMillis),
257 mMemoryPolicy.purgeScratchOnly);
258 }
259}
260
261void CacheManager::scheduleDestroyContext() {
262 if (mMemoryPolicy.contextTimeout > 0) {
263 mRenderThread.queue().postDelayed(mMemoryPolicy.contextTimeout,
264 [this, genId = mGenerationId] {
265 if (mGenerationId != genId) return;
266 // GenID should have already stopped this, but just in
267 // case
268 if (!areAllContextsStopped()) return;
269 mRenderThread.destroyRenderingContext();
270 });
271 }
272}
273
274void CacheManager::cancelDestroyContext() {
275 if (mIsDestructionPending) {
276 mIsDestructionPending = false;
277 mGenerationId++;
278 }
279}
280
281bool CacheManager::areAllContextsStopped() {
282 for (auto context : mCanvasContexts) {
283 if (!context->isStopped()) return false;
284 }
285 return true;
286}
287
288void CacheManager::checkUiHidden() {
289 if (!mGrContext) return;
290
291 if (mMemoryPolicy.useAlternativeUiHidden && areAllContextsStopped()) {
292 trimMemory(TrimLevel::UI_HIDDEN);
293 }
294}
295
296void CacheManager::registerCanvasContext(CanvasContext* context) {
297 mCanvasContexts.push_back(context);
298 cancelDestroyContext();
299}
300
301void CacheManager::unregisterCanvasContext(CanvasContext* context) {
302 std::erase(mCanvasContexts, context);
303 checkUiHidden();
304 if (mCanvasContexts.empty()) {
305 scheduleDestroyContext();
306 }
307}
308
309void CacheManager::onContextStopped(CanvasContext* context) {
310 checkUiHidden();
311 if (mMemoryPolicy.releaseContextOnStoppedOnly && areAllContextsStopped()) {
312 scheduleDestroyContext();
313 }
314}
315
316void CacheManager::notifyNextFrameSize(int width, int height) {
317 int frameArea = width * height;
318 if (frameArea > mMaxSurfaceArea) {
319 mMaxSurfaceArea = frameArea;
320 setupCacheLimits();
Nader Jawaddd1fcab2021-06-10 18:54:23 -0700321 }
322}
323
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400324} /* namespace renderthread */
325} /* namespace uirenderer */
326} /* namespace android */