blob: d9e9aafe91ea186bc1c06a2d2ba0bed532786636 [file] [log] [blame]
Stan Ilievd495f432017-10-09 15:49:32 -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 "ShaderCache.h"
Adlai Hollerd2345212020-10-07 14:16:40 -040018#include <GrDirectContext.h>
rnleece9762b2021-05-21 15:40:53 -070019#include <gui/TraceUtils.h>
Stan Ilievd495f432017-10-09 15:49:32 -040020#include <log/log.h>
Yichi Chen9f959552018-03-29 21:21:54 +080021#include <openssl/sha.h>
John Reck283bb462018-12-13 16:40:14 -080022#include <algorithm>
23#include <array>
24#include <thread>
Stan Ilievd495f432017-10-09 15:49:32 -040025#include "FileBlobCache.h"
Lingfeng Yang3a9f2232018-01-24 10:40:18 -080026#include "Properties.h"
Stan Ilievd495f432017-10-09 15:49:32 -040027
28namespace android {
29namespace uirenderer {
30namespace skiapipeline {
31
32// Cache size limits.
33static const size_t maxKeySize = 1024;
Leon Scroggins III05f5eca2021-06-07 16:09:37 -040034static const size_t maxValueSize = 2 * 1024 * 1024;
Stan Ilievda8a5102019-01-24 14:57:01 -050035static const size_t maxTotalSize = 1024 * 1024;
Stan Ilievd495f432017-10-09 15:49:32 -040036
37ShaderCache::ShaderCache() {
38 // There is an "incomplete FileBlobCache type" compilation error, if ctor is moved to header.
39}
40
41ShaderCache ShaderCache::sCache;
42
43ShaderCache& ShaderCache::get() {
44 return sCache;
45}
46
Yichi Chen9f959552018-03-29 21:21:54 +080047bool ShaderCache::validateCache(const void* identity, ssize_t size) {
John Reck283bb462018-12-13 16:40:14 -080048 if (nullptr == identity && size == 0) return true;
Yichi Chen9f959552018-03-29 21:21:54 +080049
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
John Reck283bb462018-12-13 16:40:14 -080069 if (loaded && std::equal(hash.begin(), hash.end(), mIDHash.begin())) return true;
Yichi Chen9f959552018-03-29 21:21:54 +080070
71 if (CC_UNLIKELY(Properties::debugLevel & kDebugCaches)) {
72 ALOGW("ShaderCache::validateCache cache validation fails");
73 }
74 mBlobCache->clear();
75 return false;
76}
77
78void ShaderCache::initShaderDiskCache(const void* identity, ssize_t size) {
Stan Ilievd495f432017-10-09 15:49:32 -040079 ATRACE_NAME("initShaderDiskCache");
80 std::lock_guard<std::mutex> lock(mMutex);
Lingfeng Yang3a9f2232018-01-24 10:40:18 -080081
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) {
Stan Ilievd495f432017-10-09 15:49:32 -040086 mBlobCache.reset(new FileBlobCache(maxKeySize, maxValueSize, maxTotalSize, mFilename));
Yichi Chen9f959552018-03-29 21:21:54 +080087 validateCache(identity, size);
Stan Ilievd495f432017-10-09 15:49:32 -040088 mInitialized = true;
89 }
90}
91
92void ShaderCache::setFilename(const char* filename) {
93 std::lock_guard<std::mutex> lock(mMutex);
94 mFilename = filename;
95}
96
97BlobCache* ShaderCache::getBlobCacheLocked() {
98 LOG_ALWAYS_FATAL_IF(!mInitialized, "ShaderCache has not been initialized");
99 return mBlobCache.get();
100}
101
102sk_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) {
Stan Ilievd495f432017-10-09 15:49:32 -0400107 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);
John Reck283bb462018-12-13 16:40:14 -0800121 void* newValueBuffer = realloc(valueBuffer, mObservedBlobValueSize);
Stan Iliev003a9f62018-03-29 13:33:53 -0400122 if (!newValueBuffer) {
123 free(valueBuffer);
Stan Ilievd495f432017-10-09 15:49:32 -0400124 return nullptr;
125 }
Stan Iliev003a9f62018-03-29 13:33:53 -0400126 valueBuffer = newValueBuffer;
Stan Ilievd495f432017-10-09 15:49:32 -0400127 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) {
John Reck283bb462018-12-13 16:40:14 -0800135 ALOGE("ShaderCache::load value size is too big %d", (int)valueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400136 free(valueBuffer);
137 return nullptr;
138 }
139 return SkData::MakeFromMalloc(valueBuffer, valueSize);
140}
141
Leon Scroggins III77644a22022-05-03 15:50:51 -0400142namespace {
143// Helper for BlobCache::set to trace the result.
144void set(BlobCache* cache, const void* key, size_t keySize, const void* value, size_t valueSize) {
145 switch (cache->set(key, keySize, value, valueSize)) {
146 case BlobCache::InsertResult::kInserted:
147 // This is what we expect/hope. It means the cache is large enough.
148 return;
149 case BlobCache::InsertResult::kDidClean: {
150 ATRACE_FORMAT("ShaderCache: evicted an entry to fit {key: %lu value %lu}!", keySize,
151 valueSize);
152 return;
153 }
154 case BlobCache::InsertResult::kNotEnoughSpace: {
155 ATRACE_FORMAT("ShaderCache: could not fit {key: %lu value %lu}!", keySize, valueSize);
156 return;
157 }
158 case BlobCache::InsertResult::kInvalidValueSize:
159 case BlobCache::InsertResult::kInvalidKeySize: {
160 ATRACE_FORMAT("ShaderCache: invalid size {key: %lu value %lu}!", keySize, valueSize);
161 return;
162 }
163 case BlobCache::InsertResult::kKeyTooBig:
164 case BlobCache::InsertResult::kValueTooBig:
165 case BlobCache::InsertResult::kCombinedTooBig: {
166 ATRACE_FORMAT("ShaderCache: entry too big: {key: %lu value %lu}!", keySize, valueSize);
167 return;
168 }
169 }
170}
171} // namespace
172
Yichi Chen9f959552018-03-29 21:21:54 +0800173void ShaderCache::saveToDiskLocked() {
174 ATRACE_NAME("ShaderCache::saveToDiskLocked");
175 if (mInitialized && mBlobCache && mSavePending) {
176 if (mIDHash.size()) {
177 auto key = sIDKey;
Leon Scroggins III77644a22022-05-03 15:50:51 -0400178 set(mBlobCache.get(), &key, sizeof(key), mIDHash.data(), mIDHash.size());
Yichi Chen9f959552018-03-29 21:21:54 +0800179 }
180 mBlobCache->writeToFile();
181 }
182 mSavePending = false;
183}
184
Stan Ilievd495f432017-10-09 15:49:32 -0400185void ShaderCache::store(const SkData& key, const SkData& data) {
186 ATRACE_NAME("ShaderCache::store");
187 std::lock_guard<std::mutex> lock(mMutex);
188
189 if (!mInitialized) {
Stan Ilievd495f432017-10-09 15:49:32 -0400190 return;
191 }
192
193 size_t valueSize = data.size();
194 size_t keySize = key.size();
195 if (keySize == 0 || valueSize == 0 || valueSize >= maxValueSize) {
196 ALOGW("ShaderCache::store: sizes %d %d not allowed", (int)keySize, (int)valueSize);
197 return;
198 }
199
200 const void* value = data.data();
201
202 BlobCache* bc = getBlobCacheLocked();
Stan Iliev14211aa2019-01-14 12:29:30 -0500203 if (mInStoreVkPipelineInProgress) {
204 if (mOldPipelineCacheSize == -1) {
205 // Record the initial pipeline cache size stored in the file.
206 mOldPipelineCacheSize = bc->get(key.data(), keySize, nullptr, 0);
207 }
208 if (mNewPipelineCacheSize != -1 && mNewPipelineCacheSize == valueSize) {
209 // There has not been change in pipeline cache size. Stop trying to save.
210 mTryToStorePipelineCache = false;
211 return;
212 }
213 mNewPipelineCacheSize = valueSize;
214 } else {
215 mCacheDirty = true;
216 // If there are new shaders compiled, we probably have new pipeline state too.
217 // Store pipeline cache on the next flush.
218 mNewPipelineCacheSize = -1;
219 mTryToStorePipelineCache = true;
220 }
Leon Scroggins III77644a22022-05-03 15:50:51 -0400221 set(bc, key.data(), keySize, value, valueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400222
223 if (!mSavePending && mDeferredSaveDelay > 0) {
224 mSavePending = true;
225 std::thread deferredSaveThread([this]() {
226 sleep(mDeferredSaveDelay);
227 std::lock_guard<std::mutex> lock(mMutex);
Stan Iliev14211aa2019-01-14 12:29:30 -0500228 // Store file on disk if there a new shader or Vulkan pipeline cache size changed.
229 if (mCacheDirty || mNewPipelineCacheSize != mOldPipelineCacheSize) {
230 saveToDiskLocked();
231 mOldPipelineCacheSize = mNewPipelineCacheSize;
232 mTryToStorePipelineCache = false;
233 mCacheDirty = false;
234 }
Stan Ilievd495f432017-10-09 15:49:32 -0400235 });
236 deferredSaveThread.detach();
237 }
238}
239
Adlai Hollerd2345212020-10-07 14:16:40 -0400240void ShaderCache::onVkFrameFlushed(GrDirectContext* context) {
Stan Iliev14211aa2019-01-14 12:29:30 -0500241 {
242 std::lock_guard<std::mutex> lock(mMutex);
243
244 if (!mInitialized || !mTryToStorePipelineCache) {
245 return;
246 }
247 }
248 mInStoreVkPipelineInProgress = true;
249 context->storeVkPipelineCacheData();
250 mInStoreVkPipelineInProgress = false;
251}
252
Stan Ilievd495f432017-10-09 15:49:32 -0400253} /* namespace skiapipeline */
254} /* namespace uirenderer */
255} /* namespace android */