blob: eb4d4948dc5371017debb8ed99ba87e7ece6d7af [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>
Kevin Lubickcae0b212023-09-12 18:33:10 +000020#include <GrTypes.h>
John Reck5f66fb82022-09-23 17:49:23 -040021#include <SkExecutor.h>
22#include <SkGraphics.h>
John Reck5f66fb82022-09-23 17:49:23 -040023#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"
John Reck9fc3d272023-05-01 16:33:22 -040033#include "VulkanManager.h"
Stan Ilieve0fae232020-01-07 17:21:49 -050034#include "pipeline/skia/ATraceMemoryDump.h"
Stan Ilieve75ef1f2017-11-27 17:22:42 -050035#include "pipeline/skia/ShaderCache.h"
Derek Sollenberger0057db22018-03-29 14:18:44 -040036#include "pipeline/skia/SkiaMemoryTracer.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040037#include "renderstate/RenderState.h"
John Reck322b8ab2019-03-14 13:15:28 -070038#include "thread/CommonPool.h"
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040039
40namespace android {
41namespace uirenderer {
42namespace renderthread {
43
John Reck5f66fb82022-09-23 17:49:23 -040044CacheManager::CacheManager(RenderThread& thread)
45 : mRenderThread(thread), mMemoryPolicy(loadMemoryPolicy()) {
46 mMaxSurfaceArea = static_cast<size_t>((DeviceInfo::getWidth() * DeviceInfo::getHeight()) *
47 mMemoryPolicy.initialMaxSurfaceAreaScale);
48 setupCacheLimits();
49}
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040050
Kevin Lubick80beb6f2023-01-20 17:57:00 +000051static inline int countLeadingZeros(uint32_t mask) {
52 // __builtin_clz(0) is undefined, so we have to detect that case.
53 return mask ? __builtin_clz(mask) : 32;
54}
55
56// Return the smallest power-of-2 >= n.
57static inline uint32_t nextPowerOfTwo(uint32_t n) {
58 return n ? (1 << (32 - countLeadingZeros(n - 1))) : 1;
59}
60
John Reck5f66fb82022-09-23 17:49:23 -040061void CacheManager::setupCacheLimits() {
62 mMaxResourceBytes = mMaxSurfaceArea * mMemoryPolicy.surfaceSizeMultiplier;
63 mBackgroundResourceBytes = mMaxResourceBytes * mMemoryPolicy.backgroundRetentionPercent;
64 // This sets the maximum size for a single texture atlas in the GPU font cache. If
65 // necessary, the cache can allocate additional textures that are counted against the
66 // total cache limits provided to Skia.
Kevin Lubick80beb6f2023-01-20 17:57:00 +000067 mMaxGpuFontAtlasBytes = nextPowerOfTwo(mMaxSurfaceArea);
John Reck5f66fb82022-09-23 17:49:23 -040068 // This sets the maximum size of the CPU font cache to be at least the same size as the
69 // total number of GPU font caches (i.e. 4 separate GPU atlases).
70 mMaxCpuFontCacheBytes = std::max(mMaxGpuFontAtlasBytes * 4, SkGraphics::GetFontCacheLimit());
71 mBackgroundCpuFontCacheBytes = mMaxCpuFontCacheBytes * mMemoryPolicy.backgroundRetentionPercent;
72
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -040073 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -040074 if (mGrContext) {
75 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
76 }
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040077}
78
Adlai Hollerd2345212020-10-07 14:16:40 -040079void CacheManager::reset(sk_sp<GrDirectContext> context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050080 if (context != mGrContext) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040081 destroy();
82 }
83
84 if (context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050085 mGrContext = std::move(context);
Robert Phillips57bb0bf2019-09-06 13:18:17 -040086 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
John Reck5f66fb82022-09-23 17:49:23 -040087 mLastDeferredCleanup = systemTime(CLOCK_MONOTONIC);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040088 }
89}
90
91void CacheManager::destroy() {
92 // cleanup any caches here as the GrContext is about to go away...
93 mGrContext.reset(nullptr);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040094}
95
John Reck322b8ab2019-03-14 13:15:28 -070096class CommonPoolExecutor : public SkExecutor {
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040097public:
John Reck0fa0cbc2019-04-05 16:57:46 -070098 virtual void add(std::function<void(void)> func) override { CommonPool::post(std::move(func)); }
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040099};
100
John Reck322b8ab2019-03-14 13:15:28 -0700101static CommonPoolExecutor sDefaultExecutor;
102
John Reck0fa0cbc2019-04-05 16:57:46 -0700103void CacheManager::configureContext(GrContextOptions* contextOptions, const void* identity,
104 ssize_t size) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400105 contextOptions->fAllowPathMaskCaching = true;
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400106 contextOptions->fGlyphCacheTextureMaximumBytes = mMaxGpuFontAtlasBytes;
John Reck322b8ab2019-03-14 13:15:28 -0700107 contextOptions->fExecutor = &sDefaultExecutor;
Stan Ilieve75ef1f2017-11-27 17:22:42 -0500108
Yichi Chen9f959552018-03-29 21:21:54 +0800109 auto& cache = skiapipeline::ShaderCache::get();
110 cache.initShaderDiskCache(identity, size);
111 contextOptions->fPersistentCache = &cache;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400112}
113
Kevin Lubickcae0b212023-09-12 18:33:10 +0000114static GrPurgeResourceOptions toSkiaEnum(bool scratchOnly) {
115 return scratchOnly ? GrPurgeResourceOptions::kScratchResourcesOnly :
116 GrPurgeResourceOptions::kAllResources;
117}
118
John Reck5f66fb82022-09-23 17:49:23 -0400119void CacheManager::trimMemory(TrimLevel mode) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400120 if (!mGrContext) {
121 return;
122 }
123
Greg Daniel41ef5662021-02-01 14:25:48 -0500124 // flush and submit all work to the gpu and wait for it to finish
Kevin Lubickcae0b212023-09-12 18:33:10 +0000125 mGrContext->flushAndSubmit(GrSyncCpu::kYes);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400126
127 switch (mode) {
Tim Murray328ff432023-04-03 18:47:03 -0700128 case TrimLevel::BACKGROUND:
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400129 mGrContext->freeGpuResources();
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400130 SkGraphics::PurgeAllCaches();
John Reck5f66fb82022-09-23 17:49:23 -0400131 mRenderThread.destroyRenderingContext();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400132 break;
John Reck5f66fb82022-09-23 17:49:23 -0400133 case TrimLevel::UI_HIDDEN:
Derek Sollenbergerb1f27aa2018-04-02 13:36:45 -0400134 // Here we purge all the unlocked scratch resources and then toggle the resources cache
135 // limits between the background and max amounts. This causes the unlocked resources
136 // that have persistent data to be purged in LRU order.
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400137 mGrContext->setResourceCacheLimit(mBackgroundResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400138 SkGraphics::SetFontCacheLimit(mBackgroundCpuFontCacheBytes);
Kevin Lubickcae0b212023-09-12 18:33:10 +0000139 mGrContext->purgeUnlockedResources(toSkiaEnum(mMemoryPolicy.purgeScratchOnly));
John Reck5f66fb82022-09-23 17:49:23 -0400140 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400141 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400142 break;
John Reck5f66fb82022-09-23 17:49:23 -0400143 default:
144 break;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400145 }
146}
147
Jernej Virag44db0402023-05-09 20:24:48 +0200148void CacheManager::trimCaches(CacheTrimLevel mode) {
149 switch (mode) {
150 case CacheTrimLevel::FONT_CACHE:
151 SkGraphics::PurgeFontCache();
152 break;
153 case CacheTrimLevel::RESOURCE_CACHE:
154 SkGraphics::PurgeResourceCache();
155 break;
156 case CacheTrimLevel::ALL_CACHES:
157 SkGraphics::PurgeAllCaches();
158 if (mGrContext) {
Kevin Lubickcae0b212023-09-12 18:33:10 +0000159 mGrContext->purgeUnlockedResources(GrPurgeResourceOptions::kAllResources);
Jernej Virag44db0402023-05-09 20:24:48 +0200160 }
161 break;
162 default:
163 break;
164 }
165}
166
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400167void CacheManager::trimStaleResources() {
168 if (!mGrContext) {
169 return;
170 }
Greg Danielc7ad4082020-05-14 15:38:26 -0400171 mGrContext->flushAndSubmit();
Kevin Lubickbca403b2023-09-18 12:14:59 +0000172 mGrContext->performDeferredCleanup(std::chrono::seconds(30),
173 GrPurgeResourceOptions::kAllResources);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400174}
175
John Reck39207682021-05-12 19:10:47 -0400176void CacheManager::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
177 *cpuUsage = 0;
178 *gpuUsage = 0;
179 if (!mGrContext) {
180 return;
181 }
182
183 skiapipeline::SkiaMemoryTracer cpuTracer("category", true);
184 SkGraphics::DumpMemoryStatistics(&cpuTracer);
185 *cpuUsage += cpuTracer.total();
186
187 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
188 mGrContext->dumpMemoryStatistics(&gpuTracer);
189 *gpuUsage += gpuTracer.total();
190}
191
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400192void CacheManager::dumpMemoryUsage(String8& log, const RenderState* renderState) {
John Reck5f66fb82022-09-23 17:49:23 -0400193 log.appendFormat(R"(Memory policy:
194 Max surface area: %zu
195 Max resource usage: %.2fMB (x%.0f)
196 Background retention: %.0f%% (altUiHidden = %s)
197)",
198 mMaxSurfaceArea, mMaxResourceBytes / 1000000.f,
199 mMemoryPolicy.surfaceSizeMultiplier,
200 mMemoryPolicy.backgroundRetentionPercent * 100.0f,
201 mMemoryPolicy.useAlternativeUiHidden ? "true" : "false");
202 if (Properties::isSystemOrPersistent) {
203 log.appendFormat(" IsSystemOrPersistent\n");
204 }
205 log.appendFormat(" GPU Context timeout: %" PRIu64 "\n", ns2s(mMemoryPolicy.contextTimeout));
206 size_t stoppedContexts = 0;
207 for (auto context : mCanvasContexts) {
208 if (context->isStopped()) stoppedContexts++;
209 }
210 log.appendFormat("Contexts: %zu (stopped = %zu)\n", mCanvasContexts.size(), stoppedContexts);
211
John Reck9fc3d272023-05-01 16:33:22 -0400212 auto vkInstance = VulkanManager::peekInstance();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400213 if (!mGrContext) {
John Reck9fc3d272023-05-01 16:33:22 -0400214 if (!vkInstance) {
215 log.appendFormat("No GPU context.\n");
216 } else {
217 log.appendFormat("No GrContext; however %d remaining Vulkan refs",
218 vkInstance->getStrongCount() - 1);
219 }
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400220 return;
221 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400222 std::vector<skiapipeline::ResourcePair> cpuResourceMap = {
223 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
224 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
225 {"skia/sk_resource_cache/rects-blur_", "Masks"},
226 {"skia/sk_resource_cache/tessellated", "Shadows"},
John Reck39207682021-05-12 19:10:47 -0400227 {"skia/sk_glyph_cache", "Glyph Cache"},
Derek Sollenberger0057db22018-03-29 14:18:44 -0400228 };
229 skiapipeline::SkiaMemoryTracer cpuTracer(cpuResourceMap, false);
230 SkGraphics::DumpMemoryStatistics(&cpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400231 if (cpuTracer.hasOutput()) {
232 log.appendFormat("CPU Caches:\n");
233 cpuTracer.logOutput(log);
John Reck39207682021-05-12 19:10:47 -0400234 log.appendFormat(" Glyph Count: %d \n", SkGraphics::GetFontCacheCountUsed());
235 log.appendFormat("Total CPU memory usage:\n");
236 cpuTracer.logTotals(log);
John Reck66e06d42021-05-11 17:04:54 -0400237 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400238
Derek Sollenberger0057db22018-03-29 14:18:44 -0400239 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
240 mGrContext->dumpMemoryStatistics(&gpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400241 if (gpuTracer.hasOutput()) {
242 log.appendFormat("GPU Caches:\n");
243 gpuTracer.logOutput(log);
244 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400245
John Reck66e06d42021-05-11 17:04:54 -0400246 if (renderState && renderState->mActiveLayers.size() > 0) {
247 log.appendFormat("Layer Info:\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400248
Stan Iliev564ca3e2018-09-04 22:00:00 +0000249 const char* layerType = Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL
John Reck0fa0cbc2019-04-05 16:57:46 -0700250 ? "GlLayer"
251 : "VkLayer";
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400252 size_t layerMemoryTotal = 0;
253 for (std::set<Layer*>::iterator it = renderState->mActiveLayers.begin();
John Reck1bcacfd2017-11-03 10:12:19 -0700254 it != renderState->mActiveLayers.end(); it++) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400255 const Layer* layer = *it;
John Reck1bcacfd2017-11-03 10:12:19 -0700256 log.appendFormat(" %s size %dx%d\n", layerType, layer->getWidth(),
257 layer->getHeight());
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400258 layerMemoryTotal += layer->getWidth() * layer->getHeight() * 4;
259 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400260 log.appendFormat(" Layers Total %6.2f KB (numLayers = %zu)\n",
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400261 layerMemoryTotal / 1024.0f, renderState->mActiveLayers.size());
262 }
263
Derek Sollenberger0057db22018-03-29 14:18:44 -0400264 log.appendFormat("Total GPU memory usage:\n");
265 gpuTracer.logTotals(log);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400266}
267
Stan Ilieve0fae232020-01-07 17:21:49 -0500268void CacheManager::onFrameCompleted() {
John Reck5f66fb82022-09-23 17:49:23 -0400269 cancelDestroyContext();
270 mFrameCompletions.next() = systemTime(CLOCK_MONOTONIC);
Stan Ilieve0fae232020-01-07 17:21:49 -0500271 if (ATRACE_ENABLED()) {
Nolan Scobie1083707b2024-01-11 16:45:36 -0500272 ATRACE_NAME("dumpingMemoryStatistics");
Stan Ilieve0fae232020-01-07 17:21:49 -0500273 static skiapipeline::ATraceMemoryDump tracer;
274 tracer.startFrame();
275 SkGraphics::DumpMemoryStatistics(&tracer);
Nolan Scobie1083707b2024-01-11 16:45:36 -0500276 if (mGrContext && Properties::debugTraceGpuResourceCategories) {
Stan Ilieve0fae232020-01-07 17:21:49 -0500277 mGrContext->dumpMemoryStatistics(&tracer);
278 }
Nolan Scobie1083707b2024-01-11 16:45:36 -0500279 tracer.logTraces(Properties::debugTraceGpuResourceCategories, mGrContext.get());
Stan Ilieve0fae232020-01-07 17:21:49 -0500280 }
281}
282
John Reck5f66fb82022-09-23 17:49:23 -0400283void CacheManager::onThreadIdle() {
284 if (!mGrContext || mFrameCompletions.size() == 0) return;
285
286 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
287 // Rate limiting
John Reck57cee762023-05-19 10:48:02 -0400288 if ((now - mLastDeferredCleanup) > 25_ms) {
John Reck5f66fb82022-09-23 17:49:23 -0400289 mLastDeferredCleanup = now;
290 const nsecs_t frameCompleteNanos = mFrameCompletions[0];
291 const nsecs_t frameDiffNanos = now - frameCompleteNanos;
292 const nsecs_t cleanupMillis =
John Reck57cee762023-05-19 10:48:02 -0400293 ns2ms(std::clamp(frameDiffNanos, mMemoryPolicy.minimumResourceRetention,
294 mMemoryPolicy.maximumResourceRetention));
John Reck5f66fb82022-09-23 17:49:23 -0400295 mGrContext->performDeferredCleanup(std::chrono::milliseconds(cleanupMillis),
Kevin Lubickcae0b212023-09-12 18:33:10 +0000296 toSkiaEnum(mMemoryPolicy.purgeScratchOnly));
John Reck5f66fb82022-09-23 17:49:23 -0400297 }
298}
299
300void CacheManager::scheduleDestroyContext() {
301 if (mMemoryPolicy.contextTimeout > 0) {
302 mRenderThread.queue().postDelayed(mMemoryPolicy.contextTimeout,
303 [this, genId = mGenerationId] {
304 if (mGenerationId != genId) return;
305 // GenID should have already stopped this, but just in
306 // case
307 if (!areAllContextsStopped()) return;
308 mRenderThread.destroyRenderingContext();
309 });
310 }
311}
312
313void CacheManager::cancelDestroyContext() {
314 if (mIsDestructionPending) {
315 mIsDestructionPending = false;
316 mGenerationId++;
317 }
318}
319
320bool CacheManager::areAllContextsStopped() {
321 for (auto context : mCanvasContexts) {
322 if (!context->isStopped()) return false;
323 }
324 return true;
325}
326
327void CacheManager::checkUiHidden() {
328 if (!mGrContext) return;
329
330 if (mMemoryPolicy.useAlternativeUiHidden && areAllContextsStopped()) {
331 trimMemory(TrimLevel::UI_HIDDEN);
332 }
333}
334
335void CacheManager::registerCanvasContext(CanvasContext* context) {
336 mCanvasContexts.push_back(context);
337 cancelDestroyContext();
338}
339
340void CacheManager::unregisterCanvasContext(CanvasContext* context) {
341 std::erase(mCanvasContexts, context);
342 checkUiHidden();
343 if (mCanvasContexts.empty()) {
344 scheduleDestroyContext();
345 }
346}
347
348void CacheManager::onContextStopped(CanvasContext* context) {
349 checkUiHidden();
350 if (mMemoryPolicy.releaseContextOnStoppedOnly && areAllContextsStopped()) {
351 scheduleDestroyContext();
352 }
353}
354
355void CacheManager::notifyNextFrameSize(int width, int height) {
356 int frameArea = width * height;
357 if (frameArea > mMaxSurfaceArea) {
358 mMaxSurfaceArea = frameArea;
359 setupCacheLimits();
Nader Jawaddd1fcab2021-06-10 18:54:23 -0700360 }
361}
362
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400363} /* namespace renderthread */
364} /* namespace uirenderer */
365} /* namespace android */