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 "ShaderCache.h"
18 #include <GrDirectContext.h>
19 #include <SkData.h>
20 #include <gui/TraceUtils.h>
21 #include <log/log.h>
22 #include <openssl/sha.h>
23 #include <algorithm>
24 #include <array>
25 #include <thread>
26 #include "FileBlobCache.h"
27 #include "Properties.h"
28 
29 namespace android {
30 namespace uirenderer {
31 namespace skiapipeline {
32 
33 // Cache size limits.
34 static const size_t maxKeySize = 1024;
35 static const size_t maxValueSize = 2 * 1024 * 1024;
36 static const size_t maxTotalSize = 4 * 1024 * 1024;
37 static_assert(maxKeySize + maxValueSize < maxTotalSize);
38 
ShaderCache()39 ShaderCache::ShaderCache() {
40     // There is an "incomplete FileBlobCache type" compilation error, if ctor is moved to header.
41 }
42 
43 ShaderCache ShaderCache::sCache;
44 
get()45 ShaderCache& ShaderCache::get() {
46     return sCache;
47 }
48 
validateCache(const void * identity,ssize_t size)49 bool ShaderCache::validateCache(const void* identity, ssize_t size) {
50     if (nullptr == identity && size == 0) return true;
51 
52     if (nullptr == identity || size < 0) {
53         if (CC_UNLIKELY(Properties::debugLevel & kDebugCaches)) {
54             ALOGW("ShaderCache::validateCache invalid cache identity");
55         }
56         mBlobCache->clear();
57         return false;
58     }
59 
60     SHA256_CTX ctx;
61     SHA256_Init(&ctx);
62 
63     SHA256_Update(&ctx, identity, size);
64     mIDHash.resize(SHA256_DIGEST_LENGTH);
65     SHA256_Final(mIDHash.data(), &ctx);
66 
67     std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
68     auto key = sIDKey;
69     auto loaded = mBlobCache->get(&key, sizeof(key), hash.data(), hash.size());
70 
71     if (loaded && std::equal(hash.begin(), hash.end(), mIDHash.begin())) return true;
72 
73     if (CC_UNLIKELY(Properties::debugLevel & kDebugCaches)) {
74         ALOGW("ShaderCache::validateCache cache validation fails");
75     }
76     mBlobCache->clear();
77     return false;
78 }
79 
initShaderDiskCache(const void * identity,ssize_t size)80 void ShaderCache::initShaderDiskCache(const void* identity, ssize_t size) {
81     ATRACE_NAME("initShaderDiskCache");
82     std::lock_guard lock(mMutex);
83 
84     // Emulators can switch between different renders either as part of config
85     // or snapshot migration. Also, program binaries may not work well on some
86     // desktop / laptop GPUs. Thus, disable the shader disk cache for emulator builds.
87     if (!Properties::runningInEmulator && mFilename.length() > 0) {
88         mBlobCache.reset(new FileBlobCache(maxKeySize, maxValueSize, maxTotalSize, mFilename));
89         validateCache(identity, size);
90         mInitialized = true;
91         if (identity != nullptr && size > 0 && mIDHash.size()) {
92             set(&sIDKey, sizeof(sIDKey), mIDHash.data(), mIDHash.size());
93         }
94     }
95 }
96 
setFilename(const char * filename)97 void ShaderCache::setFilename(const char* filename) {
98     std::lock_guard lock(mMutex);
99     mFilename = filename;
100 }
101 
load(const SkData & key)102 sk_sp<SkData> ShaderCache::load(const SkData& key) {
103     ATRACE_NAME("ShaderCache::load");
104     size_t keySize = key.size();
105     std::lock_guard lock(mMutex);
106     if (!mInitialized) {
107         return nullptr;
108     }
109 
110     // mObservedBlobValueSize is reasonably big to avoid memory reallocation
111     // Allocate a buffer with malloc. SkData takes ownership of that allocation and will call free.
112     void* valueBuffer = malloc(mObservedBlobValueSize);
113     if (!valueBuffer) {
114         return nullptr;
115     }
116     size_t valueSize = mBlobCache->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
117     int maxTries = 3;
118     while (valueSize > mObservedBlobValueSize && maxTries > 0) {
119         mObservedBlobValueSize = std::min(valueSize, maxValueSize);
120         void* newValueBuffer = realloc(valueBuffer, mObservedBlobValueSize);
121         if (!newValueBuffer) {
122             free(valueBuffer);
123             return nullptr;
124         }
125         valueBuffer = newValueBuffer;
126         valueSize = mBlobCache->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
127         maxTries--;
128     }
129     if (!valueSize) {
130         free(valueBuffer);
131         return nullptr;
132     }
133     if (valueSize > mObservedBlobValueSize) {
134         ALOGE("ShaderCache::load value size is too big %d", (int)valueSize);
135         free(valueBuffer);
136         return nullptr;
137     }
138     mNumShadersCachedInRam++;
139     ATRACE_FORMAT("HWUI RAM cache: %d shaders", mNumShadersCachedInRam);
140     return SkData::MakeFromMalloc(valueBuffer, valueSize);
141 }
142 
set(const void * key,size_t keySize,const void * value,size_t valueSize)143 void ShaderCache::set(const void* key, size_t keySize, const void* value, size_t valueSize) {
144     switch (mBlobCache->set(key, keySize, value, valueSize)) {
145         case BlobCache::InsertResult::kInserted:
146             // This is what we expect/hope. It means the cache is large enough.
147             return;
148         case BlobCache::InsertResult::kDidClean: {
149             ATRACE_FORMAT("ShaderCache: evicted an entry to fit {key: %lu value %lu}!", keySize,
150                           valueSize);
151             if (mIDHash.size()) {
152                 set(&sIDKey, sizeof(sIDKey), mIDHash.data(), mIDHash.size());
153             }
154             return;
155         }
156         case BlobCache::InsertResult::kNotEnoughSpace: {
157             ATRACE_FORMAT("ShaderCache: could not fit {key: %lu value %lu}!", keySize, valueSize);
158             return;
159         }
160         case BlobCache::InsertResult::kInvalidValueSize:
161         case BlobCache::InsertResult::kInvalidKeySize: {
162             ATRACE_FORMAT("ShaderCache: invalid size {key: %lu value %lu}!", keySize, valueSize);
163             return;
164         }
165         case BlobCache::InsertResult::kKeyTooBig:
166         case BlobCache::InsertResult::kValueTooBig:
167         case BlobCache::InsertResult::kCombinedTooBig: {
168             ATRACE_FORMAT("ShaderCache: entry too big: {key: %lu value %lu}!", keySize, valueSize);
169             return;
170         }
171     }
172 }
173 
saveToDiskLocked()174 void ShaderCache::saveToDiskLocked() {
175     ATRACE_NAME("ShaderCache::saveToDiskLocked");
176     if (mInitialized && mBlobCache) {
177         // The most straightforward way to make ownership shared
178         mMutex.unlock();
179         mMutex.lock_shared();
180         mBlobCache->writeToFile();
181         mMutex.unlock_shared();
182         mMutex.lock();
183     }
184 }
185 
store(const SkData & key,const SkData & data,const SkString &)186 void ShaderCache::store(const SkData& key, const SkData& data, const SkString& /*description*/) {
187     ATRACE_NAME("ShaderCache::store");
188     std::lock_guard lock(mMutex);
189     mNumShadersCachedInRam++;
190     ATRACE_FORMAT("HWUI RAM cache: %d shaders", mNumShadersCachedInRam);
191 
192     if (!mInitialized) {
193         return;
194     }
195 
196     size_t valueSize = data.size();
197     size_t keySize = key.size();
198     if (keySize == 0 || valueSize == 0 || valueSize >= maxValueSize) {
199         ALOGW("ShaderCache::store: sizes %d %d not allowed", (int)keySize, (int)valueSize);
200         return;
201     }
202 
203     const void* value = data.data();
204 
205     if (mInStoreVkPipelineInProgress) {
206         if (mOldPipelineCacheSize == -1) {
207             // Record the initial pipeline cache size stored in the file.
208             mOldPipelineCacheSize = mBlobCache->get(key.data(), keySize, nullptr, 0);
209         }
210         if (mNewPipelineCacheSize != -1 && mNewPipelineCacheSize == valueSize) {
211             // There has not been change in pipeline cache size. Stop trying to save.
212             mTryToStorePipelineCache = false;
213             return;
214         }
215         mNewPipelineCacheSize = valueSize;
216     } else {
217         mCacheDirty = true;
218         // If there are new shaders compiled, we probably have new pipeline state too.
219         // Store pipeline cache on the next flush.
220         mNewPipelineCacheSize = -1;
221         mTryToStorePipelineCache = true;
222     }
223     set(key.data(), keySize, value, valueSize);
224 
225     if (!mSavePending && mDeferredSaveDelayMs > 0) {
226         mSavePending = true;
227         std::thread deferredSaveThread([this]() {
228             usleep(mDeferredSaveDelayMs * 1000);  // milliseconds to microseconds
229             std::lock_guard lock(mMutex);
230             // Store file on disk if there a new shader or Vulkan pipeline cache size changed.
231             if (mCacheDirty || mNewPipelineCacheSize != mOldPipelineCacheSize) {
232                 saveToDiskLocked();
233                 mOldPipelineCacheSize = mNewPipelineCacheSize;
234                 mTryToStorePipelineCache = false;
235                 mCacheDirty = false;
236             }
237             mSavePending = false;
238         });
239         deferredSaveThread.detach();
240     }
241 }
242 
onVkFrameFlushed(GrDirectContext * context)243 void ShaderCache::onVkFrameFlushed(GrDirectContext* context) {
244     {
245         mMutex.lock_shared();
246         if (!mInitialized || !mTryToStorePipelineCache) {
247             mMutex.unlock_shared();
248             return;
249         }
250         mMutex.unlock_shared();
251     }
252     mInStoreVkPipelineInProgress = true;
253     context->storeVkPipelineCacheData();
254     mInStoreVkPipelineInProgress = false;
255 }
256 
257 } /* namespace skiapipeline */
258 } /* namespace uirenderer */
259 } /* namespace android */
260