blob: b87002371775c656561f006c879294399b1d6b2f [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;
Matt Buckleye9adfbd2023-07-06 23:15:30 +000091 if (identity != nullptr && size > 0 && mIDHash.size()) {
92 set(&sIDKey, sizeof(sIDKey), mIDHash.data(), mIDHash.size());
93 }
Stan Ilievd495f432017-10-09 15:49:32 -040094 }
95}
96
97void ShaderCache::setFilename(const char* filename) {
Matt Buckleye278da12023-06-20 22:51:05 +000098 std::lock_guard lock(mMutex);
Stan Ilievd495f432017-10-09 15:49:32 -040099 mFilename = filename;
100}
101
Stan Ilievd495f432017-10-09 15:49:32 -0400102sk_sp<SkData> ShaderCache::load(const SkData& key) {
103 ATRACE_NAME("ShaderCache::load");
104 size_t keySize = key.size();
Matt Buckleye278da12023-06-20 22:51:05 +0000105 std::lock_guard lock(mMutex);
Stan Ilievd495f432017-10-09 15:49:32 -0400106 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 }
Matt Buckleye9adfbd2023-07-06 23:15:30 +0000116 size_t valueSize = mBlobCache->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400117 int maxTries = 3;
118 while (valueSize > mObservedBlobValueSize && maxTries > 0) {
119 mObservedBlobValueSize = std::min(valueSize, maxValueSize);
John Reck283bb462018-12-13 16:40:14 -0800120 void* newValueBuffer = realloc(valueBuffer, mObservedBlobValueSize);
Stan Iliev003a9f62018-03-29 13:33:53 -0400121 if (!newValueBuffer) {
122 free(valueBuffer);
Stan Ilievd495f432017-10-09 15:49:32 -0400123 return nullptr;
124 }
Stan Iliev003a9f62018-03-29 13:33:53 -0400125 valueBuffer = newValueBuffer;
Matt Buckleye9adfbd2023-07-06 23:15:30 +0000126 valueSize = mBlobCache->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400127 maxTries--;
128 }
129 if (!valueSize) {
130 free(valueBuffer);
131 return nullptr;
132 }
133 if (valueSize > mObservedBlobValueSize) {
John Reck283bb462018-12-13 16:40:14 -0800134 ALOGE("ShaderCache::load value size is too big %d", (int)valueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400135 free(valueBuffer);
136 return nullptr;
137 }
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400138 mNumShadersCachedInRam++;
139 ATRACE_FORMAT("HWUI RAM cache: %d shaders", mNumShadersCachedInRam);
Stan Ilievd495f432017-10-09 15:49:32 -0400140 return SkData::MakeFromMalloc(valueBuffer, valueSize);
141}
142
Matt Buckleye9adfbd2023-07-06 23:15:30 +0000143void ShaderCache::set(const void* key, size_t keySize, const void* value, size_t valueSize) {
144 switch (mBlobCache->set(key, keySize, value, valueSize)) {
Leon Scroggins III77644a22022-05-03 15:50:51 -0400145 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);
Matt Buckleye9adfbd2023-07-06 23:15:30 +0000151 if (mIDHash.size()) {
152 set(&sIDKey, sizeof(sIDKey), mIDHash.data(), mIDHash.size());
153 }
Leon Scroggins III77644a22022-05-03 15:50:51 -0400154 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}
Leon Scroggins III77644a22022-05-03 15:50:51 -0400173
Yichi Chen9f959552018-03-29 21:21:54 +0800174void ShaderCache::saveToDiskLocked() {
175 ATRACE_NAME("ShaderCache::saveToDiskLocked");
Nolan Scobie193cd962023-02-08 20:03:31 -0500176 if (mInitialized && mBlobCache) {
Matt Buckleye278da12023-06-20 22:51:05 +0000177 // The most straightforward way to make ownership shared
178 mMutex.unlock();
179 mMutex.lock_shared();
Yichi Chen9f959552018-03-29 21:21:54 +0800180 mBlobCache->writeToFile();
Matt Buckleye278da12023-06-20 22:51:05 +0000181 mMutex.unlock_shared();
182 mMutex.lock();
Yichi Chen9f959552018-03-29 21:21:54 +0800183 }
Yichi Chen9f959552018-03-29 21:21:54 +0800184}
185
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400186void ShaderCache::store(const SkData& key, const SkData& data, const SkString& /*description*/) {
Stan Ilievd495f432017-10-09 15:49:32 -0400187 ATRACE_NAME("ShaderCache::store");
Matt Buckleye278da12023-06-20 22:51:05 +0000188 std::lock_guard lock(mMutex);
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400189 mNumShadersCachedInRam++;
190 ATRACE_FORMAT("HWUI RAM cache: %d shaders", mNumShadersCachedInRam);
Stan Ilievd495f432017-10-09 15:49:32 -0400191
192 if (!mInitialized) {
Stan Ilievd495f432017-10-09 15:49:32 -0400193 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
Stan Iliev14211aa2019-01-14 12:29:30 -0500205 if (mInStoreVkPipelineInProgress) {
206 if (mOldPipelineCacheSize == -1) {
207 // Record the initial pipeline cache size stored in the file.
Matt Buckleye9adfbd2023-07-06 23:15:30 +0000208 mOldPipelineCacheSize = mBlobCache->get(key.data(), keySize, nullptr, 0);
Stan Iliev14211aa2019-01-14 12:29:30 -0500209 }
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 }
Matt Buckleye9adfbd2023-07-06 23:15:30 +0000223 set(key.data(), keySize, value, valueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400224
Nolan Scobie193cd962023-02-08 20:03:31 -0500225 if (!mSavePending && mDeferredSaveDelayMs > 0) {
Stan Ilievd495f432017-10-09 15:49:32 -0400226 mSavePending = true;
227 std::thread deferredSaveThread([this]() {
Nolan Scobie193cd962023-02-08 20:03:31 -0500228 usleep(mDeferredSaveDelayMs * 1000); // milliseconds to microseconds
Matt Buckleye278da12023-06-20 22:51:05 +0000229 std::lock_guard lock(mMutex);
Stan Iliev14211aa2019-01-14 12:29:30 -0500230 // 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 }
Nolan Scobie193cd962023-02-08 20:03:31 -0500237 mSavePending = false;
Stan Ilievd495f432017-10-09 15:49:32 -0400238 });
239 deferredSaveThread.detach();
240 }
241}
242
Adlai Hollerd2345212020-10-07 14:16:40 -0400243void ShaderCache::onVkFrameFlushed(GrDirectContext* context) {
Stan Iliev14211aa2019-01-14 12:29:30 -0500244 {
Matt Buckleye278da12023-06-20 22:51:05 +0000245 mMutex.lock_shared();
Stan Iliev14211aa2019-01-14 12:29:30 -0500246 if (!mInitialized || !mTryToStorePipelineCache) {
Matt Buckleye278da12023-06-20 22:51:05 +0000247 mMutex.unlock_shared();
Stan Iliev14211aa2019-01-14 12:29:30 -0500248 return;
249 }
Matt Buckleye278da12023-06-20 22:51:05 +0000250 mMutex.unlock_shared();
Stan Iliev14211aa2019-01-14 12:29:30 -0500251 }
252 mInStoreVkPipelineInProgress = true;
253 context->storeVkPipelineCacheData();
254 mInStoreVkPipelineInProgress = false;
255}
256
Stan Ilievd495f432017-10-09 15:49:32 -0400257} /* namespace skiapipeline */
258} /* namespace uirenderer */
259} /* namespace android */