blob: f71e7289bd37a12e21765c4feb19245ed74e3704 [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>
Kevin Lubick1175dc02022-02-28 12:41:27 -050019#include <SkData.h>
rnleece9762b2021-05-21 15:40:53 -070020#include <gui/TraceUtils.h>
Stan Ilievd495f432017-10-09 15:49:32 -040021#include <log/log.h>
Yichi Chen9f959552018-03-29 21:21:54 +080022#include <openssl/sha.h>
John Reck283bb462018-12-13 16:40:14 -080023#include <algorithm>
24#include <array>
25#include <thread>
Stan Ilievd495f432017-10-09 15:49:32 -040026#include "FileBlobCache.h"
Lingfeng Yang3a9f2232018-01-24 10:40:18 -080027#include "Properties.h"
Stan Ilievd495f432017-10-09 15:49:32 -040028
29namespace android {
30namespace uirenderer {
31namespace skiapipeline {
32
33// Cache size limits.
34static const size_t maxKeySize = 1024;
Leon Scroggins III05f5eca2021-06-07 16:09:37 -040035static const size_t maxValueSize = 2 * 1024 * 1024;
Nolan Scobief50917c2023-02-09 13:43:52 -050036static const size_t maxTotalSize = 4 * 1024 * 1024;
37static_assert(maxKeySize + maxValueSize < maxTotalSize);
Stan Ilievd495f432017-10-09 15:49:32 -040038
39ShaderCache::ShaderCache() {
40 // There is an "incomplete FileBlobCache type" compilation error, if ctor is moved to header.
41}
42
43ShaderCache ShaderCache::sCache;
44
45ShaderCache& ShaderCache::get() {
46 return sCache;
47}
48
Yichi Chen9f959552018-03-29 21:21:54 +080049bool ShaderCache::validateCache(const void* identity, ssize_t size) {
John Reck283bb462018-12-13 16:40:14 -080050 if (nullptr == identity && size == 0) return true;
Yichi Chen9f959552018-03-29 21:21:54 +080051
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
John Reck283bb462018-12-13 16:40:14 -080071 if (loaded && std::equal(hash.begin(), hash.end(), mIDHash.begin())) return true;
Yichi Chen9f959552018-03-29 21:21:54 +080072
73 if (CC_UNLIKELY(Properties::debugLevel & kDebugCaches)) {
74 ALOGW("ShaderCache::validateCache cache validation fails");
75 }
76 mBlobCache->clear();
77 return false;
78}
79
80void ShaderCache::initShaderDiskCache(const void* identity, ssize_t size) {
Stan Ilievd495f432017-10-09 15:49:32 -040081 ATRACE_NAME("initShaderDiskCache");
Matt Buckleye278da12023-06-20 22:51:05 +000082 std::lock_guard lock(mMutex);
Lingfeng Yang3a9f2232018-01-24 10:40:18 -080083
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) {
Stan Ilievd495f432017-10-09 15:49:32 -040088 mBlobCache.reset(new FileBlobCache(maxKeySize, maxValueSize, maxTotalSize, mFilename));
Yichi Chen9f959552018-03-29 21:21:54 +080089 validateCache(identity, size);
Stan Ilievd495f432017-10-09 15:49:32 -040090 mInitialized = true;
91 }
92}
93
94void ShaderCache::setFilename(const char* filename) {
Matt Buckleye278da12023-06-20 22:51:05 +000095 std::lock_guard lock(mMutex);
Stan Ilievd495f432017-10-09 15:49:32 -040096 mFilename = filename;
97}
98
99BlobCache* ShaderCache::getBlobCacheLocked() {
100 LOG_ALWAYS_FATAL_IF(!mInitialized, "ShaderCache has not been initialized");
101 return mBlobCache.get();
102}
103
104sk_sp<SkData> ShaderCache::load(const SkData& key) {
105 ATRACE_NAME("ShaderCache::load");
106 size_t keySize = key.size();
Matt Buckleye278da12023-06-20 22:51:05 +0000107 std::lock_guard lock(mMutex);
Stan Ilievd495f432017-10-09 15:49:32 -0400108 if (!mInitialized) {
Stan Ilievd495f432017-10-09 15:49:32 -0400109 return nullptr;
110 }
111
112 // mObservedBlobValueSize is reasonably big to avoid memory reallocation
113 // Allocate a buffer with malloc. SkData takes ownership of that allocation and will call free.
114 void* valueBuffer = malloc(mObservedBlobValueSize);
115 if (!valueBuffer) {
116 return nullptr;
117 }
118 BlobCache* bc = getBlobCacheLocked();
119 size_t valueSize = bc->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
120 int maxTries = 3;
121 while (valueSize > mObservedBlobValueSize && maxTries > 0) {
122 mObservedBlobValueSize = std::min(valueSize, maxValueSize);
John Reck283bb462018-12-13 16:40:14 -0800123 void* newValueBuffer = realloc(valueBuffer, mObservedBlobValueSize);
Stan Iliev003a9f62018-03-29 13:33:53 -0400124 if (!newValueBuffer) {
125 free(valueBuffer);
Stan Ilievd495f432017-10-09 15:49:32 -0400126 return nullptr;
127 }
Stan Iliev003a9f62018-03-29 13:33:53 -0400128 valueBuffer = newValueBuffer;
Stan Ilievd495f432017-10-09 15:49:32 -0400129 valueSize = bc->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
130 maxTries--;
131 }
132 if (!valueSize) {
133 free(valueBuffer);
134 return nullptr;
135 }
136 if (valueSize > mObservedBlobValueSize) {
John Reck283bb462018-12-13 16:40:14 -0800137 ALOGE("ShaderCache::load value size is too big %d", (int)valueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400138 free(valueBuffer);
139 return nullptr;
140 }
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400141 mNumShadersCachedInRam++;
142 ATRACE_FORMAT("HWUI RAM cache: %d shaders", mNumShadersCachedInRam);
Stan Ilievd495f432017-10-09 15:49:32 -0400143 return SkData::MakeFromMalloc(valueBuffer, valueSize);
144}
145
Leon Scroggins III77644a22022-05-03 15:50:51 -0400146namespace {
147// Helper for BlobCache::set to trace the result.
148void set(BlobCache* cache, const void* key, size_t keySize, const void* value, size_t valueSize) {
149 switch (cache->set(key, keySize, value, valueSize)) {
150 case BlobCache::InsertResult::kInserted:
151 // This is what we expect/hope. It means the cache is large enough.
152 return;
153 case BlobCache::InsertResult::kDidClean: {
154 ATRACE_FORMAT("ShaderCache: evicted an entry to fit {key: %lu value %lu}!", keySize,
155 valueSize);
156 return;
157 }
158 case BlobCache::InsertResult::kNotEnoughSpace: {
159 ATRACE_FORMAT("ShaderCache: could not fit {key: %lu value %lu}!", keySize, valueSize);
160 return;
161 }
162 case BlobCache::InsertResult::kInvalidValueSize:
163 case BlobCache::InsertResult::kInvalidKeySize: {
164 ATRACE_FORMAT("ShaderCache: invalid size {key: %lu value %lu}!", keySize, valueSize);
165 return;
166 }
167 case BlobCache::InsertResult::kKeyTooBig:
168 case BlobCache::InsertResult::kValueTooBig:
169 case BlobCache::InsertResult::kCombinedTooBig: {
170 ATRACE_FORMAT("ShaderCache: entry too big: {key: %lu value %lu}!", keySize, valueSize);
171 return;
172 }
173 }
174}
175} // namespace
176
Yichi Chen9f959552018-03-29 21:21:54 +0800177void ShaderCache::saveToDiskLocked() {
178 ATRACE_NAME("ShaderCache::saveToDiskLocked");
Nolan Scobie193cd962023-02-08 20:03:31 -0500179 if (mInitialized && mBlobCache) {
Yichi Chen9f959552018-03-29 21:21:54 +0800180 if (mIDHash.size()) {
181 auto key = sIDKey;
Leon Scroggins III77644a22022-05-03 15:50:51 -0400182 set(mBlobCache.get(), &key, sizeof(key), mIDHash.data(), mIDHash.size());
Yichi Chen9f959552018-03-29 21:21:54 +0800183 }
Matt Buckleye278da12023-06-20 22:51:05 +0000184 // The most straightforward way to make ownership shared
185 mMutex.unlock();
186 mMutex.lock_shared();
Yichi Chen9f959552018-03-29 21:21:54 +0800187 mBlobCache->writeToFile();
Matt Buckleye278da12023-06-20 22:51:05 +0000188 mMutex.unlock_shared();
189 mMutex.lock();
Yichi Chen9f959552018-03-29 21:21:54 +0800190 }
Yichi Chen9f959552018-03-29 21:21:54 +0800191}
192
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400193void ShaderCache::store(const SkData& key, const SkData& data, const SkString& /*description*/) {
Stan Ilievd495f432017-10-09 15:49:32 -0400194 ATRACE_NAME("ShaderCache::store");
Matt Buckleye278da12023-06-20 22:51:05 +0000195 std::lock_guard lock(mMutex);
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400196 mNumShadersCachedInRam++;
197 ATRACE_FORMAT("HWUI RAM cache: %d shaders", mNumShadersCachedInRam);
Stan Ilievd495f432017-10-09 15:49:32 -0400198
199 if (!mInitialized) {
Stan Ilievd495f432017-10-09 15:49:32 -0400200 return;
201 }
202
203 size_t valueSize = data.size();
204 size_t keySize = key.size();
205 if (keySize == 0 || valueSize == 0 || valueSize >= maxValueSize) {
206 ALOGW("ShaderCache::store: sizes %d %d not allowed", (int)keySize, (int)valueSize);
207 return;
208 }
209
210 const void* value = data.data();
211
212 BlobCache* bc = getBlobCacheLocked();
Stan Iliev14211aa2019-01-14 12:29:30 -0500213 if (mInStoreVkPipelineInProgress) {
214 if (mOldPipelineCacheSize == -1) {
215 // Record the initial pipeline cache size stored in the file.
216 mOldPipelineCacheSize = bc->get(key.data(), keySize, nullptr, 0);
217 }
218 if (mNewPipelineCacheSize != -1 && mNewPipelineCacheSize == valueSize) {
219 // There has not been change in pipeline cache size. Stop trying to save.
220 mTryToStorePipelineCache = false;
221 return;
222 }
223 mNewPipelineCacheSize = valueSize;
224 } else {
225 mCacheDirty = true;
226 // If there are new shaders compiled, we probably have new pipeline state too.
227 // Store pipeline cache on the next flush.
228 mNewPipelineCacheSize = -1;
229 mTryToStorePipelineCache = true;
230 }
Leon Scroggins III77644a22022-05-03 15:50:51 -0400231 set(bc, key.data(), keySize, value, valueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400232
Nolan Scobie193cd962023-02-08 20:03:31 -0500233 if (!mSavePending && mDeferredSaveDelayMs > 0) {
Stan Ilievd495f432017-10-09 15:49:32 -0400234 mSavePending = true;
235 std::thread deferredSaveThread([this]() {
Nolan Scobie193cd962023-02-08 20:03:31 -0500236 usleep(mDeferredSaveDelayMs * 1000); // milliseconds to microseconds
Matt Buckleye278da12023-06-20 22:51:05 +0000237 std::lock_guard lock(mMutex);
Stan Iliev14211aa2019-01-14 12:29:30 -0500238 // Store file on disk if there a new shader or Vulkan pipeline cache size changed.
239 if (mCacheDirty || mNewPipelineCacheSize != mOldPipelineCacheSize) {
240 saveToDiskLocked();
241 mOldPipelineCacheSize = mNewPipelineCacheSize;
242 mTryToStorePipelineCache = false;
243 mCacheDirty = false;
244 }
Nolan Scobie193cd962023-02-08 20:03:31 -0500245 mSavePending = false;
Stan Ilievd495f432017-10-09 15:49:32 -0400246 });
247 deferredSaveThread.detach();
248 }
249}
250
Adlai Hollerd2345212020-10-07 14:16:40 -0400251void ShaderCache::onVkFrameFlushed(GrDirectContext* context) {
Stan Iliev14211aa2019-01-14 12:29:30 -0500252 {
Matt Buckleye278da12023-06-20 22:51:05 +0000253 mMutex.lock_shared();
Stan Iliev14211aa2019-01-14 12:29:30 -0500254 if (!mInitialized || !mTryToStorePipelineCache) {
Matt Buckleye278da12023-06-20 22:51:05 +0000255 mMutex.unlock_shared();
Stan Iliev14211aa2019-01-14 12:29:30 -0500256 return;
257 }
Matt Buckleye278da12023-06-20 22:51:05 +0000258 mMutex.unlock_shared();
Stan Iliev14211aa2019-01-14 12:29:30 -0500259 }
260 mInStoreVkPipelineInProgress = true;
261 context->storeVkPipelineCacheData();
262 mInStoreVkPipelineInProgress = false;
263}
264
Stan Ilievd495f432017-10-09 15:49:32 -0400265} /* namespace skiapipeline */
266} /* namespace uirenderer */
267} /* namespace android */