blob: babce88b8e1efb537e1a90681be79cf6604697fd [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"
John Reck9fc3d272023-05-01 16:33:22 -040032#include "VulkanManager.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
Kevin Lubick80beb6f2023-01-20 17:57:00 +000050static inline int countLeadingZeros(uint32_t mask) {
51 // __builtin_clz(0) is undefined, so we have to detect that case.
52 return mask ? __builtin_clz(mask) : 32;
53}
54
55// Return the smallest power-of-2 >= n.
56static inline uint32_t nextPowerOfTwo(uint32_t n) {
57 return n ? (1 << (32 - countLeadingZeros(n - 1))) : 1;
58}
59
John Reck5f66fb82022-09-23 17:49:23 -040060void CacheManager::setupCacheLimits() {
61 mMaxResourceBytes = mMaxSurfaceArea * mMemoryPolicy.surfaceSizeMultiplier;
62 mBackgroundResourceBytes = mMaxResourceBytes * mMemoryPolicy.backgroundRetentionPercent;
63 // This sets the maximum size for a single texture atlas in the GPU font cache. If
64 // necessary, the cache can allocate additional textures that are counted against the
65 // total cache limits provided to Skia.
Kevin Lubick80beb6f2023-01-20 17:57:00 +000066 mMaxGpuFontAtlasBytes = nextPowerOfTwo(mMaxSurfaceArea);
John Reck5f66fb82022-09-23 17:49:23 -040067 // This sets the maximum size of the CPU font cache to be at least the same size as the
68 // total number of GPU font caches (i.e. 4 separate GPU atlases).
69 mMaxCpuFontCacheBytes = std::max(mMaxGpuFontAtlasBytes * 4, SkGraphics::GetFontCacheLimit());
70 mBackgroundCpuFontCacheBytes = mMaxCpuFontCacheBytes * mMemoryPolicy.backgroundRetentionPercent;
71
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -040072 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -040073 if (mGrContext) {
74 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
75 }
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040076}
77
Adlai Hollerd2345212020-10-07 14:16:40 -040078void CacheManager::reset(sk_sp<GrDirectContext> context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050079 if (context != mGrContext) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040080 destroy();
81 }
82
83 if (context) {
Greg Daniel660d6ec2017-12-08 11:44:27 -050084 mGrContext = std::move(context);
Robert Phillips57bb0bf2019-09-06 13:18:17 -040085 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
John Reck5f66fb82022-09-23 17:49:23 -040086 mLastDeferredCleanup = systemTime(CLOCK_MONOTONIC);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040087 }
88}
89
90void CacheManager::destroy() {
91 // cleanup any caches here as the GrContext is about to go away...
92 mGrContext.reset(nullptr);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -040093}
94
John Reck322b8ab2019-03-14 13:15:28 -070095class CommonPoolExecutor : public SkExecutor {
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040096public:
John Reck0fa0cbc2019-04-05 16:57:46 -070097 virtual void add(std::function<void(void)> func) override { CommonPool::post(std::move(func)); }
Derek Sollenberger8ec9e882017-08-24 16:36:08 -040098};
99
John Reck322b8ab2019-03-14 13:15:28 -0700100static CommonPoolExecutor sDefaultExecutor;
101
John Reck0fa0cbc2019-04-05 16:57:46 -0700102void CacheManager::configureContext(GrContextOptions* contextOptions, const void* identity,
103 ssize_t size) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400104 contextOptions->fAllowPathMaskCaching = true;
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400105 contextOptions->fGlyphCacheTextureMaximumBytes = mMaxGpuFontAtlasBytes;
John Reck322b8ab2019-03-14 13:15:28 -0700106 contextOptions->fExecutor = &sDefaultExecutor;
Stan Ilieve75ef1f2017-11-27 17:22:42 -0500107
Yichi Chen9f959552018-03-29 21:21:54 +0800108 auto& cache = skiapipeline::ShaderCache::get();
109 cache.initShaderDiskCache(identity, size);
110 contextOptions->fPersistentCache = &cache;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400111}
112
John Reck5f66fb82022-09-23 17:49:23 -0400113void CacheManager::trimMemory(TrimLevel mode) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400114 if (!mGrContext) {
115 return;
116 }
117
Greg Daniel41ef5662021-02-01 14:25:48 -0500118 // flush and submit all work to the gpu and wait for it to finish
119 mGrContext->flushAndSubmit(/*syncCpu=*/true);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400120
121 switch (mode) {
Tim Murray328ff432023-04-03 18:47:03 -0700122 case TrimLevel::BACKGROUND:
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400123 mGrContext->freeGpuResources();
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400124 SkGraphics::PurgeAllCaches();
John Reck5f66fb82022-09-23 17:49:23 -0400125 mRenderThread.destroyRenderingContext();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400126 break;
John Reck5f66fb82022-09-23 17:49:23 -0400127 case TrimLevel::UI_HIDDEN:
Derek Sollenbergerb1f27aa2018-04-02 13:36:45 -0400128 // Here we purge all the unlocked scratch resources and then toggle the resources cache
129 // limits between the background and max amounts. This causes the unlocked resources
130 // that have persistent data to be purged in LRU order.
Robert Phillips57bb0bf2019-09-06 13:18:17 -0400131 mGrContext->setResourceCacheLimit(mBackgroundResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400132 SkGraphics::SetFontCacheLimit(mBackgroundCpuFontCacheBytes);
John Reck5f66fb82022-09-23 17:49:23 -0400133 mGrContext->purgeUnlockedResources(mMemoryPolicy.purgeScratchOnly);
134 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
Derek Sollenbergerb9e296e2019-04-18 16:21:42 -0400135 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400136 break;
John Reck5f66fb82022-09-23 17:49:23 -0400137 default:
138 break;
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400139 }
140}
141
Jernej Virag44db0402023-05-09 20:24:48 +0200142void CacheManager::trimCaches(CacheTrimLevel mode) {
143 switch (mode) {
144 case CacheTrimLevel::FONT_CACHE:
145 SkGraphics::PurgeFontCache();
146 break;
147 case CacheTrimLevel::RESOURCE_CACHE:
148 SkGraphics::PurgeResourceCache();
149 break;
150 case CacheTrimLevel::ALL_CACHES:
151 SkGraphics::PurgeAllCaches();
152 if (mGrContext) {
153 mGrContext->purgeUnlockedResources(false);
154 }
155 break;
156 default:
157 break;
158 }
159}
160
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400161void CacheManager::trimStaleResources() {
162 if (!mGrContext) {
163 return;
164 }
Greg Danielc7ad4082020-05-14 15:38:26 -0400165 mGrContext->flushAndSubmit();
John Reckf846aee2019-10-08 23:28:41 +0000166 mGrContext->purgeResourcesNotUsedInMs(std::chrono::seconds(30));
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400167}
168
John Reck39207682021-05-12 19:10:47 -0400169void CacheManager::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
170 *cpuUsage = 0;
171 *gpuUsage = 0;
172 if (!mGrContext) {
173 return;
174 }
175
176 skiapipeline::SkiaMemoryTracer cpuTracer("category", true);
177 SkGraphics::DumpMemoryStatistics(&cpuTracer);
178 *cpuUsage += cpuTracer.total();
179
180 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
181 mGrContext->dumpMemoryStatistics(&gpuTracer);
182 *gpuUsage += gpuTracer.total();
183}
184
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400185void CacheManager::dumpMemoryUsage(String8& log, const RenderState* renderState) {
John Reck5f66fb82022-09-23 17:49:23 -0400186 log.appendFormat(R"(Memory policy:
187 Max surface area: %zu
188 Max resource usage: %.2fMB (x%.0f)
189 Background retention: %.0f%% (altUiHidden = %s)
190)",
191 mMaxSurfaceArea, mMaxResourceBytes / 1000000.f,
192 mMemoryPolicy.surfaceSizeMultiplier,
193 mMemoryPolicy.backgroundRetentionPercent * 100.0f,
194 mMemoryPolicy.useAlternativeUiHidden ? "true" : "false");
195 if (Properties::isSystemOrPersistent) {
196 log.appendFormat(" IsSystemOrPersistent\n");
197 }
198 log.appendFormat(" GPU Context timeout: %" PRIu64 "\n", ns2s(mMemoryPolicy.contextTimeout));
199 size_t stoppedContexts = 0;
200 for (auto context : mCanvasContexts) {
201 if (context->isStopped()) stoppedContexts++;
202 }
203 log.appendFormat("Contexts: %zu (stopped = %zu)\n", mCanvasContexts.size(), stoppedContexts);
204
John Reck9fc3d272023-05-01 16:33:22 -0400205 auto vkInstance = VulkanManager::peekInstance();
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400206 if (!mGrContext) {
John Reck9fc3d272023-05-01 16:33:22 -0400207 if (!vkInstance) {
208 log.appendFormat("No GPU context.\n");
209 } else {
210 log.appendFormat("No GrContext; however %d remaining Vulkan refs",
211 vkInstance->getStrongCount() - 1);
212 }
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400213 return;
214 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400215 std::vector<skiapipeline::ResourcePair> cpuResourceMap = {
216 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
217 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
218 {"skia/sk_resource_cache/rects-blur_", "Masks"},
219 {"skia/sk_resource_cache/tessellated", "Shadows"},
John Reck39207682021-05-12 19:10:47 -0400220 {"skia/sk_glyph_cache", "Glyph Cache"},
Derek Sollenberger0057db22018-03-29 14:18:44 -0400221 };
222 skiapipeline::SkiaMemoryTracer cpuTracer(cpuResourceMap, false);
223 SkGraphics::DumpMemoryStatistics(&cpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400224 if (cpuTracer.hasOutput()) {
225 log.appendFormat("CPU Caches:\n");
226 cpuTracer.logOutput(log);
John Reck39207682021-05-12 19:10:47 -0400227 log.appendFormat(" Glyph Count: %d \n", SkGraphics::GetFontCacheCountUsed());
228 log.appendFormat("Total CPU memory usage:\n");
229 cpuTracer.logTotals(log);
John Reck66e06d42021-05-11 17:04:54 -0400230 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400231
Derek Sollenberger0057db22018-03-29 14:18:44 -0400232 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
233 mGrContext->dumpMemoryStatistics(&gpuTracer);
John Reck66e06d42021-05-11 17:04:54 -0400234 if (gpuTracer.hasOutput()) {
235 log.appendFormat("GPU Caches:\n");
236 gpuTracer.logOutput(log);
237 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400238
John Reck66e06d42021-05-11 17:04:54 -0400239 if (renderState && renderState->mActiveLayers.size() > 0) {
240 log.appendFormat("Layer Info:\n");
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400241
Stan Iliev564ca3e2018-09-04 22:00:00 +0000242 const char* layerType = Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL
John Reck0fa0cbc2019-04-05 16:57:46 -0700243 ? "GlLayer"
244 : "VkLayer";
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400245 size_t layerMemoryTotal = 0;
246 for (std::set<Layer*>::iterator it = renderState->mActiveLayers.begin();
John Reck1bcacfd2017-11-03 10:12:19 -0700247 it != renderState->mActiveLayers.end(); it++) {
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400248 const Layer* layer = *it;
John Reck1bcacfd2017-11-03 10:12:19 -0700249 log.appendFormat(" %s size %dx%d\n", layerType, layer->getWidth(),
250 layer->getHeight());
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400251 layerMemoryTotal += layer->getWidth() * layer->getHeight() * 4;
252 }
Derek Sollenberger0057db22018-03-29 14:18:44 -0400253 log.appendFormat(" Layers Total %6.2f KB (numLayers = %zu)\n",
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400254 layerMemoryTotal / 1024.0f, renderState->mActiveLayers.size());
255 }
256
Derek Sollenberger0057db22018-03-29 14:18:44 -0400257 log.appendFormat("Total GPU memory usage:\n");
258 gpuTracer.logTotals(log);
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400259}
260
Stan Ilieve0fae232020-01-07 17:21:49 -0500261void CacheManager::onFrameCompleted() {
John Reck5f66fb82022-09-23 17:49:23 -0400262 cancelDestroyContext();
263 mFrameCompletions.next() = systemTime(CLOCK_MONOTONIC);
Stan Ilieve0fae232020-01-07 17:21:49 -0500264 if (ATRACE_ENABLED()) {
265 static skiapipeline::ATraceMemoryDump tracer;
266 tracer.startFrame();
267 SkGraphics::DumpMemoryStatistics(&tracer);
268 if (mGrContext) {
269 mGrContext->dumpMemoryStatistics(&tracer);
270 }
271 tracer.logTraces();
272 }
273}
274
John Reck5f66fb82022-09-23 17:49:23 -0400275void CacheManager::onThreadIdle() {
276 if (!mGrContext || mFrameCompletions.size() == 0) return;
277
278 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
279 // Rate limiting
280 if ((now - mLastDeferredCleanup) < 25_ms) {
281 mLastDeferredCleanup = now;
282 const nsecs_t frameCompleteNanos = mFrameCompletions[0];
283 const nsecs_t frameDiffNanos = now - frameCompleteNanos;
284 const nsecs_t cleanupMillis =
285 ns2ms(std::max(frameDiffNanos, mMemoryPolicy.minimumResourceRetention));
286 mGrContext->performDeferredCleanup(std::chrono::milliseconds(cleanupMillis),
287 mMemoryPolicy.purgeScratchOnly);
288 }
289}
290
291void CacheManager::scheduleDestroyContext() {
292 if (mMemoryPolicy.contextTimeout > 0) {
293 mRenderThread.queue().postDelayed(mMemoryPolicy.contextTimeout,
294 [this, genId = mGenerationId] {
295 if (mGenerationId != genId) return;
296 // GenID should have already stopped this, but just in
297 // case
298 if (!areAllContextsStopped()) return;
299 mRenderThread.destroyRenderingContext();
300 });
301 }
302}
303
304void CacheManager::cancelDestroyContext() {
305 if (mIsDestructionPending) {
306 mIsDestructionPending = false;
307 mGenerationId++;
308 }
309}
310
311bool CacheManager::areAllContextsStopped() {
312 for (auto context : mCanvasContexts) {
313 if (!context->isStopped()) return false;
314 }
315 return true;
316}
317
318void CacheManager::checkUiHidden() {
319 if (!mGrContext) return;
320
321 if (mMemoryPolicy.useAlternativeUiHidden && areAllContextsStopped()) {
322 trimMemory(TrimLevel::UI_HIDDEN);
323 }
324}
325
326void CacheManager::registerCanvasContext(CanvasContext* context) {
327 mCanvasContexts.push_back(context);
328 cancelDestroyContext();
329}
330
331void CacheManager::unregisterCanvasContext(CanvasContext* context) {
332 std::erase(mCanvasContexts, context);
333 checkUiHidden();
334 if (mCanvasContexts.empty()) {
335 scheduleDestroyContext();
336 }
337}
338
339void CacheManager::onContextStopped(CanvasContext* context) {
340 checkUiHidden();
341 if (mMemoryPolicy.releaseContextOnStoppedOnly && areAllContextsStopped()) {
342 scheduleDestroyContext();
343 }
344}
345
346void CacheManager::notifyNextFrameSize(int width, int height) {
347 int frameArea = width * height;
348 if (frameArea > mMaxSurfaceArea) {
349 mMaxSurfaceArea = frameArea;
350 setupCacheLimits();
Nader Jawaddd1fcab2021-06-10 18:54:23 -0700351 }
352}
353
Derek Sollenbergerf9e45d12017-06-01 13:07:39 -0400354} /* namespace renderthread */
355} /* namespace uirenderer */
356} /* namespace android */