1 /*
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
19 #include "DeviceInfo.h"
20 #include "Layer.h"
21 #include "Properties.h"
22 #include "RenderThread.h"
23 #include "pipeline/skia/ATraceMemoryDump.h"
24 #include "pipeline/skia/ShaderCache.h"
25 #include "pipeline/skia/SkiaMemoryTracer.h"
26 #include "renderstate/RenderState.h"
27 #include "thread/CommonPool.h"
28 #include <utils/Trace.h>
29
30 #include <GrContextOptions.h>
31 #include <SkExecutor.h>
32 #include <SkGraphics.h>
33 #include <SkMathPriv.h>
34 #include <math.h>
35 #include <set>
36
37 namespace android {
38 namespace uirenderer {
39 namespace renderthread {
40
41 // This multiplier was selected based on historical review of cache sizes relative
42 // to the screen resolution. This is meant to be a conservative default based on
43 // that analysis. The 4.0f is used because the default pixel format is assumed to
44 // be ARGB_8888.
45 #define SURFACE_SIZE_MULTIPLIER (12.0f * 4.0f)
46 #define BACKGROUND_RETENTION_PERCENTAGE (0.5f)
47
CacheManager()48 CacheManager::CacheManager()
49 : mMaxSurfaceArea(DeviceInfo::getWidth() * DeviceInfo::getHeight())
50 , mMaxResourceBytes(mMaxSurfaceArea * SURFACE_SIZE_MULTIPLIER)
51 , mBackgroundResourceBytes(mMaxResourceBytes * BACKGROUND_RETENTION_PERCENTAGE)
52 // This sets the maximum size for a single texture atlas in the GPU font cache. If
53 // necessary, the cache can allocate additional textures that are counted against the
54 // total cache limits provided to Skia.
55 , mMaxGpuFontAtlasBytes(GrNextSizePow2(mMaxSurfaceArea))
56 // This sets the maximum size of the CPU font cache to be at least the same size as the
57 // total number of GPU font caches (i.e. 4 separate GPU atlases).
58 , mMaxCpuFontCacheBytes(
59 std::max(mMaxGpuFontAtlasBytes * 4, SkGraphics::GetFontCacheLimit()))
60 , mBackgroundCpuFontCacheBytes(mMaxCpuFontCacheBytes * BACKGROUND_RETENTION_PERCENTAGE) {
61 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
62 }
63
reset(sk_sp<GrDirectContext> context)64 void CacheManager::reset(sk_sp<GrDirectContext> context) {
65 if (context != mGrContext) {
66 destroy();
67 }
68
69 if (context) {
70 mGrContext = std::move(context);
71 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
72 }
73 }
74
destroy()75 void CacheManager::destroy() {
76 // cleanup any caches here as the GrContext is about to go away...
77 mGrContext.reset(nullptr);
78 }
79
80 class CommonPoolExecutor : public SkExecutor {
81 public:
add(std::function<void (void)> func)82 virtual void add(std::function<void(void)> func) override { CommonPool::post(std::move(func)); }
83 };
84
85 static CommonPoolExecutor sDefaultExecutor;
86
configureContext(GrContextOptions * contextOptions,const void * identity,ssize_t size)87 void CacheManager::configureContext(GrContextOptions* contextOptions, const void* identity,
88 ssize_t size) {
89 contextOptions->fAllowPathMaskCaching = true;
90 contextOptions->fGlyphCacheTextureMaximumBytes = mMaxGpuFontAtlasBytes;
91 contextOptions->fExecutor = &sDefaultExecutor;
92
93 auto& cache = skiapipeline::ShaderCache::get();
94 cache.initShaderDiskCache(identity, size);
95 contextOptions->fPersistentCache = &cache;
96 contextOptions->fGpuPathRenderers &= ~GpuPathRenderers::kCoverageCounting;
97 }
98
trimMemory(TrimMemoryMode mode)99 void CacheManager::trimMemory(TrimMemoryMode mode) {
100 if (!mGrContext) {
101 return;
102 }
103
104 // flush and submit all work to the gpu and wait for it to finish
105 mGrContext->flushAndSubmit(/*syncCpu=*/true);
106
107 switch (mode) {
108 case TrimMemoryMode::Complete:
109 mGrContext->freeGpuResources();
110 SkGraphics::PurgeAllCaches();
111 break;
112 case TrimMemoryMode::UiHidden:
113 // Here we purge all the unlocked scratch resources and then toggle the resources cache
114 // limits between the background and max amounts. This causes the unlocked resources
115 // that have persistent data to be purged in LRU order.
116 mGrContext->purgeUnlockedResources(true);
117 mGrContext->setResourceCacheLimit(mBackgroundResourceBytes);
118 mGrContext->setResourceCacheLimit(mMaxResourceBytes);
119 SkGraphics::SetFontCacheLimit(mBackgroundCpuFontCacheBytes);
120 SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
121 break;
122 }
123 }
124
trimStaleResources()125 void CacheManager::trimStaleResources() {
126 if (!mGrContext) {
127 return;
128 }
129 mGrContext->flushAndSubmit();
130 mGrContext->purgeResourcesNotUsedInMs(std::chrono::seconds(30));
131 }
132
getMemoryUsage(size_t * cpuUsage,size_t * gpuUsage)133 void CacheManager::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
134 *cpuUsage = 0;
135 *gpuUsage = 0;
136 if (!mGrContext) {
137 return;
138 }
139
140 skiapipeline::SkiaMemoryTracer cpuTracer("category", true);
141 SkGraphics::DumpMemoryStatistics(&cpuTracer);
142 *cpuUsage += cpuTracer.total();
143
144 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
145 mGrContext->dumpMemoryStatistics(&gpuTracer);
146 *gpuUsage += gpuTracer.total();
147 }
148
dumpMemoryUsage(String8 & log,const RenderState * renderState)149 void CacheManager::dumpMemoryUsage(String8& log, const RenderState* renderState) {
150 if (!mGrContext) {
151 log.appendFormat("No valid cache instance.\n");
152 return;
153 }
154
155 std::vector<skiapipeline::ResourcePair> cpuResourceMap = {
156 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
157 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
158 {"skia/sk_resource_cache/rects-blur_", "Masks"},
159 {"skia/sk_resource_cache/tessellated", "Shadows"},
160 {"skia/sk_glyph_cache", "Glyph Cache"},
161 };
162 skiapipeline::SkiaMemoryTracer cpuTracer(cpuResourceMap, false);
163 SkGraphics::DumpMemoryStatistics(&cpuTracer);
164 if (cpuTracer.hasOutput()) {
165 log.appendFormat("CPU Caches:\n");
166 cpuTracer.logOutput(log);
167 log.appendFormat(" Glyph Count: %d \n", SkGraphics::GetFontCacheCountUsed());
168 log.appendFormat("Total CPU memory usage:\n");
169 cpuTracer.logTotals(log);
170 }
171
172 skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
173 mGrContext->dumpMemoryStatistics(&gpuTracer);
174 if (gpuTracer.hasOutput()) {
175 log.appendFormat("GPU Caches:\n");
176 gpuTracer.logOutput(log);
177 }
178
179 if (renderState && renderState->mActiveLayers.size() > 0) {
180 log.appendFormat("Layer Info:\n");
181
182 const char* layerType = Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL
183 ? "GlLayer"
184 : "VkLayer";
185 size_t layerMemoryTotal = 0;
186 for (std::set<Layer*>::iterator it = renderState->mActiveLayers.begin();
187 it != renderState->mActiveLayers.end(); it++) {
188 const Layer* layer = *it;
189 log.appendFormat(" %s size %dx%d\n", layerType, layer->getWidth(),
190 layer->getHeight());
191 layerMemoryTotal += layer->getWidth() * layer->getHeight() * 4;
192 }
193 log.appendFormat(" Layers Total %6.2f KB (numLayers = %zu)\n",
194 layerMemoryTotal / 1024.0f, renderState->mActiveLayers.size());
195 }
196
197 log.appendFormat("Total GPU memory usage:\n");
198 gpuTracer.logTotals(log);
199 }
200
onFrameCompleted()201 void CacheManager::onFrameCompleted() {
202 if (ATRACE_ENABLED()) {
203 static skiapipeline::ATraceMemoryDump tracer;
204 tracer.startFrame();
205 SkGraphics::DumpMemoryStatistics(&tracer);
206 if (mGrContext) {
207 mGrContext->dumpMemoryStatistics(&tracer);
208 }
209 tracer.logTraces();
210 }
211 }
212
performDeferredCleanup(nsecs_t cleanupOlderThanMillis)213 void CacheManager::performDeferredCleanup(nsecs_t cleanupOlderThanMillis) {
214 if (mGrContext) {
215 mGrContext->performDeferredCleanup(
216 std::chrono::milliseconds(cleanupOlderThanMillis),
217 /* scratchResourcesOnly */true);
218 }
219 }
220
221 } /* namespace renderthread */
222 } /* namespace uirenderer */
223 } /* namespace android */
224