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<GrContext> context)64 void CacheManager::reset(sk_sp<GrContext> 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     mGrContext->flush();
105 
106     switch (mode) {
107         case TrimMemoryMode::Complete:
108             mGrContext->freeGpuResources();
109             SkGraphics::PurgeAllCaches();
110             break;
111         case TrimMemoryMode::UiHidden:
112             // Here we purge all the unlocked scratch resources and then toggle the resources cache
113             // limits between the background and max amounts. This causes the unlocked resources
114             // that have persistent data to be purged in LRU order.
115             mGrContext->purgeUnlockedResources(true);
116             mGrContext->setResourceCacheLimit(mBackgroundResourceBytes);
117             mGrContext->setResourceCacheLimit(mMaxResourceBytes);
118             SkGraphics::SetFontCacheLimit(mBackgroundCpuFontCacheBytes);
119             SkGraphics::SetFontCacheLimit(mMaxCpuFontCacheBytes);
120             break;
121     }
122 
123     // We must sync the cpu to make sure deletions of resources still queued up on the GPU actually
124     // happen.
125     mGrContext->flush(kSyncCpu_GrFlushFlag, 0, nullptr);
126 }
127 
trimStaleResources()128 void CacheManager::trimStaleResources() {
129     if (!mGrContext) {
130         return;
131     }
132     mGrContext->flush();
133     mGrContext->purgeResourcesNotUsedInMs(std::chrono::seconds(30));
134 }
135 
dumpMemoryUsage(String8 & log,const RenderState * renderState)136 void CacheManager::dumpMemoryUsage(String8& log, const RenderState* renderState) {
137     if (!mGrContext) {
138         log.appendFormat("No valid cache instance.\n");
139         return;
140     }
141 
142     log.appendFormat("Font Cache (CPU):\n");
143     log.appendFormat("  Size: %.2f kB \n", SkGraphics::GetFontCacheUsed() / 1024.0f);
144     log.appendFormat("  Glyph Count: %d \n", SkGraphics::GetFontCacheCountUsed());
145 
146     log.appendFormat("CPU Caches:\n");
147     std::vector<skiapipeline::ResourcePair> cpuResourceMap = {
148             {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
149             {"skia/sk_resource_cache/rrect-blur_", "Masks"},
150             {"skia/sk_resource_cache/rects-blur_", "Masks"},
151             {"skia/sk_resource_cache/tessellated", "Shadows"},
152     };
153     skiapipeline::SkiaMemoryTracer cpuTracer(cpuResourceMap, false);
154     SkGraphics::DumpMemoryStatistics(&cpuTracer);
155     cpuTracer.logOutput(log);
156 
157     log.appendFormat("GPU Caches:\n");
158     skiapipeline::SkiaMemoryTracer gpuTracer("category", true);
159     mGrContext->dumpMemoryStatistics(&gpuTracer);
160     gpuTracer.logOutput(log);
161 
162     log.appendFormat("Other Caches:\n");
163     log.appendFormat("                         Current / Maximum\n");
164 
165     if (renderState) {
166         if (renderState->mActiveLayers.size() > 0) {
167             log.appendFormat("  Layer Info:\n");
168         }
169 
170         const char* layerType = Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL
171                                         ? "GlLayer"
172                                         : "VkLayer";
173         size_t layerMemoryTotal = 0;
174         for (std::set<Layer*>::iterator it = renderState->mActiveLayers.begin();
175              it != renderState->mActiveLayers.end(); it++) {
176             const Layer* layer = *it;
177             log.appendFormat("    %s size %dx%d\n", layerType, layer->getWidth(),
178                              layer->getHeight());
179             layerMemoryTotal += layer->getWidth() * layer->getHeight() * 4;
180         }
181         log.appendFormat("  Layers Total         %6.2f KB (numLayers = %zu)\n",
182                          layerMemoryTotal / 1024.0f, renderState->mActiveLayers.size());
183     }
184 
185     log.appendFormat("Total GPU memory usage:\n");
186     gpuTracer.logTotals(log);
187 }
188 
onFrameCompleted()189 void CacheManager::onFrameCompleted() {
190     if (ATRACE_ENABLED()) {
191         static skiapipeline::ATraceMemoryDump tracer;
192         tracer.startFrame();
193         SkGraphics::DumpMemoryStatistics(&tracer);
194         if (mGrContext) {
195             mGrContext->dumpMemoryStatistics(&tracer);
196         }
197         tracer.logTraces();
198     }
199 }
200 
201 } /* namespace renderthread */
202 } /* namespace uirenderer */
203 } /* namespace android */
204