blob: c1bcb5550e51dd3aab6679f73231431a67708e62 [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");
82 std::lock_guard<std::mutex> 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) {
95 std::lock_guard<std::mutex> lock(mMutex);
96 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();
107 std::lock_guard<std::mutex> lock(mMutex);
108 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");
179 if (mInitialized && mBlobCache && mSavePending) {
180 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 }
184 mBlobCache->writeToFile();
185 }
186 mSavePending = false;
187}
188
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400189void ShaderCache::store(const SkData& key, const SkData& data, const SkString& /*description*/) {
Stan Ilievd495f432017-10-09 15:49:32 -0400190 ATRACE_NAME("ShaderCache::store");
191 std::lock_guard<std::mutex> lock(mMutex);
Leon Scroggins III8cedb662022-05-02 10:38:38 -0400192 mNumShadersCachedInRam++;
193 ATRACE_FORMAT("HWUI RAM cache: %d shaders", mNumShadersCachedInRam);
Stan Ilievd495f432017-10-09 15:49:32 -0400194
195 if (!mInitialized) {
Stan Ilievd495f432017-10-09 15:49:32 -0400196 return;
197 }
198
199 size_t valueSize = data.size();
200 size_t keySize = key.size();
201 if (keySize == 0 || valueSize == 0 || valueSize >= maxValueSize) {
202 ALOGW("ShaderCache::store: sizes %d %d not allowed", (int)keySize, (int)valueSize);
203 return;
204 }
205
206 const void* value = data.data();
207
208 BlobCache* bc = getBlobCacheLocked();
Stan Iliev14211aa2019-01-14 12:29:30 -0500209 if (mInStoreVkPipelineInProgress) {
210 if (mOldPipelineCacheSize == -1) {
211 // Record the initial pipeline cache size stored in the file.
212 mOldPipelineCacheSize = bc->get(key.data(), keySize, nullptr, 0);
213 }
214 if (mNewPipelineCacheSize != -1 && mNewPipelineCacheSize == valueSize) {
215 // There has not been change in pipeline cache size. Stop trying to save.
216 mTryToStorePipelineCache = false;
217 return;
218 }
219 mNewPipelineCacheSize = valueSize;
220 } else {
221 mCacheDirty = true;
222 // If there are new shaders compiled, we probably have new pipeline state too.
223 // Store pipeline cache on the next flush.
224 mNewPipelineCacheSize = -1;
225 mTryToStorePipelineCache = true;
226 }
Leon Scroggins III77644a22022-05-03 15:50:51 -0400227 set(bc, key.data(), keySize, value, valueSize);
Stan Ilievd495f432017-10-09 15:49:32 -0400228
229 if (!mSavePending && mDeferredSaveDelay > 0) {
230 mSavePending = true;
231 std::thread deferredSaveThread([this]() {
232 sleep(mDeferredSaveDelay);
233 std::lock_guard<std::mutex> lock(mMutex);
Stan Iliev14211aa2019-01-14 12:29:30 -0500234 // Store file on disk if there a new shader or Vulkan pipeline cache size changed.
235 if (mCacheDirty || mNewPipelineCacheSize != mOldPipelineCacheSize) {
236 saveToDiskLocked();
237 mOldPipelineCacheSize = mNewPipelineCacheSize;
238 mTryToStorePipelineCache = false;
239 mCacheDirty = false;
240 }
Stan Ilievd495f432017-10-09 15:49:32 -0400241 });
242 deferredSaveThread.detach();
243 }
244}
245
Adlai Hollerd2345212020-10-07 14:16:40 -0400246void ShaderCache::onVkFrameFlushed(GrDirectContext* context) {
Stan Iliev14211aa2019-01-14 12:29:30 -0500247 {
248 std::lock_guard<std::mutex> lock(mMutex);
249
250 if (!mInitialized || !mTryToStorePipelineCache) {
251 return;
252 }
253 }
254 mInStoreVkPipelineInProgress = true;
255 context->storeVkPipelineCacheData();
256 mInStoreVkPipelineInProgress = false;
257}
258
Stan Ilievd495f432017-10-09 15:49:32 -0400259} /* namespace skiapipeline */
260} /* namespace uirenderer */
261} /* namespace android */