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 <GrContext.h>
19 #include <log/log.h>
20 #include <openssl/sha.h>
21 #include <algorithm>
22 #include <array>
23 #include <thread>
24 #include "FileBlobCache.h"
25 #include "Properties.h"
26 #include "utils/TraceUtils.h"
27 
28 namespace android {
29 namespace uirenderer {
30 namespace skiapipeline {
31 
32 // Cache size limits.
33 static const size_t maxKeySize = 1024;
34 static const size_t maxValueSize = 512 * 1024;
35 static const size_t maxTotalSize = 1024 * 1024;
36 
ShaderCache()37 ShaderCache::ShaderCache() {
38     // There is an "incomplete FileBlobCache type" compilation error, if ctor is moved to header.
39 }
40 
41 ShaderCache ShaderCache::sCache;
42 
get()43 ShaderCache& ShaderCache::get() {
44     return sCache;
45 }
46 
validateCache(const void * identity,ssize_t size)47 bool ShaderCache::validateCache(const void* identity, ssize_t size) {
48     if (nullptr == identity && size == 0) return true;
49 
50     if (nullptr == identity || size < 0) {
51         if (CC_UNLIKELY(Properties::debugLevel & kDebugCaches)) {
52             ALOGW("ShaderCache::validateCache invalid cache identity");
53         }
54         mBlobCache->clear();
55         return false;
56     }
57 
58     SHA256_CTX ctx;
59     SHA256_Init(&ctx);
60 
61     SHA256_Update(&ctx, identity, size);
62     mIDHash.resize(SHA256_DIGEST_LENGTH);
63     SHA256_Final(mIDHash.data(), &ctx);
64 
65     std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
66     auto key = sIDKey;
67     auto loaded = mBlobCache->get(&key, sizeof(key), hash.data(), hash.size());
68 
69     if (loaded && std::equal(hash.begin(), hash.end(), mIDHash.begin())) return true;
70 
71     if (CC_UNLIKELY(Properties::debugLevel & kDebugCaches)) {
72         ALOGW("ShaderCache::validateCache cache validation fails");
73     }
74     mBlobCache->clear();
75     return false;
76 }
77 
initShaderDiskCache(const void * identity,ssize_t size)78 void ShaderCache::initShaderDiskCache(const void* identity, ssize_t size) {
79     ATRACE_NAME("initShaderDiskCache");
80     std::lock_guard<std::mutex> lock(mMutex);
81 
82     // Emulators can switch between different renders either as part of config
83     // or snapshot migration. Also, program binaries may not work well on some
84     // desktop / laptop GPUs. Thus, disable the shader disk cache for emulator builds.
85     if (!Properties::runningInEmulator && mFilename.length() > 0) {
86         mBlobCache.reset(new FileBlobCache(maxKeySize, maxValueSize, maxTotalSize, mFilename));
87         validateCache(identity, size);
88         mInitialized = true;
89     }
90 }
91 
setFilename(const char * filename)92 void ShaderCache::setFilename(const char* filename) {
93     std::lock_guard<std::mutex> lock(mMutex);
94     mFilename = filename;
95 }
96 
getBlobCacheLocked()97 BlobCache* ShaderCache::getBlobCacheLocked() {
98     LOG_ALWAYS_FATAL_IF(!mInitialized, "ShaderCache has not been initialized");
99     return mBlobCache.get();
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<std::mutex> 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     BlobCache* bc = getBlobCacheLocked();
117     size_t valueSize = bc->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
118     int maxTries = 3;
119     while (valueSize > mObservedBlobValueSize && maxTries > 0) {
120         mObservedBlobValueSize = std::min(valueSize, maxValueSize);
121         void* newValueBuffer = realloc(valueBuffer, mObservedBlobValueSize);
122         if (!newValueBuffer) {
123             free(valueBuffer);
124             return nullptr;
125         }
126         valueBuffer = newValueBuffer;
127         valueSize = bc->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
128         maxTries--;
129     }
130     if (!valueSize) {
131         free(valueBuffer);
132         return nullptr;
133     }
134     if (valueSize > mObservedBlobValueSize) {
135         ALOGE("ShaderCache::load value size is too big %d", (int)valueSize);
136         free(valueBuffer);
137         return nullptr;
138     }
139     return SkData::MakeFromMalloc(valueBuffer, valueSize);
140 }
141 
saveToDiskLocked()142 void ShaderCache::saveToDiskLocked() {
143     ATRACE_NAME("ShaderCache::saveToDiskLocked");
144     if (mInitialized && mBlobCache && mSavePending) {
145         if (mIDHash.size()) {
146             auto key = sIDKey;
147             mBlobCache->set(&key, sizeof(key), mIDHash.data(), mIDHash.size());
148         }
149         mBlobCache->writeToFile();
150     }
151     mSavePending = false;
152 }
153 
store(const SkData & key,const SkData & data)154 void ShaderCache::store(const SkData& key, const SkData& data) {
155     ATRACE_NAME("ShaderCache::store");
156     std::lock_guard<std::mutex> lock(mMutex);
157 
158     if (!mInitialized) {
159         return;
160     }
161 
162     size_t valueSize = data.size();
163     size_t keySize = key.size();
164     if (keySize == 0 || valueSize == 0 || valueSize >= maxValueSize) {
165         ALOGW("ShaderCache::store: sizes %d %d not allowed", (int)keySize, (int)valueSize);
166         return;
167     }
168 
169     const void* value = data.data();
170 
171     BlobCache* bc = getBlobCacheLocked();
172     if (mInStoreVkPipelineInProgress) {
173         if (mOldPipelineCacheSize == -1) {
174             // Record the initial pipeline cache size stored in the file.
175             mOldPipelineCacheSize = bc->get(key.data(), keySize, nullptr, 0);
176         }
177         if (mNewPipelineCacheSize != -1 && mNewPipelineCacheSize == valueSize) {
178             // There has not been change in pipeline cache size. Stop trying to save.
179             mTryToStorePipelineCache = false;
180             return;
181         }
182         mNewPipelineCacheSize = valueSize;
183     } else {
184         mCacheDirty = true;
185         // If there are new shaders compiled, we probably have new pipeline state too.
186         // Store pipeline cache on the next flush.
187         mNewPipelineCacheSize = -1;
188         mTryToStorePipelineCache = true;
189     }
190     bc->set(key.data(), keySize, value, valueSize);
191 
192     if (!mSavePending && mDeferredSaveDelay > 0) {
193         mSavePending = true;
194         std::thread deferredSaveThread([this]() {
195             sleep(mDeferredSaveDelay);
196             std::lock_guard<std::mutex> lock(mMutex);
197             // Store file on disk if there a new shader or Vulkan pipeline cache size changed.
198             if (mCacheDirty || mNewPipelineCacheSize != mOldPipelineCacheSize) {
199                 saveToDiskLocked();
200                 mOldPipelineCacheSize = mNewPipelineCacheSize;
201                 mTryToStorePipelineCache = false;
202                 mCacheDirty = false;
203             }
204         });
205         deferredSaveThread.detach();
206     }
207 }
208 
onVkFrameFlushed(GrContext * context)209 void ShaderCache::onVkFrameFlushed(GrContext* context) {
210     {
211         std::lock_guard<std::mutex> lock(mMutex);
212 
213         if (!mInitialized || !mTryToStorePipelineCache) {
214             return;
215         }
216     }
217     mInStoreVkPipelineInProgress = true;
218     context->storeVkPipelineCacheData();
219     mInStoreVkPipelineInProgress = false;
220 }
221 
222 } /* namespace skiapipeline */
223 } /* namespace uirenderer */
224 } /* namespace android */
225