blob: 23611efccd731e3446f2b5ed808c3d41708fedd0 [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>
John Reck5f66fb82022-09-23 17:49:23 -040022#include <math.h>
23#include <utils/Trace.h>
24
25#include <set>
26
27#include "CanvasContext.h"
Alec Mouri22d753f2019-09-05 17:11:45 -070028#include "DeviceInfo.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040029#include "Layer.h"
Stan Ilieve75ef1f2017-11-27 17:22:42 -050030#include "Properties.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040031#include "RenderThread.h"
Stan Ilieve0fae232020-01-07 17:21:49 -050032#include "pipeline/skia/ATraceMemoryDump.h"
Stan Ilieve75ef1f2017-11-27 17:22:42 -050033#include "pipeline/skia/ShaderCache.h"
Derek Sollenberger0057db22018-03-29 14:18:44 -040034#include "pipeline/skia/SkiaMemoryTracer.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040035#include "renderstate/RenderState.h"
John Reck322b8ab2019-03-14 13:15:28 -070036#include "thread/CommonPool.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040037
38namespace android {
39namespace uirenderer {
40namespace renderthread {
41
John Reck5f66fb82022-09-23 17:49:23 -040042CacheManager::CacheManager(RenderThread& thread)
43 : mRenderThread(thread), mMemoryPolicy(loadMemoryPolicy()) {
44 mMaxSurfaceArea = static_cast<size_t>((DeviceInfo::getWidth() * DeviceInfo::getHeight()) *
45 mMemoryPolicy.initialMaxSurfaceAreaScale);
46 setupCacheLimits();
47}
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040048
Kevin Lubick80beb6f2023-01-20 17:57:00 +000049static inline int countLeadingZeros(uint32_t mask) {
50 // __builtin_clz(0) is undefined, so we have to detect that case.
51 return mask ? __builtin_clz(mask) : 32;
52}
53
54// Return the smallest power-of-2 >= n.
55static inline uint32_t nextPowerOfTwo(uint32_t n) {
56 return n ? (1 << (32 - countLeadingZeros(n - 1))) : 1;
57}
58
John Reck5f66fb82022-09-23 17:49:23 -040059void CacheManager::setupCacheLimits() {
60 mMaxResourceBytes = mMaxSurfaceArea * mMemoryPolicy.surfaceSizeMultiplier;
61 mBackgroundResourceBytes = mMaxResourceBytes * mMemoryPolicy.backgroundRetentionPercent;
62 // This sets the maximum size for a single texture atlas in the GPU font cache. If
63 // necessary, the cache can allocate additional textures that are counted against the
64 // total cache limits provided to Skia.
Kevin Lubick80beb6f2023-01-20 17:57:00 +000065 mMaxGpuFontAtlasBytes = nextPowerOfTwo(mMaxSurfaceArea);
John Reck5f66fb82022-09-23 17:49:23 -040066 // This sets the maximum size of the CPU font cache to be at least the same size as the
67 // total number of GPU font caches (i.e. 4 separate GPU atlases).
68 mMaxCpuFontCacheBytes = std::max(mMaxGpuFontAtlasBytes * 4, SkGraphics::GetFontCacheLimit());
69 mBackgroundCpuFontCacheBytes = mMaxCpuFontCacheBytes * mMemoryPolicy.backgroundRetentionPercent;
70
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -040071 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -040072 if (mGrContext) {
73 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
74 }
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040075}
76
Adlai Hollerd2345212020-10-07 14:16:40 -040077void CacheManager::reset(sk_sp<GrDirectContext> context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050078 if (context != mGrContext) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040079 destroy();
80 }
81
82 if (context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050083 mGrContext = std::move(context);
Robert Phillips57bb0bf2019-09-06 13:18:17 -040084 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
John Reck5f66fb82022-09-23 17:49:23 -040085 mLastDeferredCleanup = systemTime(CLOCK_MONOTONIC);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040086 }
87}
88
89void CacheManager::destroy() {
90 // cleanup any caches here as the GrContext is about to go away...
91 mGrContext.reset(nullptr);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040092}
93
John Reck322b8ab2019-03-14 13:15:28 -070094class CommonPoolExecutor : public SkExecutor {
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040095public:
John Reck0fa0cbc2019-04-05 16:57:46 -070096 virtual void add(std::function<void(void)> func) override { CommonPool::post(std::move(func)); }
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040097};
98
John Reck322b8ab2019-03-14 13:15:28 -070099static CommonPoolExecutor sDefaultExecutor;
100
John Reck0fa0cbc2019-04-05 16:57:46 -0700101void CacheManager::configureContext(GrContextOptions* contextOptions, const void* identity,
102 ssize_t size) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400103 contextOptions->fAllowPathMaskCaching = true;
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400104 contextOptions->fGlyphCacheTextureMaximumBytes = mMaxGpuFontAtlasBytes;
John Reck322b8ab2019-03-14 13:15:28 -0700105 contextOptions->fExecutor = &sDefaultExecutor;
Stan Ilieve75ef1f2017-11-27 17:22:42 -0500106
Yichi Chen9f959552018-03-29 21:21:54 +0800107 auto& cache = skiapipeline::ShaderCache::get();
108 cache.initShaderDiskCache(identity, size);
109 contextOptions->fPersistentCache = &cache;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400110}
111
John Reck5f66fb82022-09-23 17:49:23 -0400112void CacheManager::trimMemory(TrimLevel mode) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400113 if (!mGrContext) {
114 return;
115 }
116
Greg Daniel41ef5662021-02-01 14:25:48 -0500117 // flush and submit all work to the gpu and wait for it to finish
118 mGrContext->flushAndSubmit(/*syncCpu=*/true);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400119
John Reck5f66fb82022-09-23 17:49:23 -0400120 if (!Properties::isHighEndGfx && mode >= TrimLevel::MODERATE) {
121 mode = TrimLevel::COMPLETE;
122 }
123
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400124 switch (mode) {
John Reck5f66fb82022-09-23 17:49:23 -0400125 case TrimLevel::COMPLETE:
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400126 mGrContext->freeGpuResources();
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400127 SkGraphics::PurgeAllCaches();
John Reck5f66fb82022-09-23 17:49:23 -0400128 mRenderThread.destroyRenderingContext();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400129 break;
John Reck5f66fb82022-09-23 17:49:23 -0400130 case TrimLevel::UI_HIDDEN:
Derek Sollenbergerb1f27aa2018-04-02 13:36:45 -0400131 // Here we purge all the unlocked scratch resources and then toggle the resources cache
132 // limits between the background and max amounts. This causes the unlocked resources
133 // that have persistent data to be purged in LRU order.
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400134 mGrContext->setResourceCacheLimit(mBackgroundResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400135 SkGraphics::SetFontCacheLimit(mBackgroundCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -0400136 mGrContext->purgeUnlockedResources(mMemoryPolicy.purgeScratchOnly);
137 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400138 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400139 break;
John Reck5f66fb82022-09-23 17:49:23 -0400140 default:
141 break;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400142 }
143}
144
145void CacheManager::trimStaleResources() {
146 if (!mGrContext) {
147 return;
148 }
Greg Danielc7ad4082020-05-14 15:38:26 -0400149 mGrContext->flushAndSubmit();
John Reckf846aee2019-10-08 23:28:41 +0000150 mGrContext->purgeResourcesNotUsedInMs(std::chrono::seconds(30));
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400151}
152
John Reck39207682021-05-12 19:10:47 -0400153void CacheManager::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
154 *cpuUsage = 0;
155 *gpuUsage = 0;
156 if (!mGrContext) {
157 return;
158 }
159
160 skiapipeline::SkiaMemoryTracer cpuTracer("category", true);
161 SkGraphics::DumpMemoryStatistics(&cpuTracer);
162 *cpuUsage += cpuTracer.total();
163
164 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
165 mGrContext->dumpMemoryStatistics(&gpuTracer);
166 *gpuUsage += gpuTracer.total();
167}
168
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400169void CacheManager::dumpMemoryUsage(String8& log, const RenderState* renderState) {
John Reck5f66fb82022-09-23 17:49:23 -0400170 log.appendFormat(R"(Memory policy:
171 Max surface area: %zu
172 Max resource usage: %.2fMB (x%.0f)
173 Background retention: %.0f%% (altUiHidden = %s)
174)",
175 mMaxSurfaceArea, mMaxResourceBytes / 1000000.f,
176 mMemoryPolicy.surfaceSizeMultiplier,
177 mMemoryPolicy.backgroundRetentionPercent * 100.0f,
178 mMemoryPolicy.useAlternativeUiHidden ? "true" : "false");
179 if (Properties::isSystemOrPersistent) {
180 log.appendFormat(" IsSystemOrPersistent\n");
181 }
182 log.appendFormat(" GPU Context timeout: %" PRIu64 "\n", ns2s(mMemoryPolicy.contextTimeout));
183 size_t stoppedContexts = 0;
184 for (auto context : mCanvasContexts) {
185 if (context->isStopped()) stoppedContexts++;
186 }
187 log.appendFormat("Contexts: %zu (stopped = %zu)\n", mCanvasContexts.size(), stoppedContexts);
188
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400189 if (!mGrContext) {
John Reck5f66fb82022-09-23 17:49:23 -0400190 log.appendFormat("No GPU context.\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400191 return;
192 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400193 std::vector<skiapipeline::ResourcePair> cpuResourceMap = {
194 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
195 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
196 {"skia/sk_resource_cache/rects-blur_", "Masks"},
197 {"skia/sk_resource_cache/tessellated", "Shadows"},
John Reck39207682021-05-12 19:10:47 -0400198 {"skia/sk_glyph_cache", "Glyph Cache"},
Derek Sollenberger0057db22018-03-29 14:18:44 -0400199 };
200 skiapipeline::SkiaMemoryTracer cpuTracer(cpuResourceMap, false);
201 SkGraphics::DumpMemoryStatistics(&cpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400202 if (cpuTracer.hasOutput()) {
203 log.appendFormat("CPU Caches:\n");
204 cpuTracer.logOutput(log);
John Reck39207682021-05-12 19:10:47 -0400205 log.appendFormat(" Glyph Count: %d \n", SkGraphics::GetFontCacheCountUsed());
206 log.appendFormat("Total CPU memory usage:\n");
207 cpuTracer.logTotals(log);
John Reck66e06d42021-05-11 17:04:54 -0400208 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400209
Derek Sollenberger0057db22018-03-29 14:18:44 -0400210 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
211 mGrContext->dumpMemoryStatistics(&gpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400212 if (gpuTracer.hasOutput()) {
213 log.appendFormat("GPU Caches:\n");
214 gpuTracer.logOutput(log);
215 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400216
John Reck66e06d42021-05-11 17:04:54 -0400217 if (renderState && renderState->mActiveLayers.size() > 0) {
218 log.appendFormat("Layer Info:\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400219
Stan Iliev564ca3e2018-09-04 22:00:00 +0000220 const char* layerType = Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL
John Reck0fa0cbc2019-04-05 16:57:46 -0700221 ? "GlLayer"
222 : "VkLayer";
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400223 size_t layerMemoryTotal = 0;
224 for (std::set<Layer*>::iterator it = renderState->mActiveLayers.begin();
John Reck1bcacfd2017-11-03 10:12:19 -0700225 it != renderState->mActiveLayers.end(); it++) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400226 const Layer* layer = *it;
John Reck1bcacfd2017-11-03 10:12:19 -0700227 log.appendFormat(" %s size %dx%d\n", layerType, layer->getWidth(),
228 layer->getHeight());
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400229 layerMemoryTotal += layer->getWidth() * layer->getHeight() * 4;
230 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400231 log.appendFormat(" Layers Total %6.2f KB (numLayers = %zu)\n",
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400232 layerMemoryTotal / 1024.0f, renderState->mActiveLayers.size());
233 }
234
Derek Sollenberger0057db22018-03-29 14:18:44 -0400235 log.appendFormat("Total GPU memory usage:\n");
236 gpuTracer.logTotals(log);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400237}
238
Stan Ilieve0fae232020-01-07 17:21:49 -0500239void CacheManager::onFrameCompleted() {
John Reck5f66fb82022-09-23 17:49:23 -0400240 cancelDestroyContext();
241 mFrameCompletions.next() = systemTime(CLOCK_MONOTONIC);
Stan Ilieve0fae232020-01-07 17:21:49 -0500242 if (ATRACE_ENABLED()) {
243 static skiapipeline::ATraceMemoryDump tracer;
244 tracer.startFrame();
245 SkGraphics::DumpMemoryStatistics(&tracer);
246 if (mGrContext) {
247 mGrContext->dumpMemoryStatistics(&tracer);
248 }
249 tracer.logTraces();
250 }
251}
252
John Reck5f66fb82022-09-23 17:49:23 -0400253void CacheManager::onThreadIdle() {
254 if (!mGrContext || mFrameCompletions.size() == 0) return;
255
256 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
257 // Rate limiting
258 if ((now - mLastDeferredCleanup) < 25_ms) {
259 mLastDeferredCleanup = now;
260 const nsecs_t frameCompleteNanos = mFrameCompletions[0];
261 const nsecs_t frameDiffNanos = now - frameCompleteNanos;
262 const nsecs_t cleanupMillis =
263 ns2ms(std::max(frameDiffNanos, mMemoryPolicy.minimumResourceRetention));
264 mGrContext->performDeferredCleanup(std::chrono::milliseconds(cleanupMillis),
265 mMemoryPolicy.purgeScratchOnly);
266 }
267}
268
269void CacheManager::scheduleDestroyContext() {
270 if (mMemoryPolicy.contextTimeout > 0) {
271 mRenderThread.queue().postDelayed(mMemoryPolicy.contextTimeout,
272 [this, genId = mGenerationId] {
273 if (mGenerationId != genId) return;
274 // GenID should have already stopped this, but just in
275 // case
276 if (!areAllContextsStopped()) return;
277 mRenderThread.destroyRenderingContext();
278 });
279 }
280}
281
282void CacheManager::cancelDestroyContext() {
283 if (mIsDestructionPending) {
284 mIsDestructionPending = false;
285 mGenerationId++;
286 }
287}
288
289bool CacheManager::areAllContextsStopped() {
290 for (auto context : mCanvasContexts) {
291 if (!context->isStopped()) return false;
292 }
293 return true;
294}
295
296void CacheManager::checkUiHidden() {
297 if (!mGrContext) return;
298
299 if (mMemoryPolicy.useAlternativeUiHidden && areAllContextsStopped()) {
300 trimMemory(TrimLevel::UI_HIDDEN);
301 }
302}
303
304void CacheManager::registerCanvasContext(CanvasContext* context) {
305 mCanvasContexts.push_back(context);
306 cancelDestroyContext();
307}
308
309void CacheManager::unregisterCanvasContext(CanvasContext* context) {
310 std::erase(mCanvasContexts, context);
311 checkUiHidden();
312 if (mCanvasContexts.empty()) {
313 scheduleDestroyContext();
314 }
315}
316
317void CacheManager::onContextStopped(CanvasContext* context) {
318 checkUiHidden();
319 if (mMemoryPolicy.releaseContextOnStoppedOnly && areAllContextsStopped()) {
320 scheduleDestroyContext();
321 }
322}
323
324void CacheManager::notifyNextFrameSize(int width, int height) {
325 int frameArea = width * height;
326 if (frameArea > mMaxSurfaceArea) {
327 mMaxSurfaceArea = frameArea;
328 setupCacheLimits();
Nader Jawaddd1fcab2021-06-10 18:54:23 -0700329 }
330}
331
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400332} /* namespace renderthread */
333} /* namespace uirenderer */
334} /* namespace android */